<?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 CStatusQuo extends CPlugin{
	
	var $tplvars; 
	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $license = "";

	function __construct() {
		//$this->CPlugin($db, $tables , $templates);

		$this->name == "statusquo";
	}

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

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

			if (constant("STP_ENABLE_DEMO") == 1) {
				urlredirect("index.php?mod=dashboard&sub=landing");
			}
			
			

			$this->tpl_module= array(
				"module_name"	=> "Product Registration",
				"module_code"	=> $this->name
			);

		parent::DoEvents();		

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


			switch ($sub) {
	
				case "modules":
				case "updates":
					$this->tpl_module["module_name"] = "Update Manager";

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

					$this->PrepareFields($data->forms["forms"]);
					return $data->DoEvents();
				break;

				case "install":
					$this->tpl_module["module_name"] = "Update Manager";

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

						if (!is_writable("../")) {
							$tpl = new CTemplateDynamic($this->tpl_path . "install.htm");
							return $tpl->blockReplace("Error");
						}
						

						$ret = $this->StoreNewAddon();


						if ($ret != true) {

							$data->_errors = array(
								"error" => "The file you are trying to upload is not valid for this product!",
								"errors"	=> array("file"	=> 1 ),	
							);

							return $data->Show($this->vars->data);
						}
						
					}
					
					return $data->Show($this->vars->data);
				break;

				case "module.delete":
					return $this->DeleteModule();
				break;


				case "licensing":

					if ($this->license) {
						urlredirect("index.php?mod=statusquo&sub=modules");
					}

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

					$GLOBALS["siteInfo"]["name"] = $this->vars->data["set_template_name"];				
					$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
					$this->PrepareDashboard($data->form);
					return $data->Show($this->vars->data);
				break;

				case "licensing/change":
					return $this->ApiLicenseVerify();
				break;


				case "check-updates":
					return $this->CheckUpdates();
				break;

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

				case "firstrun":
					return $this->CMSFirstRun();
				break;
			}
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Error($message) {

		return "<div class='alert alert-danger'><div class='icon-danger'></div>" . $message .  "</div>";
	}

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

		if (!$_POST["set_global_license"]) {
			return "error:Please enter the license code!";
		}
		

		//debug($_POST);

		$response = CDevSaverApi::newInstance($this->vars->data["set_engine_code"] , $_POST["set_global_license"])
				->addAliases(is_object($this->plugins["redirects"]) ? $this->plugins["redirects"]->GetAllDomains() : array())
				->verifyLicense();
		
		//debug($response,1);
		if ($response["status"] == "ok") {
			$type = $_GET["status"];

			$this->vars->SetVars(
				array(
					"set_global_license_valid"	=> "1",
					"set_global_license"		=>	$response["license"],
					"set_engine_code"			=>	$response["product"],
				)
			);

			//update the license

			return "License Validated !";

		}
	
		return "error:" . $response["error"];

	}

	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CheckUpdates() {
		global $_SESS;

		//might take some time so better set execution to unlimited
		set_time_limit(0);


		if (((constant("STP_ENABLE_DEMO") == 1) && ($_ADMIN ==true)) || ($_SESS["minibase"]["raw"]["acl"] == "viewonly")){
			urlredirect("index.php?mod=statusquo&sub=firstrun&returnurl=" . urlencode($_GET["returnurl"]));
		}		


		$this->vars->set("set_installer_done" , 1 , true);


		//search all folders for meta.xml
		
		$modules = CDIR::GetFolders(_MODPATH);

		//make sure a few modules are first

		if (is_array($modules)) {
			ksort($modules);
		}

		$first = array(
			"mail"			=> "mail",
			"modules"		=> "modules",
			"layouts"		=> "layouts",
			"widgets"		=> "widgets",
			"redirects"		=> "redirects",
			"shortcodes"	=> "shortcodes",
			"core"			=> "core",
		);

		foreach ($modules as $key => $val) {
			if (!$first[$val]) {
				$first[$key] = $val;
			}			
		}

		$modules = $first;

		if (is_array($modules)) {
			
			foreach ($modules as $key => $val) {
				$meta = _MODPATH . $val . "/updates/meta.xml";

				if (file_exists($meta)) {
					$modules[$key] = $meta;
				} else {
					unset($modules[$key]);
				}				
			}
			
		}


		
		//check if there are any update files for existing modules
		if (is_array($modules) && count($modules)) {

			//get all this modules
			foreach ($modules as $key => $val) {
				$module_data = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_code LIKE '{$key}'");

				

				//check only for updates
				if (is_array($module_data)) {
					$meta = new CConfig($val);

					//run the updater for error modules
					if (($meta->vars["module"]["version"] == $module_data["module_version"]) ) {
						unset($modules[$key]);
					} 
				}
								
			}
		}

		$_SESS["minibase"]["update-modules"] = $modules;


		//check for modules that should be removed
		$all_modules = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules']}");

		if (is_array($all_modules)) {
		
			if (is_array($_SESS["minibase"]["remove-modules"])) {
				unset($_SESS["minibase"]["remove-modules"]);
			}
			
			foreach ($all_modules as $key => $val) {
				if (!is_dir(_MODPATH . $val["module_code"])) {
					$_SESS["minibase"]["remove-modules"][$val["module_code"]] = $val["module_code"];
				}				
			}			
		}
		
		if ((is_array($_SESS["minibase"]["update-modules"]) && count($_SESS["minibase"]["update-modules"])) || (is_array($_SESS["minibase"]["remove-modules"]) && count($_SESS["minibase"]["remove-modules"]))) {
			return $this->RunUpdates();
		}

		//if at this point then go back to 


		urlredirect("index.php?mod=statusquo&sub=firstrun&returnurl=" . urlencode($_GET["returnurl"]));

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RunUpdates() {
		global $base , $_TSM , $_SESS;

		$_TSM["PUB:MODULE_NAME"] = "Automated Installer";

		$template = new CTemplateDynamic($this->tpl_path . "updates.htm");


		$_SESS["cnt"] = 1;

		return $base->htmlElements->Widget(
			array(
				"title"		=> "Running...",
				"icon"		=> "cogs",
				"skin"		=> "Red",

				"content"	=> $template->blockReplace(
					"Main" , 
					array(
						"date" => date("d/m/Y H:i:s"),
						
					)
				),
			)
		);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UpdateStatus() {
		global $_SESS;

		//get current module

		//first run all updates
		if (count($_SESS["minibase"]["update-modules"])) {

			reset($_SESS["minibase"]["update-modules"]);

			$module_key = key($_SESS["minibase"]["update-modules"]);
			$module = $_SESS["minibase"]["update-modules"][$module_key];

			//if the past version / module generated an error then jumo to the next one
			//error mail was sent to administrator
			if ($_GET["skip"] == true) {
				//remove current module from session
				unset($_SESS["minibase"]["update-modules"][$module_key]);
				unset($module);
				unset($module_key);

				//jump to the next module
				if (count($_SESS["minibase"]["update-modules"])) {
					reset($_SESS["minibase"]["update-modules"]);
					$module_key = key($_SESS["minibase"]["update-modules"]);
					$module = $_SESS["minibase"]["update-modules"][$module_key];
				}		
			}

			//run updates / version for this module
			if ($module && file_exists($module)) {
				//open module xml file and check for the next version to be updated
	
				$meta = new CConfig($module);
				$versions = $meta->vars["module"]["history"];

				//get current module
				$old_data = $this->GetModule($meta->vars["module"]["id"]);



				if (!is_array($old_data)) {
					//install new module & remove it from session
					//unset($_SESS["minibase"]["update-modules"][$module_key]);
					//if i dont unset then next timeit will try to upgrade the module.
					return $this->InstallVersion($meta->vars["module"]);
				} else {	
					//sort all versions by id

					if (is_Array($versions) && count($versions)) {
						ksort($versions);

						//filter versions and remove the old ones
						if (is_array($versions)) {
							foreach ($versions as $key => $val) {
								if ($key <= $old_data["module_version"]) {
									unset($versions[$key]);
								}					
							}				
						}



						//if i have any versions left then install them one by one 
						if (is_array($versions) && count($versions)) {
							reset($versions);
							$version = $versions[key($versions)];
							return $this->UpdateVersion($version , $old_data);

						} else {

							//no more operaions left so remove the current module and jump to next one 
							unset($_SESS["minibase"]["update-modules"][$module_key]);
							return $this->UpdateStatus();							
						}


					}

					//no more operaions left so remove the current module and jump to next one 
					unset($_SESS["minibase"]["update-modules"][$module_key]);
		
					//jump to next module
					return $this->UpdateStatus();
				}

				return $return;
			} else {
				//there is no meta info for this module so remove it, nothing to do.
				unset($_SESS["minibase"]["update-modules"][$module_key]);
				return $this->UpdateStatus();
			}

		} 

		
		//run delete modules
		if (count($_SESS["minibase"]["remove-modules"])) {
			$module_key = key($_SESS["minibase"]["remove-modules"]);
			$module = $_SESS["minibase"]["remove-modules"][$module_key];


			unset($_SESS["minibase"]["remove-modules"][$module_key]);
			return $this->UninstallModule($module_key);
		}
		

		//nothing else to do so i'm done
		if (!count($_SESS["minibase"]["update-modules"])  && !count($_SESS["minibase"]["remove-modules"])) {
			return "[done]";
		}


			
				
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UpdateVersion($version , $module) {
		//note for full compatibility i should check for all instances based on this module and update the settings and languages for ALL of them 

		//update start install
		$this->db->QueryUpdate(
			$this->tables['core:modules'],
			array(
				"module_installed"	=> "1",
			),
			"module_id={$module[module_id]}"
		);

		//check if i should update the name of the module
		if ($version["module"]["name"]) {
			$this->db->QueryUpdate(
				$this->tables['core:modules'],
				array(
					"module_type_name"		=> $version["module"]["name"],
					"module_name"			=> $version["module"]["name"],
				),
				"module_id={$module[module_id]}"
			);
		}

		//update all settings
		if (is_array($version["data"]["settings"])) {
			foreach ($version["data"]["settings"] as $key => $val) {

				//check if setting exists 
				if (is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[module_code]}' AND `type`=2 AND `type_var`=1 "))) {
				} else {				
					//inset the new value
					$this->db->QueryInsert(
						$this->tables["core:modules_settings"],
						array(
							"module"	=> $module["module_code"],
							"type"		=> "2",
							"type_var"	=> "1",
							"setting"	=> $key, 
							"value"		=> $val,
						)
					);
				}
			}			
		}

		//update all language settings
		if (is_array($version["data"]["language"])) {
			foreach ($version["data"]["language"] as $key => $val) {

				if (is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[module_code]}' AND `type`=2 AND `type_var`=2 "))) {
				} else {
					$this->db->QueryInsert(
						$this->tables["core:modules_settings"],
						array(
							"module"	=> $module["module_code"],
							"type"		=> "2",
							"type_var"	=> "2",
							"setting"	=> $key, 
							"value"		=> $val,
							"lang_id"	=> $_GET["lang_id"],
						)
					);
				}
			}			
		}


		if (is_array($version["files"])) {

			if (!is_array($version["files"]["file"])) {
				$version["files"]["file"] = array($version["files"]["file"]);
			}

			foreach ($version["files"]["file"] as $key => $val) {
				$path = pathinfo($val);

				if ($path["basename"] == 'emails.xml') {
					$this->RunEmails(_MODPATH . $module["module_code"] . "/updates/" . $val);
				} else {		
					switch ($path["extension"]) {

						//mysql updates
						case "sql":
							$queries = $this->db->SplitStrQueries(
								CFile::GetContents(_MODPATH . $module["module_code"] . "/updates/" . $val)							
							);

							if (is_Array($queries)) {
								foreach ($queries as $k => $v) {
									$this->db->Query($v);
								}				
							}			
						break;

						case "php":
							$this->RunExternal(_MODPATH . $module["module_code"] . "/updates/" . $val);
						break;
					}					
				}
			}			
		}
		

		$this->db->QueryUpdate(
			$this->tables["core:modules"],
			array(
				"module_version"		=> $version["name"],
				"module_last_update"	=> time(),
				"module_installed"		=> "2",
			),
			"module_id={$module[module_id]}"
		);		

		return date("[d/m/Y H:i:s] ") . "Upgraded module '{$module[module_code]}' to version {$version[name]}";
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function InstallVersion($module) {
		//note for full compatibility i should check for all instances based on this module and update the settings and languages for ALL of them 
		$mod = array(
			"module_id"				=> $module["id"],
			"lang_id"				=> $_GET["lang_id"],
			"module_code"			=> $module["code"], 
			"module_type_name"		=> $module["name"],
			"module_name"			=> $module["name"],
			"module_allow_url"		=> $module["url"] ? "1" : "0",
			"module_url"			=> $module["url"],
			"module_type"			=> $module["type"] == "system"  ? "2" : "1",
			"module_system"			=> $module["system"],
			"module_no_perm"		=> $module["noperms"],
			"module_status"			=> "1",	//enabled
			"module_version"		=> $module["install"]["version"],
			"module_last_update"	=> time(),			
			"module_protected"		=> $module["protected"] ? "1" : "0", 			
			"module_antispam"		=> $module["antispam"], 			
			"module_installed"		=> "1",
			"module_addon"			=> $module["addon"],

		);

		//install the module in the database
		$mod["module_id"] = $this->db->QueryInsert(
			$this->tables["core:modules"],
			$mod
		);

		//install the module in language table
		$this->db->QueryInsert(
			$this->tables["core:modules_lang"],
			$mod
		);


		//install default settings for this module
		if (is_array($module["install"]["data"]["settings"])) {
			foreach ($module["install"]["data"]["settings"] as $key => $val) {
				$this->db->QueryInsert(
					$this->tables["core:modules_settings"],
					array(
						"module"	=> $module["code"],
						"type"		=> "2",
						"type_var"	=> "1",
						"setting"	=> $key, 
						"value"		=> $val,
					)
				);
			}			
		}

		//install default language settings
		if (is_array($module["install"]["data"]["language"])) {
			foreach ($module["install"]["data"]["language"] as $key => $val) {
				$this->db->QueryInsert(
					$this->tables["core:modules_settings"],
					array(
						"module"	=> $module["code"],
						"type"		=> "2",
						"type_var"	=> "2",
						"setting"	=> $key, 
						"value"		=> $val,
						"lang_id"	=> $_GET["lang_id"],
					)
				);
			}			
		}	
		if (is_array($module["install"]["files"])) {

			if (!is_array($module["install"]["files"]["file"])) {
				$module["install"]["files"]["file"] = array($module["install"]["files"]["file"]);
			}

			foreach ($module["install"]["files"]["file"] as $key => $val) {
				$path = pathinfo($val);

				if ($path["basename"] == 'emails.xml') {
					$this->RunEmails(_MODPATH . $module["code"] . "/updates/" . $val);
				} else {		

					switch ($path["extension"]) {

						//mysql updates
						case "sql":
							$queries = $this->db->SplitStrQueries(
								CFile::GetContents(_MODPATH . $module["code"] . "/updates/" . $val)
							);

							if (is_Array($queries)) {
								foreach ($queries as $k => $v) {
									$this->db->Query($v);
								}				
							}			
						break;

						case "php":
							$this->RunExternal(_MODPATH . $module["code"] . "/updates/" . $val);
						break;
					}	
				}
			}			
		}
		
		$this->db->QueryUpdate(
			$this->tables["core:modules"],
			array(
				"module_version"		=> $module["install"]["version"],
				"module_last_update"	=> time(),
				"module_installed"		=> "2",
				"module_install_error"	=> $error,
			),
			"module_id={$mod[module_id]}"
		);		

		return date("[d/m/Y H:i:s] ") . "Installed module '{$module[code]}' version {$module[install][version]}";
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UninstallModule($module) {


		//read module by code
		$module_data = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_code LIKE '{$module}'");

		if (is_array($module_data) && !is_dir(_MODPATH . $module_data["module_code"]) ) {

			//remove module language
			$this->db->Query("DELETE FROM {$this->tables['core:modules_lang']} WHERE module_id={$module_data[module_id]}");
			$this->db->Query("DELETE FROM {$this->tables['core:modules']} WHERE module_id={$module_data[module_id]}");

			//delete all settings assigned to this module
			$this->db->Query("DELETE FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$module}'");

			//search all tables that has that preffix
			$tables = $this->db->QFetchRowArray("SHOW TABLES LIKE 'site_plugin_{$module}_%'");

			//drop all tables related to this module
			if (is_array($tables)) {
				foreach ($tables as $key => $val) {
					//$this->db->Query("DROP TABLE `" . $val[key($val)] . "`");
				}				
			}
			
			//check if this is an instance module
			switch ($module_data["module_type"]) {
				//instance module
				case "1":

					$user_modules = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:user_modules']} WHERE mod_module_code LIKE '{$module}'");

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

							//delete instance module and language
							$this->db->Query("DELETE FROM {$this->tables['core:user_modules']} WHERE mod_id={$val[mod_id]}");
							$this->db->Query("DELETE FROM {$this->tables['core:user_modules_lang']} WHERE mod_id={$val[mod_id]}");

							//delete settings
							$this->db->Query("DELETE FROM {$this->tables['core:modules_settings']} WHERE module={$val[mod_id]}");

							//delete Language Variables & pages
							$this->db->Query("DELETE FROM {$this->tables['core:texts']} WHERE module_id = {$val[mod_id]}");
							$this->db->Query("DELETE FROM {$this->tables['core:texts_lang']} WHERE module_id = {$val[mod_id]}");

							//read all widgets
							$widgets = $this->db->QFetchRowArray("SELECT widget_id FROM {$this->tables['core:widgets']} WHERE widget_module={$val[mod_id]}");
							if (is_array($widgets)) {
								foreach ($widgets as $k => $v) {
									$this->db->Query("DELETE FROM {$this->tables['core:widgets']} WHERE widget_id={$v[widget_id]}");
									$this->db->Query("DELETE FROM {$this->tables['core:widgets_lang']} WHERE widget_id={$v[widget_id]}");
								}						
							}
						}						
					}					
				break;

				//system module
				case "2":

					//delete all static pages & texts
					$this->db->Query("DELETE FROM {$this->tables['core:texts']} WHERE module_id = {$module_data[module_id]}");
					$this->db->Query("DELETE FROM {$this->tables['core:texts_lang']} WHERE module_id = {$module_data[module_id]}");

					//read all widgets
					$widgets = $this->db->QFetchRowArray("SELECT widget_id FROM {$this->tables['core:widgets']} WHERE widget_module={$module_data[module_id]} AND widget_module_type=2");
					if (is_array($widgets)) {
						foreach ($widgets as $key => $val) {
							$this->db->Query("DELETE FROM {$this->tables['core:widgets']} WHERE widget_id={$val[widget_id]}");
							$this->db->Query("DELETE FROM {$this->tables['core:widgets_lang']} WHERE widget_id={$val[widget_id]}");
						}						
					}
					
				break;
			}
						

		}
		

		return date("[d/m/Y H:i:s] ") . "Removed missing module '{$module}'";
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetModule($id) {

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

		return $module;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RunExternal($file) {
		global $base, $site , $_SESS , $_TSM;

		if (file_exists($file)) {
			include_once($file);
		}

	}

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

		$email = new CConfig($file);

		if (!is_array($email->vars["emails"]["email"])) {
			return false;
		}

		$mails = $email->vars["emails"]["email"];

		if (isset($mails["code"])) {
			$mails = array($mails);
		}


		foreach ($mails as $key => $val) {
			$this->plugins["mail"]->AddMail(
				$val["code"],

				array(
					"status"		=> $val["status"],
					"subject"		=> $val["subject"],
					"from"			=> $val["from"],
					"from_name"		=> $val["from_name"],
					"to"			=> $val["to"],
					"to_name"		=> $val["to_name"],
					"reply"			=> $val["reply"],
					"reply_name"	=> $val["reply_name"],

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

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function initializeEngine() {
		global $_SESS;

		if ($_SESS["minibase"]["license"]["timeout"]) {
			return true;
		}
		
		if ($this->vars->data["set_global_license"]) {

//			$this->vars->data["set_global_license_valid"] = 0;

			$host = $_SERVER["HTTP_HOST"];


			$path = dirname(dirname($_SERVER["REQUEST_URI"]));
	
			if (
				($this->vars->data["set_global_license_valid"] != 1) ||
				($this->vars->data["set_global_license_path"] != $path)				
				){
			
				$response = CDevSaverApi::newInstance($this->vars->data["set_engine_code"] , $this->vars->data["set_global_license"])
					->addAliases(is_object($this->plugins["redirects"]) ? $this->plugins["redirects"]->GetAllDomains() : array())
					->verifyLicense();					

				switch ($response["status"]) {
					case "timedout":
						$_SESS["minibase"]["license"]["timeout"] = true;
					break;

					case "ok":
						$this->vars->SetVars(array(
							"set_global_license_valid"	=> "1",
							"set_global_license_path"	=> $path,
							"set_global_license"		=> $response["license"],
							"set_engine_code"			=> $response["product"],
						));
					break;

					//clean the license and show the box
					case "error":
						$_GET["sub"] = "licensing";

						$this->vars->SetVars(array(
							"set_global_license"		=> "",
							"set_global_license_path"	=> "",
							"set_global_license_valid"	=> "0",
						));

						return false;
					break;
				}				
			}			
			
		} else{
			if ($_GET["mod"] != "statusquo") {
				$_GET["mod"] = "statusquo";
				$_GET["sub"] = "licensing";
			}		
		}
		
		
	}
	

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CMSFirstRun() {
		global $_MODULES , $_SESS , $_ADMIN;

		if (((constant("STP_ENABLE_DEMO") == 1) && ($_ADMIN ==true)) || ($_SESS["minibase"]["raw"]["acl"] == "viewonly")){
			urlredirect("index.php?mod=dashboard&sub=landing");
		}


		$modules = $this->db->QFetchRowArray("
			SELECT * FROM 
				{$this->private->tables['core:modules']}, 
				{$this->private->tables['core:user_modules']}
			WHERE 
				module_code = mod_module_code AND
				module_installed=2 AND 
				module_status=1 AND
				mod_status=1 
			ORDER BY 
				mod_order ASC");

		$core = $this->db->QFetchRowArray("SELECT * FROM {$this->private->tables['core:modules']} WHERE module_installed=2 AND module_type=2 AND module_status=1 ORDER BY module_type_name");


		if (is_array($core)) {
			foreach ($core as $key => $val) {
				if (method_exists($_MODULES[$val["module_code"]] , "onCMSFirstRun")) {
					$this->plugins[$val["module_code"]]->onCMSFirstRun($val);
				}				
			}			
		}
		
		if (is_array($modules)) {
			foreach ($modules as $key => $val) {
				if (method_exists($_MODULES[$val["module_code"]] , "onCMSFirstRun")) {
					$this->plugins[$val["module_code"]]->onCMSFirstRun($val);
				}				
			}			
		}

		if ($_GET["returnurl"]) {
			urlredirect($_GET["returnurl"]);
		} else {		
			urlredirect("index.php?mod=dashboard&sub=landing");
		}

	}

	

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

		if ($_FILES["file"]) {	
	
			CFile::Remove("../upload/tmp/update.zip");
			//decrypt the file
			$res = CFile::Decrypt(
				$this->vars->data["set_global_license"] . "-" . $this->vars->data["set_engine_code"], 
				$_FILES["file"]["tmp_name"],
				"../upload/tmp/update.zip"
			);

			if (!$res) {
				return false;
			}

			$zip = new ZipArchive;
			if (($zip->open("../upload/tmp/update.zip") === TRUE) && $zip->numFiles) {

			} else {
				return false;
			}

			$meta = new CConfig($zip->getFromName("meta.xml") , "string");
			$meta = $meta->vars["update"];

			//remove the meta name
			$zip->deleteName ("meta.xml");


			for ($i = 0 ; $i < $zip->numFiles ; $i++ ) {
				$files[] = $zip->getNameIndex($i);				
			}
			
			$this->db->QueryInsert(
				$this->tables["core:updates"],
				array(
					"update_date"			=> strtotime($meta["date"]),
					"update_name"			=> $meta["title"],
					"update_note"			=> $meta["description"],
					"update_date_install"	=> time(),
					"update_license"		=> "",
					"update_files"			=> implode("\n" , $files),
					"update_version"		=> $meta["version"]["pack"],
				)
			);



			$zip->extractTo("../");
			$zip->close();

			//redirect to status quo
			urlredirect("index.php?mod=statusquo&sub=check-updates&returnurl=" . urlencode("index.php?mod=statusquo&sub=modules"));
		}

		urlredirect("index.php?mod=statusquo&sub=check-updates&returnurl=" . urlencode("index.php?mod=statusquo&sub=modules"));		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DeleteModule() {
		$module = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['core:modules']} " . 
			"WHERE module_id='{$_GET[module_id]}'"
		);

		if (is_array($module) && $module["module_addon"]) {

			//delete the module
			CDir::Delete("modules/" . $module["module_code"]);

			urlredirect("index.php?mod=statusquo&sub=check-updates&returnurl=" . urlencode("index.php?mod=statusquo&sub=modules"));		
		} else {
			urlredirect("index.php?mod=statusquo&sub=modules");		
		}
		
	}
	


}



class CDevSaverApi {

	var $version = "v1.2";
	var $actions = array(
		"verifyLicense"	=> "license/verify",

		"downloadHelp"	=> "help/download",

		"updateCheck"		=> "",
		"updateDownload"	=> "",
	);
		
	static function newInstance($product , $license) {
		return new self($product , $license);
	}
	

	function __construct($product , $license ) {

		$this->product = $product;
		$this->license = $license;
		$this->server = "https://licensing.devsaver.com/api/{$this->version}/" . $this->product.  "/";
		$this->domain = $this->detectDomain();
	}

	function downloadHelp($date = "") {
		$this->action = $this->actions["downloadHelp"];
		if ($data) {
			$this->action.= "?date=" . $date;
		}
		
		return $this->call(array());
	}
	
	function verifyLicense() {

		$this->action = $this->actions["verifyLicense"];

		return $this->call(
			array(
				"license"		=> $this->license,
			),
			1000	//keep it to1 seccond to avoid stressing the user.
		);


		
	}
	
	private function detectDomain() {

		$domain = $_SERVER["HTTP_HOST"];
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function addAliases($domains = array()) {
		$this->domains = $domains;

		return $this;
	}
	



	private function call($request , $timeout = 0) {

		$connection = curl_init();
		curl_setopt($connection , CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($connection , CURLOPT_URL, $this->server . $this->action); 
		curl_setopt($connection , CURLOPT_POSTFIELDS , $this->prepareRequest($request)); 
		curl_setopt($connection , CURLOPT_CONNECTTIMEOUT_MS , $timeout);
		curl_setopt($connection , CURLOPT_TIMEOUT_MS , $timeout);
		curl_setopt($connection , CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($connection , CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($connection , CURLOPT_SSL_VERIFYPEER, false);

		
		$answer =  curl_exec($connection);

		switch (curl_errno($connection)) {
			case 5:		//CURLE_COULDNT_RESOLVE_PROXY:
			case 6:		//CURLE_COULDNT_RESOLVE_HOST:
			case 7:		//CURLE_COULDNT_CONNECT:
			case 28:	//CURLE_OPERATION_TIMEDOUT:
				$response = array(
					"status"	=> "timedout",
				);
			break;
			
			case 0:		//ok
				$response = json_decode($answer , 1);
			break;
		}
		
		return $this->prepareResponse($response , $request);
	}
	
	function prepareResponse($response , $request = array()) {

		if (!is_array($response)) {
				
			return array(
				"status"	=> "error",
				"error"		=> "Unknown error! If this happens more than once, please contact our support!",
			);
		} else {


			$response["call"] = $this->prepareRequest($request , "array");

			if ($response["code"] == "0001") {
				global $site;
				$site->vars->SetVars(
					array(
						"set_global_license_valid"	=> "0",
					)
				);
			}
			

			return $response;
		}		
	}

	function prepareRequest($request , $type = "json") {
		global $site;

		$request["client"] = $this->apiClient();
		$request["product"] = $site->vars->data["set_engine_code"];

		if (is_array($this->domains)) {
			$request["domains"] = $this->domains;
		}
		

		return $type == "json" ? json_encode($request) : $request;
	}	

	function apiClient() {
		global $_SESS;

		return array(
			"domain"	=> stristr("www." , $_SERVER["HTTP_HOST"]) ? str_replace("www." , "" , $_SERVER["HTTP_HOST"]) : $_SERVER["HTTP_HOST"],
			"domain_ip"	=> $_SERVER["SERVER_ADDR"],					
			"path"		=> dirname(dirname($_SERVER["REQUEST_URI"])),
		);
	}
	
	
}

?>