<?php
/*
	Stempora Web Framework
	Copyright (c) 2002-2016 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com		
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CHelp extends CPlugin{
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __construct() {
		//parent::CModule("auth");
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DoEvents() {
		global $_CONF, $base , $_TSM , $_USER , $_SESS , $_PAGE;

		parent::DoEvents();
		//$this->GetInfoBlock();
		//$this->__protect();

		if ($_GET["mod"] == "help") {

			$this->__init();

			$_TSM["PUB:MODULE_NAME"] = "User Guide";

			//run update every month.
			//$this->update();

			if ($_GET["module"]) {
				$_GET["sub"] = "detect";
			}			
		
			switch ($_GET["sub"]) {

				case "landing":
					return $this->Landing();
				break;

				case "important":
					return $this->Important();
				break;

				case "static":
					return $this->StaticFile();
				break;


				case "article":
					return $this->Article();
				break;

				case "update":
					return $this->Update();
				break;

				
			}
		}		
	}	

	function __init() {
		global $_CONF;

		if ($this->__inited) {
			return "";
		}


		$this->__inited = true;
		
		$path = $this->tpl_path;

		$templates = array(
			"widget-links"		=> "widget-links.htm",
			"landing"			=> "landing.htm",
			"shortcodes"		=> "shortcodes.htm",
			"important"			=> "important.htm",
			"article"			=> "article.htm",
			"static"			=> "static.htm",
		);

		foreach ($templates as $key => $val) {
			$this->private->templates[$key] = new CTemplateDynamic(
				$path . $val
			);
		}

		//read the module
		$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("help");
	} 


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Landing() {
		global $base;
		$blocks = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['cms:help_blocks']}
			ORDER BY 
				block_order ASC
			"
		);

		if (is_array($blocks)) {
			foreach ($blocks as $key => $val) {

				switch ($val["block_type"]) {
					case "1":
						$blocks[$key]["content"] = $this->_t("landing")->blockReplace(
							"Text" ,
							$val						
						);
					break;

					case "2":

						$articles =  null;
						$_articles = null;
						$_tmp = null;


						if ($val["block_articles"]) {
							$articles = $this->db->QFetchRowArray(
								"SELECT item_id , item_title FROM 
									{$this->tables['cms:help_articles']}
								WHERE
									item_id in ($val[block_articles])
								"
							);

							if (is_array($articles)) {

								foreach ($articles as $_key => $_val) {
									$_articles[$_val["item_id"]] = $_val;
								}
								$articles = $_articles;


								$tmp = explode("," , $val["block_articles"]);

								foreach ($tmp as $_key => $_val) {
									if (is_Array($articles[$_val])) {
										$_tmp[] = $articles[$_val];
									}
								}

								$articles = $_tmp;
								
								

								$link = "";
								foreach ($articles as $k => $v) {

									$articles[$k]["link"] = "index.php?mod=help&sub=article&article={$v[item_id]}&chapter={$val[block_id]}";

									if (!$link) {
										$link = $articles[$k]["link"];
									}
									
									//if one page then force the link of the first article to be the main one.
									if ($val["block_onepage"]) {
										$articles[$k]["link"] = $link . "#a" . $v["item_id"];
									} 
								}							
							}

							$blocks[$key]["content"] = $base->html->Table(
								$this->_t("landing"), 
								"Articles",
								$articles,
								$val
							);
						} else {
							$blocks[$key]["content"] = "";
						}
						
					break;
				}
				
			}			
		}

		if (is_array($blocks)) {
			foreach ($blocks as $key => $val) {

				$content .= $base->htmlElements->Widget(
					array(
						"title"		=> $val["block_title"],
						"icon"		=> "cogs",
						"skin"		=> "Help",
						"height"	=> "260",

						"content"	=> $val["content"],
					)
				);
			}		
		}
			

		return $this->Shortcodes(
			$this->_t("landing")->blockReplace(
				"Main",
				array(

					"blocks"	=> $base->html->table(
						$this->_t("landing") , 
						"Blocks",
						$blocks,
						array(
							"class"		=> " Purple ",
							"important"	=> $this->ImportantArticles(),
						)
					),

					
				),
				$chapter
			)
		);

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Article() {
		global $base , $_LANG_ID;

		$article = $this->getArticle($_GET["article"]);

		if (!is_array($article)) {
			urlredirect("index.php?mod=help&sub=landing");
		}
		

		//check the block this article is part of 
		$block = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['cms:help_blocks']} 
			WHERE
				block_type = 2 AND 
				find_in_set({$article[item_id]}, block_articles)
			"
		);

		switch ($block["block_onepage"]) {				
			case "1":


				if ($block["block_articles"]) {
					//multiple articles on the same page appended
					$articles = $this->db->QFetchRowArray(
						"SELECT * FROM 
							{$this->tables['cms:help_articles']} 
						WHERE
							item_id in ($block[block_articles])
						"
					);

					foreach ($articles as $key => $val) {
						$content .= $this->_t("article")->blockReplace(
							"Multiple",
							$val				
						);
					}								
				}
				

			break;

			default:
				//standard article or if not part of a block
				$content = $this->_t("article")->blockReplace(
					"Main",
					$article				
				);
			break;
		}

		$content = $this->Shortcodes($content , $chapter);

		
		return $this->_t("article")->blockReplace(
			"Layout",
			array(
				"content"	=> $content, 
				"widget"	=> $this->widgetCurrentBlock()
			)
		);
	}

	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Important() {
		global $base , $_LANG_ID;

		$article = 	$this->db->QFetchArray(
			"SELECT 
				*
			FROM 
				{$this->tables['cms:help_important']}
			WHERE
				item_id = %d
			ORDER BY 
				item_order ASC
			",
			array($_GET["article"])
		);

		if (!is_array($article)) {
			urlredirect("index.php?mod=help&sub=landing");
		}
		

		$article["item_body"] = $this->Shortcodes($article["item_body"] , "");

		
		return $this->_t("important")->blockReplace(
			"Layout",
			array(
				"content"	=> $this->_t("important")->blockReplace(
					"Main" ,
					$article
				),
				"widget"	=> $this->widgetCurrentBlock()
			)
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function getArticle($code , $type = "id") {
		global $_LANG_ID;

		$type = "id";

		switch ($type) {
			case "url":
				$cond = "l.item_url LIKE '{$code}'";
			break;

			case "id":
				$cond = "item_id = '{$code}'";
			break;
		}
		
		return $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['cms:help_articles']} 
			WHERE
				{$cond}
			"
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function getBlock($id) {
		$block = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['cms:help_blocks']} as p,
				{$this->tables['cms:help_blocks_lang']} as l
			WHERE
				p.block_id = l.block_id AND 
				l.lang_id = {$this->tpl_module[lang_id]} 
			ORDER BY 
				block_order ASC
			"
		);

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Shortcodes($content , $chapter = array()) {

		$content = preg_replace(
			'/\[icomoon=(.*?)\]/',
			"<span class='sign IcomoonCustom $1'></span>",
			 $content
		);

		$content = preg_replace_callback(
			'/\[help=(.*?)\](.*?)\[\/help]/',
			array($this, 'replace_links'),
			 $content
		);

		$content = preg_replace_callback(
			'/\[imp=(.*?)\](.*?)\[\/imp]/',
			array($this, 'replace_links_important'),
			 $content
		);



		$replace = array(
			"[path]"	=> "path_start",
			"[/path]"	=> "path_end",

			"[tooltip]"	=> "tooltip_start",
			"[/tooltip]"	=> "tooltip_end",

		);

		foreach ($replace as $key => $val) {
			$content = str_replace(
				$key , 
				$this->_t("shortcodes")->blockReplace($val) , 
				$content
			);
		}


		
		//check the block this article is part of 
		$content = str_replace("width=" , "data-width=" ,$content);
		$content = str_replace("height=" , "data-height=" ,$content);

		$content = str_replace("style=\"height:" , "data-style=\"height:" ,$content);


//		$content = str_replace("/upload/help/" , "modules/help/images/" , $content);
//		$content = str_replace("http://www.devsaver.com" , "" , $content);
//		$content = str_replace("https://devsaver.comhttp://images.devsaver.com" , "http://images.devsaver.com" , $content);

		
		return $content;
	}

	// the callback function
	function replace_links($matches){
		global $_MODULES;


		if (stristr($matches[1] , "#")) {
			$tmp = explode("#", $matches[1] );
			$aid = $tmp[0];
			$hash = "#" . $tmp[1];
		} else {
			$aid = $matches[1];
		}
		
		$article = $this->getArticle($aid , "id");
		$link = "index.php?mod=help&sub=article&chapter=" . $_GET["chapter"] . "&article=" . $article["item_id"] . "{$hash}";


		//debug($matches);
		return "<a href=\"{$link}\">{$matches[2]}</a>" ;
	}


	// the callback function
	function replace_links_important($matches){
		global $_MODULES;


		if (stristr($matches[1] , "#")) {
			$tmp = explode("#", $matches[1] );
			$aid = $tmp[0];
			$hash = "#" . $tmp[1];
		} else {
			$aid = $matches[1];
		}
		
		$link = "index.php?mod=help&sub=important&article=" . $aid;


		//debug($matches);
		return "<a href=\"{$link}\">{$matches[2]}</a>" ;
	}

	function widgetCurrentBlock() {
		global $_LANG_ID , $base;

		$blocks = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['cms:help_blocks']} 
			ORDER BY 
				block_order ASC
			"
		);

		$article = $this->getArticle($_GET["article"]);
		if ($article["item_parent"]) {
			$article = $this->getArticle($article["item_parent"] , "id");
		}



		if (is_array($blocks)) {
			foreach ($blocks as $_key => $chapter) {
				$chapter["class"] = "Purple collapsed";

				if ($chapter["block_articles"]) {
					$articles = $this->db->QFetchRowArray(
						"SELECT  item_id , item_title FROM 
							{$this->tables['cms:help_articles']} 
						WHERE
							item_id in ($chapter[block_articles])
						"
					);
				}

				if (is_array($articles)) {
					$_articles = array();
					$_tmp = array();

					foreach ($articles as $__key => $__val) {
						$_articles[$__val["item_id"]] = $__val;
					}
					$articles = $_articles;


					$tmp = explode("," , $chapter["block_articles"]);

					foreach ($tmp as $__key => $__val) {
						if (is_Array($articles[$__val])) {
							$_tmp[] = $articles[$__val];
						}
					}

					$articles = $_tmp;

					foreach ($articles as $key => $val) {
						$articles[$key]["link"] = "index.php?mod=help&sub=article&chapter={$chapter[block_id]}&article={$val[item_id]}";
						$articles[$key]["sub"]  = "";
						$articles[$key]["class"] = $val["item_id"] == $_GET["article"] ? "current" : "";

						if ($val["item_id"] == $article["item_id"]) {
							$chapter["class"] = "Purple";



							$kids = $this->db->QFetchRowArray(
							"SELECT  item_id , item_title FROM 
								{$this->tables['cms:help_articles']} 
							WHERE
								item_parent = {$val[item_id]} 
							ORDER BY
								item_order ASC
							"
							);

							if (is_array($kids)) {
								$cur = false;

								foreach ($kids as $_k => $_v) {
									$kids[$_k]["link"] = "index.php?mod=help&sub=article&chapter={$chapter[block_id]}&article={$_v[item_id]}";
									$kids[$_k]["class"] = $_v["item_id"] == $_GET["article"] ? "current" : "";

									if ($_v["item_id"] == $_GET["article"]) {
										$articles[$key]["cur"] = true;
									}					
								}

													
								$articles[$key]["sub"] = $base->html->Table(
									$this->_t("widget-links") , 
									"Sub" , 
									$kids
								);
								$chapter["class"] = "";

							} 
						}

					}
					
				}


				$content .= $this->_t("widget-links")->blockReplace(
					"Widget",
					array(
						"links"			=> $base->html->Table(
							$this->_t("widget-links"),
							"" , 
							$articles
						),
						"widget_name"	=> $chapter["block_title"],
						"class"			=> $chapter["class"] ? $chapter["class"] : " Purple ",
					)
				);


			}
			
		}

		return $this->Shortcodes(
			$this->ImportantArticles() .
			$content
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ImportantArticles() {
		global $imp , $base;

		$imp = 	$this->db->QFetchRowArray(
			"SELECT 
				 item_id , item_title 
			FROM 
				{$this->tables['cms:help_important']} 
			ORDER BY 
				item_order ASC
			"
		);

		if (is_array($imp)) {
			foreach ($imp as $key => $val) {
				$imp[$key]["sub"] = "";
				$imp[$key]["link"] = "index.php?mod=help&sub=important&article={$val[item_id]}";
			}
			
		}

		return $this->_t("widget-links")->blockReplace(
			"Widget",
			array(
				"links"			=> $base->html->Table(
					$this->_t("widget-links"), 
					"" , 
					$imp
				),
				"widget_name"	=> "Important Articles",
				"class"			=> "Red",
			)
		);

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Redirect() {
		global $_LANG_ID;

		$module = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['cms:help_articles']} 
			WHERE
				item_module like '{$_GET[module]}'
			"
		);

		if (!is_array($module)) {
			urlredirect("index.php?mod=help&sub=landing");
		}
		
		$block = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['cms:help_blocks']} as p,
				{$this->tables['cms:help_blocks_lang']} as l
			WHERE
				p.block_id = l.block_id AND 
				block_type = 2 AND 
				l.lang_id = {$_LANG_ID} AND 
				find_in_set({$module[item_id]}, block_articles)
			"
		);
		
		if (!is_array($block)) {
			urlredirect("index.php?mod=help&sub=landing");
		}

		urlredirect("index.php?mod=help&sub=article&article={$module[item_id]}&chapter={$block[block_id]}");	

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Update() {
		//load the api 

		if ($this->vars->data["set_global_help_date"] > (time() - 24 * 3600 * 30)) {
			return true;
		}
		
		$help = CDevSaverApi::newInstance($this->vars->data["set_global_license"])
				->downloadHelp($this->vars->data["set_global_help_date"]);

		debug($help,1);

		$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_blocks']}");
		$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_articles']}");
		$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_important']}");




		if (is_array($help["help"]) && !STP_ENABLE_DEMO) {
			//upddate chapters
			$ids = array();
			foreach ($help["help"]["chapters"] as $key => $val) {
				$old = $this->db->QFetchArray("SELECT * FROM {$this->tables['cms:help_blocks']} WHERE block_id = {$val[block_id]}");

				if (is_array($old)) {
					$this->db->QueryUpdate($this->tables["cms:help_blocks"] , $val , "block_id={$val[block_id]}");
				} else {
					$this->db->QueryInsert($this->tables["cms:help_blocks"] , $val , "block_id={$val[block_id]}");
				}

				$ids[] = $val["block_id"];				
			}

			//delete old records
			$this->db->Query("DELETE FROM  {$this->tables['cms:help_blocks']} WHERE block_id NOT IN (" . implode("," , $ids) . ")");


			//update articles
			$ids = array();
			foreach ($help["help"]["articles"] as $key => $val) {
				$val["item_date"] = $val["item_date_update"];

				if ($val["item_body"]) {
					$old = $this->db->QFetchArray("SELECT * FROM {$this->tables['cms:help_articles']} WHERE item_id = {$val[item_id]}");

					if (is_array($old)) {
						$this->db->QueryUpdate($this->tables["cms:help_articles"] , $val , "item_id={$val[item_id]}");
					} else {
						$this->db->QueryInsert($this->tables["cms:help_articles"] , $val , "item_id={$val[item_id]}");
					}
				}			
				$ids[] = $val["item_id"];				
			}

			//delete old records
			$this->db->Query("DELETE FROM  {$this->tables['cms:help_articles']} WHERE item_id NOT IN (" . implode("," , $ids) . ")");


			//update important
			$ids = array();
			foreach ($help["help"]["important"] as $key => $val) {
				$val["item_date"] = $val["item_date_update"];

				if ($val["item_body"]) {
					$old = $this->db->QFetchArray("SELECT * FROM {$this->tables['cms:help_important']} WHERE item_id = {$val[item_id]}");

					if (is_array($old)) {
						$this->db->QueryUpdate($this->tables["cms:help_important"] , $val , "item_id={$val[item_id]}");
					} else {
						$this->db->QueryInsert($this->tables["cms:help_important"] , $val , "item_id={$val[item_id]}");
					}
				}			
				$ids[] = $val["item_id"];				
			}

			//delete old records
			$this->db->Query("DELETE FROM  {$this->tables['cms:help_important']} WHERE item_id NOT IN (" . implode("," , $ids) . ")");

			$this->vars->SetVars(
				array(
					"set_global_help_date"	=> time()
				)
			);
		}

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StaticFile() {

		$file = "modules/help/docs/" . basename($_GET["file"]) . ".htm" ;

		if (file_exists($file)) {

			$tpl = new CTemplateDynamic($file);
			return $this->_t("static")->blockReplace(
				"Widget",
				array(
					"content"	=> $tpl->blockReplace("Content"),
					"title"	=> $tpl->blockReplace("Title"),
				)
			);
		}		
	}
	

}

?>