<?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 CMaintenance extends CPlugin{
	
	var $tplvars; 

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

	}

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

		parent::DoEvents();


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

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

			switch ($_GET["sub"]) {
				default:					
					return $this->Landing();
				break;

				case "ajax.send":
					return $this->AjaxSendMessage();
				break;

				case "ajax.subscribe":
					return $this->AjaxSubscribe();
				break;

			}
		}
		
	}

	function __init() {
		global $_CONF;

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

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

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

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

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


		//$this->tpl_module["settings"]["link_dashboard"] = $this->tpl_module["link"] . "dashboard/";	
	} 

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

		$this->__init();
		$ok = 1;


		$isActive = false;


		switch ($this->tpl_module["settings"]["set_active"]) {

			//disabled
			default: 
			break;

			//everyone
			case "1":
				$isActive = true;
			break;

			//admins only
			case "2":
				if (is_array($_SESS["minibase"])) {
					$isActive = true;
				}
			break;

			//visitors only
			case "3":
				if (!is_array($_SESS["minibase"])) {
					$isActive = true;
				}
			break;

		}
		


		if (!$isActive) {
			return "";
		}
				
		if ($_GET["invite"] || $_COOKIE["invite"]) {

			$invite = $_GET["invite"] ? $_GET["invite"] : $_COOKIE["invite"];

			$data = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:maintenance_users']} WHERE user_key LIKE '%s'" , array($invite));

			if (is_array($data)) {

				//save the data in the cookie for 30days
				setcookie ( "invite", $invite, time() + 60*60*30 , "/" );

				$this->db->QueryUpdate(
					$this->tables["plugin:maintenance_users"],
					array(
						"user_last_login"		=> time(),
						"user_last_login_ip"	=> $_SERVER["REMOTE_ADDR"],
					),
					"user_id={$data['user_id']}"
				);

				return true;
				
			}
			
		}
		

		if ( !$this->tpl_module["settings"]["set_date"] ||  ($this->tpl_module["settings"]["set_date"] && ( $this->tpl_module["settings"]["set_date"] < time()))) {

			$_GET["mod"]	= "maintenance";
			$_GET["sub"]	= "landing";
			global $_PAGE;

			$_PAGE = "maintenance";

		}
	}


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

		$template = &$this->private->templates["main"];

		if ($this->plugins["socialmedia"]) {
			$this->plugins["socialmedia"]->__init();

			$social = $this->plugins["socialmedia"]->items;

			if (is_array($social)) {
				foreach ($social as $key => $val) {
					if (!$val["service_profile"]) {
						unset($social[$key]);
					}
				}
				
			}
			
		}
		

		$texts = $this->GetTexts(array(
			"core"		=> $this->tables["plugin:maintenance_texts"],
			"lang"		=> $this->tables["plugin:maintenance_texts_lang"],
		));

		//if no language was set for ths, then fall back on default language
		if (!is_array($texts) && !is_array($_SESS["minibase"])) {


			if (is_array($this->plugins["languages"]->languages)) {
				unset($this->plugins["languages"]->languages);
			}
		
			$this->plugins["languages"]->DetectLang();

			//update the lang_id inside the module id 
			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("maintenance" , true);


			//reload the text for the default language
			$texts = $this->GetTexts(array(
				"core"		=> $this->tables["plugin:maintenance_texts"],
				"lang"		=> $this->tables["plugin:maintenance_texts_lang"],
			));		
		}

		$this->plugins["seo"]->PageMeta(array(
			"seo_title"	=> $texts["seo_title"],
			"seo_desc"	=> $texts["seo_desc"],
		), "" , true);



		if ($this->tpl_module["settings"]["set_background"] && $this->plugins["backgrounds"]) {
			$bg = $this->plugins["backgrounds"]->GetBg($this->tpl_module["settings"]["set_background"]);			

			$_TSM["BG_CLASS"] = $bg["class"];
			$_TSM["BG_HTML"] = $bg["html"];
		} else {
			$_TSM["BG_CLASS"] = $_TSM["BG_HTML"] = "";
		}
				
		//overwrite the http reponse vode
		switch ($this->tpl_module["settings"]["set_type"]) {
			case "1":
				header('HTTP/1.1 503 Service Temporarily Unavailable' , true);
				header('Status: 503 Service Temporarily Unavailable');

				if ($this->tpl_module["settings"]["set_date_end"] > time()) {
					header('Retry-After: ' . date( "D, j M Y H:i:s T" , $this->tpl_module["settings"]["set_date_end"]));
				}

			break;

		}



		return $template->blockReplace(
			"Main" , 
			array(

				"newsletter"			=> $this->tpl_module["settings"]["set_newsletter"] && is_object($this->plugins['newsletters']) ? 
					$template->blockReplace(
						"Newsletter" , 
						array(
							"script"				=> $this->plugins["modules"]->ScriptLink("ajax.maintenance-subscribe"),
							"captcha_subscribe"		=> $this->plugins["antispam"]->GetCaptchaField($this->tpl_module["settings"]["set_newsletter_post_capcha"] , "subscribe" , $template , "NewsletterCaptcha"),
							"data-email-error"		=> $this->plugins["modules"]->modules["newsletters"]["settings"]["lang_error_email"],
						)
					) : "",
				"newsletter_control"	=> $this->tpl_module["settings"]["set_newsletter"] ? $template->blockReplace("NewsletterButton") : "",
				"countdown"				=> $this->tpl_module["settings"]["set_countdown"] && ($this->tpl_module["settings"]["set_date_end"] > time())? $template->blockReplace("Countdown" , array("date"=> date("+r" , $this->tpl_module["settings"]["set_date_end"]))) : "",

				"backgrounds"			=> $backgrounds,

				"logo"					=> $texts["text_image"] = 1 ? $template->blockReplace("Logo") : "",
				"title"					=> $texts["text_title"] ? $template->blockReplace("Title") : "",
				"header"				=> $texts["text_header"] ? $template->blockReplace("Header") : "",
				"footer"				=> $texts["text_footer"] ? $template->blockReplace("Footer") : "",

				"triggers"				=> $this->tpl_module["settings"]["set_about"] || $this->tpl_module["settings"]["set_contact"] ? 
					$template->blockReplace(
						"Triggers",
						array(
							"right_btn"		=> $this->tpl_module["settings"]["set_about"] ? $template->blockReplace("RightBtn") : "",
							"left_btn"		=> $this->tpl_module["settings"]["set_contact"] ? $template->blockReplace("LeftBtn") : "",
						)
					) : "",

				"right_body"			=> $this->tpl_module["settings"]["set_about"] ? 
					$template->blockReplace(
						"RightBody" , 
						array(
							"title"		=> $texts["text_footer_title"] ? $template->blockREplace("RightTitle") : "",
							"header"	=> $texts["text_footer_header"] ? $template->blockREplace("RightHeader") : "",
						)
					) : "",

				"left_body"				=> $this->tpl_module["settings"]["set_contact"] ? 
					$template->blockReplace(
						"LeftBody" , 
						array(
							"script"	=> $this->plugins["modules"]->ScriptLink("ajax.maintenance-send"),							
							"form"		=> formBuilder::newInstance()
								-> setFields(array(
									array(
										"type"		=> "textbox",
										"name"		=> "name",
										"title"		=> $this->tpl_module["settings"]["lang_form_name"],									
									),
									array(
										"type"		=> "textbox",
										"name"		=> "email",
										"title"		=> $this->tpl_module["settings"]["lang_form_email"],									
									),
									array(
										"type"		=> "textarea",
										"name"		=> "message",
										"title"		=> $this->tpl_module["settings"]["lang_form_message"],									

										"textarea"	=> array(
												"rows"	=> 5,
										)
									),
								))
								-> setCaptcha(array(
									"type"	=> $this->tpl_module["settings"]["set_post_capcha"],
									"name"	=> "maintenance",
								))
								-> buildFields(),
						)
					) : "",

				"lang_menu"				=> $this->plugins["languages"]->Menu($this->private->templates["lang"]),


				"social"				=> is_array($social) && count($social) && $this->tpl_module["settings"]["set_social"] ? $base->html->table(
					$template , 
					"Social",
					$social
				): "",

			),

			$texts,

			$this->tpl_module["settings"]
		);
	}
	

	function AjaxSubscribe() {
		global $_CONF;

		$this->plugins["newsletters"]->__init();


		$response = CFormError::newInstance()
			->SetErrorStyle(1)//$this->tpl_module["settings"]["set_form_validate"])
			->SetSuccessStyle($this->tpl_module["settings"]["set_form_success"])
			->SetPopupBtn($this->tpl_module["settings"]["lang_popup_close"])
			->SetPopupBg($this->tpl_module["settings"]["set_form_popup_bg"])
			->SetScript("ProcessNewsletterErrors()");


		if (!Validate::Email($_POST["email"])) {
			$response->AddField("email" , $this->plugins["modules"]->modules["newsletters"]["settings"]["lang_error_email"]);
		} else {
			if (!$this->plugins["antispam"]->ValidateEmail($this->tpl_module, $_POST["email"])) {
				$response->AddField("email" , $this->plugins["antispam"]->EmailError());
			}
		}

		if (!$this->plugins["antispam"]->ValidateClient($this->tpl_module)) {
			$response->AddField("__global" , $this->plugins["antispam"]->ClientError());
		}

		if (!$this->plugins["antispam"]->ValidateCaptcha($this->tpl_module["settings"]["set_newsletter_post_capcha"] , "subscribe")) {
			$response->AddField("image_code" , $this->plugins["antispam"]->CaptchaError());
		}

		if ($response->HasErrors()) {
			return $response->GetJson();
		}


		$user = array(
			"first_name"	=> $_POST["first_name"],
			"last_name"		=> $_POST["last_name"],
			"name"			=> $_POST["name"],
			"email"			=> $_POST["email"],
			"list"			=> $this->tpl_module["settings"]["set_newsletter_list"],
			"date"			=> time(),
			"key_code"		=> md5($_POST["email"]),
		);

		$result = $this->plugins["newsletters"]->RecordUser($user);

		if ($result !== true) {
			$response->AddField("email" , $result);
			return $response->GetJson();

		}
		
		$user["confirm_link"]	= $_CONF["url"] . "/newsletters/confirm/" . $user["key_code"];


		$email = $this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->plugins["modules"]->modules["newsletters"]["settings"]["set_mail_subscribe"],
				$user
			)
		);

		return $response->SetReset()
			->SetSuccess($this->plugins["modules"]->modules["newsletters"]["settings"]["lang_success"])
			->GetJson();

	}

	

	function AjaxSendMessage() {
		global $_CONF , $_NO_HTACCESS , $_SESS , $_LANG_ID;
		$this->__init();

		$response = CFormError::newInstance()
			->SetErrorStyle($this->tpl_module["settings"]["set_form_validate"])
			->SetSuccessStyle(0);

		if (!$this->tpl_module) {
			$response->AddField("__global" , "Invalid module!");
		}

		if (!$_POST["name"]) {
			$response->AddField("name" , $this->tpl_module["settings"]["lang_form_err_name"]);
		}

		if (!Validate::Email($_POST["email"])) {
			$response->AddField("email" , $this->tpl_module["settings"]["lang_form_err_email"]);
		} else {
			if (!$this->plugins["antispam"]->ValidateEmail($this->tpl_module , $_POST["email"])) {
				$response->AddField("email" , $this->plugins["antispam"]->EmailError());
			}							
		}

		if (!$_POST["message"]) {
			$response->AddField("message" , $this->tpl_module["settings"]["lang_form_err_message"]);
		}

		if (!$this->plugins["antispam"]->ValidateClient($this->tpl_module)) {
			$response->AddField("__global" , $this->plugins["antispam"]->ClientError());
		}

		if (!$this->plugins["antispam"]->ValidateCaptcha($this->tpl_module["settings"]["set_post_capcha"] , "maintenance")) {
			$response->AddField("image_code" , $this->plugins["antispam"]->CaptchaError());
		}

		if ($response->HasErrors()) {
			return $response->GetJson();
		}			
		
		$vars = $_POST;

		//save the email to database
		$id = $this->db->QueryInsert(
			$this->tables["plugin:maintenance_messages"],
			$contact = array(
				"item_new"		=> 1,
				"item_date"		=> time(),
				"item_email"	=> $vars["email"],

				"item_name"		=> $vars["name"],
				"item_message"	=> $vars["message"],

				"log_ip"			=> $_SERVER["REMOTE_ADDR"],
				"log_domain"		=> $_SERVER["REMOTE_HOST"],
				"log_agent"			=> $_SERVER["HTTP_USER_AGENT"],
			)
		);

		$mail_template = $this->module->plugins["mail"]->GetMail(
			$this->tpl_module["settings"]["set_mail_admin"],
			$vars
		);
		
		$responder_template = $this->module->plugins["mail"]->GetMail(
			$this->tpl_module["settings"]["set_mail_client"],
			$vars
		);

		//validate the spam
		$isSpam = $this->plugins["antispam"]->isSpam(
			$this->tpl_module,
			array(
				"type"		=> "message",
				"author"	=> $contact["item_name"],
				"email"		=> $contact["item_email"],
				"message"	=> $contact["item_message"],
			)
		);

		if (!$isSpam) {
			if (is_array($mail_template)) {
				$email = $this->module->plugins["mail"]->SendMail(
					$mail_template
				);
			}

			if (is_array($responder_template)) {
				$email = $this->module->plugins["mail"]->SendMail(
					$responder_template
				);			
			}			
		} else {
			//mark as spam
			$this->db->QueryUpdateById(
				$this->tables["plugin:maintenance_messages"],
				array(
					"item_spam"	=> 1,
				),
				$id
			);
		}

		return $response->SetReset()
			->SetSuccess($this->tpl_module["settings"]["lang_form_success"])
			->GetJson();
	}
	

}

?>