Go to the documentation of this file.00001 <?php
00032 class axCaptcha {
00033
00038 protected $_options;
00039
00044 protected $_dictionnary_struct;
00045
00050 protected $_session;
00051
00056 public function __construct (array $options = array()) {
00057 $default = array(
00058 'dictionnaries_path' => null,
00059 'dictionnary' => 'static.dictionary.ini',
00060 'dictionnary_type' => 'static',
00061 );
00062
00063 $this->_config = $config + $default;
00064 }
00065
00076 protected function _parseDictionnary ($path) {
00077 if (!$this->_dictionnary_struct = parse_ini_file($path, true))
00078 throw new RuntimeException("Cannot parse {$path}");
00079 }
00080
00091 public function generate ($lang) {
00092 if (empty($this->_dictionnary_struct)) {
00093 if (!is_file($path = realpath($this->_config['dictionnaries_path']) . '/' . $this->_config['dictionnary']))
00094 throw new axMissingFileException($path);
00095
00096 $this->_parseDictionnary($path);
00097 }
00098
00099 if (empty($this->_session)) {
00100 $this->_session = new axSession;
00101 $this->_session->start();
00102 }
00103
00104 if (empty($this->_dictionnary_struct[$lang]))
00105 throw new RuntimeException("Dictionnary does not provide any data for {$lang} language");
00106
00107 $question = array_rand($this->_dictionnary_struct[$lang]);
00108
00109 if ($this->_config['dictionnary_type'] == 'static') {
00110 $answer = array_map('strtolower', array_map('trim', explode(',', $this->_dictionnary_struct[$lang][$question])));
00111 }
00112 elseif ($this->_config['dictionnary_type'] == 'dynamic') {
00113 if (!$alpha = callback($this->_dictionnary_struct[$lang][$question]))
00114 throw new RuntimeException("Cannot understand alpha function definition");
00115
00116 $argc = substr_count($question, '%d');
00117 $argv = array();
00118 for ($i=0; $i<$argc; $i++)
00119 $argv[] = rand(0,9);
00120
00121 $answer = array(call_user_func_array($alpha, $argv));
00122 array_unshift($argv, $question);
00123 $question = call_user_func_array('sprintf', $argv);
00124 }
00125 else {
00126 throw new RuntimeException("Unrecognized dictionnary type " . $this->_config['dictionnary_type']);
00127 }
00128
00129 $this->_session->captcha_ans = $answer;
00130 return $question;
00131 }
00132
00142 public function verify ($answer) {
00143 if (empty($this->_session)) {
00144 $this->_session = new axSession;
00145 $this->_session->start();
00146 }
00147
00148 return in_array(strtolower(trim($answer)), $this->_session->captcha_ans);
00149 }
00150 }
00151
00152 if (!function_exists('callback')) {
00166 function callback ($fct) {
00167 if (!preg_match('~(function)?\s*\((?P<args>[^\)]*)\)\s*\{(?P<code>.*)\}~', $fct, $matches))
00168 return false;
00169
00170 $args = $matches['args'];
00171 $code = $matches['code'];
00172 return create_function($args, $code);
00173 }
00174 }