<?php


class sfValidatorReCAPTCHA extends sfValidatorBase
{
    protected function configure($options = array(), $messages = array())
    {
        $this->setMessage('invalid', 'Invalid');

        $this->addOption('keys');
    }

    protected function doClean($value)
    {
        if ($value){
            $post = false;
            $keys = $this->hasOption('keys') ? $this->getOption('keys') : array(
                'site_key' => sfConfig::get("app_reCAPTCHA_site_key"),
                'secret_key' => sfConfig::get("app_reCAPTCHA_secret_key")
            );
            if (is_array($keys) && isset($keys['secret_key']) && $keys['secret_key'] && sfConfig::get('app_reCAPTCHA_siteverify')){
                $post = ProjectUtils::post(sfConfig::get('app_reCAPTCHA_siteverify'), array(
                    'secret' => $keys['secret_key'],
                    'response' => $value
                ));
            }
            if ($post !== false) {
                $decoded_response = json_decode($post, true);
                if ($decoded_response) {
                    if (isset($decoded_response['success']) && $decoded_response['success'] === true) {
                        return $value;
                    }
                }
            }
        }
        throw new sfValidatorError($this, 'invalid');
    }
}
