Symfony Google Recaptcha Widget + Validator
Наскоро си поиграх с Google Recaptcha и реших да си направя собствен widget и validator. Не ми се занимаваше с 3rd party plugins за това си написах собствена имплементация.
I. Google Recaptcha Widget
Widget-а приема 2 опции: public_key и theme. public_key се получава след регистриране на домейн в http://www.google.com/recaptcha. Чрез theme се посочва някоя от поддържаните теми от Google Recaptcha.
lib/widget/sfWidgetFormGoogleRecaptcha.class
<?php
/**
* Simple widget based on the Google Recaptcha library
*
* @author Stef
*/
class sfWidgetFormGoogleRecaptcha extends sfWidgetForm
{
public function configure($options = array(), $attributes = array())
{
$this->addOption('public_key');
$this->addOption('theme', null);
}
public function render($name, $value = null, $attributes = array(), $errors = array())
{
require_once(sfConfig::get('sf_lib_dir') . '/recaptcha/recaptchalib.php');
$output = '';
if ($this->getOption('theme')) {
$output .= '<script type="text/javascript">
var RecaptchaOptions = {
theme : "' . $this->getOption('theme') . '"
};
</script>';
}
$output .= recaptcha_get_html($this->getOption('public_key'));
return $output;
}
}
II. Google Recaptcha Validator
Необходимо е да се въведе опцията private_key. private_key се полузава при регистриране на нов домейн в http://www.google.com/recaptcha.
lib/validator/sfWidgetFormGoogleRecaptcha.class
<?php
/**
* Recaptcha validator based on the Google Recaptcha library
*
* @author Stef
*/
class sfValidatorGoogleRecaptcha extends sfValidatorBase
{
public function configure($options = array(), $messages = array())
{
$this->addOption('private_key');
}
public function doClean($value)
{
require_once(sfConfig::get('sf_lib_dir') . '/recaptcha/recaptchalib.php');
$response = recaptcha_check_answer(
$this->getOption('private_key'),
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$response->is_valid) {
throw new sfValidatorError($this, 'invalid');
}
return $value;
}
public function isEmpty($value) {
return false;
}
}
Google Recaptcha се намира в:
Ето и как се използват widget-а и validator-а: lib/recaptcha
// The most awesome Google Recaptcha Widget!!!
$this->widgetSchema['secret'] = new sfWidgetFormGoogleRecaptcha(array(
'public_key' => 'MY_PUBLIC_KEY',
'theme' => 'clean'));
// The most awesome Google Recaptcha Validator!!!
$this->validatorSchema['secret'] = new sfValidatorGoogleRecaptcha(array(
'private_key' => 'MY_PRIVATE_KEY'
), array(
'invalid' => 'The verification words are incorrect.'
));

Твоето мнение