<?php
/*-----------------------------------------------\
| 												 |
|  @Author:       Andrey Brykin (Drunya)         |
|  @Version:      1.4.0                          |
|  @Project:      CMS                            |
|  @package       CMS Fapos                      |
|  @subpackege    Pages Module                   |
|  @copyright     ©Andrey Brykin 2010-2011       |
|  @last mod                    2011/10/10       |
\-----------------------------------------------*/

/*-----------------------------------------------\
| 												 |
|  any partial or not partial extension          |
|  CMS Fapos,without the consent of the          |
|  author, is illegal                            |
|------------------------------------------------|
|  Любое распространение                         |
|  CMS Fapos или ее частей,                      |
|  без согласия автора, является не законным     |
\-----------------------------------------------*/



Class PagesModule extends Module {

	/**
	* @module_title  title of module
	*/
	var $module_title;
	/**
	* @template  layout for module
	*/
	//var $template;
	/**
	* @module module indentifier
	*/
	var $module = 'pages';


	
	/**
	* default action
	*/
	function index($id = null, $s =null, $x = null) {
		//if isset ID - we need load page with this ID
		if (!empty($id)) {
			if (!is_numeric($id)) redirect('/pages/');
			$id = (int)$id;
			if ($id < 1)  redirect('/pages/');
		
		
			$content = $this->DB->select('htmlpage', DB_FIRST, array('cond' => array('id' => $id), 'limit' => 1));
			if (empty($content)) return showInfoMessage(__('Can not find this page'), '/');
			
			$this->page_title = $content[0]['name'];
			$this->template = (!empty($content[0]['template'])) ? $content[0]['template'] : 'default';
			$this->Parser->templateDir = $this->template;
			$html = $content[0]['content'];
			$html = $this->Parser->parseString($html);
			
			
			$navi['{NAVIGATION}'] = get_link(__('Home'), '/') . __('Separator') . h($content[0]['name']);
			$this->_globalize($navi);
			
			
			return $this->_view($html);
			
		//may be need view latest materials	
		} else {
			$this->page_title = Config::read('title');
			$latest_on_home = Config::read('latest_on_home');
			$navi = null; //vsyakiy sluchay:)
			
			
			//if we want view latest materials on home page
			if (is_array($latest_on_home) && count($latest_on_home) > 0) {
			
				// Navigation Block
				$navi = array();
				$navi['{ADD_LINK}'] = ($this->ACL->turn(array('news', 'add_materials'), false)) 
					? get_link(__('Add material'), '/news/add_form') : '';
				$navi['{NAVIGATION}'] = get_link(__('Home'), '/');
				$this->_globalize($navi);
			
			
				if ($this->cached && $this->Cache->check($this->cacheKey)) {
					$html = $this->Cache->read($this->cacheKey);
				} else {
				
					
					
					//create SQL query
					$sql = '';
					if (in_array('news', $latest_on_home)) 
					$sql .= "(SELECT `title`, `description`, `date`, `on_home_top`, `id`, `views`, `author_id`, (SELECT \"news\") AS skey  FROM `" 
						 . $this->DB->getFullTableName('news') . "` "
						 . "WHERE `view_on_home` = '1' AND `available` = '1') ";
					if (in_array('loads', $latest_on_home)) {
						if (!empty($sql)) $sql .= 'UNION ';
						$sql .= "(SELECT `title`, `description`, `date`, `on_home_top`, `id`, `views`, `author_id`, (SELECT \"loads\") AS skey   FROM `" 
							 . $this->DB->getFullTableName('loads') . "` "
							 . "WHERE `view_on_home` = '1' AND `available` = '1') ";
					}
					if (in_array('stat', $latest_on_home)) {
						if (!empty($sql)) $sql .= 'UNION ';
						$sql .= "(SELECT `title`, `description`, `date`, `on_home_top`, `id`, `views`, `author_id`, (SELECT \"stat\") AS skey  FROM `" 
							 . $this->DB->getFullTableName('stat') . "` " 
							 . "WHERE `view_on_home` = '1' AND `available` = '1') ";
					}
					if (!empty($sql)) {
						$sql .= 'ORDER BY `on_home_top` DESC, `date` DESC LIMIT ' . Config::read('cnt_latest_on_home');
						$materials = $this->DB->query($sql);	
						
						//if we have records
						if (count($materials) > 0) {
						
							// Get users(authors)
							$uids = array();
							$mod_mats = array('news' => array(), 'stat' => array(), 'loads' => array());
							foreach ($materials as $key => $mat) {
								$uids[] = $mat['author_id'];
								switch ($mat['skey']) {
									case 'news':
										$mod_mats['news'][$key] = $mat;
										break;
									case 'stat':
										$mod_mats['stat'][$key] = $mat;
										break;
									case 'loads':
										$mod_mats['loads'][$key] = $mat;
										break;
								}
							}
							$uids = '(' . implode(', ', $uids) . ')';
							$authors = $this->DB->select('users', DB_ALL, array('cond' => 'WHERE `id` IN ' . $uids));

							
							// Merge records with additional fields
							if (is_object($this->AddFields)) {
								if (!empty($mod_mats['news']) && count($mod_mats['news']) > 0) 
									$mod_mats['news'] = $this->AddFields->mergeRecords($mod_mats['news'], false, 'news');
								if (!empty($mod_mats['stat']) && count($mod_mats['stat']) > 0) 
									$mod_mats['stat'] = $this->AddFields->mergeRecords($mod_mats['stat'], false, 'stat');
								if (!empty($mod_mats['loads']) && count($mod_mats['loads']) > 0) 
									$mod_mats['loads'] = $this->AddFields->mergeRecords($mod_mats['loads'], false, 'loads');
							}
							
							
							$all_attaches = array('news' => array(), 'stat' => array());
							foreach ($mod_mats as $module => $mats) {
								if (count($mats) > 0 && ($module == 'news' || $module == 'stat')) {
									$attach_ids = array();
									foreach ($mats as $mat) {
										$attach_ids[] = $mat['id'];
									}
									
									$ids = implode(', ', $attach_ids);
									$attaches = $this->DB->select($module . '_attaches', DB_ALL
									, array('cond' => array('`entity_id` IN ('.$ids.')')));
									foreach ($mats as $mat) {
										foreach ($attaches as $attach) {
											if ($mat['id'] == $attach['entity_id']) {
												if (!empty($all_attaches[$module][$mat['id']])) 
													$all_attaches[$module][$mat['id']] = array();
												$all_attaches[$module][$mat['id']][] = $attach;
											}
										}
									}
								}
							}

							
							$materials = $mod_mats['news'] + $mod_mats['stat'] + $mod_mats['loads'];
							ksort($materials);
						
							
							//if we have materials for view on home page (now we get their an create page)
							$info = null;
							foreach ($materials as $result) {
								foreach ($authors as $author) {
									if ($result['author_id'] == $author['id']) {
										$result['author_status'] = $author['status'];
										break;
									}
								}
							
							
								// Create and replace markets
								$markets = array();
								$result = $this->Parser->quoteTags($result);
								$_SESSION['current_vars'] = $result;
								$htmlstats = $this->Parser->getAndParse('tablemat.html');
								
								//moder panel
								$markets['{MODER_PANEL}'] = $this->_getAdminBar($result['id'], $result['skey']);
								$entry_url = get_url(entryUrl($result, $result['skey']));
								$markets['{ENTRY_URL}'] = $entry_url;
								
								
								$matattaches = (!empty($all_attaches[$result['skey']][$result['id']])
								&& count($all_attaches[$result['skey']][$result['id']]))
								? $all_attaches[$result['skey']][$result['id']] : array();
								$announce = $this->Parser->unquoteTags($result['description']);
								
								if (count($matattaches) > 0) {
									$attachDir = R . 'sys/files/' . $result['skey'] . '/';
									foreach ($matattaches as $attach) {
										if ($attach['is_image'] == 1 && file_exists($attachDir . $attach['filename'])) {
											$announce = str_replace('{IMAGE'.$attach['attach_number'].'}'
											, '[img]' . get_url('/sys/files/'.$result['skey'].'/'.$attach['filename']).'[/img]'
											, $announce);
										}
									}
								}
								$announce = $this->Textarier->getAnnounce($announce, $entry_url, 0, 
									Config::read('announce_lenght'), $result);
								$markets['{ANNOUNCE}'] = $this->Parser->quoteTags($announce);
								
								
								
								foreach ($result as $key => $value) {
								   $markets['{' . strtoupper($key) . '}'] = h($value);
								}
								$markets['{MODULE_TITLE}'] = Config::read('title', $result['skey']);
								$info .= $this->_replaceMarkets($markets, $htmlstats);
								
								
								//set users_id that are on this page
								$this->setCacheTag(array(
									'module_' . $result['skey'],
									'record_id_' . $result['id'],
								));
							}
							
							$html = $info; unset($info);
							$materials_tpl = $this->Parser->getAndParse('materials_container.html');
							$markets = array(
								'{MATERIALS}' => $html,
							);
							$html = $this->_replaceMarkets($markets, $materials_tpl);
							
							
							//write int cache
							if ($this->cached)
								$this->Cache->write($html, $this->cacheKey, $this->cacheTags);
							
						}
					}
				}
				if (empty($html)) $html = __('Materials not found');
				return $this->_view($html);
			}
			return $this->_view(__('Materials not found'));
		}
	}


	
	
	/**
	* @param int $id - record ID
	* @param string $module - module
	* @return string - admin buttons
	*
	* create and return admin bar
	*/
	protected function _getAdminBar($id, $module) {
		$moder_panel = '';
		if ($this->ACL->turn(array($module, 'edit_materials'), false)) {
			$moder_panel .= get_link(get_img('/sys/img/edit_16x16.png', array('alt' => __('Edit'), 'title' => __('Edit'))),
			'/' . $module . '/edit_form/' . $id) . '&nbsp;';
		}
		if ($this->ACL->turn(array($module, 'up_materials'), false)) {
			$moder_panel .= get_link(get_img('/sys/img/up_arrow_16x16.png', array('alt' => __('Up'), 'title' => __('Up'))),
			'/' . $module . '/upper/' . $id, array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
		}
		if ($this->ACL->turn(array($module, 'on_home'), false)) {
			$moder_panel .= get_link(get_img('/sys/img/round_ok.png', array('alt' => __('On home'), 'title' => __('On home'))),
			'/' . $module . '/off_home/' . $id, array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
		}
		if ($this->ACL->turn(array($module, 'delete_materials'), false)) {
			$moder_panel .= get_link(get_img('/sys/img/delete_16x16.png', array('alt' => __('Delete'), 'title' => __('Delete'))),
			'/' . $module . '/delete/' . $id, array('onClick' => "return confirm('" . __('Are you sure') . "')")) . '&nbsp;';
		}

		return $moder_panel;
	}

	
}
?>
