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

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CTools extends CPlugin{
	
	var $tplvars; 

	function __construct() {
		//$this->CPlugin($db, $tables , $templates);
		$this->name = "tools";
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;

		if ($_GET["mod"] == $this->name) {
			$this->tpl_module = array(
				"module_code"	=> $this->name,
				"module_name"	=> "Tools",
			);
			parent::DoEvents();

			$sub = $_GET["sub"];
			$action = $_GET["action"];

			//read the module
			switch ($sub) {

				case "browsefonts":
					return $this->BrowseFonts();
				break;

				case "browsecss":
					return $this->BrowseCss();
				break;

				case "filemanager":

					return $this->FileManager();
				break;
			}
		}
	}


	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DetectIconFiles() {
		$path = CDir::GetFiles("../assets/css" , ".css" , "font.icon.");

		if (count($path)) {
			foreach ($path as $key => $val) {
				$tmp = new CTemplateDynamic($val);

				if ($tmp->blockExists("META")) {				
					$meta = json_decode($tmp->blockReplace("META") , true);
					$meta["file"] = $val;
					$meta["key"] = ++$cnt;
					$fonts[] = $meta;
				}
			}			
		}
		
		return $fonts;
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function BrowseFonts() {
		global $base;

		$path  = "../assets/css/";
		$tpl = new CTemplateDynamic($this->tpl_path . "fonts.htm");

		$fonts = $this->DetectIconFiles();

		$cur = explode(" " , $_GET["sel"]);

		foreach ($fonts as $k => $font) {

			if (file_exists($font["file"])) {
				$file = file($font["file"]);

				foreach ($file as $key => $val) {
					
					if (stristr($val , $font["prefix"]) && stristr($val , ":before {")) {
					

						$icon = trim(str_replace(array("." , ":before {") ,array("" , "") ,  $val));

						$fonts[$k]["icons"][] = array(
								"icon" => $icon,
								"icon_class" => $font["class"],
								"class"	=> ($icon == $cur[1]) && $cur[0] == $font["class"] ? "selected" : "",
						);
					}
				}

			} else {
				unset($fonts[$k]);
			}
		
		}

		foreach ($fonts as $key => $val) {
			$fonts[$key]["items"] = CTemplateStatic::REplace(
				$base->html->table(
					$tpl , 
					"", 
					$val["icons"]
				),
				$val,
				$val["shortcode"]
			);
		}
		
		
		if (is_dir("../assets/svgicons/")) {
			$font = array(
				"title"		=> "SVG Icons",
				"prefix"	=> "svgicon-",
				"class"		=> "svgicon",
				"shortcode"	=> array(
					"code"	=> "svgicon",
					"body"	=> "",
					"sample"	=> "[svgicon=icon-something]"
				),

				"items"	=> ""
			);

			//get all the svg items
			$files = CDir::GetFiles("../assets/svgicons/" , "svg");
			sort($files);

			if (is_array($files)) {
				foreach ($files as $key => $val) {
					$files[$key] = array(
						"src"	=> $val,
						"icon"	=> pathinfo($val)["filename"],
					);
				}				
			}
			
			$font["items"] = CTemplateStatic::REplace(
				$base->html->table(
					$tpl , 
					"Svg", 
					$files
				),
				$font,
				$font["shortcode"]
			);


			$fonts[] = $font;
		}
		


		$content = $tpl->blockReplace(
			"Main" , 
			array(
					
				"fonts"	=> $base->html->Table(
					$tpl , 
					"Font" , 
					$fonts
				),

				"fontslink"	=> $base->html->Table(
					$tpl , 
					"FontLink" , 
					$fonts
				),

				"button"	=> $_GET["field"] ? $tpl->blockReplace("Script" , $_GET) : "",

				"control"	=> $tpl->blockReplace($_GET["field"] ? "ControlText" : "ControlShortcode"),

			)
		);

		die($content);
	}
	

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

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

		echo $tpl->blockreplace(
			"Main",
			array()
		);
		die();
	}

	


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

		$path  = "../assets/css/";
		$tpl = new CTemplateDynamic($this->tpl_path . "css.htm");
		$font = array();

		$css = array(
			1	=> array(
				"key"	=> "1",
				"file"	=> $path . "plugin.animate.css",
				"title"	=> "Animations",
				"function"	=> "__getAnimateCssClasses",
			),
		);


		foreach ($css as $k => $file) {

			if (file_exists($file["file"])) {
				
				$classes = call_user_func_array(array(&$this , $file["function"]) , array($file["file"]));

				$cnt = 1;

				foreach ($classes as $key => $val) {
					$css[$k]["classes"][] = array(
							"class" => $val,							
							"shortcode" => htmlentities("[animated=\"" . str_replace("animated " , "" , $val) . "\"]text[/animated]"),							
							"cnt"	=> $cnt ++,
					);
				}


			} else {
				unset($fonts[$k]);
			}	
		}


		$titles = $css;


		foreach ($css as $key => $val) {
			$css[$key]["items"] = CTemplateStatic::REplace(
				$base->html->table(
					$tpl , 
					"", 
					$val["classes"]
				),
				$val
			);
		}
		
		$cnt = 0;
		if (file_exists("../assets/css/user-classes.xml")) {

			//append helper classes
			$titles[] = array(
				"key"		=> "helper",
				"title"		=> "Helper Classes",

			);

			$helpers = new CConfig("../assets/css/user-classes.xml");
			$helpers = $helpers->vars["classes"]["class"];

			foreach ($helpers as $key => $val) {
				$helpers[$key]["cnt"] = ++$cnt;
			}		
			
			$extra = $base->html->table(
				$tpl , 
				"Helper",
				$helpers
			);
		}
		
		
		
		$content = $tpl->blockReplace(
			"Main" , 
			array(
					
				"fonts"	=> $base->html->Table(
					$tpl , 
					"Font" , 
					$css
				) . $extra,

				"fontslink"	=> $base->html->Table(
					$tpl , 
					"FontLink" , 
					$titles
				),

			)
		);

		die($content);

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __getAnimateCssClasses($file) {

		$classes = $this->__getCssClasses($file);

		foreach ($classes as $key => $val) {

			if ($val == "animated") {
				unset($classes[$key]);
			} else {			
				$classes[$key] = "animated "  . $val;
			}
		}
		
		return $classes;
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __getCssClasses($file) {

		$contents = CFile::Get($file);


		//Strip out everything between { and }
		$pattern_one = '/(?<=\{)(.*?)(?=\})/s';


		//Match any and all selectors (and pseudos)
		$pattern_two = '/[\.|#][\w]([:\w]+?)+/';
		//$pattern_two = '/[\.|#][a-zA-Z-]+/';

		//Run the first regex pattern on the input
		$stripped = preg_replace($pattern_one, '', $contents);

		//Variable to hold results
		$selectors = array();

		//Run the second regex pattern on $stripped input
		$matches = preg_match_all($pattern_two, $stripped, $selectors);

		//Show the results
		$classes= array_unique($selectors[0]);

		foreach ($classes as $key => $val) {
			$classes[$key] = substr($val , 1);
		}

		return $classes;
		



		preg_match_all("/\.(\w+)\s*\{(\w*)\}/", $contents , $match); 

		return $match;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareSkinFields(&$forms) {

		if (isModSubAct("skineditor" , "fonts" , "add")) {

			//debug($this->CSSReadFiles("../assets/css/"),1);

			$forms["add"]["fields"]["box"][2]["fields"]["skin_css"]["default"] = $this->CSSReadFiles("../assets/css/");
		}
		
	}
	


	function CSSBuilsClasses($res) {
		foreach ($res as $key => $val) {

			$data[] .= implode(",\n" , $val) . " {\n\t" . str_replace(";" , "; \n\t" , $key) .  "\n}\n" ;
		}
		
		return implode("\n" , $data);
	}
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CSSProcess($css , &$results) {

		$css = preg_replace('!/\*.*?\*/!s', '', $css);
		$css = preg_replace('/\n\s*\n/', "\n", $css);
		
		$lines = explode("\n" , $css);


		foreach ($lines as $key => $val) {

			if (stristr($val , "font-family")) {


				//read to the top until you find the start of the class
				$tmpk = $key;

				while ( !stristr($lines[$tmpk] , "{")) {
					$tmpk --;
				}

				//go down till in find the font weight;
				$tmpk2 = $tmpk;
				$weight = "";

				while ( !stristr($lines[$tmpk2] , "}") ) {

					if (stristr($lines[$tmpk2], "font-weight")) {
						$weight = trim($lines[$tmpk2]);
					}
					
					$lines[$tmpk];
					$tmpk2 ++;
				}




				//go back till i find } or first key
				
				while ( !stristr($lines[$tmpk] , "}") && ($tmpk >= 0)) {

					$results[trim($val) . $weight][] = $lines[$tmpk];
					$tmpk --;
				}
			}			
		}		

		//debug($results);
	}

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

		$this->updateButtonsCss();
		$this->updateIconShortcodes();
		$this->updateAnimateCSS();
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function updateButtonsCss() {
		$file = "../assets/css/global.button-styles.css";

		if (file_exists($file)) {
			$file = file($file);

			foreach ($file as $key => $val) {
				$val = trim($val);

				if ($val) {
					$tmp = explode(" "  , $val);
					$tmp[0] = str_replace("." , "" , $tmp[0]);

					if (!is_array($old = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:skins_classes']} WHERE class_name LIKE '$tmp[0]' AND class_type=1"))) {
						$id = $this->db->QueryInsert(
							$this->tables['core:skins_classes'],
							array(
								"class_name"	=> $tmp[0],
								"class_type"	=> "1",
							)
						);

						$bids[] = $id;
					} else {
						$bids[] = $old["class_id"];
					}					
				}				
			}
			
			if (count($bids)) {
				$this->db->Query("DELETE FROM {$this->tables['core:skins_classes']} WHERE class_type=1 AND class_id NOT IN (" . implode(',' , $bids) . ")");
			}		
		}
		
	}
	

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

		if (!is_object($this->plugins["shortcodes"])) {
			return false;
		}
		
		$fonts = $this->DetectIconFiles();

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

				$old = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:shortcodes']} WHERE shortcode_code LIKE '{$val[shortcode][code]}'");

				if (!is_array($old)) {

					$new = array(
							"shortcode_status"	=> "1",
							"shortcode_code"	=> $val["shortcode"]["code"],
							"shortcode_sample"	=> $val["shortcode"]["sample"],
							"shortcode_replace"	=> $val["shortcode"]["body"],
							"shortcode_device"	=> "1,2,3",
							"shortcode_note"	=> $val["title"],
							"shortcode_type"	=> 3,
						);

					$this->db->QUeryInsert(
						$this->tables["plugin:shortcodes"],
						$new
						
					);
				}
			}			
		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function updateAnimateCSS() {
		$classes = $this->__getAnimateCssClasses("../assets/css/plugin.animate.css");

		foreach ($classes as $key => $val) {
			$val = trim(str_replace("animated" , "" , $val));

			if (!$this->db->QFetchArray("select * from {$this->tables['core:skins_animations']} WHERE animate_class LIKE '%s'" , array($val))) {
				$this->db->QueryInsert(
					$this->tables['core:skins_animations'],
					array(
						"animate_class"	=> $val, 
						"animate_name"	=> $val,
					)
				);
			}			
		}
	}

	
}

?>