<?php
/*
	Stempora Web Framework
	Copyright (c) 2002-2014 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com		
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CComments extends CPlugin{
	
	var $tplvars; 

	function CComments() {
		//$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;

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


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

				return $this->LocalComments(
					$url , 
					$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->private->templates["comments"]->blockreplace(
			"AjaxMain" , 
			array(

				"comments"		=> $base->html->Table(
					$this->private->templates["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->private->templates["comments"]->blockreplace(
			"Main" , 
			array(

				"url"	=> $url,

				"comments"		=> $base->html->Table(
					$this->private->templates["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"]
					)
				),


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

		//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(5,$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=\"{$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=\"{$url}\" {$cond}  " . 
			"ORDER BY  comment_date ASC " .
			"LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count 
		);

		$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;


		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 (!$data[$key]) {
				return $this->module->plugins["common"]->ErrorMsg(
					$this->tpl_module["settings"][$val]
				);
			}			
		}


		if (!Validate::Email($data["email"])) {
			return $this->module->plugins["common"]->ErrorMsg(
				$this->tpl_module["settings"][$fields["email"]]
			);
		}

		//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) {
				return $this->module->plugins["common"]->ErrorMsg(
					$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) {
				return $this->module->plugins["common"]->ErrorMsg(
					$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]}'"))) {
				return $this->module->plugins["common"]->ErrorMsg(
					$this->tpl_module["settings"]["lang_error_parent"]
				);
			}
			
		}
		

		//check for capcha
		if (!$this->plugins["captcha"]->Validate($this->tpl_module["settings"]["set_post_capcha"])) {
			return $this->plugins["captcha"]->ErrorMSG();
		}

		$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"	=> "1",	//pending,
				"module_id"		=> $data["m"],
				"comment_reserved"	=> $data["r"],
				"comment_log_ip"	=> $_SERVER["REMOTE_ADDR"],

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

		//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);
			}
			
		}
		
		$this->db->QueryUpdate(
			$this->tables["plugin:comments"],
			array(
				"comment_code"	=> md5($id . $_data["email"] )
			),

			"comment_id={$id}"
		);

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

		return $this->module->plugins["common"]->SuccessMsg(
			$this->tpl_module["settings"]["lang_success"] .
			"reset:" . $this->private->templates["comments"]->blockReplace(
				"Success" , 
				array(
					"script"	=> $this->plugins["modules"]->ScriptLink("ajax.comments.read.php"),
				)
			)						
		);

	}
	

	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->private->templates["comments"];

		$data = array(
			"url"		=> $url,
			"script"	=> $this->plugins["modules"]->ScriptLink("ajax.comments.post.php"),
			"reserved"	=> $extra["reserved"] ? $template->blockReplace("Reserved" , array("reserved" => $extra["reserved"]) ) : "",
			"module"	=> $extra["module"] ? $template->blockReplace("Module" , array("module" => $extra["module"]) ) : "",
		);


		$data["captcha"] = $data["capcha"] = $this->plugins["captcha"]->GetCaptchaField($this->tpl_module["settings"]["set_post_capcha"]);

		

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

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

			$html =  $template->blockReplace(
				"NewSimple"	,
				$data
			);			
		} else {

			$html = $template->blockReplace(
				"NewFull" , 
				$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->private->templates["comments"],
						 "Replies",
						 $val["reply"]
					);
				 } else {
					 $comments["records"][$key]["replies"] = "";
				 }
				 
			 }
			 
		 }


		 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"]
				//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"]
			)
		);
	}

	/**
	* 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"]

				)
			)
		);
		
	}

}

?>