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

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $connect = array(
		"link"		=> "",
		"status"	=> true,
		"new"		=> true,
		"extra"		=> array(
			"module"	=> "",
			"reserved"	=> "",
		)
	);
	

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

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

		parent::DoEvents();

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

			$this->__init();

			if ($this->tpl_module["module_status"] != "1") {
				return "";
			}

			switch ($_GET["sub"]) {
				case "ajax.post":
					return $this->AjaxPost();
				break;

				case "ajax.read":
					return $this->AjaxRead();
				break;
			}
		}

	}

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"fbcomments"				=> "fbcomments.htm",
			"comments"					=> "comments.htm",
			"disqus"					=> "disqus.htm",
		);

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

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


	} 

	function Comments($url = "", $type , $new = true , $extra = "") {
		global $_CONF , $_TSM;

		$this->__init();
		
//		$type = 1;


		$data = $_GET;
		if (isset($data["page"])) {	unset($data["page"]); }

		if (!$url) {
			$url = $_TSM["PRIV.SELF_URI"];
		}

		if (!$this->connect["status"]) {
			return "";
		}
		

		switch ($type) {
			//local comments
			case "1":

				return $this->LocalComments(
					$url , 
					$this->connect["new"],
					$extra
				);
			break;

			case "2":

				return $this->FBComments(
					$url
				);
			break;

			case "3":
				return $this->DisqusComments(
					$url
				);
			break;
		}

	}

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

		$comments = $this->GetRecords($_POST["url"]);

		$comments = $this->ProcessReplies($comments);

		$url = $_POST["url"];

		$return = $this->_t("comments")->blockreplace(
			"AjaxMain" , 
			array(

				"comments"		=> $base->html->Table(
					$this->_t("comments"),
					"",
					$comments["records"]
				),

				"paging"=> $this->module->plugins["paging"]->Paging(
					$comments["pages"] , 
					$comments["page"], 
					array(
						"first"		=> "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}' , '{$_LANG}');",
						"all"		=> "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}' , '{$_LANG}');",
					),

					array(
						"ipp"	=> $comments["ipp"],
						"total"	=> $comments["count"]
					)
				)
			)
		);

		return CTemplateStatic::Replace(
			$return , 
			$this->tpl_module["settings"]
		);		

	}
	

	function FBComments($url) {
		$this->__init();

		if (!$this->tpl_module["module_status"]) {
			return "";
		}

		return $this->private->templates["fbcomments"]->blockReplace(
			"Comments",
			array(
				"url"			=> $url,
			),
			$this->tpl_module["settings"]

		);
	}

	function LocalComments($url ,$new , $extra) {
		global $base , $_SESS , $_LANG;

		$this->__init();

		if ($this->tpl_module["module_status"] != "1") {
			return "";
		}

		$comments = $this->GetRecords($url , $extra);
		$comments = $this->ProcessReplies($comments);

		$return = $this->_t("comments")->blockreplace(
			"Main" , 
			array(

				"url"	=> $url,

				"comments"		=> $base->html->Table(
					$this->_t("comments"),
					"",
					$comments["records"]
				),

				"paging"=> $this->module->plugins["paging"]->Paging(
					$comments["pages"] , 
					$comments["page"], 
					array(
						"first"		=> "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}' , '{$_LANG}');",
						"all"		=> "javascript:loadComments('" . urlencode($url) . "' , '{PAGE}' , '{$_LANG}');",
					),

					array(
						"ipp"	=> $comments["ipp"],
						"total"	=> $comments["count"]
					)
				),

				"page"	=> $comments["page"],


				"new_comment"	=> $new ? $this->NewComment($url , $extra) : "",
			),
			$this->tpl_module
		);

		//prepare the comments title
		if ($comments["count"]) {
			$this->tpl_module["settings"]["set_title"] = CTemplateStatic::Replace(
				$this->tpl_module["settings"]["set_title"],
				array(
					"comments"	=> $comments["count"]
				)
			);
		} else 
			$this->tpl_module["settings"]["set_title"] = $this->tpl_module["settings"]["set_titleno"];
	
		$this->tpl_module["settings"]["set_post_comment"] = nl2br($this->tpl_module["settings"]["set_post_comment"]);

		return CTemplateStatic::Replace(
			$return , 
			$this->tpl_module["settings"]
		);		
	}


	function GetRecords($url , $extra = array()) {
		global $_CONF , $_SESS;
		
		$count = max(1,$this->tpl_module["settings"]["set_local_posts"]);

		$page = $_REQUEST["page"];
		
		if ($this->tpl_module["settings"]["set_local_show"] == "2") {

			if (!$extra["forceall"]) {
				$cond = " AND comment_status=2 ";
			}
			

			if ($_SESS["client"]) {
				$cond = " AND (comment_status=2 OR comment_user={$_SESS[client][user_id]} )";
			}			
		}
		

		$comment_count = $this->db->RowCount(
			$this->tables['plugin:comments'],
			"WHERE comment_parent = 0 AND comment_url='" . $this->db->escapeString($url)  . "'  {$cond} "
		);

		if (!$page && $comment_count) {
			$page = $comment_count ? ceil($comment_count / $count) : 1;
		} else 
			$page = (int)$page;

		$items = $this->db->QFetchRowArray(
			"SELECT * " . 
			"FROM {$this->tables['plugin:comments']} " . 
			"WHERE comment_parent = 0 AND comment_url='%s' {$cond}  " . 
			"ORDER BY  comment_date ASC " .
			"LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count ,
			array($url)
		);

		$today = strtotime("today");

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

				$_items[$val["comment_id"]] = $val;

				$pids[] = $val["comment_id"];
			}

			$items = $_items;

			$parents = $this->db->QFetchROwArray("SELECT * FROM {$this->tables['plugin:comments']} WHERE comment_parent in (" . implode("," , $pids) . ") {$cond} ORDER BY comment_parent , comment_date ASC");

			if (is_array($parents)) {
				foreach ($parents as $key => $val) {
					$pdata[$val["comment_parent"]][] = $val;
				}
				
				$parents = $pdata;
			}


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

				$items[$key] = $val = $this->ProcessComment($val);

				//$final[] = $val;

				if ($parents[$val["comment_id"]]) {
					foreach ($parents[$val["comment_id"]] as $k => $v) {
						$v = $this->processComment($v);

						$final[] = $v;

						$items[$key]["reply"][] = $v;
					}					
				}													
			}	
			
			//$items = $final;
		}

		return array(
			"records"	=> $items, 
			"count"		=> $comment_count , 
			"pages"		=> $comment_count ? ceil($comment_count / $count) : 1,
			"page"		=> $page,

			"ipp"		=> $count
		);

	}


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

		$val["comment_body"]	=	nl2br(
			strip_tags(
				$val["comment_body"]
			)
		);

		//process the link
		if ($val["comment_website"]) {
			if (!stristr($val["comment_website"] , "http://")) {
				$val["comment_website"] = "http://" . $val["comment_website"];
			}
		} else 
			$val["comment_website"] = "#";

		$val["avatar"] = $this->ProcessAvatar($val);
		
		$val["reply_class"] = $val["comment_parent"] ? "reply"  :"";

		$val["comment_body"] = $this->show_youtube($val["comment_body"]);


		if ($val["comment_date"] > $today) {
			$val["date"] = date("G:i a" , $val["comment_date"]);
		} else {
			$val["date"] = date("j M" , $val["comment_date"]);
		}				

		$val["day"] =  date("d" , $val["comment_date"]);
		$val["month"] =  date("m" , $val["comment_date"]);
		$val["year"] =  date("y" , $val["comment_date"]);

		return $val;


	}
	

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


		if ($val["comment_avatar"]) {
			$val["avatar"] = $val["comment_avatar"];
		} else {				
			//check if i have facebook avatar
			if ($val["comment_fbid"]) {
				$val["avatar"] = "https://graph.facebook.com/{$val[comment_fbid]}/picture";
			} else {
				//process gravatar link
				$val["avatar"] = "https://secure.gravatar.com/avatar/" . md5(strtolower(trim($val["comment_email"]))) . "?r=g&default=" . urlencode($_CONF["url"] . "upload/default-images/avatar.jpg");
			}
		}

		return $val["avatar"];
	}
	

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

		$this->__init();

		$data = $_POST;

		$response = CFormError::newInstance()
			->SetErrorStyle($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"]);


		if ($_SESS["client"] && ($this->tpl_module["settings"]["set_local_form"] == "2")) {
			$data["name"] = $_SESS["client"]["user_first_name"] . " "  . $_SESS["client"]["user_last_name"];
			$data["email"]	= $_SESS["client"]["user_email"];
		}

		$fields = array(
			"url"		=> "lang_error_unknown",
			"name"		=> "lang_error_name",
			"email"		=> "lang_error_mail",
			"message"	=> "lang_error_message",
		);

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

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

			if (!$data[$key] || (($key == "email") && (!Validate::Email($data["email"])))) {
				$response->AddField($key, $this->tpl_module["settings"][$val]);
			}			
		}

		//check protection
		if ($this->tpl_module["settings"]["set_max_comm"]) {
			$last = time()  - $this->tpl_module["settings"]["set_max_sec"];

			$comments = $this->db->RowCount(
				$this->tables["plugin:comments"],
				"WHERE comment_log_ip LIKE '{$_SERVER[REMOTE_ADDR]}' AND comment_date > {$last} "
			);


			if ($this->tpl_module["settings"]["set_max_comm"] <= $comments) {
				$response->AddField("__global", $this->tpl_module["settings"]["lang_error_spam"]);
			}			
		}

		//secondary filter protection
		if ($this->tpl_module["settings"]["set_max2_comm"]) {
			$last = time()  - $this->tpl_module["settings"]["set_max2_sec"];

			$comments = $this->db->RowCount(
				$this->tables["plugin:comments"],
				"WHERE comment_log_ip LIKE '{$_SERVER[REMOTE_ADDR]}' AND comment_date > {$last} "
			);


			if ($this->tpl_module["settings"]["set_max2_comm"] <= $comments) {
				$response->AddField("__global", $this->tpl_module["settings"]["lang_error_spam"]);
			}			
		}
		

		if ($data["parent"]) {
			if (!is_array($parent = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:comments']} WHERE comment_code LIKE '{$data[parent]}'"))) {
				$response->AddField("__global", $this->tpl_module["settings"]["lang_error_parent"]);
			}
		}

		if (!$this->plugins["antispam"]->ValidateClient($this->tpl_module)) {
			$response->AddField("__global" , $this->plugins["antispam"]->ClientError());
		}
		
		//check for capcha
		if (!$this->plugins["antispam"]->ValidateCaptcha($this->tpl_module["settings"]["set_post_capcha"] , $data["url"])) {
			$response->AddField("image_code" , $this->plugins["antispam"]->CaptchaError());
		}

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


		//validate the spam
		$spam = $this->plugins["antispam"]->isSpam(
			$this->tpl_module,
			array(
				"type"		=> "comment",
				"author"	=> $data["name"],
				"email"		=> $data["email"],
				"message"	=> $data["message"],
				"url"		=> $data["url"],
			)
		);

		if ($spam) {
			$status = 3;
		} else {
			$status = "1";
		}
		

		$id = $this->db->QueryInsert(
			$this->tables["plugin:comments"],
			$comment = array(
				"comment_user"		=> $_SESS["client"]["user_id"],
				"comment_url"		=> $data["url"],
				"comment_date"		=> time(),
				"comment_parent"	=> $parent["comment_id"],
				"comment_author"	=> strip_tags($data["name"]),
				"comment_email"		=> strip_tags($data["email"]),
				"comment_body"		=> strip_tags($data["message"]),
				"comment_status"	=> $status,	//pending,
				"module_id"			=> $data["m"],
				"comment_reserved"	=> $data["r"],

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

				"comment_avatar"	=> $_SESS["client"]["avatar"],
			)
		);

		$this->db->QueryUpdate(
			$this->tables["plugin:comments"],
			array(
				"comment_code"	=> md5($id . $_data["email"] )
			),

			"comment_id={$id}"
		);

		//check if ther eis a method for 
		$mod = $this->plugins["modules"]->modules[$data["m"]];

		if (is_array($mod) && $this->plugins[$mod["module_code"]]) {
			if (method_exists($this->plugins[$mod["module_code"]] , "onCommentPost")) {
				$this->plugins[$mod["module_code"]]->onCommentPost($comment);
			}				
		}


		//if not spam send the notification to admin if set
		if (!$spam) {

			$email = $this->module->plugins["mail"]->SendMail(
				$this->module->plugins["mail"]->GetMail(
					$this->tpl_module["settings"]["set_mail_admin"],
					$comment
				)
			);			
		}


		return $response->SetReset()
			->SetSuccess($this->tpl_module["settings"]["lang_success"])
			->SetScript($this->_t("comments")->blockReplace("Success"))
			->GetJson();
	}
	

	function show_youtube($input)
	{

//		preg_match_all('#(http://www.youtube.com)?/(v/([-|~_0-9A-Za-z]+)|watch\?v\=([-|~_0-9A-Za-z]+)&?.*?)#i',$input,$output);
		preg_match_all('#(http://www.youtube.com)?(v=|\/)([\w-]+)(&.+)?$#i',$input,$output);

		$VID_WID = 320;
		$VID_HEI = 240;

		$link2 = "http://youtube.com/v/" . $output[3][0];

		$tmp = explode(" " , $output[0][0]);

		return str_replace(
			"http://www.youtube.com/watch?" . $tmp[0] ,

			'<object width="' . $VID_WID . '" height="' . $VID_HEI . '">'.
			'<param name="movie" value="' . $link2 . '"></param>'.
			'<param name="allowFullScreen" value="true"></param>'.
			'<param name="allowscriptaccess" value="always"></param>'.
			'<embed src="' . $link2 . '" type="application/x-shockwave-flash" '.
			'allowscriptaccess="always" allowfullscreen="true" '.
			'width="' . $VID_WID . '" height="' . $VID_HEI . '"></embed></object>',

			$input 
		);
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function NewComment($url , $extra) {
		global $_SESS;

		$template = $this->_t("comments");

		$data = array(
			"script"	=> $this->plugins["modules"]->ScriptLink("ajax.comments.post.php"),
		);

		if ($_SESS["client"] && ($this->tpl_module["settings"]["set_local_form"] == "2")) {

			$data["user"] = $template->blockReplace(
				"NewSimpleUser",
				$_SESS["client"]
			);

			$html =  $template->blockReplace(
				"New"	,					
				array(
					"form"	=> formBuilder::newInstance()
					-> setFields(array(
						array(
							"type"		=> "hidden",
							"name"		=> "url",
							"default"	=> $url,
						),
						array(
							"type"		=> "hidden",
							"name"		=> "r",
							"default"	=> $this->connect["extra"]["reserved"],
						),

						array(
							"type"		=> "hidden",
							"name"		=> "parent",
							"default"	=> "",
						),

						array(
							"type"		=> "hidden",
							"name"		=> "m",
							"default"	=> $this->connect["extra"]["module"],
						),

						array(
							"type"		=> "textarea",
							"name"		=> "message",
							"title"		=> $this->tpl_module["settings"]["lang_message"],									
						),

					))
					-> setCaptcha(array(
						"type"	=> $this->tpl_module["settings"]["set_post_capcha"],
						"name"	=> $url,
					))
					-> buildFields(),			
				),
				$data
			);			
		} else {

			$html = $template->blockReplace(
				"New" , 
				array(
					"form"	=> formBuilder::newInstance()
					-> setFields(array(
						array(
							"type"		=> "hidden",
							"name"		=> "url",
							"default"	=> $url,
						),
						array(
							"type"		=> "hidden",
							"name"		=> "r",
							"default"	=> $this->connect["extra"]["reserved"],
						),

						array(
							"type"		=> "hidden",
							"name"		=> "parent",
							"default"	=> "",
						),

						array(
							"type"		=> "hidden",
							"name"		=> "m",
							"default"	=> $this->connect["extra"]["module"],
						),

						array(
							"type"		=> "textbox",
							"name"		=> "name",
							"title"		=> $this->tpl_module["settings"]["lang_name"],									
							"default"	=> "",
							"size"		=> array("phone" => 12 , "tablet"	=> 6)
						),
						array(
							"type"		=> "textbox",
							"name"		=> "email",
							"title"		=> $this->tpl_module["settings"]["lang_email"],									
							"size"		=> array("phone" => 12 , "tablet"	=> 6)
						),

						array(
							"type"		=> "textarea",
							"name"		=> "message",
							"title"		=> $this->tpl_module["settings"]["lang_message"],									
						),

					))
					-> setCaptcha(array(
						"type"	=> $this->tpl_module["settings"]["set_post_capcha"],
						"name"	=> $url,
					))
					-> buildFields(),				
				),
				$data
			);
		}

		return CTemplateStatic::Replace(
			$html , 
			$this->tpl_module["settings"]
		);
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function getLastLocalComments($count = 5, $link = "" , $module = "" , $reserved = "") {

		if ($link)
			$cond .= " AND comment_url LIKE '{$link}' ";
		
		if ($module)
			$cond .= " AND module_id LIKE '{$module}' ";
		
		if ($reserved)
			$cond .= " AND comment_reserved {$reserved} ";

		$items =  $this->db->QFetchRowArray(
			"
			SELECT * FROM {$this->tables['plugin:comments']} WHERE

			comment_status = 2 
			{$cond}
			
			ORDER BY
				comment_date DESC
			LIMIT 
				$count
			
			"
		);

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

		return $items;
		
	}
	

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

		 if (is_Array($comments["records"])) {
			 foreach ($comments["records"] as $key => $val) {

				 if (is_array($val["reply"])) {

					 $comments["records"][$key]["replies"] = $base->html->table(
						 $this->_t("comments"),
						 "Replies",
						 $val["reply"]
					);
				 } else {
					 $comments["records"][$key]["replies"] = "";
				 }
				 

				 $comments["records"][$key]["reply_btn"] = $this->connect["new"] ? $this->_t("comments")->blockReplace("ReplyBtn" , $val ) : "";
			 }
			 
		 }


		 return $comments;
		 
	}

	
	function FacebookCommentsCount($link) {
		$this->__init();

		return $this->private->templates["fbcomments"]->blockReplace(
			"CommentsCount",
			array(
				"url"	=> $link
			)
		);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CommentsCount($type , $link , $local) {
		switch ($type) {
			//local
			case "1":
				return $local;
			break;

			case "2":
				return $this->FacebookCommentsCount($link);
			break;

			case "3":
				return $this->DisqusCommentsCount($link);
			break;
		}
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DisqusComments($link) {
		$this->__init();

		return $this->private->templates["disqus"]->blockReplace(
			"Comments",
			array(
				"url"	=> $link,
				"id"	=> $this->tpl_module["settings"]["set_disqus_id"],
				"uid"	=> md5($link),

				//id
			),
			$this->tpl_module["settings"]
		);

	}
	
	
	function DisqusCommentsCount($link) {
		$this->DisqusInit();

		return $this->private->templates["disqus"]->blockReplace(
			"CommentsCount",
			array(
				"url"	=> $link,
				"id"	=> $this->tpl_module["settings"]["set_disqus_id"],
				"uid"	=> md5($link),
			)
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DisqusInit() {
		$this->__init();

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

		$this->disqus__inited = true;

		
		$this->plugins["seo"]->AppendToBody(
			$this->private->templates["disqus"]->blockREplace(
				"Footer",
				array(	
					//add the id
					"id"	=> $this->tpl_module["settings"]["set_disqus_id"]

				)
			)
		);
		
	}

}

?>