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

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}
// dependencies

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

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

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

		if ($_GET["mod"] == $this->name) {

			$this->__init();

			switch ($_GET["sub"]) {
				case "ajax.widget":
					return $this->AjaxWidget();
				break;

				case "static.download":
					return $this->StaticDownload();
				break;


				case "ajax.cms":
					return $this->AjaxWidgetCms();
				break;
			}
			
		}
		

		parent::DoEvents();
	}

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"widgets"	=> "widgets.htm",
		);

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


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetWidget($wid , $settings = false) {
		global $_LANG_ID , $base;

		$wid = (int)$wid;

		if ($wid == -1) {
			$data = $this->db->QFetchArray(
				"
					SELECT * FROM 
						{$this->tables['core:widgets']}
					WHERE 
						widget_id = -1
				"
			);

			return $data;
		}
		


		if ($base->isTablet) {
				$cond = " AND find_in_set(2,widget_device) ";
		} elseif ($base->isPhone) {
				$cond = " AND find_in_set(3,widget_device) ";
			} else {
				$cond = " AND find_in_set(1,widget_device) ";
			}


		$data = $this->db->QFetchArray(
			"
				SELECT * FROM 
					{$this->tables['core:widgets']} as w,
					{$this->tables['core:widgets_lang']} as l
				WHERE 
					w.widget_id = l.widget_id AND 
					l.lang_id = {$_LANG_ID} AND
					w.widget_id = {$wid}
					{$cond}
			"
		);


		if (is_array($data) && $data["widget_settings"]) {
			$data["settings"] = unserialize(($data["widget_settings"]));
		}


		return $data;

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Widgets($wdata , $return = "string") {
		global $base , $_LANG_ID , $_SESS;

		if (!$wdata) {
			return "";
		}

		

		$this->__init();

		//tablet
		if ($base->isTablet) {
				$cond = " AND find_in_set(2,widget_device) ";
		} elseif ($base->isMobile) {
				//phone
				$cond = " AND find_in_set(3,widget_device) ";
			} else {
				//desktop
				$cond = " AND find_in_set(1,widget_device) ";
			}

		if (is_array($_SESS["minibase"]["raw"])) {
			$condx .= " AND (mod_status=1 OR mod_status=2) ";
		} else {
			$condx .= " AND mod_status=1 ";
		}
		
		//user modules
		$widgets = $this->db->QFetchRowArray(
			"
				SELECT * 
				FROM 
					{$this->tables['core:widgets']} as w,
					{$this->tables['core:widgets_lang']} as wl
				WHERE 
					w.widget_id = wl.widget_id AND 
					w.widget_id IN ({$wdata}) AND 
					widget_status=1 AND 
					wl.lang_id = {$_LANG_ID} 
					{$cond}
			"
		);

		$this->cacheStatic($wdata);


		//filter widgets to be sure there is no access to widgets witout modules
		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {

				$mod = "";

				switch ($val["widget_module_type"]) {
					//instance
					case "1":
						if (!is_array($this->plugins["modules"]->instancemodules[$val["widget_module"]]) || $this->plugins["modules"]->instancemodules[$val["widget_module"]]["deny"]) {
							unset($widgets[$key]);
						} else {
							$mod = $this->plugins["modules"]->modules[$val["widget_module"]];
						}
					break;

					//global
					case "2":
						if (!is_array($this->plugins["modules"]->globalmodules[$val["widget_module"]]) || $this->plugins["modules"]->globalmodules[$val["widget_module"]]["deny"]) {
							unset($widgets[$key]);
						} else {
							$mod = $this->plugins["modules"]->globalmodules[$val["widget_module"]];
						}

					break;
				}
				


				//show rules
				if (is_array($widgets[$key])) {

					switch ($val["widget_perm"]) {
						case "1": //every one, so do mothing 
						break;

						//guests only
						case "2":
							if ($_SESS["client"]) {
								unset($widgets[$key]);
							}
						break;

						//certain permissions
						case "3":
							if (is_object($this->plugins["users"]) && $this->plugins["users"]->isProtected(array(
										"mod_protected"	=> "1",
										"mod_groups"	=> $val["widget_perm_groups"],
								))) {
								unset($widgets[$key]);
							}
							
						break;
							
					}
				}

				//check permissions for the module linked to this widget
				if (is_array($widgets[$key] && is_object($this->plugins["users"]) &&  $this->plugins["users"]->isProtected($mod))) {
					unset($widgets[$key]);
				}
				

				//widget its set for display
				if (is_array($widgets[$key])) {

					$mod["mod_settings"] = $mod["settings"];
					unset($mod["settings"]);

					$widgets[$key] = array_merge(
						$val , 
						$mod
					);

				}
				
			}			
		}


		if (is_Array($widgets) && count($widgets)) {

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

				$start = microtime(true);

				
				if ($val["widget_cache"] && ($val["widget_cache_update"] + $val["widget_cache"] > time()) ) {
					$content[$val["widget_id"]] = array(
						"link"		=> $val["link"],
						"content" => $val["widget_cache_data"]
					);
				} else {			
					if ($this->uwidgets_cache[$val["widget_id"]]) {
						$content[$val["widget_id"]] = $this->uwidgets_cache[$val["widget_id"]];
					} else {

					
						if ($val["widget_settings"]) {
							$val["settings"] = unserialize(($val["widget_settings"]));
						}

						if ($val["widget_set_lang"]) {
							$tmp_settings = unserialize(($val["widget_set_lang"]));

							if (is_array($tmp_settings)) {
								foreach ($tmp_settings as $k => $v) {
									$val["settings"][$k] = stripslashes($v);
								}						
							}					
						}

						if ($val["widget_bg"]) {
							$bg = $this->plugins["backgrounds"]->GetBg($val["widget_bg"]);
							
						} else {
							$bg = array();
						}


						//process extra fields
						$val["_header"] = $val["_footer"] = $val["_title"] = $val["_icon"] = "";

						if ($val["settings"]["set_icon"]) {
							$val["_icon"] = $this->_t("widgets")->blockReplace("WidgetIcon" , $val , $val["settings"]);
						} 

						if ($val["widget_name"]) {
							$val["_title"] = $this->_t("widgets")->blockReplace("WidgetTitle" , $val);
						} 

						if ($val["widget_header"]) {
							$val["_header"] = $this->_t("widgets")->blockReplace("WidgetHeader" , $val);
						} 
						
						if ($val["widget_footer"] || $val["widget_link_type"] || $val["widget_link2_type"]) {

							$foot = array(
								"content"	=> $val["widget_footer"] ? $this->_t("widgets")->blockReplace("FooterContent" , $val) : "",								
								"buttons"	=> "",
							);

							if ($val["widget_link_type"] || $val["widget_link2_type"]) {

								$btn1 = $this->plugins["modules"]->BuildLink(array(
									"type"	=> $val["widget_link_type"],
									"link"	=> $val["widget_link_link"],
									"module"=> $val["widget_link_module"],
									"global"=> $val["widget_link_global"]
								));

								$btn2 = $this->plugins["modules"]->BuildLink(array(
									"type"	=> $val["widget_link2_type"],
									"link"	=> $val["widget_link2_link"],
									"module"=> $val["widget_link2_module"],
									"global"=> $val["widget_link2_global"]
								));

								if ($btn1) {
									$btn1 = $this->_t("widgets")->blockreplace(
										"Button" , 
										array(
											"link"		=> $btn1,
											"target"	=> $val["widget_link_target"],
											"text"		=> $val["widget_link_text"],
											"size"		=> $val["widget_link_size"],
											"rel"		=> $val["widget_link_rel"],
											"style"		=> str_Replace("," , " " ,  $val["widget_link_style"]),
										)
									);
								}

								if ($btn2) {
									$btn2 = $this->_t("widgets")->blockreplace(
										"Button" , 
										array(
											"link"		=> $btn2,
											"target"	=> $val["widget_link2_target"],
											"text"		=> $val["widget_link2_text"],
											"size"		=> $val["widget_link2_size"],
											"rel"		=> $val["widget_link2_rel"],
											"style"		=> str_Replace("," , " " ,  $val["widget_link2_style"]),
										)
									);
								}

								$foot["buttons"] = $this->_t("widgets")->blockREplace(
									"FooterButtons",
									array(
										"btn1"	=> $btn1,
										"btn2"	=> $btn2,
									)
								);							
							}
							

							$val["_footer"] = $this->_t("widgets")->blockReplace("WidgetFooter" , $foot , $val);
						} 

						$val["background_class"] = $bg["class"];
						$val["background_html"] = $bg["html"];

						if ($bg["bg:scheme"]) {
							$val["bg:scheme"] = $bg["bg:scheme"];
						}
						
						
										
						$content[$val["widget_id"]] = array(
							"link"		=> $val["link"],
							"content" => CtemplateStatic::Replace(
								$this->plugins[$val["module_code"]]->Widget($val), 
								$val
							)
						);

						//$this->uwidgets_cache[$val["widget_id"]] = $content[$val["widget_id"]];
					}

					if ($val["widget_cache"]) {
						$this->db->QueryUpdate(
							$this->tables["core:widgets_lang"],
							array(
								"widget_cache_data"		=> $content[$val["widget_id"]]["content"],
								"widget_cache_update"	=> time()
							),

							"widget_id={$val[widget_id]} AND lang_id={$val[lang_id]}"
						);
					}					
				}


				$time = microtime(true) - $start;
				//debug("<span style='color: red'>W:{$val[widget_name]}:{$val[widget_id]}:" . $time ."ms: ". $query . "</span>");

			}			
		}

		if (!count($content)) {
			return "";
		}
		

		switch ($return) {
			case "string":
				return $base->html->Table(
					$this->private->templates["widgets"],
					"",
					$content
				);

			break;

			case "array":

				if (is_array($content)) {
					return $content;
				}
				
			break;

		}		

	}



	function onGlobalHooksExecute($module) {
		$this->plugins["shortcodes"]->dynamic[] = array(
			"code"	=> 'widget',
			"method"	=> array(&$this, "shortcode")
		);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ShortCode($matches) {
		//debug($matches);
		return $this->Widgets($matches["vars"]["attr"]);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxWidget() {
		return $this->Widgets($_GET["wid"] , "string");
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetAjaxLink($wid) {
		return $this->plugins["modules"]->ScriptLink(
			"ajax.widget.php",
			array(
				"wid"	=> $wid
			)
		);
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetButtons($widget , &$tpl , $block = "More") {

		$more = $this->plugins["modules"]->BuildLink(array(
			"type"	=> $widget["settings"]["lang_link_type"],
			"link"	=> $widget["settings"]["lang_link_link"],
			"module"=> $widget["settings"]["lang_link_module"],
			"global"=> $widget["settings"]["lang_link_global"]
		));

		if ($more) {
			$more = $tpl->blockReplace(
				$block,
				array(
					"link"		=> $more,
					"target"	=> $widget["settings"]["lang_link_target"],
					"text"		=> $widget["settings"]["lang_link_text"],
					"size"		=> $widget["settings"]["lang_link_size"],
					"style"		=> str_replace("," , " ", $widget["settings"]["lang_link_style"]),
					"rel"		=> $widget["settings"]["lang_link_rel"],
				)
			);
		} else {
			$more = "";
		}


		$more2 = $this->plugins["modules"]->BuildLink(array(
			"type"	=> $widget["settings"]["lang_link2_type"],
			"link"	=> $widget["settings"]["lang_link2_link"],
			"module"=> $widget["settings"]["lang_link2_module"],
			"global"=> $widget["settings"]["lang_link2_global"]
		));

		if ($more2) {
			$more2 = $tpl->blockReplace(
				$block,
				array(
					"link"		=> $more2,
					"target"	=> $widget["settings"]["lang_link2_target"],
					"text"		=> $widget["settings"]["lang_link2_text"],
					"size"		=> $widget["settings"]["lang_link2_size"],
					"style"		=> str_replace("," , " ", $widget["settings"]["lang_link2_style"]),
					"rel"		=> $widget["settings"]["lang_link2_rel"],
				)
			);

		} else {
			$more2 = "";
		}

		return array(
			"btn1"	=> $more , 
			"btn2"	=> $more2
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetStaticItems($widget) {

		$this->cacheStatic($widget["widget_id"]);
		$items = $this->static_cache[$widget["widget_id"]];
	
/*
		$items = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:widgets_static']} as r,
				{$this->tables['core:widgets_static_lang']} as l
			WHERE
				r.item_id = l.item_id AND 
				l.lang_id={$widget[lang_id]} AND
				r.widget_id={$widget[widget_id]}
			ORDER BY 
				item_order ASC			
			"
		);

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

				if ($val["item_vars"]) {
					$val = array_merge(
						$val , 
						unserialize($val["item_vars"])
					);
				}
				
				if ($val["item_vars_lang"]) {
					$val = array_merge(
						$val , 
						unserialize($val["item_vars_lang"])
					);
				}

				$items[$key] = $val;
			}			
		}
*/		
		return $items;
	}


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

		$tmp = explode(",", $wdata);

		foreach ($tmp as $key => $val) {
			if ($this->static_cache[$tmp[$key]]) {
				unset($tmp[$key]);
			} else {			
				$this->static_cache[$tmp[$key]] = array();
			}
		}
	
		if (count($tmp)) {
			$wdata = implode("," , $tmp);
		} else {
			return false;
		}

		$items = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:widgets_static']} as r,
				{$this->tables['core:widgets_static_lang']} as l
			WHERE
				r.item_id = l.item_id AND 
				l.lang_id={$_LANG_ID} AND
				r.widget_id in ({$wdata})
			ORDER BY 
				item_order ASC			
			"
		);

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

				if ($val["item_vars"]) {
					$val = array_merge(
						$val , 
						unserialize($val["item_vars"])
					);
				}
				
				if ($val["item_vars_lang"]) {
					$val = array_merge(
						$val , 
						unserialize($val["item_vars_lang"])
					);
				}

				$this->static_cache[$val["widget_id"]][] = $val;
			}			
		}

	}

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

		$widget = $this->GetWidget($_GET["widget"] , true);

		if (!is_array($widget)) {
			return $this->module->plugins["redirects"]->ErrorPage("404" , true);
		}

		$item = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:widgets_static']} as r,
				{$this->tables['core:widgets_static_lang']} as l
			WHERE
				r.item_id = l.item_id AND 
				l.lang_id={$widget[lang_id]} AND
				r.widget_id={$widget[widget_id]} AND 
				r.item_id = %d
			",
			array($_GET["item_id"])
		);

		if (!is_array($item)) {
			return $this->module->plugins["redirects"]->ErrorPage("404" , true);
		}
		
		$vars = unserialize($item["item_vars"]);

		if ($vars[$_GET["field"]] == "1") {
			$file = "upload/widgets/static/{$item[item_id]}.file";

			if (file_exists($file)) {

				$mime = new CMime();
				$mime->Set("unknown");
				$mime->Filename($vars[$_GET["field"] . "_file"]);

				CFile::ReadChunked($file);
				die();
			}			
		}
		
		return $this->module->plugins["redirects"]->ErrorPage("404" , true);
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxWidgetCms() {
		global $_SESS , $_CONF;

		if (!$_SESS["minibase"]["raw"]) {
			urlredirect($_CONF["url"]);
		}

		$this->plugins["seo"]->PageMeta(array("seo_title" => "Preview Widget" , "seo_meta" => "noindex,nofollow"));

		return $this->Widgets($_GET["wid"] , "string");		

	}
	
}

?>