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

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

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

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

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

			switch ($_GET["sub"]) {
				case "image.captcha":
					return $this->CaptchaImage();
				break;

			}
		}
		
	}

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"classic"			=> "classic.htm",
			"recaptcha"			=> "recaptcha.htm",
		);

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

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


		//add recaptcha header
		if ($this->tpl_module["settings"]["set_captcha_type"] == "2") {
			$this->plugins["seo"]->AppedToHead($this->private->templates["recaptcha"]->blockReplace("Header"));
		}
		

	} 


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetCaptchaField($default = 0) {
		global $_SESS;

		$this->__init();

		switch ($this->tpl_module["settings"]["set_captcha_type"]) {
			case "1":
				$tpl = &$this->private->templates["classic"];
			break;

			case "2":
				$tpl = &$this->private->templates["recaptcha"];
			break;

			default: 
				return "";
			break;
		}


		switch ($default) {
			case "0":
				//never show capcha
				return "";
			break;

			case "1":
				if (!$_SESS["client"]) {					
					return $tpl->blockReplace("Field" , $this->tpl_module["settings"]);
				}
				
			break;

			case "2":				
				return $tpl->blockReplace("Field" , $this->tpl_module["settings"]);
			break;
		}

		return "";

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Validate($default = 0) {
		global $_SESS;


		$this->__init();

		switch ($default) {
			default:
				//never show capcha
				$validate = false;
			break;

			case "1":
				if (!$_SESS["client"]) {					
					$validate = true;
				}
				
			break;

			case "2":
				$validate = true;
			break;
		}



		if ($validate) {


			switch ($this->tpl_module["settings"]["set_captcha_type"]) {
				case "1":

					if (!$this->tpl_module["settings"]["set_capcha_cs"]) {
					   $_POST["image_code"] = strtoupper($_POST["image_code"]);
					} 

					if ((!$_POST["image_code"]) || ($_POST["image_code"] != $_SESS["XML_verify_key"])) {
						return false;
					}
				break;

				case "2":
					$data = CHTTP::NewInstance()
					->Get(
						"https://www.google.com/recaptcha/api/siteverify",
						array(
							"secret"	=> $this->tpl_module["settings"]["set_recaptcha_secret"],
							"response"	=> $_POST["g-recaptcha-response"],
							"remoteip"	=> $_SERVER["REMOTE_ADDR"],
						)
					)
					->Json();

					if (!$data["success"]) {
						return false;
					}
					
					return false;
					//validate
				break;
			}
		}

		//foce one use 
		if (isset($_SESS["XML_verify_key"])) {
			unset($_SESS["XML_verify_key"]);
		}	

		return true;
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ErrorMSG() {
		return $this->plugins["common"]->ErrorMSG(
			"captcha:" . $this->tpl_module["settings"]["lang_capcha"]
		);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CaptchaImage() {
		global $_SESS;
		
		//Select Font
		$font = file_exists("assets/captcha/default.") ? "assets/captcha/default." : $this->path . "assets/default.";

		//Select random background image
		$bgurl = rand(1, 1);
		$im = ImageCreateFromPNG(file_exists("assets/captcha/bg".$bgurl.".png") ? "assets/captcha/bg".$bgurl.".png" : $this->path . "assets/bg".$bgurl.".png");
		//Generate the random string
		$chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J","k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T","u","U","v","V","w","W","x","X","y","Y","z","Z",/*"1",*/"2","3","4","5","6","7","8","9");

		$length = max(2,$this->tpl_module["settings"]["set_captcha_width"]);
		$textstr = "";

		for ($i=0; $i<$length; $i++) {

			//case sensitive ?
			if ($this->tpl_module["settings"]["set_capcha_cs"]) {
			   $textstr .= ($chars[rand(0, count($chars)-1)]);
			} else {
			   $textstr .= strtoupper($chars[rand(0, count($chars)-1)]);
			}
			
		}

		$_SESS["XML_verify_key"] = $textstr;

		//Create random size, angle, and dark color
		$size = 14;//rand(, 5);
		$angle = 0;//rand(-0, 5);
		$color = ImageColorAllocate($im, 255,255,255);
		$bgcolor = ImageColorAllocate($im, 0,0,0);

		if (function_exists("imagettfbbox")) {
			//Determine text size, and use dimensions to generate x & y coordinates
			$textsize = imagettfbbox($size, $angle, $font . "ttf", $textstr);
			$twidth = abs($textsize[2]-$textsize[0]);
			$theight = abs($textsize[1]-$textsize[7]);
			$x = (imagesx($im)/2)-($twidth/2);//+(rand(-20, 20));
			$y = (imagesy($im)/2)-($theight/2);//+(rand(-20, 20));
			$y = 30;

			//Add text to image
			ImageTTFText($im, $size, $angle, $x, $y, $color, $font. "ttf", $textstr);
		} elseif (function_exists("_imagepstext")) {

			$font = imagepsloadfont($font . 'pfb');
			$font_size = imagepsbox($textstr , $font , $size );

			$textsize = imagepsbbox($textstr , $font . "ttf", $size);
			$twidth = abs($textsize[2]-$textsize[0]);
			$theight = abs($textsize[3]-$textsize[1]);

			$x = (imagesx($im)/2)-($twidth/2);//+(rand(-20, 20));
			$y = (imagesy($im)/2)-($theight/2);//+(rand(-20, 20));

			imagepstext(
				$im, 
				$textstr, 
				$font, 
				$size, 
				$bgcolor, 
				$color, 
				$x, 
				$y);
		}else {

			$font = 5;
			$y = 30;
			$x = 1;

			$twidth = imagefontwidth($font) * $length;
			$theight = imagefontheight($font);
			$x = (imagesx($im)/2)-($twidth/2);//+(rand(-20, 20));
			$y = (imagesy($im)/2)-($theight/2);//+(rand(-20, 20));

			imagestring ( 
				$im , 
				$font , 
				$x , 
				$y , 
				$textstr , 
				$color 
			);
		}
		

		//Output PNG Image
		header("Content-Type: image/png");
		ImagePNG($im);

		//Destroy the image to free memory
		imagedestroy($im);

		die();

	}
	

}

?>