<?php
/*---------------------------------------------\
|											   |
| @Author:       Andrey Brykin (Drunya)        |
| @Version:      1.4.5                         |
| @Project:      CMS                           |
| @package       CMS Fapos                     |
| @subpackege    Stats Module                  |
| @copyright     ©Andrey Brykin 2010-2011      |
| @last mod     2011/11/15                     |
|----------------------------------------------|
|											   |
| any partial or not partial extension         |
| CMS Fapos,without the consent of the         |
| author, is illegal                           |
|----------------------------------------------|
| Любое распространение                        |
| CMS Fapos или ее частей,                     |
| без согласия автора, является не законным    |
\---------------------------------------------*/




Class StatModule extends Module {

	/**
	* @module_title  title of module
	*/
	var $module_title = 'Статьи';
	/**
	* @template  layout for module
	*/
	var $template = 'stat';
	/**
	* @module module indentifier
	*/
	var $module = 'stat';


	
	/**
	* default action ( show main page )
	*/
	function index() {
		//turn access
		$this->ACL->turn(array('stat', 'view_list'));
		
		//формируем блок со списком  разделов
		$this->_getCatsTree();
		
		
		//check content cache
		if ($this->cached && $this->Cache->check($this->cacheKey)) {
			$html = $this->Cache->read($this->cacheKey);
		} else {
		
		
			//Узнаем кол-во материалов в БД (!we need to know whether to show hidden )
			//Узнаем кол-во материалов в БД (!we need to know whether to show hidden )
			$query_params = array('cond' => array());
			if (!$this->ACL->turn(array('other', 'can_see_hidden'), false)) {
				$query_params['cond']['available'] = 1;
			}
			$order = getOrderParam(__CLASS__);
			if (!empty($order)) $query_params['order'] = $order;
			

			$total = $this->DB->select('stat', DB_COUNT, $query_params);
			$cntPages = ceil( $total / Config::read('per_page', 'stat') );
			if ( isset($_GET['page']) ) {
				$page = (int)$_GET['page'];
				if ( $page < 1 ) $page = 1;
			} else {
				$page = 1;
			}
			if ( $page > $cntPages ) $page = $cntPages;
			$pages = pagination( $page, $cntPages, '/stat/');
			$_SESSION['page'] = $page;
			$_SESSION['pagescnt'] = $cntPages;

			
			
			//navigation panel
			$nav = array();
			$nav['{ADD_LINK}'] = ($this->ACL->turn(array('stat', 'add_materials'), false)) ? 
				get_link(__('Add material'), '/stat/add_form/') : '';
			$nav['{NAVIGATION}'] = $this->_buildBreadCrumbs();
			$nav['{PAGINATION}'] = $pages;
			$nav['{META}'] = __('Count all material') . $total;
			$this->_globalize($nav);
			
			if ($total == 0) {
				return $this->_view(__('Materials not found'));
			}

			
			$html = '';
			$query_params = array(
				'joins' => array(
					array(
						'table' => 'stat_sections',
						'type' => 'LEFT',
						'alias' => 'b',
						'cond' => 'a.`category_id` = b.`id`',
					),
					array(
						'table' => 'users',
						'type' => 'LEFT',
						'alias' => 'd',
						'cond' => 'd.`id` = a.`author_id`',
					),
				),
				'fields' => array('a.*', 'b.`title` as category_name'
				, 'd.`name` AS author', 'd.`status` AS author_status'),
				'alias' => 'a',
				'page' => $page,
				'limit' => Config::read('per_page', 'stat'),
			);
			if (!$this->ACL->turn(array('other', 'can_see_hidden'), false)) $query_params['cond']['`a`.`available`'] = '1';
			$order = getOrderParam(__CLASS__);
			if (!empty($order)) $query_params['order'] = $order;
			$sql = $this->DB->select('stat', DB_ALL, $query_params);
			if (is_object($this->AddFields) && count($sql) > 0) {
				$sql = $this->AddFields->mergeRecords($sql);
			}
			
			
			// get ids list
			$ids = array();
			foreach ($sql as $result) {
				$ids[] = $result['id'];
			}
			$ids = implode(', ', $ids);
			$attaches = $this->DB->select($this->module . '_attaches', DB_ALL, array('cond' => array('`entity_id` IN ('.$ids.')')));
			

			foreach ($sql as $result) {
				$markets = array();
				$result = $this->Parser->quoteTags($result);
				$_SESSION['current_vars'] = $result;
				$htmlstats = $this->Parser->getAndParse('tablemat.html');
				
				
				$rec_attaches = array();
				if (!empty($attaches) && count($attaches) > 0) {
					foreach ($attaches as $k => $attach) {
						if ($attach['entity_id'] == $result['id']) {
							$rec_attaches[] = $attach;
							unset($attaches[$k]);
						}
					}
				}
				
				
				$markets['{MODER_PANEL}'] = $this->_getAdminBar($result);
				$entry_url = get_url(entryUrl($result, $this->module));
				$markets['{ENTRY_URL}'] = $entry_url;
	
	
				$announce = $this->Parser->unquoteTags($result['description']);
				// replace image tags in text
				if (!empty($rec_attaches) && count($rec_attaches) > 0) {
					$attachDir = R . 'sys/files/' . $this->module . '/';
					foreach ($rec_attaches as $attach) {
						if ($attach['is_image'] == 1 && file_exists($attachDir . $attach['filename'])) {
							$announce = str_replace('{IMAGE'.$attach['attach_number'].'}'
							, '[img]' . get_url('/sys/files/'.$this->module.'/'.$attach['filename']).'[/img]'
							, $announce);
						}
					}
				}
				$announce = $this->Textarier->getAnnounce($announce, $entry_url, 0, 
					Config::read('announce_lenght', 'stat'), $result);
				$markets['{ANNOUNCE}'] = $this->Parser->quoteTags($announce);
				
				
				foreach ($result as $key=>$value) {
				   $markets['{'.strtoupper($key).'}'] = h($value);
				}
				
				$markets['{PROFILE_URL}'] = getProfileUrl($result['author_id']);
				$markets['{CATEGORY_URL}'] = get_url('/stat/category/' . $result['category_id']);  
				$html .= $this->_replaceMarkets($markets, $htmlstats);

				
				//set cache tags
				$this->setCacheTag(array(
					'record_id_' . $result['id'],
					'user_id_' . $result['author_id'],
				));
			}

			
			$materials_tpl = $this->Parser->getAndParse('materials_container.html');
			$markets = array(
				'{MATERIALS}' => $html,
			);
			$html = $this->_replaceMarkets($markets, $materials_tpl);
			
			
			//save cache
			if ($this->cached)
			$this->Cache->write($html, $this->cacheKey, $this->cacheTags);
		}
		return $this->_view($html);
	}


	

	 
	function category($id = null) {
		//turn access
		$this->ACL->turn(array('stat', 'view_list'));
		$id = intval($id);
		if (empty($id) || $id < 1) redirect('/');

		
		$catinfo = $this->DB->select('stat_sections', DB_FIRST, array('cond' => array('id' => $id)));
		if (count($catinfo) < 1)
			return showInfoMessage(__('Can not find category'), '/stat/');
		if (!$this->ACL->checkCategoryAccess($catinfo[0]['no_access'])) 
			return showInfoMessage(__('Permission denied'), '/stat/');
		
		
		
		//формируем блок со списком  разделов
		$this->_getCatsTree($id);
		
		
		
		if ($this->cached && $this->Cache->check($this->cacheKey)) {
			$html = $this->Cache->read($this->cacheKey);
		} else {
		
		
			$category = intval($id);
			$query_params = array('cond' => array('category_id' => $category));
			//(!we need to know whether to show hidden )
			if (!$this->ACL->turn(array('other', 'can_see_hidden'), false)) $query_params['cond']['available'] = '1';
			
			$total    = $this->DB->select('stat', DB_COUNT, $query_params);
			$cntPages = ceil( $total / Config::read('per_page', 'stat') );
			if ( isset($_GET['page']) ) {
				$page = (int)$_GET['page'];
				if ( $page < 1 ) $page = 1;
			} else {
				$page = 1;
			}
			if ( $page > $cntPages ) $page = $cntPages;
			$pages = pagination( $page, $cntPages, '/stat/category/' . $id );
			$_SESSION['page'] = $page;
			$_SESSION['pagescnt'] = $cntPages;

			
			
			
			//navigation panel
			$nav = array();
			$nav['{NAVIGATION}'] = $this->_buildBreadCrumbs($id);
			$nav['{ADD_LINK}'] = ($this->ACL->turn(array('stat', 'add_materials'), false)) ? 
				get_link(__('Add material'), '/stat/add_form/') : '';
			$nav['{PAGINATION}'] = $pages;
			$nav['{META}'] = __('Count material in cat') . $total;
			$this->_globalize($nav);
			
			
			if ($total == 0) {
				return $this->_view(__('Materials not found'));
			}
			
			
			$html = '';
			$query_params = array(
				'joins' => array(
					array(
						'table' => 'stat_sections',
						'type' => 'LEFT',
						'alias' => 'b',
						'cond' => 'a.`category_id` = b.`id`',
					),
					array(
						'table' => 'users',
						'type' => 'LEFT',
						'alias' => 'd',
						'cond' => 'd.`id` = a.`author_id`',
					),
				),
				'fields' => array('`a`.*', '`b`.`title` as category_name', '`d`.`name` AS author'
				, '`d`.`status` AS author_status'),
				'alias' => 'a',
				'page' => $page,
				'limit' => Config::read('per_page', 'stat'),
			);
			$query_params['cond'] = array('`a`.`category_id`' => $id);
			if (!$this->ACL->turn(array('other', 'can_see_hidden'), false)) $query_params['cond']['`a`.`available`'] = '1';
			$order = getOrderParam(__CLASS__);
			if (!empty($order)) $query_params['order'] = $order;
			$sql = $this->DB->select('stat', DB_ALL, $query_params);
			if (is_object($this->AddFields) && count($sql) > 0) {
				$sql = $this->AddFields->mergeRecords($sql);
			}
			
			
			// get ids list
			$ids = array();
			foreach ($sql as $result) {
				$ids[] = $result['id'];
			}
			$ids = implode(', ', $ids);
			$attaches = $this->DB->select($this->module . '_attaches', DB_ALL, array('cond' => array('`entity_id` IN ('.$ids.')')));
			

			foreach ($sql as $result) {
				$markets = array();
				$result = $this->Parser->quoteTags($result);
				$_SESSION['current_vars'] = $result;
				$htmlstats = $this->Parser->getAndParse('tablemat.html');

				
				$rec_attaches = array();
				if (!empty($attaches) && count($attaches) > 0) {
					foreach ($attaches as $k => $attach) {
						if ($attach['entity_id'] == $result['id']) {
							$rec_attaches[] = $attach;
							unset($attaches[$k]);
						}
					}
				}
				
				
				$markets['{MODER_PANEL}'] = $this->_getAdminBar($result);
				$entry_url = get_url(entryUrl($result, $this->module));
				$markets['{ENTRY_URL}'] = $entry_url;
				
				
				$announce = $this->Parser->unquoteTags($result['main']);
				// replace image tags in text
				if (!empty($rec_attaches) && count($rec_attaches) > 0) {
					$attachDir = R . 'sys/files/' . $this->module . '/';
					foreach ($rec_attaches as $attach) {
						if ($attach['is_image'] == 1 && file_exists($attachDir . $attach['filename'])) {
							$announce = str_replace('{IMAGE'.$attach['attach_number'].'}'
							, '[img]' . get_url('/sys/files/'.$this->module.'/'.$attach['filename']).'[/img]'
							, $announce);
						}
					}
				}
				$announce = $this->Textarier->getAnnounce($announce, $entry_url, 0, 
					Config::read('announce_lenght', 'stat'), $result);
				$markets['{ANNOUNCE}'] = $this->Parser->quoteTags($announce);
				
				
				foreach ($result as $key => $value) {
				   $markets['{'.strtoupper($key).'}'] = h($value);
				}
				
				$markets['{PROFILE_URL}'] = getProfileUrl($result['author_id']);
				$markets['{CATEGORY_URL}'] = get_url('/stat/category/' . $result['category_id']);  
				$html .= $this->_replaceMarkets($markets, $htmlstats);
				
				//set cache tags
				$this->setCacheTag(array(
					'record_id_' . $result['id'],
					'user_id_' . $result['author_id'],
					'category_id_' . $id,
				));
			}
			
			
			$materials_tpl = $this->Parser->getAndParse('materials_container.html');
			$markets = array(
				'{MATERIALS}' => $html,
			);
			$html = $this->_replaceMarkets($markets, $materials_tpl);
			
			
			//write cache
			if ($this->cached)
				$this->Cache->write($html, $this->cacheKey, $this->cacheTags);
		}
		return $this->_view($html);
	}
	  
	  


	function view ($id = null) {
		$this->ACL->turn(array('stat', 'view_materials'));
		$id = intval($id);
		if (empty($id) || $id < 1) redirect('/');
		
		
		// извлекаем из БД информацию материала
		$sql = $this->DB->select('stat', DB_FIRST, array(
			'joins' => array(
				array(
					'table' => 'stat_sections',
					'type' => 'LEFT',
					'alias' => 'b',
					'cond' => 'a.`category_id` = b.`id`',
				),
				array(
					'table' => 'users',
					'type' => 'LEFT',
					'alias' => 'd',
					'cond' => 'd.`id` = a.`author_id`',
				),
			),
			'fields' => array('`a`.*', '`b`.`title` as category_name', '`d`.`name` AS author'
			, '`d`.`status` AS author_status', 'b.`no_access` as no_access'),
			'alias' => 'a',
			'cond' => array('`a`.`id`' => $id),
		));
		if (count($sql) < 1) return showInfoMessage(__('Some error occurred'), '/stat/');
		if ($sql[0]['available'] == 0 && !$this->ACL->turn(array('other', 'can_see_hidden'), false)) 
			return showInfoMessage(__('Permission denied'), '/stat/' );
		if (!$this->ACL->checkCategoryAccess($sql[0]['no_access'])) 
			return showInfoMessage(__('Permission denied'), '/news/');
			

		if (is_object($this->AddFields) && count($sql) > 0) {
			$sql = $this->AddFields->mergeRecords($sql);
		}
		
		$attaches = $this->DB->select('stat_attaches', DB_ALL, array('cond' => array('entity_id' => $id)));
		$max_attaches = Config::read('max_attaches', 'stat');
		if (empty($max_attaches) || !is_numeric($max_attaches)) $max_attaches = 5;
		
		$result = $this->Parser->quoteTags($sql[0]);
		$_SESSION['current_vars'] = $result;
		
		//  в другом случае извлекаем шаблон отображения материала
		$html = $this->Parser->getAndParse('vievmat.html');


		// Navigation Panel
		$nav = array();
		$nav['{MODULE_URL}'] = get_url('/stat/');
		$nav['{CATEGORY_URL}'] = get_url('/stat/category/' . $result['category_id']);
		$nav['{CATEGORY_NAME}'] = h($result['category_name']);
		$nav['{NAVIGATION}'] = $this->_buildBreadCrumbs($result['category_id']);
		$this->_globalize($nav);

		
		
		// Local markets
		$markets = array();
		$markets['{MODER_PANEL}'] = $this->_getAdminBar($result);

		
		$text_stat  = $this->Parser->unquoteTags($result['main']);
		// replace image tags in text
		if (!empty($attaches) && count($attaches) > 0) {
			$attachDir = R . 'sys/files/' . $this->module . '/';
			foreach ($attaches as $attach) {
				if ($attach['is_image'] == 1 && file_exists($attachDir . $attach['filename'])) {
					$text_stat = str_replace('{IMAGE'.$attach['attach_number'].'}'
					, '[img]' . get_url('/sys/files/'.$this->module.'/'.$attach['filename']).'[/img]'
					, $text_stat);
				}
			}
		}
		$text_stat  = $this->Textarier->print_page($text_stat, $result['author_status'], $result['title']);
		$markets['{MAIN_TEXT}']  = $this->Parser->quoteTags($text_stat);
		
		
		foreach ($result as $key => $value) {
			$markets['{'.strtoupper($key).'}'] = h($value);
		}
		
		$markets['{PROFILE_URL}'] = getProfileUrl($result['author_id']);
		$markets['{CATEGORY_URL}'] = get_url('/stat/category/' . $result['category_id']);
		$html = $this->_replaceMarkets($markets, $html);

		$this->DB->save('stat', array(
			'`views` = `views` + 1',
			'id' => $id,
		));
		
		$this->page_title = $this->page_title . '-' . h($result['title']);
		if (!empty($result['tags'])) $this->page_meta_keywords = h($result['tags']);
		if (!empty($result['description'])) $this->page_meta_description = h($result['description']);
		
		
		/* COMMENT BLOCK */
		if (Config::read('comment_active', 'stat') == 1 
		&& $this->ACL->turn(array('stat', 'view_comments'), false) && $result['commented'] == 1) {
			if ($this->ACL->turn(array('stat', 'add_comments'), false)) 
				$this->comments  = $this->_add_comment_form($id);
			$this->comments  = $this->_get_comments($id) . $this->comments;
		}
		
		
		//формируем блок со списком  разделов
		$this->_getCatsTree($result['category_id']);
		
		
		$this->DB->cleanSqlCache();
		return $this->_view($html);
	}




	 
	function add_form () {
		//turn access
		$this->ACL->turn(array('stat', 'add_materials'));
		$writer_status = (!empty($_SESSION['user']['status'])) ? $_SESSION['user']['status'] : 0;

		
		// categories block
		$this->_getCatsTree();
		
		
		$title 			= null;
		$add 			= null;
		$description 	= null;
		$tags 			= null;
		$sourse			= null;
		$sourse_email	= null;
		$sourse_site	= null;
		$commented	    = null;
		$available	    = null;
		$html = $this->Parser->getAndParse('addform.html' );
		
		// Additional fields
		if (is_object($this->AddFields)) {
			$_addFields = $this->AddFields->getInputs();
			foreach($_addFields as $k => $field) {
				$html = str_replace('{' . strtoupper($k) . '}', $field, $html );
			}
		}
		
		
		
		$sql = $this->DB->select('stat_sections', DB_ALL);
		$cats_change = '';
		foreach ($sql as $cat) {
			if (!empty($_SESSION['FpsForm']['in_cat']) && $_SESSION['FpsForm']['in_cat'] == $cat['id'])
				$selected = ' selected="selected"';
			else if (!empty($_SESSION['viewMessage']['in_cat']) && $_SESSION['viewMessage']['in_cat'] == $cat['id'])
				$selected = ' selected="selected"';
			else
				$selected = '';
				
			$cats_change .= '<option value="' . $cat['id'] . '"'
			. $selected . ' >' . h($cat['title']) . '</option>';
		}

		
		
		// Preview
		if (isset($_SESSION['viewMessage']) and !empty($_SESSION['viewMessage']['mainText'])) {
			$view = $this->Parser->getAndParse('previewmessage.html');
			$view = str_replace('{MESSAGE}', 
				$this->Textarier->print_page($_SESSION['viewMessage']['mainText'], $writer_status), $view);
			$html     			= $html.$view."\n";
			$title    		    = h($_SESSION['viewMessage']['title']);
			$add       			= h($_SESSION['viewMessage']['mainText']);
			$description		= h($_SESSION['viewMessage']['description']);
			$tags 				= h($_SESSION['viewMessage']['tags']);
			$sourse 			= h($_SESSION['viewMessage']['sourse']);
			$sourse_email 		= h($_SESSION['viewMessage']['sourse_email']);
			$sourse_site 		= h($_SESSION['viewMessage']['sourse_site']);
			$commented 			= h($_SESSION['viewMessage']['commented']);
			$available 			= h($_SESSION['viewMessage']['available']);
			unset($_SESSION['viewMessage']);
		}

		// Errors
		if (isset($_SESSION['FpsForm'])) {
			$info = $this->Parser->getAndParse('infomessage.html' );
			$info = str_replace( '{INFO_MESSAGE}', $_SESSION['FpsForm']['error'], $info );
			$html     		= $info . $html . "\n";
			$title     		= h($_SESSION['FpsForm']['title']);
			$add  	   		= h($_SESSION['FpsForm']['mainText']);
			$description 	= h($_SESSION['FpsForm']['description']);
			$tags 			= h($_SESSION['FpsForm']['tags']);
			$sourse			= h($_SESSION['FpsForm']['sourse']);
			$sourse_email	= h($_SESSION['FpsForm']['sourse_email']);
			$sourse_site	= h($_SESSION['FpsForm']['sourse_site']);
			$commented	    = h($_SESSION['FpsForm']['commented']);
			$available	    = h($_SESSION['FpsForm']['available']);
			unset($_SESSION['FpsForm']);
		}
		
		//comments and hide
		$commented = (!empty($commented) || !isset($_POST['submitForm'])) ? 'checked="checked"' : '';
		if (!$this->ACL->turn(array('stat', 'record_comments_management'), false)) $commented .= ' disabled="disabled"';
		$available = (!empty($available) || !isset($_POST['submitForm'])) ? 'checked="checked"' : '';
		if (!$this->ACL->turn(array('stat', 'hide_material'), false)) $available .= ' disabled="disabled"';

		
		$markets = array();
		$markets['{ACTION}'] = '/stat/add/';
		$markets['{CATS_SELECTOR}'] = $cats_change;
		$markets['{TITLE}'] = $title;
		$markets['{MAIN_TEXT}'] = $add;
		$markets['{DESCRIPTION}'] = $description;
		$markets['{TAGS}'] = $tags;
		$markets['{SOURSE}'] = $sourse;
		$markets['{SOURSE_EMAIL}'] = $sourse_email;
		$markets['{SOURSE_SITE}'] = $sourse_site;
		$markets['{COMMENTED}'] = $commented;
		$markets['{AVAILABLE}'] = $available;
		$markets['{MAX_ATTACHES}'] = Config::read('max_attaches', $this->module);
		if (empty($markets['{MAX_ATTACHES}']) || !is_numeric($markets['{MAX_ATTACHES}'])) 
			$markets['{MAX_ATTACHES}'] = 5;
		$html = $this->_replaceMarkets($markets, $html);
		
		
		//navigation panel
		$nav = array();
		$nav['{NAVIGATION}'] = $this->_buildBreadCrumbs() . __('Separator') . __('Добавление материала');
		$this->_globalize($nav);
		
		
		return $this->_view($html);
	}





	// Функция добавляет новую новость 
	function add() {
		//turn access
		$this->ACL->turn(array('stat', 'view_list'));
		if (!isset($_POST['title']) 
		|| !isset($_POST['mainText']) 
		|| !isset($_POST['cats_selector'])) {
			redirect('/');
		}
		if (!is_numeric($_POST['cats_selector'])) redirect('/stat/');
		
		
		$error  = '';
		// Additional fields checker
		if (is_object($this->AddFields)) {
			$_addFields = $this->AddFields->checkFields();
			if (is_string($_addFields)) $error .= $_addFields; 
		}
		
		$fields = array('description', 'tags', 'sourse', 'sourse_email', 'sourse_site');
		$fields_settings = Config::read('fields', 'stat');
		foreach ($fields as $field) {
			if (empty($_POST[$field]) && in_array($field, $fields_settings)) {
				$error = $error.'<li>' . __('Empty field') . '"' . $field . '"</li>'."\n";
				$$field = null;
			} else {
				$$field = trim($_POST[$field]);
			}
		}
		// Обрезаем переменные до длины, указанной в параметре maxlength тега input
		$title   	= trim(mb_substr( $_POST['title'], 0, 128 ));
		$add 		= trim($_POST['mainText']);
		$in_cat 	= intval($_POST['cats_selector']);
		$commented = (!empty($_POST['commented'])) ? 1 : 0;
		$available = (!empty($_POST['available'])) ? 1 : 0;
		
		
		// Если пользователь хочет посмотреть на сообщение перед отправкой
		if ( isset( $_POST['viewMessage'] ) ) {
			$_SESSION['viewMessage'] = array_merge(array('title' => null, 'mainText' => null, 'in_cat' => $in_cat,
				'description' => null, 'tags' => null, 'sourse' => null, 'sourse_email' => null, 
				'sourse_site' => null, 'commented' => null, 'available' => null), $_POST);
			redirect('/stat/add_form/');
		}

		// Check fields
		$valobj = new Validate;
		if ( empty( $in_cat ) )                     
			$error = $error.'<li>' . __('Category not selected') . '</li>'."\n";
		if ( empty( $title ) )                       
			$error = $error.'<li>' . __('Empty field "title"') . '</li>'."\n";
		elseif (!$valobj->cha_val($title, V_TITLE))  
			$error = $error.'<li>' . __('Wrong chars in "title"') . '</li>'."\n";
		if ( empty( $add ) )                    	 
			$error = $error.'<li>' . __('Empty field "material"') . '</li>'."\n";
		else if (mb_strlen($add) > Config::read('max_lenght', 'stat'))
			$error = $error.'<li>' . sprintf(__('Wery big "material"'), Config::read('max_lenght', 'stat')) . '</li>'."\n";
		if (!empty($tags) && !$valobj->cha_val($tags, V_TITLE)) 
			$error = $error.'<li>' . __('Wrong chars in "tags"') . '</li>'."\n";
		if (!empty($sourse) && !$valobj->cha_val($sourse, V_TITLE)) 
			$error = $error.'<li>' . __('Wrong chars in "sourse"') . '</li>'."\n";
		if (!empty($sourse_email) && !$valobj->cha_val($sourse_email, V_MAIL)) 
			$error = $error.'<li>' . __('Wrong chars in "email"') . '</li>'."\n";
		if (!empty($sourse_site) && !$valobj->cha_val($sourse_site, V_URL)) 
			$error = $error.'<li>' . __('Wrong chars in "sourse site"') . '</li>'."\n";
		
		
		
		// Check attaches size and format
		$max_attach = Config::read('max_attaches', $this->module);
		if (empty($max_attach) || !is_numeric($max_attach)) $max_attach = 5;
		$max_attach_size = Config::read('max_attaches_size', $this->module);
		if (empty($max_attach_size) || !is_numeric($max_attach_size)) $max_attach_size = 1000;
		for ($i = 1; $i <= $max_attach; $i++) {
			$attach_name = 'attach' . $i;
			if (!empty($_FILES[$attach_name]['name'])) {
			
				$img_extentions = array('.png','.jpg','.gif','.jpeg', '.PNG','.JPG','.GIF','.JPEG');
				$ext = strrchr($_FILES[$attach_name]['name'], ".");

				
				
				if ($_FILES[$attach_name]['size'] > $max_attach_size) {
					$error .= '<li>' . sprintf(__('Wery big file'), $i, round(($max_attach_size / 1000), 2)) . '</li>'."\n";
				}
				if (($_FILES[$attach_name]['type'] != 'image/jpeg'
				&& $_FILES[$attach_name]['type'] != 'image/jpg'
				&& $_FILES[$attach_name]['type'] != 'image/gif'
				&& $_FILES[$attach_name]['type'] != 'image/png')
				|| !in_array($ext, $img_extentions)) {
					$error .= '<li>' . __('Wrong file format') . '</li>'."\n";
				}
			}
		}
		
		
		$sql = $this->DB->select('stat_sections', DB_FIRST, array('cond' => array('id' => $in_cat)));
		if ($sql < 1) $error .= '<li>' . __('Can not find category') . '</li>'."\n";
		$info_cat = $sql[0];
		
		
		// Errors
		if ( !empty( $error ) ) {
			$_SESSION['FpsForm'] = array_merge(array('title' => null, 'mainText' => null, 'in_cat' => $in_cat,
				'description' => null, 'tags' => null, 'sourse' => null, 'sourse_email' => null, 
				'sourse_site' => null, 'commented' => null, 'available' => null), $_POST);
			$_SESSION['FpsForm']['error']   = '<p class="errorMsg">' . __('Some error in form') . '</p>'.
				"\n".'<ul class="errorMsg">'."\n".$error.'</ul>'."\n";
			redirect('/stat/add_form/');
		}


		if (!$this->ACL->turn(array('stat', 'record_comments_management'), false)) $commented = '1';
		if (!$this->ACL->turn(array('stat', 'hide_material'), false)) $available = '1';
		
		
		// Защита от того, чтобы один пользователь не добавил
		// 100 материалов за одну минуту
		if ( isset( $_SESSION['unix_last_post'] ) and ( time()-$_SESSION['unix_last_post'] < 10 ) ) {
			return showInfoMessage(__('Your message has been added'), '/stat/');
		}
		
		// Формируем SQL-запрос на добавление темы	
		$add = mb_substr($add, 0, Config::read('max_lenght', 'stat'));
		$res = $this->DB->save('stat', array(
			'title'        => $title,
			'main'         => $add,
			'date'         => new Expr('NOW()'),
			'author_id'    => $_SESSION['user']['id'],
			'category_id'  => $in_cat,
			'description'  => $description,
			'tags'         => $tags,
			'sourse'  	   => $sourse,
			'sourse_email' => $sourse_email,
			'sourse_site'  => $sourse_site,
			'commented'    => $commented,
			'available'    => $available,
			'view_on_home' => $info_cat['view_on_home'],
		));
		$last_id = mysql_insert_id();
		if (is_object($this->AddFields)) {
			$this->AddFields->save($last_id, $_addFields);
		}
		
		
		downloadAttaches($this->module, $last_id);
		
		
		//clean cache
		$this->Cache->clean(CACHE_MATCHING_TAG, array('module_stat'));
		$this->DB->cleanSqlCache();
		if ($this->Log) $this->Log->write('adding stat', 'stat id(' . $last_id . ')');
		return showInfoMessage(__('Material successful added'), '/stat/' );
							  
	}





	// Функция возвращает форму для редактирования новости;
	// ID новости передаются методом GET
	function edit_form($id = null) {	
		$id = (int)$id;
		if ( $id < 1 ) redirect('/');
		$writer_status = (!empty($_SESSION['user']['status'])) ? $_SESSION['user']['status'] : 0;

		
		$res = $this->DB->select('stat', DB_FIRST, array(
			'joins' => array(
				array(
					'table' => 'stat_sections',
					'type' => 'LEFT',
					'alias' => 'b',
					'cond' => 'a.`category_id` = b.`id`',
				),
				array(
					'table' => 'users',
					'type' => 'LEFT',
					'alias' => 'd',
					'cond' => 'd.`id` = a.`author_id`',
				),
			),
			'fields' => array('`a`.*', '`b`.`title` as category_name', '`d`.`name` AS author'
			, 'd.`status` as author_status', 'b.`no_access` as no_access'),
			'alias' => 'a',
			'cond' => array('`a`.`id`' => $id),
		));
		if (count($res) == 0) redirect('/stat/');
		
		if ($res[0]['available'] == 0 && !$this->ACL->turn(array('other', 'can_see_hidden'), false))
			return showInfoMessage(__('Permission denied'), '/stat/' );
			
		// Additional fields
		if (is_object($this->AddFields) && count($res) > 0) {
			$res = $this->AddFields->mergeRecords($res, true);
		}
		
		
		$stat = $res[0];
		$html = '';
		$markets = array();
		
		if (!$this->ACL->turn(array('stat', 'edit_materials')) 
		|| (!empty($_SESSION['user']['id']) && $stat['author_id'] == $_SESSION['user']['id'] 
		&& !$this->ACL->turn(array('stat', 'edit_mine_materials')))) {
			return showInfoMessage(__('Permission denied'), '/stat/' );
		}
		
		$_SESSION['current_vars'] = $stat;

		
		$cats = $this->DB->select('stat_sections', DB_ALL);
		$cats_change = '';
		foreach ($cats as $cat) {
			if($stat['category_id'] == $cat['id']) {
				$cats_change .= "<option value=\"" . $cat['id'] . "\" selected=\"selected\">" 
				. h($cat['title']) . "</option>";
			} else {
				$cats_change .= "<option value=\"" . $cat['id'] . "\">" 
				. h($cat['title']) . "</option>";
			}
		}
		
		
		//формируем блок со списком  разделов
		$this->_getCatsTree($stat['category_id']);
		
		
		//предварительный просмотр
		if (isset($_SESSION['viewMessage']) and !empty($_SESSION['viewMessage']['mainText'])) {
			$view = $this->Parser->getAndParse('previewmessage.html');
			$view = str_replace('{MESSAGE}', 
				$this->Textarier->print_page($_SESSION['viewMessage']['mainText'], $writer_status), $view);
			$html               = $html . $view . "\n";
			$title    		    = h($_SESSION['viewMessage']['title']);
			$edit       		= h($_SESSION['viewMessage']['mainText']);
			$description		= h($_SESSION['viewMessage']['description']);
			$tags 				= h($_SESSION['viewMessage']['tags']);
			$sourse 			= h($_SESSION['viewMessage']['sourse']);
			$sourse_email 		= h($_SESSION['viewMessage']['sourse_email']);
			$sourse_site 		= h($_SESSION['viewMessage']['sourse_site']);
			$commented 			= h($_SESSION['viewMessage']['commented']);
			$available 			= h($_SESSION['viewMessage']['available']);
			unset($_SESSION['viewMessage']);
		} else {
			// Errors
			if ( isset( $_SESSION['FpsForm'] ) ) {
				$html     			= $html . $_SESSION['FpsForm']['error'];
				$title    			= h($_SESSION['FpsForm']['title']);
				$edit               = h($_SESSION['FpsForm']['mainText']);
				$description		= h($_SESSION['FpsForm']['description']);
				$tags 				= h($_SESSION['FpsForm']['tags']);
				$sourse 			= h($_SESSION['FpsForm']['sourse']);
				$sourse_email 		= h($_SESSION['FpsForm']['sourse_email']);
				$sourse_site 		= h($_SESSION['FpsForm']['sourse_site']);
				$commented 			= h($_SESSION['FpsForm']['commented']);
				$available 			= h($_SESSION['FpsForm']['available']);
				unset( $_SESSION['FpsForm'] );
			} else {
				$title    			= h($stat['title']);
				$edit     			= h($stat['main']);
				$description		= h($stat['description']);
				$tags 				= h($stat['tags']);
				$sourse 			= h($stat['sourse']);
				$sourse_email 		= h($stat['sourse_email']);
				$sourse_site 		= h($stat['sourse_site']);
				$commented 			= h($stat['commented']);
				$available 			= h($stat['available']);
			}
		}
		
		//comments and hide
		$commented = (!empty($commented)) ? 'checked="checked"' : '';
		if (!$this->ACL->turn(array('stat', 'record_comments_management'), false)) 
			$commented .= ' disabled="disabled"';
		$available = (!empty($available)) ? 'checked="checked"' : '';
		if (!$this->ACL->turn(array('stat', 'hide_material'), false))
			$available .= ' disabled="disabled"';
		
		
		$tpl = $this->Parser->getAndParse('editform.html' );
		
		$markets['{ACTION}'] = get_url('/stat/update/' . $id);
		$markets['{CATS_SELECTOR}'] = $cats_change;
		$markets['{AUTHOR}'] = h($stat['author']);
		$markets['{MAIN_TEXT}'] = $edit;
		$markets['{TITLE}'] = $title;
		$markets['{DESCRIPTION}'] = $description;
		$markets['{TAGS}'] = $tags;
		$markets['{SOURSE}'] = $sourse;
		$markets['{SOURSE_EMAIL}'] = $sourse_email;
		$markets['{SOURSE_SITE}'] = $sourse_site;
		$markets['{COMMENTED}'] = $commented;
		$markets['{AVAILABLE}'] = $available;
		foreach ($stat as $key => $value) {
			if (preg_match('#^add_field_[\d]+$#i', $key) && is_object($this->AddFields)) {
				$markets['{' . strtoupper($key) . '}'] = $value;
			}
		}
		
		
		/****  ATTACH  TODO****/
		$unlinkfiles = array();
		$attach_files = $this->DB->select($this->module.'_attaches', DB_ALL, array('cond' => array('entity_id' => $id)));
		if (count($attach_files) > 0) {
			foreach ($attach_files as $attach_file) {
				if (file_exists(R . 'sys/files/'.$this->module.'/' . $attach_file['filename'])) {
					$unlinkfiles[$attach_file['attach_number']] = '<input type="checkbox" name="unlink' . $attach_file['attach_number'] 
					. '" value="1" />&nbsp;' . __('Delete') ."\n";
				}
			}
		}
		foreach ($unlinkfiles as $key => $unlinkfile) {
			$markets['{ATTACH' . $key . '}'] = $unlinkfile;
		}
		/****  END  ATTACH  ****/
		
		
		$markets = $this->Parser->quoteTags($markets);
		$html = $html . $this->_replaceMarkets($markets, $tpl);

		
		//navigation panel
		$nav = array();
		$nav['{NAVIGATION}'] = $this->_buildBreadCrumbs($stat['category_id']);
		$this->_globalize($nav);
		
		setReferer();
		return $this->_view($html);
	}





	// Функция обновляет информацию о новости 
	// уникальный ID новости передается методом GET
	function update($id = null) {		
		// Если не переданы данные формы - функция вызвана по ошибке
		if (empty( $id ) 
		|| !isset( $_POST['title'] ) 
		||  !isset( $_POST['mainText'] ) 
		|| !isset($_POST['cats_selector'])) {
			redirect('/');
		}
		$id = (int)$id;
		if ($id < 1) redirect('/');


		// Получаем из БД информацию о редактируемой теме
		$res = $this->DB->select('stat', DB_FIRST, array('cond' => array('id' => $id)));
		if (count($res) < 1) redirect('/stat/');
		$stat = $res[0];
		$html = '';
		
		if (!$this->ACL->turn(array('stat', 'edit_materials')) 
		|| (!empty($_SESSION['user']['id']) && $stat['author_id'] == $_SESSION['user']['id'] 
		&& !$this->ACL->turn(array('stat', 'edit_mine_materials')))) {
			return showInfoMessage(__('Permission denied'), '/stat/' );
		}
		$error  = null;
		if (is_object($this->AddFields)) {
			$_addFields = $this->AddFields->checkFields();
			if (is_string($_addFields)) $error .= $_addFields; 
		}
		
		$valobj = new Validate;
		$fields = array('description', 'tags', 'sourse', 'sourse_email', 'sourse_site');
		$fields_settings = Config::read('fields', 'stat');
		foreach ($fields as $field) {
			if (empty($_POST[$field]) && in_array($field, $fields_settings)) {
				$error = $error.'<li>' . __('Empty field') . '"' . $field . '"</li>'."\n";
				$$field = null;
			} else {
				$$field = trim($_POST[$field]);
			}
		}
		// Обрезаем переменные до длины, указанной в параметре maxlength тега input
		$title     = trim(mb_substr( $_POST['title'], 0, 128 ));
		$edit      = trim($_POST['mainText']);
		$commented = (!empty($_POST['commented'])) ? 1 : 0;
		$available = (!empty($_POST['available'])) ? 1 : 0;
		
		
		// Если пользователь хочет посмотреть на сообщение перед отправкой
		if (isset($_POST['viewMessage'])) {
			$_SESSION['viewMessage'] = array_merge(array('title' => null, 'mainText' => null, 'in_cat' => $in_cat, 
				'description' => null, 'tags' => null, 'sourse' => null, 'sourse_email' => null, 
				'sourse_site' => null, 'commented' => null, 'available' => null), $_POST);
			redirect('/stat/edit_form/' . $id );
		}
		
		// Check fields
		if ( empty( $title ) )                    
			$error = $error.'<li>' . __('Empty field "title"') . '</li>'."\n";
		if (!Validate::cha_val($title, V_TITLE))  
			$error = $error.'<li>' . __('Wrong chars in "title"') . '</li>'."\n";
		if ( empty( $edit ) )                     
			$error = $error.'<li>' . __('Empty field "material"') . '</li>'."\n";
		else if (mb_strlen($edit) > Config::read('max_lenght', 'stat'))
			$error = $error.'<li>' . sprintf(__('Wery big "material"'), Config::read('max_lenght', 'stat')) . '</li>'."\n";
		if (!empty($tags) && !$valobj->cha_val($tags, V_TITLE)) 
			$error = $error.'<li>' . __('Wrong chars in "tags"') . '</li>'."\n";
		if (!empty($sourse) && !$valobj->cha_val($sourse, V_TITLE)) 
			$error = $error.'<li>' . __('Wrong chars in "sourse"') . '</li>'."\n";
		if (!empty($sourse_email) && !$valobj->cha_val($sourse_email, V_MAIL)) 
			$error = $error.'<li>' . __('Wrong chars in "email"') . '</li>'."\n";
		if (!empty($sourse_site) && !$valobj->cha_val($sourse_site, V_URL)) 
			$error = $error.'<li>' . __('Wrong chars in "sourse site"') . '</li>'."\n";


		$in_cat = intval($_POST['cats_selector']);
		$sql = $this->DB->select('stat_sections', DB_FIRST, array('cond' => array('id' => $in_cat)));
		if ($sql < 1) $error = $error.'<li>' . __('Can not find category') . '</li>'."\n";
		$info_cat = $sql[0];
			
			
		// Errors
		if (!empty($error)) {
			$_SESSION['FpsForm'] = array_merge(array('title' => null, 'mainText' => null, 'in_cat' => $in_cat, 
				'description' => null, 'tags' => null, 'sourse' => null, 'sourse_email' => null, 
				'sourse_site' => null, 'commented' => null, 'available' => null), $_POST);
			$_SESSION['editForm']['error']   = '<p class="errorMsg">' . __('Some error in form') . '</p>'
			."\n".'<ul class="errorMsg">'."\n".$error.'</ul>'."\n";
			redirect('/stat/edit_form/' . $id );
		}
		

		if (!$this->ACL->turn(array('stat', 'record_comments_management'), false)) $commented = '1';
		if (!$this->ACL->turn(array('stat', 'hide_material'), false)) $available = '1';
		
		
		// Запрос на обновление новости
		$edit = mb_substr($edit, 0, Config::read('max_lenght', 'stat'));
		$res = $this->DB->save('stat', array(
			'title'        => $title,
			'main'         => $edit,
			'category_id'  => $in_cat,
			'description'  => $description,
			'tags'         => $tags,
			'sourse'  	   => $sourse,
			'sourse_email' => $sourse_email,
			'sourse_site'  => $sourse_site,
			'commented'    => $commented,
			'available'    => $available,
			'id'           => $id,
			'view_on_home' => $info_cat['view_on_home'],
		));
		if (is_object($this->AddFields)) {
			$this->AddFields->save($id, $_addFields);
		}
		
		//clean cache
		$this->Cache->clean(CACHE_MATCHING_TAG, array('module_stat', 'record_id_' . $id));
		$this->DB->cleanSqlCache();
		if ($this->Log) $this->Log->write('editing stat', 'stat id(' . $id . ')');
		return showInfoMessage(__('Operation is successful'), getReferer());

	}





	// Функция удаляет тему; ID темы передается методом GET
	function delete($id = null) {	
		$this->cached = false;
		// Если новость пытается удалить не зарегистрированный пользователь
		if ( empty( $id ) ) {
			redirect('/');
		}
		$id = (int)$id;
		if ( $id < 1 ) {
			redirect('/');
		}
		
		$sql = $this->DB->select('stat', DB_FIRST, array('cond' => array('id' => $id)));
		$result = $sql[0];

		if (!$this->ACL->turn(array('stat', 'delete_materials')) 
		|| (!empty($_SESSION['user']['id']) && $result['author_id'] == $_SESSION['user']['id'] 
		&& !$this->ACL->turn(array('stat', 'delete_mine_materials')))) {
			return showInfoMessage(__('Permission denied'), '/stat/' );
		}
		
		
		// Теперь удаляем материал 
		$res = $this->DB->query("DELETE FROM `" . $this->DB->getFullTableName('stat') 
		. "` WHERE `id` = '" . $id . "'");	
		$this->DB->query("DELETE FROM `" . $this->DB->getFullTableName($this->module . '_add_content') 
		. "` WHERE `entity_id` = '" . $id . "'");
		
		$attaches = $this->DB->select($this->module . '_attaches', DB_ALL, array('cond' => array('entity_id' => $id)));
		if (count($attaches) > 0) {
			foreach ($attaches as $attach) {
				unlink(R . 'sys/files/' . $this->module . '/' . $attach['filename']);
			}
		}
		$this->DB->query("DELETE FROM `" . $this->DB->getFullTableName($this->module . '_attaches') 
		. "` WHERE `entity_id` = '" . $id . "'");
		
		
		//clean cache
		$this->Cache->clean(CACHE_MATCHING_TAG, array('module_stat'));
		$this->DB->cleanSqlCache();
		if ($this->Log) $this->Log->write('delete stat', 'stat id(' . $id . ')');
		return showInfoMessage(__('Material has been delete'), getReferer());
	}


	
	
	
	
	/**
	* add comment to stat
	*
	* @id (int)    stat ID
	* @return      info message
	*/
	public function add_comment($id = null) {
		include_once(R . 'sys/inc/includes/add_comment.php');
	}
	
	
	/**
	* add comment form to stat
	*
	* @id (int)    stat ID
	* @return      html form
	*/
	private function _add_comment_form($id = null) {
		include_once(R . 'sys/inc/includes/_add_comment_form.php');
		return $html;
	}
	
	
	
	/**
	* edit comment form to stat
	*
	* @id (int)    comment ID
	* @return      html form
	*/
	public function edit_comment_form($id = null) {
		include_once(R . 'sys/inc/includes/edit_comment_form.php');
	}
	
	
	
	/**
	* update comment
	*
	* @id (int)    comment ID
	* @return      info message
	*/
	public function update_comment($id = null) {
		include_once(R . 'sys/inc/includes/update_comment.php');
	}
	
	
	
	/**
	* get comments for stat
	*
	* @id (int)    stat ID
	* @return      html comments list
	*/
	private function _get_comments($id = null) {
		include_once(R . 'sys/inc/includes/_get_comments.php');
		return $html;
	}
	
	
	
	/**
	* delete comment
	*
	* @id (int)    comment ID
	* @return      info message
	*/
	public function delete_comment($id = null) {
		include_once(R . 'sys/inc/includes/delete_comment.php');
	}
	
	
	
	
	
	
	/**
	* @param int $id - record ID
	*
	* update date by record also up record in recods list
	*/
	public function upper($id) {
		$this->ACL->turn(array('stat', 'up_materials'));
		$id = (int)$id;
		if ($id < 1) {
			redirect('/');
		}
		$this->DB->save('stat', array('id' => $id, 'date' => new Expr('NOW()')));
		return showInfoMessage(__('Operation is successful'), '/stat/');
	}
	
	
	
	/**
	* @param int $id - record ID
	*
	* allow record be on home page
	*/
	public function on_home($id) {
		$this->ACL->turn(array('stat', 'on_home'));
		$id = (int)$id;
		if ($id < 1) {
			redirect('/');
		}
		$this->DB->save('stat', array('id' => $id, 'view_on_home' => 1));
		return showInfoMessage(__('Operation is successful'), '/stat/');
	}
	
	
	/**
	* @param int $id - record ID
	*
	* denied record be on home page
	*/
	public function off_home($id) {
		$this->ACL->turn(array('stat', 'on_home'));
		$id = (int)$id;
		if ($id < 1) {
			redirect('/');
		}
		$this->DB->save('stat', array('id' => $id, 'view_on_home' => 0));
		return showInfoMessage(__('Operation is successful'), '/stat/');
	}
	
	
	
	/**
	* @param int $id - record ID
	*
	* fix or unfix record on top on home page
	*/
	public function fix_on_top($id) {
		$this->ACL->turn(array('stat', 'on_home'));
		$id = (int)$id;
		if ($id < 1) {
			redirect('/');
		}
		$target = $this->DB->select('stat', DB_FIRST, array('cond' => array('id' => $id)));
		if (empty($target[0])) redirect('/');
		$dest = ($target[0]['on_home_top'] == '1') ? '0' : '1';
		$this->DB->save('stat', array('id' => $id, 'on_home_top' => $dest));
		return showInfoMessage(__('Operation is successful'), '/stat/');
	}
	
	
	
	/**
	* @param array $record - assoc record array
	* @return string - admin buttons
	*
	* create and return admin bar
	*/
	protected function _getAdminBar($record) {
		$moder_panel = '';
		if ($this->ACL->turn(array('stat', 'edit_materials'), false) 
		|| (!empty($_SESSION['user']['id']) && $record['author_id'] == $_SESSION['user']['id'] 
		&& $this->ACL->turn(array('stat', 'edit_mine_materials'), false))) {
			$moder_panel .= get_link(get_img('/sys/img/edit_16x16.png'), '/stat/edit_form/' . $record['id']) . '&nbsp;';
		}
		
		if ($this->ACL->turn(array('stat', 'up_materials'), false)) {
			$moder_panel .= get_link(get_img('/sys/img/star.png'), 
			'/stat/fix_on_top/' . $record['id'], array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
			$moder_panel .= get_link(get_img('/sys/img/up_arrow_16x16.png'), 
			'/stat/upper/' . $record['id'], array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
		}
		if ($this->ACL->turn(array('stat', 'on_home'), false)) {
				if ($record['view_on_home'] == 1) {
					$moder_panel .= get_link(get_img('/sys/img/round_ok.png', array('title' => __('On home'))), 
					'/stat/off_home/' . $record['id'], array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
				} else {
					$moder_panel .= get_link(get_img('/sys/img/round_not_ok.png', array('title' => __('On home'))), 
					'/stat/on_home/' . $record['id'], array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
				}
		}
		
		if ($this->ACL->turn(array('stat', 'delete_materials'), false) 
		|| (!empty($_SESSION['user']['id']) && $record['author_id'] == $_SESSION['user']['id'] 
		&& $this->ACL->turn(array('stat', 'delete_mine_materials'), false))) {
			$moder_panel .= get_link(get_img('/sys/img/delete_16x16.png'), 
			'/stat/delete/' . $record['id'], array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
		}
		return $moder_panel;
	}
	
	
	

    /**
     * RSS for news
	 *
     */
    function rss() {
		include_once R . 'sys/inc/includes/rss.php';
    }	
	
}
?>
