<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2016 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flFormElementRecaptcha Class
 *
 * Form element to implement Google reCAPTCHA.
 *
 * @package fusionLib
 */
class flFormElementRecaptcha extends flFormElement {

	/**
	 * The site key.
	 *
	 * @var string
	 */
	protected $siteKey;

	/**
	 * The secret key.
	 *
	 * @var string
	 */
	protected $secretKey;

	/**
	 *    Construct the element.
	 *
	 * @param flForm $form The form the element will be used with or null if not using flForm
	 * @param string $name The name of the element.
	 * @param string $content The content for the pane.
	 */
	function __construct($form, $name, $siteKey, $secretKey) {
		parent::__construct($form, $name);
		$this->siteKey = $siteKey;
		$this->secretKey = $secretKey;
	}

	/**
	 * Draw the element.
	 */
	function render() {
		$this->form->getCodeBuffer()->bufferHeadJS('https://www.google.com/recaptcha/api.js');
		return "<div class=\"g-recaptcha $this->class\" data-sitekey=\"" . $this->siteKey . "\"></div>\n";
	}

	/**
	 * @inheritdoc
	 */
	function processRequest($request) {
		if($this->form->isSubmitted()) {
			parent::processRequest($request);

			$value = $request->getParam('g-recaptcha-response');

			if($value === null || empty($value))
				$this->isValid = false;
			else {
				// Query Google
				$client = new flHttpClient('https://www.google.com/recaptcha/api/siteverify');
				$client->setPostData(array(
					'secret' => $this->secretKey,
					'response' => $value,
					'remoteip' => $request->getClientIp()
				));

				if($client->sendRequest() && $client->getResponseCode() == 200) {
					$d = json_decode($client->getBody());
					$this->isValid = $d->success;
				} else
					$this->isValid = false;
			}

			if(!$this->isValid) {
				$this->forceError(__('Please correctly answer the reCAPTCHA.', 'fusionLib'));
			}
		}
	}
}
