<?php
/*
	PHPbase web framework
	copyright (c) 2003 @authors

	$Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $
	description
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CHelp extends CPlugin{
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CHelp() {
		//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") {

			$_TSM["PUB:MODULE_NAME"] = "CMS Documentation";

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

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

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

				case "detect":
					return $this->Redirect();
				break;

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

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

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

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Chapters() {
		global $base;

		$tpl = new CTemplateDynamic($this->tpl_path . "chapter.htm");

		$blocks = $this->db->QFetchRowArray(
			"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
			"
		);

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

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

					case "2":

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


						if ($val["block_articles"]) {
							$articles = $this->db->QFetchRowArray(
								"SELECT item_url , p.item_id , item_title FROM 
									{$this->tables['cms:help_articles']} as p,
									{$this->tables['cms:help_articles_lang']} as l
								WHERE
									p.item_id = l.item_id AND 
									p.item_status = 1 AND
									l.lang_id = {$this->tpl_module[lang_id]} AND 
									p.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(
								$tpl , 
								"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(
			$tpl->blockReplace(
				"Main",
				array(
					"blocks"	=> $base->html->table(
						$tpl , 
						"Blocks",
						$blocks
					),
				),
				$chapter
			)
		);

	}

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

		$tpl = new CTemplateDynamic($this->tpl_path . "article.htm");

		$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']} 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({$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']} as p,
							{$this->tables['cms:help_articles_lang']} as l
						WHERE
							p.item_id = l.item_id AND 
							p.item_status = 1 AND
							l.lang_id = {$this->tpl_module[lang_id]} AND 
							p.item_id in ($block[block_articles])
						"
					);

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

			break;

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

		$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);

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

		
		return $tpl->blockReplace(
			"Layout",
			array(
				"content"	=> $content, 
				"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 = "p.item_id = '{$code}'";
			break;
		}
		
		return $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['cms:help_articles']} as p,
				{$this->tables['cms:help_articles_lang']} as l
			WHERE
				p.item_id = l.item_id AND 
				l.lang_id = {$_LANG_ID} AND 
				{$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=(.*?)\]/',
			"",
			 $content
		);

		//if (count($chapter)) {
		{

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



			$replace = array(
				"[warning]"	=> "warning_start",
				"[/warning]"	=> "warning_end",

				"[tip]"	=> "tip_start",
				"[/tip]"	=> "tip_end",

				"[note]"	=> "note_start",
				"[/note]"	=> "note_end",

				"[path]"	=> "path_start",
				"[/path]"	=> "path_end",

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

			);


			$tpl = new CTemplateDynamic($this->tpl_path . "shortcodes.htm");

			foreach ($replace as $key => $val) {
				$content = str_replace(
					$key , 
					$tpl->blockReplace($val) , 
					$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>" ;
	}


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

		$blocks = $this->db->QFetchRowArray(
			"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
			"
		);

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


		$tpl = new CTemplateDynamic($this->tpl_path . "widget.htm");

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

				if ($chapter["block_articles"]) {
					$articles = $this->db->QFetchRowArray(
						"SELECT item_url , p.item_id , item_title FROM 
							{$this->tables['cms:help_articles']} as p,
							{$this->tables['cms:help_articles_lang']} as l
						WHERE
							p.item_id = l.item_id AND 
							p.item_status = 1 AND
							l.lang_id = {$this->tpl_module[lang_id]} AND 
							p.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"] = "";



							$kids = $this->db->QFetchRowArray(
							"SELECT item_url , p.item_id , item_title FROM 
								{$this->tables['cms:help_articles']} as p,
								{$this->tables['cms:help_articles_lang']} as l
							WHERE
								p.item_id = l.item_id AND 
								l.lang_id = {$_LANG_ID} AND 
								p.item_parent = {$val[item_id]} 
							ORDER BY
								item_order ASC
							"
							);

							
//					debug($val,1);
							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(
									$tpl , 
									"Sub" , 
									$kids
								);
								$chapter["class"] = "";

							} 
						}

					}
					
				}


				$content .= $tpl->blockReplace(
					"Widget",
					array(
						"links"			=> $base->html->Table(
							$tpl , 
							"" , 
							$articles
						),
						"widget_name"	=> $chapter["block_title"],
						"class"			=> $chapter["class"],
					)
				);


			}
			
		}

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

	/**
	* 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 

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

		//update
		if (is_array($help["help"]) && !STP_ENABLE_DEMO) {
			//delete chapters
			$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_blocks']}");
			$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_blocks_lang']}");
			$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_articles']}");
			$this->db->Query("TRUNCATE TABLE {$this->tables['cms:help_articles_lang']}");

			if (is_array($help["help"]["chapters"])) {
				foreach ($help["help"]["chapters"] as $key => $val) {
					$this->db->QueryInsert($this->tables["cms:help_blocks"], $val);
					$this->db->QueryInsert($this->tables["cms:help_blocks_lang"], $val);
				}				
			}
			
			if (is_array($help["help"]["articles"])) {
				foreach ($help["help"]["articles"] as $key => $val) {
					$this->db->QueryInsert($this->tables["cms:help_articles"], $val);
					$this->db->QueryInsert($this->tables["cms:help_articles_lang"], $val);
				}				
			}


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

		} else {

			//set the update to be run tomoroow
			$this->vars->SetVars(
				array(
					"set_global_help_date"	=> time() - 24 * 3600 * 29
				)
			);
		}

	}
	

}

?>