response = $this->generate_challenge(); Event::add('system.post_controller', array($this, 'update_response_session')); } abstract public function generate_challenge(); abstract public function render($html); public function update_response_session() { Session::instance()->set('captcha_response', sha1(strtoupper($this->response))); } public function valid($response) { return (sha1(strtoupper($response)) === Session::instance()->get('captcha_response')); } public function image_type($filename) { switch (strtolower(substr(strrchr($filename, '.'), 1))) { case 'png': return 'png'; case 'gif': return 'gif'; case 'jpg': case 'jpeg': return 'jpeg'; default: return FALSE; } } public function image_create($background = NULL) { if ( ! function_exists('imagegd2')) throw new Kohana_Exception('captcha.requires_GD2'); $this->image = imagecreatetruecolor(Captcha::$config['width'], Captcha::$config['height']); if ( ! empty($background)) { $function = 'imagecreatefrom'.$this->image_type($background); $this->background_image = $function($background); if (imagesx($this->background_image) !== Captcha::$config['width'] OR imagesy($this->background_image) !== Captcha::$config['height']) { imagecopyresampled ( $this->image, $this->background_image, 0, 0, 0, 0, Captcha::$config['width'], Captcha::$config['height'], imagesx($this->background_image), imagesy($this->background_image) ); } imagedestroy($this->background_image); } } public function image_gradient($color1, $color2, $direction = NULL) { $directions = array('horizontal', 'vertical'); if ( ! in_array($direction, $directions)) { $direction = $directions[array_rand($directions)]; if (mt_rand(0, 1) === 1) { $temp = $color1; $color1 = $color2; $color2 = $temp; } } $color1 = imagecolorsforindex($this->image, $color1); $color2 = imagecolorsforindex($this->image, $color2); $steps = ($direction === 'horizontal') ? Captcha::$config['width'] : Captcha::$config['height']; $r1 = ($color1['red'] - $color2['red']) / $steps; $g1 = ($color1['green'] - $color2['green']) / $steps; $b1 = ($color1['blue'] - $color2['blue']) / $steps; if ($direction === 'horizontal') { $x1 =& $i; $y1 = 0; $x2 =& $i; $y2 = Captcha::$config['height']; } else { $x1 = 0; $y1 =& $i; $x2 = Captcha::$config['width']; $y2 =& $i; } for ($i = 0; $i <= $steps; $i++) { $r2 = $color1['red'] - floor($i * $r1); $g2 = $color1['green'] - floor($i * $g1); $b2 = $color1['blue'] - floor($i * $b1); $color = imagecolorallocate($this->image, $r2, $g2, $b2); imageline($this->image, $x1, $y1, $x2, $y2, $color); } } public function image_render($html) { if ($html) return 'Captcha'; header('Content-Type: image/'.$this->image_type); $function = 'image'.$this->image_type; $function($this->image); imagedestroy($this->image); } }