<?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 CRedirects extends CRedirectsBackend{	
	
	var $tplvars; 

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

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


		parent::DoEvents();

		$this->CheckSSL();


		if ($_GET["mod"] == "redirects") {



			$this->__init();
			$this->plugins["globalhooks"]->SetModule($this->tpl_module);

			switch ($_GET["sub"]) {				
				case "detect":
					return $this->Detect();
				break;

				case "robots":
					return $this->Robots();
				break;

				case "errorpage":
					return $this->ErrorPage($_GET["code"] , true) ;
				break;
			}
		}

	}

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"page"	=> "page.htm"

		);

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

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

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Detect() {
		$domain = $this->GetDomain($_SERVER["HTTP_HOST"]);

		if (is_array($domain)) {
			//update clicks
			$this->db->QueryUpdate(
				$this->tables["plugin:redirects_domains"],
				array(
					"domain_clicks"	=> $domain["domain_clicks"] + 1,			
				),
				"domain_id={$domain['domain_id']}"
			);

		}
		


		//compare the domain against the main one 
		$redir = true;
		if (!$domain["domain_main"]) {
			$main = $this->GetMainDomain();

			if (!is_array($main)) {
				$redir = false;
			} else {
				$redir = true;
			}			
		} else {
			//this is the main domain
			$redir = false;
		}
		
		$link = explode("?" , $_SERVER["REQUEST_URI"]);
		$url = $link[0] != "" ? $link[0] : "/";
		$url = urldecode($url);
		
		
		//priority has the rule set for the current domain
		$rule = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:redirects']} 
			WHERE 
				redirect_source LIKE '%s' AND 
				(redirect_domain = 0 OR redirect_domain = %d)
			ORDER BY 
				redirect_domain DESC
			LIMIT 1
			",
			array(
				$url,
				$domain["domain_id"]
			)
		);

		if (is_array($rule)) {
			//update the clicks for this rule
			$this->db->QueryUpdate(
				$this->tables["plugin:redirects"],
				array(
					"redirect_clicks"	=> $rule["redirect_clicks"] + 1
				),
				"redirect_id={$rule[redirect_id]}"
			);

			//record stat, i guess no need as long it doesnt appear in admin yet
			//$this->RecordStat($rule["redirect_id"]);
			//redirect to the main domain, to the same protocol
 
			//if there are redirects then use them, else do nothing
			switch ($rule["redirect_code"]) {
				case "301":
				case "302":

					
					switch ($rule["redirect_destination_type"]) {

						//simple link
						default: 
							$new_url  = ($_SERVER["HTTPS"] ? "https://" : "http://") . 
								(is_array($main) ? $main["domain_name"] : $domain["domain_name"]) .
								$rule["redirect_destination"];
						break;

						//instance module
						case "2":
							$this->plugins["modules"]->__preinit();
							$mod = $this->plugins["modules"]->GetModuleByID($rule["redirect_destination_module"]);

							if (is_array($mod)) {
								$new_url = $mod["link"];
							}
						break;

						//global module
						case "3":
							$mod = $this->plugins["modules"]->LoadDefaultModule($rule["redirect_destination_global"] , false , "id");

							if (is_array($mod)) {
								$new_url = $mod["link"];
							}				
						break;
					}
										
																	
					header ( "Location: {$new_url} ", true, $rule["redirect_code"] );
					exit();
				break;
			}

		} 
		
		
		//full domain redirect, this applies for rules without redirect codes also 
		if ($redir ) {

			$new_url  = ($_SERVER["HTTPS"] ? "https://" : "http://") . 
						$main["domain_name"] . 
						$_SERVER["REQUEST_URI"];
					
			header ( "Location: {$new_url} ", true, 301 );
			exit();
		}
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ErrorPage($code , $full = false , $record = true) {
		global $_PAGE , $_LANG_ID  , $_CONF ,$_LANG;


		if (!$_PAGE) {
			$_PAGE = $this->path . "pages/";
		}


		$_GET["module_id"] = "redirects";
		$_GET["mod"] = "redirects";
		$_GET["sub"] = "errorpage";
		
		$this->__init();
		$this->plugins["globalhooks"]->SetModule($this->tpl_module);

		if ($record = true) {

			$url = $_SERVER["REQUEST_URI"];

			//if its the main site dont record it 
			if (($url == "/") || ($url == "") || ($url == "/" . $_LANG . "/")) {
			} else {


				$rule = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:redirects']} WHERE redirect_source LIKE '%s'" , array($url));

				if (is_Array($rule)) {
					//update the usese
					$this->db->QueryUpdate(
						$this->tables["plugin:redirects"],
						array(
							"redirect_clicks"	=> $rule["redirect_clicks"] + 1
						),
						"redirect_id = {$rule[redirect_id]}"
					);

				} else {
					//save a new rule as 404 in the databas

					$id = $this->db->QueryInsert(
						$this->tables["plugin:redirects"],
						array(
							"redirect_source"	=> $url , 
							"redirect_code"		=> 404,
							"redirect_date"		=> time(),	//first record
							"redirect_type"		=> "2"	,	//automatic
							"redirect_clicks"	=> "1",
						)
					);
				}
			}

			//$this->RecordStat($id);

		}		
		
		if (!$_LANG_ID) {
			$site->modules["languages"]->DefaultLang();
		}
		

		$page = $this->db->QFetchArray("
			SELECT * FROM 
				{$this->tables['plugin:redirects_pages']} as p, 
				{$this->tables['plugin:redirects_pages_lang']} as l 
			WHERE 
				item_code='{$code}' AND 
				p.item_id = l.item_id AND 
				l.lang_id={$_LANG_ID}
		");


		if (!is_array($page)) {
			$code = "404";
			$page = $this->db->QFetchArray("
				SELECT * FROM 
					{$this->tables['plugin:redirects_pages']} as p, 
					{$this->tables['plugin:redirects_pages_lang']} as l 
				WHERE 
					item_code='404' AND 
					p.item_id = l.item_id AND 
					l.lang_id={$_LANG_ID}
			");
		}


		$this->module->plugins["breadcrumb"]->Add(
			array(
				"show"		=> $page["item_status"],
				"title"		=> $page["item_title"],
				"subtitle"	=> $page["item_subtitle"]
			),
			array(
				$_CONF["url"]	=> $page["item_title"]
			)
		);


		$this->module->plugins["seo"]->PageMeta($page);

		if ($code = "404") {
			header("HTTP/1.1 404 Not Found");
		}


	
		if ($full) {

			return $this->module->plugins["layouts"]->Render(

				$this->tpl_module["settings"]["set_layout"],

				$this->private->templates["page"]->blockReplace(
					"Main" ,
					$page
				),
				$this->tpl_module["settings"]["set_widgets"]
			);

		} else {		

			return $this->private->templates["page"]->blockREplace(
				"Main" , 
				$page
			);

		}
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Robots() {
		global $_CONF;

		if (isset($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
			$content = $this->vars->data["set_robots_https"] ;
		} else {		
			$content = $this->vars->data["set_robots_http"] ;
		}

		$instance_mods = explode("," , $this->vars->data["set_sitemap_modules"]);
		$global_mods = explode("," , $this->vars->data["set_sitemap_modules_global"]);

		if (is_array($instance_mods)) {
			foreach ($instance_mods as $key => $val) {
				if (trim($val)) {
					$index[] =	$val;
				}				
			}			
		}

		if (is_array($global_mods)) {
			foreach ($global_mods as $key => $val) {
				if (trim($val)) {
					$index[] =	$val;
				}				
			}			
		}

	
		switch ($this->vars->data["set_sitemap_default"]) {
			//all modules
			default:
				$modules = null;
			break;

			//specific modules, its the OPPOSITE from the sitemaps
			case "2":
				foreach ($this->plugins["modules"]->modules as $key => $val) {
					if (!in_array($key , $index) || $val["mod_protected"] || $val["module_protected"]) {
						$modules[$key] = $val;
					}						
				}										
			break;

			//all except modules, its the OPPOSITE from the sitemaps
			case "3":
				foreach ($this->plugins["modules"]->modules as $key => $val) {
					if (in_array($key , $index) || $val["mod_protected"] || $val["module_protected"]) {
						$modules[$key] = $val;
					}						
				}										
			break;
		}

		if (is_Array($modules)) {

			$content .= "\nUser-agent: *";

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

				if ($this->vars->data["set_multilanguage"]) {
					if ($val["mod_id"] ) {

						if ($val["mod_module_code"] != "category") {						
							$langs = $this->db->QFetchRowArray("
								SELECT * FROM 
									{$this->tables['core:user_modules_lang']} as m,
									{$this->tables['core:languages']} as l
								WHERE
									lang_status = 1 AND 
									m.lang_id = l.lang_id AND 
									m.mod_id = %d
								", 
								array($val["mod_id"])
							);

							if (is_array($langs)) {
								foreach ($langs as $key => $val) {
									$deny[] = "Disallow: /{$val[lang_code]}/{$val[mod_url]}/";
								}						
							}
						}

					} elseif ($val["module_allow_url"]) {
						$langs = $this->db->QFetchRowArray("
							SELECT * FROM 
								{$this->tables['core:modules_lang']} as m,
								{$this->tables['core:languages']} as l
							WHERE
								lang_status = 1 AND 
								m.lang_id = l.lang_id AND 
								m.module_id = %d
							", 
							array($val["module_id"])
						);

						if (is_array($langs)) {
							foreach ($langs as $key => $val) {
								$deny[] = "Disallow: /{$val[lang_code]}/{$val[module_url]}/";
							}						
						}
					}

				} else {
					if ($val["mod_id"]) {
						if ($val["mod_module_code"] != "category") {						
							$deny[] = "Disallow: /{$val[mod_url]}/";
						}
					} elseif ($val["module_allow_url"]) {
						$deny[] = "Disallow: /{$val[module_url]}/";
					}
				}
				
			}
			

		}
		

		

		$mime = new CMime();
		$mime->Set("text");

		echo $content . "\n" . (is_array($deny) ? implode("\n" , $deny) : "") . "\nSITEMAP: " . $_CONF["url"] . "sitemap.xml";

		die();
	}
	
}

