1: <?php
  2: 
  3:   4:   5: 
  6: class Quform_Validator_Captcha extends Quform_Validator_Abstract
  7: {
  8:     const INVALID = 'captchaInvalid';
  9:     const NOT_MATCH = 'captchaNotMatch';
 10: 
 11:      12:  13: 
 14:     protected $session;
 15: 
 16:      17:  18:  19:  20:  21: 
 22:     public function __construct(array $options = array())
 23:     {
 24:         if ( ! array_key_exists('session', $options) || ! ($options['session'] instanceof Quform_Session)) {
 25:             throw new InvalidArgumentException('Session instance is required for the Captcha validator');
 26:         }
 27: 
 28:         $this->session = $options['session'];
 29:         unset($options['session']);
 30: 
 31:         parent::__construct($options);
 32:     }
 33: 
 34:      35:  36:  37:  38:  39: 
 40:     public function isValid($value)
 41:     {
 42:         $this->reset();
 43: 
 44:         if ( ! is_string($value)) {
 45:             $this->error(self::INVALID);
 46:             return false;
 47:         }
 48: 
 49:         $code = $this->session->get($this->config('sessionKey'));
 50: 
 51:         if (is_string($code) && strtolower($code) == strtolower($value)) {
 52:             return true;
 53:         }
 54: 
 55:         $this->error(self::NOT_MATCH);
 56:         return false;
 57:     }
 58: 
 59:      60:  61:  62:  63:  64: 
 65:     public static function getMessageTemplates($key = null)
 66:     {
 67:         $messageTemplates = array(
 68:             self::INVALID => __('Invalid data type, string expected',  'quform'),
 69:             self::NOT_MATCH => __('The value does not match',  'quform')
 70:         );
 71: 
 72:         if (is_string($key)) {
 73:             return array_key_exists($key, $messageTemplates) ? $messageTemplates[$key] : null;
 74:         }
 75: 
 76:         return $messageTemplates;
 77:     }
 78: 
 79:      80:  81:  82:  83:  84: 
 85:     public static function getDefaultConfig($key = null)
 86:     {
 87:         $config = apply_filters('quform_default_config_validator_captcha', array(
 88:             'sessionKey' => '',
 89:             'messages' => array(
 90:                 self::INVALID => '',
 91:                 self::NOT_MATCH => ''
 92:             )
 93:         ));
 94: 
 95:         $config['type'] = 'captcha';
 96: 
 97:         if (Quform::isNonEmptyString($key)) {
 98:             return Quform::get($config, $key);
 99:         }
100: 
101:         return $config;
102:     }
103: }
104: