<?php
/*-----------------------------------------------\
| 												 |
|  Author:       Andrey Brykin (Drunya)          |
|  Version:      1.2                             |
|  Project:      CMS                             |
|  package       CMS Fapos                       |
|  subpackege    Module Class                    |
|  copyright     ©Andrey Brykin 2010-2011        |
\-----------------------------------------------*/

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

class Module {

	/**
	* @page_title title of the page
	*/
	public $page_title = '';
	/**
	* @var string 
	*/
	public $page_meta_keywords;
	/**
	* @var string
	*/
	public $page_meta_description;
	/**
	* @template layout for module
	*/
	public $template = 'default';
	/**
	* @categories list of categories
	*/
	public $categories = '';
	/**
	* @module_title title for module
	*/
	public $module_title = '';
	/**
	* @module current module
	*/
	public $module = '';
	/**
	* @cacheTags Cache tags
	*/
	public $cacheTags = array();
	/**
	* @cached   use the cache engine
	*/
	protected $cached = true;
	/**
	* @var (str)   comments block
	*/
	protected $comments = '';
	/**
	* @var    database object
	*/
	protected $Database;
	/**
	* uses for work with actions log
	*
	* @var    logination object
	*/
	protected $Log;
	/**
	* uses for work with parser (chuncks, snippets, global markets ...)
	*
	* @var    parser object
	*/
	protected $Parser;
	/**
	* contains system settings
	*
	* @var (array)   system settings
	*/
	public $set;
	
	/**
	* Access control list
	*
	* @var object
	*/
	protected $ACL;
	
	/**
	 * Object for work with text
	 */
	protected $Textarier;
	
	/**
	 * @var object
	 */
	protected $AddFields = false; 
	
	/**
	 * if true - counter not worck
	 *
	 * @var boolean
	 */
	public $counter = true;
	
	/**
	 * Use wrapper?
	 *
	 * @var boolean
	 */
	protected $wrap = true;
	 
	 
	
	
	/**
	 * @var array
	 */
	protected $globalMarkets = array(
		'{NAVIGATION}' => '',
		'{PAGINATION}' => '',
		'{META}' => '',
		'{ADD_LINK}' => '',
	);
	
	
	
	
	/**
	 * @param array $params - array with modul, action and params
	 *
	 * Initialize needed objects adn set needed variables
	 */
	function __construct($params) {
		//get settings and launch before render
		$this->set = Config::read('all');
		
		//init needed objects. Core...
		$this->Parser = new Document_Parser;
		$this->Parser->templateDir = $this->template;
		
		$this->DB = FpsDataBase::get();
		$this->Textarier = new PrintText;
		if ($this->set['secure']['system_log']) $this->Log = new Logination;
		
		// init aditional fields
		if (Config::read('use_additional_fields') == 1) {
			include dirname(__FILE__) . '/additional_fields.php';
			$this->AddFields = new FpsAdditionalFields;
			$this->AddFields->module = $this->module;
		}

		
		//init Access Control List
		$this->ACL = new ACL;
		$this->beforeRender();
		
		if (Config::read('active', $params[0]) == 0) return showInfoMessage('Этот модуль отключен', '/');
		$this->page_title = (Config::read('title', $this->module)) ? h(Config::read('title', $this->module)) : h($this->module);
		$this->params = $params;
		
		//cache
		$this->Cache = new Cache;
		if (Config::read('cache') == 1) {
			$this->cached = true;
			$this->cacheKey = $this->getKeyForCache($params);
			$this->setCacheTag(array('module_' . $params[0]));
			if (!empty($params[1])) $this->setCacheTag(array('action_' . $params[1]));
		} else {
			$this->cached = false;
		}
		
		//meta tags
		$this->page_meta_keywords = h(Config::read('keywords', $this->module));
		$this->page_meta_description = h(Config::read('description', $this->module));
		
		if (empty($this->page_meta_keywords)) {
			$this->page_meta_keywords = h(Config::read('meta_keywords'));
		}
		if (empty($this->page_meta_description)) {
			$this->page_meta_description = h(Config::read('meta_description'));
		}
		
	}
	
	
	/**
	 * Uses for before render
	 * All code in this function will be worked before
	 * begin render page and launch controller(module)
	 *
	 * @return none
	 */
	protected function beforeRender() {
	}
	
	
	
	
	/**
	 * Uses for after render
	 * All code in this function will be worked after
	 * render page.
	 *
	 * @return none
	 */
	protected function afterRender() {
		// Cron
		if (Config::read('auto_sitemap')) {
			fpsCron('createSitemap', 86400);
		}
		
		
		/*
		* counter ( if active )
		* and if we not in admin panel
		*/
		if (in_array($this->module, array('chat', 'rating'))) return;
		if ($this->counter === false) return;
		
		if (substr($_SERVER['PHP_SELF'], 1, 5) != 'admin') {
			include_once R . 'modules/statistics/index.php';
			if (Config::read('active', 'statistics') == 1) {
				StatisticsModule::index();
			} else {
				StatisticsModule::viewOffCounter();
			}
		}
	}
	

	
	/**
	* @content  data for parse and view
	* @access   protected
	*/
	public function _view($content) {
		if (!empty($this->template) && $this->wrap == true) {
			$html = $this->Parser->getAndParse('main_index.html' );
			
			$html = str_replace( '{TITLE}', $this->page_title, $html );
			$html = str_replace( '{META_DESCRIPTION}', $this->page_meta_description, $html );
			$html = str_replace( '{META_KEYWORDS}', $this->page_meta_keywords, $html );
			$html = str_replace( '{MODULE_NAME}', $this->module_title, $html );

			$html = $this->Parser->headMenu($html, $this->module);
			
			$html = $this->_parseInformers($html);
		
			$html = str_replace( '{CATEGORIES}', $this->categories, $html );
			$html = str_replace( '{CONTENT}', $content, $html );
			/* COMMENT BLOCK */
			$html = str_replace('{COMMENTS}', $this->comments, $html);
			$html = $this->Parser->ParseTemplate($html);
			
			
			// Cache global markets
			if ($this->cached && $this->Cache->check($this->cacheKey . '_global_markets')) {
				$gdata = $this->Cache->read($this->cacheKey . '_global_markets');
				$this->globalMarkets = array_merge($this->globalMarkets, unserialize($gdata));
			}
			if ($this->cached && !$this->Cache->check($this->cacheKey . '_global_markets')) {
				$gdata = serialize($this->globalMarkets);
				$this->Cache->write($gdata, $this->cacheKey . '_global_markets', $this->cacheTags);
			}
			
			
			$html = str_replace(array_keys($this->globalMarkets), $this->globalMarkets, $html);
		} else {
			$html = $content;
		}
		
		
		$boot_time = round(getMicroTime() - FPS_START_TIME, 4);
		$html = str_replace('{BOOT_TIME}', $boot_time, $html);
		
		$html = $this->hooks('before_view', $html);
		
		$html = $this->Parser->unquoteTags($html);
		
		$this->afterRender();
		
		echo $html;
		
		
		
		if (Config::read('debug_mode') == 1 && !empty($_SESSION['db_querys'])) {
			$n = 1;
			$debug = '<div id="sql_querys" style="clear:both;position:relative;"><table align="center" style="position:relative;">';
			foreach ($_SESSION['db_querys'] as $query) {
				$debug .= '<tr><td width="5">' . $n . '</td><td>' . $query . '</td></tr>';
				$n++;
			}
			$debug .= '</table></div>';
			echo $debug;
		}
	}
	
	
	
