<?php
/**
 * ###############################################
 *
 * SWIFT Framework
 * _______________________________________________
 *
 * @author		Varun Shoor
 *
 * @package		SWIFT
 * @copyright	Copyright (c) 2001-2012, Kayako
 * @license		http://www.kayako.com/license
 * @link		http://www.kayako.com
 *
 * ###############################################
 */

SWIFT_Loader::LoadInterface('Captcha:Captcha');

/**
 * The ReCaptcha Class
 *
 * @author Varun Shoor
 */
class SWIFT_CaptchaReCaptcha extends SWIFT_CaptchaManager implements SWIFT_Captcha_Interface
{
	/**
	 * Constructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __construct()
	{
		parent::__construct();

		require_once ('./' . SWIFT_BASEDIRECTORY . '/' . SWIFT_THIRDPARTYDIRECTORY . '/ReCaptcha/recaptchalib.php');

		return true;
	}

	/**
	 * Destructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __destruct()
	{
		parent::__destruct();

		return true;
	}

	/**
	 * Retrieve the relevant HTML for Captcha
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Captcha_Exception If the Class is not Loaded
	 */
	public function GetHTML($_scriptLoaded = false)
	{
		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Captcha_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		} else if (!parent::GetHTML()) {
			return false;
		}

		$_returnHTML = '';

		if ($_scriptLoaded == false)
		{
			$_returnHTML .= '<script type="text/javascript" src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>';
		}

		$_returnHTML .= '<div id="recaptcha_div"></div>
				<script type=\'text/javascript\'>
				Recaptcha.create("' . $this->Settings->Get('security_recpublickey') . '",
				"recaptcha_div", {
				   theme: "clean"
				});

				</script>';

		return $_returnHTML;
	}

	/**
	 * Check to see if Captcha is Valid
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Captcha_Exception If the Class is not Loaded or If Invalid Captcha Response Received
	 */
	public function IsValidCaptcha()
	{
		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Captcha_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		} else if (!parent::IsValidCaptcha()) {
			return true;
		}

		if (!isset($_POST['recaptcha_challenge_field']) || !isset($_POST['recaptcha_response_field']))
		{
			return false;
		}

		$_ResponseObject = recaptcha_check_answer($this->Settings->Get('security_recprivatekey'), SWIFT::Get('IP'), $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
		if (!$_ResponseObject->is_valid) {
			return false;
		}

		return true;
	}
}
?>