<?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) {
			//read the module
			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule($this->name);			

		parent::DoEvents();

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


			switch ($sub) {

				case "landing":					
					$_GET["sub"] = $sub = "widgets";

				case "widgets":					
				
					//filter by module type
					switch ($_GET["widget_module_filter"]) {
						case "1":
							$_GET["widget_module"] = $_GET["widget_module_instance"];
							$_GET["widget_module_type"] = "1";
								
						break;

						case "2":
							$_GET["widget_module"] = $_GET["widget_module_global"];
							$_GET["widget_module_type"] = "2";

							$_POST["extra_cond"] = " AND widget_module != 106 ";
						break;

						case "3":
							$_GET["widget_module"] = "106";
							$_GET["widget_module_type"] = "2";
						break;

					}					
					
				case "widgets.mod":					
				case "widgets.module":										

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);

					$this->PrepareWidgetFields($data->forms);
					$this->PrepareFields($data->forms["forms"]);
					$this->PrepareModuleTabs($data->forms);


					$data->functions = array( 
							"ondetails"			=> array(&$this , "WidgetsDecodeValues" ),
							"onedit"			=> array(&$this , "WidgetsDecodeValues" ),
							"onstore_prepare"	=> array(&$this , "WidgetsStorePrepare"),
							"onstore"			=> array(&$this , "WidgetsStore"),
							"list_process"		=> array(&$this , "WidgetsList"),
							"ondelete"			=> array(&$this , "WidgetsDelete"),
							"after"				=> array(
								"list_process"	=> array(&$this , "WidgetStaticList"),
							)

					);					

					return $data->DoEvents();

				break;


				default:
					$file = $this->forms_path  . $sub . ".xml";

					if (file_exists($file)) {
						$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
						$this->PrepareFields($data->forms["forms"]);

						$data->functions = array( 
								"onstore_prepare"	=> array(&$this , "WidgetStaticStorePrepare"),
								"onstore"			=> array(&$this , "WidgetStaticStore" ),
								"ondownload"		=> array(&$this , "WidgetStaticDecodeValues"),
								"ondetails"			=> array(&$this , "WidgetStaticDecodeValues"),
								"onedit"			=> array(&$this , "WidgetStaticDecodeValues"),
								"list_process"		=> array(&$this , "WidgetStaticList"),
						);					

						return $data->DoEvents("" , "" , $values);
					}
				break;
					

				case "add-widget":

					if (!$_GET["action"]) {
						$_GET["action"] = "edit";
					}


					$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
					$this->LangPrepareFields($data->form);
					$this->PrepareAddForm($data->form);
					$this->PrepareDashboard($data->form);

					if ($data->Done()) {

						$this->SaveWidget();

					}					
					return $data->Show($_GET);

				break;


				case "duplicate":
					return $this->DuplicateWidget();
				break;
			}
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/

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

		if (!$_GET["module_code"]) {

			if ($_GET["mod_id"]) {
				$cond = "m.mod_id={$_GET[mod_id]} AND " ;
			}
			

			$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:languages']} as l,
					{$this->tables['core:user_modules']} as m,
					{$this->tables['core:user_modules_lang']} as ml
				WHERE
					{$cond}
					ml.lang_id = l.lang_id AND 
					l.lang_default = 1 AND 
					m.mod_id = ml.mod_id 
				");


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

					if (method_exists($this->module->plugins[$val["mod_module_code"]] , "adminGetWidgets")) {
						if ($base->acl->checkModRule($val , "widgets")) {
							$tmp_widgets = $this->module->plugins[$val["mod_module_code"]]->adminGetWidgets($val);

							if (is_array($tmp_widgets)) {
								foreach ($tmp_widgets as $k => $v) {
									$widgets[] = $v;
								}						
							}
						}
						
						
					}
					
				}			
			}

			if ($_GET["mod_id"]) {
				return $widgets;
			}

		}
		

		if ($_GET["module_code"]) {
			$cond2 = " r.module_code LIKE '{$_GET[module_code]}' AND ";
		}
		
		
		//process the core modules
		$core = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} as r,
				{$this->tables['core:modules_lang']} as l,
				{$this->tables['core:languages']} as ml
			WHERE 
				{$cond2}
				r.module_id = l.module_id AND 
				ml.lang_id = l.lang_id AND 
				ml.lang_default=1 AND 
				module_status=1 AND 
				module_type=2 
			");

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

				if (method_exists($this->module->plugins[$val["module_code"]] , "adminGetWidgets")) {
					if ($base->acl->checkModRule($val , "widgets")) {
						$tmp_widgets = $this->module->plugins[$val["module_code"]]->adminGetWidgets($val);

						if (is_array($tmp_widgets)) {
							foreach ($tmp_widgets as $k => $v) {
								$widgets[] = $v;
							}						
						}
					}
					
				}
				
			}			
		}



		return $widgets;

	}

	
	function PrepareAddForm(&$form) {

		$widgets = $this->GetWidgets();


		function wsort($a, $b)
		{
			if ($a["module_name"] == $b["module_name"]) {

				if ($a["name"] < $b["name"]) {
					return -1;
				} elseif ($a["name"] > $b["name"]) {
					return 1;
				} else {		

					return 0;
				}
			}
			return ($a["module_name"] < $b["module_name"]) ? -1 : 1;
		}

		usort($widgets, "wsort");

		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				$form["fields"]["type"]["options"][$val["type"] . "-" . $val["module"]] = $val["module_name"] . " - " . $val["name"];
			}
			
		}
		
	}


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

		$widgets = $this->GetWidgets();

		$tmp = explode("-" , $_POST["type"]);

		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				if (($val["type"] == $tmp[0]) && ($val["module"] == $tmp[1])) {
					$widget = $val;
				}				
			}
		}
		

		$id = $this->db->QueryInsert(
			$this->tables["core:widgets"],
			array(
				"widget_type"			=> $widget["type"],
				"widget_type_name"		=> $widget["name"],
				"widget_module"			=> $widget["module"] , 
				"widget_module_type"	=> $widget["module_type"] , 
				"widget_name"			=> $_POST["name"],
				"widget_status"			=> "1", //disabled				
				"widget_show_title"		=> "1", //disabled				
				"widget_device"			=> "1,2,3",

			)
		);


		if ($_GET["mod_id"]) {
			urlredirect(
				"index.php?mod=widgets&sub=widgets.mod&action=edit&widget_id={$id}&t=u&hideback=1&new=true&returnurl=" . 
				urlencode("index.php?mod=widgets&sub=landing&action=details&widget_id={$id}&t=u&returnurl=" . 
					urlencode("index.php?mod=widgets&sub=widgets.mod&module_id={$_GET[mod_id]}")
				)
			);		
		} else {	


			if ($_GET["module_code"]) {

				urlredirect(
					"index.php?mod=widgets&sub=landing&action=edit&widget_id={$id}&t=u&hideback=1&new=true&returnurl=" . 
					urlencode("index.php?mod=widgets&sub=widgets.module&action=details&widget_id={$id}&t=u&returnurl=" . 
						urlencode("index.php?mod=widgets&sub=widgets.module&module_code={$_GET[module_code]}")
					)
				);	

			}
			

			urlredirect(
				"index.php?mod=widgets&sub=landing&action=edit&widget_id={$id}&hideback=1&new=true&returnurl=" . 
				urlencode("index.php?mod=widgets&sub=landing&action=details&widget_id={$id}&returnurl=" . 
					urlencode("index.php?mod=widgets&sub=landing")
				)
			);	
		}
	}


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

		if (!$_REQUEST["widget_id"]) {
			return false;
		}
		
		$widget = $this->GetWidgetById($_REQUEST["widget_id"]);

		if (!is_array($widget)) {
			return false;
		}

		switch ($widget["widget_module_type"]) {
			case "1":
				$module = $this->plugins["modules"]->GetModuleInfo($widget["widget_module"]);
			break;

			case "2":
				$module = $this->plugins["modules"]->GetDefaultModuleInfoById($widget["widget_module"]);
			break;
		}


		//process edit
		$forms["forms"]["edit"] = $this->WidgetsForm($widget , $forms["forms"]["edit"] , $module);
		//process details;
		$forms["forms"]["details"] = $this->WidgetsForm($widget , $forms["forms"]["details"] , $module);



		$forms["forms"]["details"]["fields"]["box"]["1"]["fields"]["assigned"]["description"] = $this->WidgetAssigned($widget);

		if (!$forms["forms"]["details"]["fields"]["box"]["1"]["fields"]["assigned"]["description"]) {
			unset($forms["forms"]["details"]["fields"]["box"]["1"]["fields"]["assigned"]);
			unset($forms["forms"]["details"]["fields"]["box"]["1"]["fields"]["subtitle_stats"]);
		}
		
	
		if ($forms["forms"]["details"]["sql.after"]) {
			$forms["after"] = $forms["forms"]["details"]["sql.after"];
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetAssigned($widget , $list = false) {
		global $base;

		$layouts = $this->db->QFetchRowArray("
			SELECT 
				layout_id, layout_name 
			FROM 	
				{$this->tables['core:layouts']}
			WHERE
				layout_id in (
					SELECT
						layout_parent 
					FROM 
						{$this->tables['core:layouts']}
					WHERE
						layout_id in (

							SELECT 
								layitem_layout 
							FROM 
								{$this->tables['core:layouts_items']}
							WHERE
								layitem_widget = %d
						)
				)
			ORDER BY 
				layout_system DESC,
				layout_name ASC
			", 
			array(
				$widget["widget_id"]
			)
		);


		if (is_array($layouts)) {
			foreach ($layouts as $key => $val) {
				$data[] = array(
					"layout_id"	=> $val["layout_id"],
					"layout_name"	=> $val["layout_name"],
					"cnt"			=> ++$cnt,
				);
			}
		
			return $base->html->table(
				new CTemplateDynamic($this->tpl_path . "admin.uses.htm"),
				$list ? "List" :  "",
				$data
			);

		} else {
			return "";
		}
		
		
	}
	
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetsForm($data , $form , $module) {

		if (is_array($form)) {
			$fields = $this->WidgetFormFields($data , $module);
		}

		if (!is_array($fields)) {
			return $form;
		}
	

		if ($module["mod_id"]) {
			$link = "index.php?mod={$module[module_code]}&sub=settings.static-texts&module_id={$module[mod_id]}";
			$form["fields"]["box"]["1"]["fields"]["content_source"]["forcevalue"] = $module["mod_name"];
		} else {
			$link = "index.php?mod={$module[module_code]}&sub=settings.static-texts";
			$form["fields"]["box"]["1"]["fields"]["content_source"]["forcevalue"] = $module["module_type_name"];
		}
				

		if (file_exists(_MODPATH . $module["module_code"] . "/forms/language.xml")) {		
			$form["fields"]["box"]["1"]["fields"]["content_source"]["description"] = 
				CTemplateStatic::Replace(
					$form["fields"]["box"]["1"]["fields"]["content_source"]["description"],
					array(
						"link"	=> $link
					)
				);
		} else {
			unset($form["fields"]["box"]["1"]["fields"]["content_source"]["description"]);
		}

		if ($module["module_code"] == "widgets") {
			$form["fields"]["box"]["1"]["fields"]["content_source"]["forcevalue"] = "Static";
		}
	

		//debug($form["fields"],1);
		//append fields
		if (is_array($fields["fields"])) {
			foreach ($fields["fields"] as $key => $val) {

				if (!$_GET["new"] && $val["default"]) {
					unset($val["default"]);
				}

				//move the field to the css widget
				if (stristr($key , "_css")) {
					$form["fields"]["box"][1]["fields"] = $this->fieldInsertAtPosition(
						$form["fields"]["box"][1]["fields"],
						array($key => $val), 
						$this->fieldGetPossitionByKeyword(
							$form["fields"]["box"][1]["fields"],
							"_css"
						),				
						1
					);
				} else {								
					$form["fields"]["box"][0]["fields"][$key] = $val;						
				}
			}
		}

		//append javascript
		if (is_Array($fields["javascript"])) {
			$form["javascript"]["after"] .= $fields["javascript"]["after"];
		}		

		//remove permission fields
		if (is_array($fields["settings"])) {
			if ($fields["settings"]["permissions"] == "false") {
				$remove = array("subtitle_persmissions" , "widget_perm" , "widget_perm_groups" , "widget_perm_memberships" );
				CForm::DeleteFields($form , $remove);
			}				
		}

		//append the optional fields if exists after the rest of fields
		if (is_array($form["optional"]) && !STP_WIDGETS_NO_OPTIONAL_CONTENT) {
			foreach ($form["optional"] as $key => $val) {
				$form["fields"]["box"]["0"]["fields"][$key] = $val;
			}
		}
		
		if (is_array($fields["removefields"])) {
			CForm::DeleteFields($form , array_keys($fields["removefields"]));
		}

		if (is_Array($fields["after"])) {
			$form["sql.after"] = $fields["after"];
		}		

		return $form;	
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetFormFields($widget , $module) {
		
		if (!$widget["widget_id"]) {
			return false;
		}


		//if module exists initialize module
		if (is_array($module) && is_object($this->plugins[$module["module_code"]])) {
			$this->plugins[$module["module_code"]]->LoadWidgets();
			$this->plugins[$module["module_code"]]->InitWidget($widget["widget_type"]);

			if (is_object($this->plugins[$module["module_code"]]->widgets[$widget["widget_type"]])) {
				$path = $this->plugins[$module["module_code"]]->widgets[$widget["widget_type"]]->GetFormPath($module);
			}
			
		}

		if (file_exists($path)) {
			$fields = new CConfig($path);
					
			if (!is_array($fields->vars["widget"]) && is_Array($fields->vars["fields"])) {
				$fields->vars = array(
					"widget"	=> array(
						"fields" => $fields->vars["fields"]
					) 
				);
			}

			return $fields->vars["widget"];
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetsStorePrepare($record , $forms) {

		$fields = CForm::AllFields($forms["forms"]["edit"]);


		if (is_array($fields)) {
			foreach ($fields as $key => $val) {
				switch ($val["type"]) {
					case "image":
					case "file":
					case "upload":
						$_fields[$key] = $val;
					break;


				}								
			}

			
			if (is_array($_fields)) {

				$old = $this->GetWidgetById($record["widget_id"]);

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

					if (!$record[$key] && $old[$key]) {
						$_POST[$key] = $old[$key];
					}					
				}				
			}			
		}
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetsStore($record , $forms) {

		//get all fields
		$fields = CForm::AllFields($record["item_id"] ? $forms["forms"]["edit"] : $forms["forms"]["add"]);

		if (is_array($fields)) {

			$vars = array();
			$vars_lang = array();
	
			foreach ($record as $key => $val) {

				if (
					stristr($key , "_temp") || 
					stristr($key , "_temp_file") ||  
					stristr($key , "_radio_type") || 
					stristr($key , "_crop_oxbc"))    
				{ 
				
				} else {

					if (stristr($key , "lang_")) {
						$vars_lang[$key] = $record[$key];
					} elseif (stristr($key , "set_")) {
						$vars[$key] = $record[$key];
					}
				}

			}

			$this->db->QueryUpdate(
				$this->tables["core:widgets"],
				array(
					"widget_settings"	=> serialize($vars)
				),
				"widget_id={$record[widget_id]}"
			);

			$this->db->QueryUpdate(
				$this->tables["core:widgets_lang"],
				array(
					"widget_set_lang"=> serialize($vars_lang)
				),
				"widget_id={$record[widget_id]} AND lang_id={$record[lang_id]}"
			);

		}


		return $_POST;		
	}

	

	function adminGetWidgets($module) {
		$module["module_name"] = "Static";
		$content = parent::adminGetWidgetsList($module);

		if (is_array($content)) {		
			foreach ($content as $key => $val) {
				if ($val["type"] == "cwidgetswidgetmodule") {
					unset($content[$key]);
				}			
			}
		}

		return $content;
	}



	

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

		$id = $this->db->QueryInsert(
			$this->tables['core:widgets'],
			array(
				"widget_type"			=> strtolower($widget["type"]),
				"widget_type_name"		=> $widget["type_name"] ,
				"widget_note"			=> $widget["note"] ,
				"widget_settings"		=> (serialize($widget["settings"])),
				"widget_status"			=> "1",
				"widget_module"			=> $widget["module"],

				"widget_module_type"	=> $widget["module"] < 1000 ? "2" : "1",
				"widget_show_title"		=> isset($widget["show_title"]) ? $widget["show_title"] : 1,

				"widget_perm"			=> "1",
				"widget_device"			=> "1,2,3",
			)
		);

		//get all the languages, its up to the user to translate them
		$langs = $this->plugins["languages"]->GetLanguages();

		if (is_array($langs)) {
			foreach ($langs as $key => $lang) {
				$this->db->QueryInsert(
					$this->tables['core:widgets_lang'],
					array(
						"widget_id"				=> $id,
						"lang_id"				=> $lang["lang_id"],
						"widget_settings"		=> (serialize($widget["language"])),
						"widget_name"			=> $widget["title"],
					)
				);
			}			
		}

		//return the widget id
		return $id;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareModuleTabs(&$forms) {
		global $_TSM;

		if ($_REQUEST["widget_id"]) {
			$widget = $this->GetWidgetById($_REQUEST["widget_id"]);
			$_GET["module_id"] = $widget["widget_module"];
		}


		if (($_GET["t"] == "u") && (($_GET["sub"] == "landing") || ($_GET["sub"] == "widgets"))) {
			//get widget 
			switch ($widget["widget_module_type"]) {
				case "1":
					$_GET["sub"] = "widgets.mod";
				break;

				case "2":
					$_GET["sub"] = "widgets.module";
				break;

			}								
		}
		

		switch ($_GET["sub"]) {
			case "widgets.mod":
				$module = $this->plugins["modules"]->GetModuleInfo($widget["widget_module"] ? $widget["widget_module"] : $_GET["module_id"] , false);
				$tabs_file = $this->module->plugins[$module["mod_module_code"]]->forms_path . "dashboard.xml";

				if ($module["mod_parent"]) {
					$parent = $this->plugins["modules"]->GetModuleInfo($module["mod_parent"],false);
					$_TSM["PUB:MODULE_NAME_PARENT"] = array(
							"title"	=> $parent["mod_name"],
							"id"	=> $parent["mod_id"],
					);
				}

				$_TSM["PUB:MODULE_NAME"]= $module["mod_name"];
				$_TSM["PUB:MODULE_LINK"] = $this->plugins["modules"]->PrepareLink($module);
			break;

			case "widgets.module":
			
				if (!$_GET["module_code"] && $_GET["module_id"]) {
					$module = $this->module->plugins["modules"]->LoadDefaultModule($widget["widget_module"] ? $widget["widget_module"] : $_GET["module_id"] , "id"); 
				} else {
					$module = $this->module->plugins["modules"]->LoadDefaultModule($_GET["module_code"]);
				}

				$_GET["module_id"] = $module["module_id"];
				$_GET["module_code"] = $module["module_code"];

				$tabs_file = $this->module->plugins[$module["module_code"]]->forms_path . "dashboard.xml";

				$_TSM["PUB:MODULE_NAME"]= $module["module_name"] ? $module["module_name"]  : $module["module_type_name"] ;
				$_TSM["PUB:MODULE_LINK"] = $this->plugins["modules"]->PrepareLink($module);
			break;

		}


		if (file_exists($tabs_file)) {
			$tabs = new CConfig($tabs_file);
			$tabs = $tabs->vars["tabs"];

			if ($tabs["link"]) {
				$tabs = new CConfig($tabs["link"]);
			} else {
			//debug($tabs,1);

				$forms["forms"]["details"]["tabs"] = 
				$forms["forms"]["edit"]["tabs"] = 
				$forms["forms"]["list"]["tabs"] = $this->PrepareTabsAcl($tabs, $module);

			}
			


		}			
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareDashboard(&$form) {
		global $_TSM;

		parent::PrepareDashboard($form);

		if ($_GET["module_code"]) {

			$module = $this->module->plugins["modules"]->LoadDefaultModule($_GET["module_code"]);
			$_GET["module_id"] = $module["module_id"];
			$tabs_file = $this->module->plugins[$module["module_code"]]->forms_path . "dashboard.xml";

			$_TSM["PUB:MODULE_NAME"]= $module["module_name"] ? $module["module_name"]  : $module["module_type_name"] ;

		}

		if ($_GET["mod_id"]) {

			$_GET["module_id"] = $_GET["mod_id"];
			$module = $this->plugins["modules"]->GetModuleInfo($_GET["mod_id"] , false);
			$tabs_file = $this->module->plugins[$module["mod_module_code"]]->forms_path . "dashboard.xml";
			$_TSM["PUB:MODULE_NAME"]= $module["mod_name"];

			if ($module["mod_parent"]) {
				$parent = $this->plugins["modules"]->GetModuleInfo($module["mod_parent"],false);
				$_TSM["PUB:MODULE_NAME_PARENT"] = array(
						"title"	=> $parent["mod_name"],
						"id"	=> $parent["mod_id"],
				);
			}


		}
		

		if (file_exists($tabs_file)) {
			$tabs = new CConfig($tabs_file);
			$tabs = $tabs->vars["tabs"];

			$form["tabs"] = $tabs;
		}
		
	}


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

		$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("widgets");			


		$widgets = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:widgets']} as r,
				{$this->tables['core:widgets_lang']} as l

			WHERE
				r.widget_id = l.widget_id AND 
				l.lang_id = {$_LANG_ID} AND
				r.widget_id != -1 
			ORDER BY widget_type_name
			"
		);

		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				$widgets[$key]["cnt"] = ++$cnt;

				$tmp = explode("," , $val["widget_device"]);
				$data = null;


				if (in_array("1" , $tmp))
					$data[] = '<span class="f16 sign sign-desktop"></span>';

				if (in_array("2" , $tmp))
					$data[] = '<span class="f16 sign sign-tablet"></span>';

				if (in_array("3" , $tmp))
					$data[] = '<span class="f16 sign sign-mobile"></span>';

				
				if (is_Array($data)) {
					$widgets[$key]["devices"] = implode(", " , $data);
				} else {
					$widgets[$key]["devices"] = "";
				}

			}
			
		}
		

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

		return array(
			"title"				=> $this->tpl_module["module_name"] , 
			"html"				=> $base->html->Table(
				$tpl, 
				"" , 
				$widgets			
			)
		);
	}


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

		if (!$_REQUEST["lang_id"]) {
			$lang = $this->module->plugins["languages"]->DefaultLang();
			$_REQUEST["lang_id"] = $lang["lang_id"];

		}		


		if ($_REQUEST["widget_id"]) {			
			$widget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_id={$_REQUEST[widget_id]}");
			$lwidget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets_lang']} WHERE widget_id={$_REQUEST[widget_id]} AND lang_id={$_REQUEST[lang_id]}");

			//$module = $this-

			switch ($widget["widget_module_type"]) {
				case "1":
					$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:user_modules']} WHERE mod_id={$widget[widget_module]}");
				break;

				case "2":
					$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_id={$widget[widget_module]}");
				break;
			}

			
			//just changed
			$values = /*RemoveArraySlashes*/(unserialize(($widget["widget_settings"])));
			$lvalues = /*RemoveArraySlashes*/(unserialize(($lwidget["widget_set_lang"])));

			if (is_array($lvalues)) {
				foreach ($lvalues as $key => $val) {
					$values[$key] = $val;
				}				
			}	

			$values = array_merge(
				$values , 
				$widget , 
				(array)$lwidget
			);
		
			return array(
				"edit"	=> $values,
				"details"	=> $values
			);

		}

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetsList($items , $count) {

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

				switch ($val["widget_module_type"]) {
					//instance
					case "1":
						$mod = $this->plugins["modules"]->GetModuleInfo($val["widget_module"]);
						$items[$key]["widget_module"] = $mod["mod_name"];
					break;

					//global
					case "2":
						if ($val["widget_module"] == "106") {
							$items[$key]["widget_module"] = "Static";
						} else {						
							$mod = $this->plugins["modules"]->GetDefaultModuleInfoById($val["widget_module"]);
							$items[$key]["widget_module"] = $mod["module_name"];
						}
					break;
				}


				$items[$key]["assigned"] = $this->WidgetAssigned($val , true);
			}			
		}

		return array(
			"items"	=> $items,
			"count"	=> $count
		);

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetsDelete($record) {
		$this->db->QueryDelete("DELETE FROM {$this->tables['core:widgets_static']} WHERE widget_id=%d" , array($record["widget_id"]));
		$this->db->QueryDelete("DELETE FROM {$this->tables['core:widgets_static_lang']} WHERE widget_id=%d" , array($record["widget_id"]));
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetsDecodeValues($data, $forms = array()) {

		$vars = unserialize(($data["widget_settings"]));
		$vars_lang = unserialize(($data["widget_set_lang"]));

		$data = array_merge(
			(array)$vars, 
			(array)$vars_lang,
			$data
		);


		return $data;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetStaticStorePrepare($record , $forms) {

		if (!$record["item_id"]) {
			return $record;
		}
				
		$fields = CForm::AllFields($forms["forms"]["edit"]);


		if (is_array($fields)) {
			foreach ($fields as $key => $val) {
				switch ($val["type"]) {
					case "image":
					case "file":
					case "upload":
						$_fields[$key] = $val;
						
					break;

					case "columns":
					case "widths":
						$_fields[$key] = $val;

						if (defined("STP_LAYOUT_GRID") && (STP_LAYOUT_GRID == "BS3")) {
							$_fields[$key . "_desktop"] = $val;
							$_fields[$key . "_tablet"] = $val;
							$_fields[$key . "_phone"] = $val;
						} else {
							$_fields[$key . "_lg"] = $val;
							$_fields[$key . "_md"] = $val;
							$_fields[$key . "_sm"] = $val;
							$_fields[$key . "_xs"] = $val;
						}
					break;


				}								
			}


			if (is_array($_fields)) {

				$old = $this->GetStaticItem($record["item_id"]);

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

					switch ($val["type"]) {
						case "image":
						case "upload":
							if (!$record[$key] && $old[$key] && !($record[$key . "_radio_type"] == "-1")) {
								$_POST[$key] = $old[$key];
							}					

							if ($_POST[$key . "_temp"]) {
								$_POST[$key . "_file"] = $_POST[$key . "_temp"];
							} else {
								$_POST[$key . "_file"] = $old[$key . "_file"];
							}

							if ($_POST[$key . "_alt"]) {
								$_POST[$key . "_alt"] = $_POST[$key . "_alt"];
							} else {
								$_POST[$key . "_alt"] = $old[$key . "_alt"];
							}
							
						break;
					}
					
				}				
			}			
		}

		//debug($_POST,1);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetStaticStore($record , $forms) {

		//get all fields
		$fields = CForm::AllFields($record["item_id"] ? $forms["forms"]["edit"] : $forms["forms"]["add"]);

		if (is_array($fields)) {

			$vars = array();
			$vars_lang = array();

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

				if (!(stristr($key , "_temp") || 
					stristr($key , "_temp_file") ||  
					stristr($key , "_radio_type") || 
					stristr($key , "_crop_oxbc") ||
					($key == "item_order") ||
					($key == "item_id") )) {

					if (!in_array($key , array("widget_id" , "item_id" , "lang_id"))) {
						if ($val["lang"] == "true") {
							$vars_lang[$key] = $record[$key];
						} else {
							$vars[$key] = $record[$key];
						}
					}

					switch ($val["type"]) {
						case "image":
						case "upload":
							$vars[$key . "_file"] = $record[$key . "_file"];
							$vars[$key . "_alt"] = $record[$key . "_alt"];
						break;
					}
					
				}
			}

			$this->db->QueryUpdate(
				$this->tables["core:widgets_static"],
				array(
					"item_vars"	=> serialize($vars)
				),
				"item_id={$record[item_id]}"
			);

			$this->db->QueryUpdate(
				$this->tables["core:widgets_static_lang"],
				array(
					"item_vars_lang"=> serialize($vars_lang)
				),
				"item_id={$record[item_id]} AND lang_id={$record[lang_id]}"
			);
			
		}

		return $_POST;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetStaticDecodeValues($data, $forms = array()) {

	
		$vars = unserialize($data["item_vars"]);
		$vars_lang = unserialize($data["item_vars_lang"]);

//		debug($vars);
//		debug($vars_lang,1);

		foreach ($vars as $key => $val) {
			if ($key == "item_order") {
				unset($vars[$key]);
			}			
		}

		foreach ($vars_lang as $key => $val) {
			if ($key == "item_order") {
				unset($vars_lang[$key]);
			}			
		}


		$data = array_merge(
			(array)$vars, 
			(array)$vars_lang,
			$data
		);



		return $data;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function WidgetStaticList($items , $count) {

		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$items[$key] = $this->WidgetStaticDecodeValues( $val );
			}			
		}

		return array(
			"items"	=> $items,
			"count"	=> $count
		);

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetWidgetById($wid) {
		global $_LANG_ID;
	
		$widget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_id={$wid}");

		if (!is_array($widget)) {
			return null;
		}
		
		$widget_data = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets_lang']} WHERE widget_id={$wid} AND lang_id={$_LANG_ID}");

		if (is_array($widget_data)) {
			$widget = array_merge(
				$widget , 
				$widget_data
			);
		}

		if ($widget["widget_settings"]) {
			$tmp = unserialize($widget["widget_settings"]);

			if (is_array($tmp) && count($tmp)) {
				$widget = array_merge(
					$widget , 
					$tmp
				);
			}			
		}
		

		if ($widget["widget_set_lang"]) {
			$tmp = unserialize($widget["widget_set_lang"]);

			if (is_array($tmp) && count($tmp)) {
				$widget = array_merge(
					$widget , 
					$tmp
				);
			}			
		}

		return $widget;		
	}

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

		$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={$_LANG_ID} AND
				r.item_id={$id}
			"
		);

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

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

		$widget = $this->GetWidgetById($_GET["widget_id"]);

		if (!is_array($widget)) {
			return "Invalid Link!";
		}
		
		$widget_lang = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:widgets_lang']}		WHERE widget_id={$widget[widget_id]}");
		$static		 = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:widgets_static']} 		WHERE widget_id={$widget[widget_id]} ");

		unset($widget["widget_id"]);
		$widget["widget_note"] .= " (Copy)";
		
		$oid = $_GET["widget_id"];
		$nid = $this->db->QueryInsert(
			$this->tables["core:widgets"],
			$widget
		);

		//insert language data for widgets
		if (is_array($widget_lang)) {
			foreach ($widget_lang as $key => $val) {
				$val["widget_id"] = $nid;
				$this->db->QueryInsert(
					$this->tables["core:widgets_lang"],
					$val
				);
			}			
		}

		//process static items if exists
		if (is_array($static)) {
			foreach ($static as $key => $val) {

				$static_lang = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:widgets_static_lang']} WHERE item_id={$val[item_id]}");

				$sid = $val["item_id"];
				unset($val["item_id"]);
				$val["widget_id"] = $nid;

				$nsid = $this->db->QueryInsert(
					$this->tables['core:widgets_static'],
					$val
				);

				//update the order
				$this->db->QueryUpdate(
					$this->tables["core:widgets_static"],
					array(
						"item_order"	=> $nsid
					),
					"item_id={$nsid}"
				);

				//process the language data
				if (is_array($static_lang)) {
					foreach ($static_lang as $k => $v) {						
						$v["item_id"] = $nsid;
						$v["widget_id"] = $nid;

						$this->db->QueryInsert(
							$this->tables["core:widgets_static_lang"],
							$v
						);
					}			
				}

				//copy images if are any
				if (file_exists("../upload/widgets/static/{$sid}.mp4")) {
					CFile::copy(
						"../upload/widgets/static/{$sid}.mp4",
						"../upload/widgets/static/{$nsid}.mp4"
					);
				}

				if (file_exists("../upload/widgets/static/{$sid}.jpg")) {
					CFile::copy(
						"../upload/widgets/static/{$sid}.jpg",
						"../upload/widgets/static/{$nsid}.jpg"
					);
				}

				if (file_exists("../upload/widgets/static/tn_{$sid}.jpg")) {
					CFile::copy(
						"../upload/widgets/static/tn_{$sid}.jpg",
						"../upload/widgets/static/tn_{$nsid}.jpg"
					);
				}


				if (file_exists("../upload/widgets/static/{$sid}.png")) {
					CFile::copy(
						"../upload/widgets/static/{$sid}.png",
						"../upload/widgets/static/{$nsid}.png"
					);
				}

				if (file_exists("../upload/widgets/static/tn_{$sid}.png")) {
					CFile::copy(
						"../upload/widgets/static/tn_{$sid}.png",
						"../upload/widgets/static/tn_{$nsid}.png"
					);
				}
			}			
		}


		//copy files if exists
		if (file_exists("../upload/widgets/{$oid}.mp4")) {
			CFile::copy(
				"../upload/widgets/{$oid}.mp4",
				"../upload/widgets/{$nid}.mp4"
			);
		}

		if (file_exists("../upload/widgets/{$oid}.jpg")) {
			CFile::copy(
				"../upload/widgets/{$oid}.jpg",
				"../upload/widgets/{$nid}.jpg"
			);
		}

		if (file_exists("../upload/widgets/tn_{$oid}.jpg")) {
			CFile::copy(
				"../upload/widgets/tn_{$oid}.jpg",
				"../upload/widgets/tn_{$nid}.jpg"
			);
		}


		if (file_exists("../upload/widgets/{$oid}.png")) {
			CFile::copy(
				"../upload/widgets/{$oid}.png",
				"../upload/widgets/{$nid}.png"
			);
		}

		if (file_exists("../upload/widgets/tn_{$oid}.png")) {
			CFile::copy(
				"../upload/widgets/tn_{$oid}.png",
				"../upload/widgets/tn_{$nid}.png"
			);
		}


		if ($_GET["osub"]) {
			//redirect to details page
			urlredirect(
				"index.php?mod=widgets&sub={$_GET[osub]}&t=u&module_id={$_GET[module_id]}&module_code={$_GET[module_code]}&widget_id={$nid}&action=edit&returnurl=" . 
				urlencode("index.php?mod=widgets&sub={$_GET[osub]}&t=u&module_id={$_GET[module_id]}&module_code={$_GET[module_code]}&widget_id={$nid}&action=details&returnurl=" . 
					urlencode($_GET["returnurl"])
				)
			);
		} else {

			//redirect to details page
			urlredirect(
				"index.php?mod=widgets&sub=widgets&widget_id={$nid}&action=edit&returnurl=" . 
				urlencode("index.php?mod=widgets&sub=widgets&widget_id={$nid}&action=details&returnurl=" . 
					urlencode($_GET["returnurl"])
				)
			);
		}	
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function fieldGetPossitionByKeyword($array , $skey) {
		$found = null;

		if (is_array($array)) {
			foreach ($array as $key => $val) {
				if (stristr($key , $skey)) {
					$found = $key;
				}				
			}							
		}

		return $found;
		
	}
	

	#https://stackoverflow.com/questions/3353745/how-to-insert-element-into-arrays-at-specific-position
	function fieldInsertAtPosition(array $input_array, array $insert, $target_key, $location = 1) {
	  $output = array();
	  $new_value = reset($insert);
	  $new_key = key($insert);
	  foreach ($input_array as $key => $value) {
		if ($key === $target_key) {
		  // Insert before.
		  if ($location == -1) {
			$output[$new_key] = $new_value;
			$output[$key] = $value;
		  }
		  // Replace.
		  if ($location == 0) {
			$output[$new_key] = $new_value;
		  }
		  // After.
		  if ($location == 1) {
			$output[$key] = $value;
			$output[$new_key] = $new_value;
		  }
		}
		else {
		  // Pick next key if there is an number collision.
		  if (is_numeric($key)) {
			while (isset($output[$key])) {
			  $key++;
			}
		  }
		  $output[$key] = $value;
		}
	  }
	  // Add to array if not found.
	  if (!isset($output[$new_key])) {
		// Before everything.
		if ($location == -1) {
		  $output = $insert + $output;
		}
		// After everything.
		if ($location == 1) {
		  $output[$new_key] = $new_value;
		}

	  }
	  return $output;
	}
	
}

?>