	/**
	 * Replace markets in template. Get list of markets 
	 * and content wthat will be instead markets
	 *
	 * @param array $markets - market->value
	 * @param string $content
	 * @return string content with replaced markets
	 */
	protected function _replaceMarkets($markets = array(), $content) {
		$output = str_replace(array_keys($markets), $markets, $content);
		return $output;
	}
	
	
	/**
	 * Save markets. Get list of markets 
	 * and content wthat will be instead markets
	 * Before view this markets will be replaced in 
	 * all content
	 *
	 * @param array $markets - market->value
	 * @return none
	 */
	protected function _globalize($markets = array()) {
		$this->globalMarkets = array_merge($this->globalMarkets, $markets);
	}
	
	
	
	
	
	/**
	* @param string $html - html template
	* @return strin html template
	*
	* Parse template and find informers inside 
	*/
	protected function _parseInformers($html) {
		return $html;
	}
	
	
	/**
	* @tag     tag for save
	* @access  public
	*/
	function setCacheTag($tag) {
		if ((Config::read('cache') == true || Config::read('cache') == 1) && $this->cached === true) {
			if (is_array($tag)) {
				foreach ($tag as $_tag) {
					$this->setCacheTag($_tag);
				}
			} else {
				$this->cacheTags[] = $tag;
				return true;
			}
		}
		return false;
	}
	
	
	
	/**
	* create unique id for cache file
	* @params <module>[ action [ param1 [ param2 ]]]
	* @_GET[page] if exists
	* @user_group
	*/
	private function getKeyForCache($params) {
		$cacheId = '';
		foreach ($params as $value) {
			if (is_array($value)) {
				foreach ($value as $_value) {
					$cacheId = $cacheId . $_value . '_';
				}
				continue;
			}
			$cacheId = $cacheId . $value . '_';
		}
		
		if (!empty($_GET['page'])) {
				$cacheId = $cacheId . $_GET['page'] . '_';
		}
		$cacheId = (!empty($_SESSION['user']['status'])) ? $cacheId . $_SESSION['user']['status'] : $cacheId . 'guest';
		return $cacheId;
	}
	

	/**
	 * Find plugin by key and launch his
	 *
	 * @param string $key
	 * @param mixed $params
	 */
	protected function hooks($key, $params = array()) {
		$plugins = glob(R . 'sys/plugins/' . $key . '*');
	
		if (count($plugins) > 0 && is_array($plugins)) {
			foreach ($plugins as $plugin) {
				if (!is_dir($plugin)) continue;
				
				$pl_conf = file_get_contents($plugin . '/config.dat');
				$pl_conf = unserialize($pl_conf);
				if (empty($pl_conf['active'])) continue;
				
				
				include_once $plugin . '/index.php';
				
				$pl_obj = new $pl_conf['className']($params);
				$params = $pl_obj->common($params);
			}
		}
		
		return $params;
	}
	

}







?>
