<?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 CMail extends CMailBackend{
	
	var $tplvars; 

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

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

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

			//read the module
			//$this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]);

			$this->tpl_module = array(
				"module_code"	=> $this->name,
				"module_name"	=> "Emails & Mailing Servers",
				
			);

			parent::DoEvents();
			$sub = $_GET["sub"];
			$action = $_GET["action"];


			switch ($sub) {

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

				case "failed-flush":
					$this->FlushErrors();
				break;

				case "sent-flush":
					$this->FlushSent();
				break;

				case "landing":
					$sub = "emails";
				case "emails":
				case "queue":
				case "failed":
				case "sent":
				case "servers":
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"]);
					$this->PrepareVariables($data->forms , $sub);

					if ($sub == "servers") {
						$data->functions = array( 
								"onstore" => array(&$this , "StoreServer"),
//									"ondelete" => array(&$this , "DeleteServer"),
						);					
					}
					

					return $data->DoEvents();
				break;

				case "test-email":
					$this->SendTestEmail();
				break;

				case "replace":
						$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);

						$this->PrepareDashboard($data->form);

						if ($data->Done()) {

							$this->processREplace();
						}

						return $data->Show();
				break;


				case "template.vars":
					return $this->mailTemplateGetVars();
				break;

			}
		}
	}

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

		$emails = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:mail_emails_lang']}");

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

				$val["email_from"] = str_replace($_POST["find"] , $_POST["replace"] , $val["email_from"]);
				$val["email_to"] = str_replace($_POST["find"] , $_POST["replace"] , $val["email_to"]);

				$this->db->QueryUpdate(
					$this->tables["plugin:mail_emails_lang"],
					$val , 
					"email_id={$val[email_id]} AND lang_id={$val[lang_id]}"
				);
			}			
		}

		urlredirect("index.php?mod=mail&sub=emails");		
	}
	

	
	function PrepareVariables(&$forms , $sub) {

		//read all the forms

		global $_MODULES;

		switch ($sub) {
			case "emails":


				$instance = $this->plugins["modules"]->GetInstanceModules();
				$core = $this->plugins["modules"]->GetCoreModules();

				if (is_array($instance)) {
					foreach ($instance as $key => $val) {
						if (method_exists($this->module->plugins[$val["mod_module_code"]] , "mailTemplateVars")) {
							$tmp = $this->module->plugins[$val["mod_module_code"]]->mailTemplateVars($val);

							if (is_array($tmp)) {
								foreach ($tmp as $k => $v) {
									$modules["ajax.php?mod=mail&sub=template.vars&type=1&module={$val[mod_id]}&tpl={$k}"] = $val["mod_name"] . " - " . $v;
								}								
							}							
						}						
					}					
				}

				if (is_array($core)) {
					foreach ($core as $key => $val) {
						if (method_exists($this->module->plugins[$val["module_code"]] , "mailTemplateVars")) {
							$tmp = $this->module->plugins[$val["module_code"]]->mailTemplateVars($val);

							if (is_array($tmp)) {
								foreach ($tmp as $k => $v) {
									$modules["ajax.php?mod=mail&sub=template.vars&type=2&module={$val[module_code]}&tpl={$k}"] = $val["module_name"] . " - " . $v;
								}								
							}
						}						
					}					
				}

				$forms["forms"]["add"]["fields"]["box"]["0"]["fields"]["template"]["options"] = $modules;
				$forms["forms"]["edit"]["fields"]["box"]["0"]["fields"]["template"]["options"] = $modules;

			break;

			case "servers":
				if (!External::Load("swiftmailer")) {
					unset($forms["forms"]["edit"]["fields"]["box"][0]["fields"]["set_switft_transport"]["options"]["smtp"]);
					unset($forms["forms"]["edit"]["fields"]["box"][0]["fields"]["set_switft_transport"]["options"]["sendmail"]);
					unset($forms["forms"]["edit"]["fields"]["box"][0]["fields"]["set_switft_transport"]["options"]["php"]);
				} 

				if (!External::Load("phpmailer")) {
					unset($forms["forms"]["edit"]["fields"]["box"][0]["fields"]["set_switft_transport"]["options"]["php-smtp"]);
					unset($forms["forms"]["edit"]["fields"]["box"][0]["fields"]["set_switft_transport"]["options"]["php-local"]);
				} 

			break;
		}
				
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function FlushErrors() {
		$this->db->Query("TRUNCATE TABLE {$this->tables['plugin:mail_failed']}");
		urlredirect($_GET["returnURL"]);
	}

	
	function FlushSent() {
		$this->db->Query("TRUNCATE TABLE {$this->tables['plugin:mail_log']}");
		urlredirect($_GET["returnURL"]);
	}


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

		$item = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:mail_emails']} as e,
				{$this->tables['plugin:mail_emails_lang']} as l
			WHERE 
				e.email_id = l.email_id AND 
				l.lang_id = {$_LANG_ID} AND 
				e.email_id={$_GET['email_id']}
		");

		if (!is_array($item)) {
			return "Invalid link !";
		}

		unset($item["email_id"]);
		$item["email_code"] .= "_copy_";

		$item["email_id"] = $this->db->QueryInsert(
			$this->tables['plugin:mail_emails'] , 
			$item
		);

		$this->db->QueryInsert(
			$this->tables['plugin:mail_emails_lang'] , 
			$item
		);

		
		//redirect to details page
		urlredirect(
			"index.php?mod=mail&sub=emails&email_id={$item[email_id]}&action=edit&returnurl=" . 
				urlencode("index.php?mod=mail&sub=emails")
		);
				

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StoreServer($record) {

		if ($record["server_id"]) {

			//check for default 
			if ($record["server_default"]) {

				$this->db->QueryUpdate(
					$this->tables["plugin:mail_servers"],
					array( "server_default"	=>	0) ,
					"server_default=1 AND server_id != {$record[server_id]}"
				);
			}


			if ($record["server_dkim_key"]) {
				CFile::Save("../upload/mail/" . $record["server_id"]. ".key" , $record["server_dkim_key"]);
			}
			
			//send the test email if applies
			if ($_POST["test"]) {
				//send the test mail	
				$results = $this->SendMail(
					array(
						"email_to" => $_POST["test_to"],
						"email_from" => "no-reply@" . $_SERVER["HTTP_HOST"],
						"email_subject" => $_POST["test_subject"],
						"email_body" => $_POST["test_body"],
						"email_server"	=> $record["server_id"]
					)
				);
				
			}		



			
		}
		

	}

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

		if (!Validate::Email($_POST["test_to"])) {
			die("email");
		}
		

		$email = $_POST;
		$_POST["email_to"] = $_POST["test_to"];
		$_POST["email_to_name"]	= "";

		//overwrite the from name
		$_POST["email_from"] = "no-reply@" . $_SERVER["HTTP_HOST"];
		$_POST["email_from_name"] = $_SERVER["HTTP_HOST"];

		$this->SendMail(
			$_POST
		);

		die("1");
	}
	

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

		if ($this->loaded) {
			return true;
		}

		$servers = $this->db->QFetchRowArray(
			"SELECT * FROM {$this->tables['plugin:mail_servers']} WHERE server_status=1"
		);

		$this->loaded = 1;

		if (is_array($servers)) {
			foreach ($servers as $key => $val) {
				$this->servers[$val["server_id"]] = $val;

				if ($val["server_default"]) {
					$this->servers["default"] = &$this->servers[$val["server_id"]];
				}				
			}			
		}

		//if no server is set as default then use the local server
		if (!is_array($this->servers["default"])) {

			//try smtp
			if (External::Load("swiftmailer")) {
				$type = "php";
			} elseif(External::Load("phpmailer")) {
				$type = "php-local";
			} else {
				throw new Exception("No mailing library could be found. Please install Swiftmailer or PHPMailer.");
			}

			$this->servers["default"] = array(
				"set_switft_transport"	=> $type,
			);
		}	
	}


	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function processVars(&$vars) {

		if (is_array($vars)) {
			foreach ($vars as $key => $val) {
				//replace password fields
				if (stristr($key , "password") || stristr($key , "_pass")) {
				}				
			}
			
		}
		
	}

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

		switch ($_GET["type"]) {
			case "1":
				$mod = $this->plugins["modules"]->GetModuleInfo($_GET["module"]);
				$module = $mod["mod_module_code"];
			break;

			case "2":
				$mod = $this->plugins["modules"]->GetDefaultModuleInfo($_GET["module"]);
				$module = $mod["module_code"];
			break;
		}


		if (!is_array($mod) || !is_object($this->plugins[$module]) || !method_exists($this->module->plugins[$module] , "mailTemplateVars")) {
			return "";
		}

		
		$vars = $this->plugins[$module]->mailTemplateVars($mod , "vars" , $_GET["tpl"]);

		if (!is_array($vars)) {
			return "";
		}

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


		//append an extra group
		$vars[] = array(
			"set"		=> "Global Variables",
			"fields"	=> array(
				"visitor_date"		=> "Visitor Date",
				"visitor_ip"		=> "Visitor IP",
				"visitor_domain"	=> "Visitor Domain",
				"visitor_agent"		=> "Browser Agent",
				"site_link"			=> "Site Link",
			)
		);
		
		foreach ($vars as $key => $val) {

			$cnt = 1;
			foreach ($val["fields"] as $k => $v) {
				if (!is_array($v)) {
					$val["fields"][$k] = array(
						"var"	=> strtoupper($k),
						"title"	=> $v,
						"info"	=> "",
					);
				}

				$val["fields"][$k]["cnt"] = $cnt++;
				
			}
			

			$vars[$key]["_fields"] = $base->html->Table(
				$tpl , 
				"Fields",
				$val["fields"]
			);
		}

		
		return $base->html->table(
			$tpl , 
			"Vars",
			$vars
		);
		

		echo "X";

		
		
	}
	
}

?>