|
- <?php
-
-
- namespace yii\captcha;
-
- use Yii;
- use yii\base\Action;
- use yii\base\InvalidConfigException;
- use yii\helpers\Url;
- use yii\web\Response;
-
-
- class CaptchaAction extends Action
- {
-
-
- const REFRESH_GET_VAR = 'refresh';
-
-
-
- public $testLimit = 3;
-
-
- public $width = 120;
-
-
- public $height = 50;
-
-
- public $padding = 2;
-
-
- public $backColor = 0xFFFFFF;
-
-
- public $foreColor = 0x2040A0;
-
-
- public $transparent = false;
-
-
- public $minLength = 6;
-
-
- public $maxLength = 7;
-
-
- public $offset = -2;
-
-
- public $fontFile = '@yii/captcha/SpicyRice.ttf';
-
-
- public $fixedVerifyCode;
-
-
- public $imageLibrary;
-
-
-
-
- public function init()
- {
- $this->fontFile = Yii::getAlias($this->fontFile);
- if (!is_file($this->fontFile)) {
- throw new InvalidConfigException("The font file does not exist: {$this->fontFile}");
- }
- }
-
-
-
- public function run()
- {
- if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
-
- $code = $this->getVerifyCode(true);
- Yii::$app->response->format = Response::FORMAT_JSON;
- return [
- 'hash1' => $this->generateValidationHash($code),
- 'hash2' => $this->generateValidationHash(strtolower($code)),
-
-
- 'url' => Url::to([$this->id, 'v' => uniqid()]),
- ];
- } else {
- $this->setHttpHeaders();
- Yii::$app->response->format = Response::FORMAT_RAW;
- return $this->renderImage($this->getVerifyCode());
- }
- }
-
-
-
- public function generateValidationHash($code)
- {
- for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) {
- $h += ord($code[$i]);
- }
-
- return $h;
- }
-
-
-
- public function getVerifyCode($regenerate = false)
- {
- if ($this->fixedVerifyCode !== null) {
- return $this->fixedVerifyCode;
- }
-
- $session = Yii::$app->getSession();
- $session->open();
- $name = $this->getSessionKey();
- if ($session[$name] === null || $regenerate) {
- $session[$name] = $this->generateVerifyCode();
- $session[$name . 'count'] = 1;
- }
-
- return $session[$name];
- }
-
-
-
- public function validate($input, $caseSensitive)
- {
- $code = $this->getVerifyCode();
- $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0;
- $session = Yii::$app->getSession();
- $session->open();
- $name = $this->getSessionKey() . 'count';
- $session[$name] = $session[$name] + 1;
- if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {
- $this->getVerifyCode(true);
- }
-
- return $valid;
- }
-
-
-
- protected function generateVerifyCode()
- {
- if ($this->minLength > $this->maxLength) {
- $this->maxLength = $this->minLength;
- }
- if ($this->minLength < 3) {
- $this->minLength = 3;
- }
- if ($this->maxLength > 20) {
- $this->maxLength = 20;
- }
- $length = mt_rand($this->minLength, $this->maxLength);
-
- $letters = 'bcdfghjklmnpqrstvwxyz';
- $vowels = 'aeiou';
- $code = '';
- for ($i = 0; $i < $length; ++$i) {
- if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
- $code .= $vowels[mt_rand(0, 4)];
- } else {
- $code .= $letters[mt_rand(0, 20)];
- }
- }
-
- return $code;
- }
-
-
-
- protected function getSessionKey()
- {
- return '__captcha/' . $this->getUniqueId();
- }
-
-
-
- protected function renderImage($code)
- {
- if (isset($this->imageLibrary)) {
- $imageLibrary = $this->imageLibrary;
- } else {
- $imageLibrary = Captcha::checkRequirements();
- }
- if ($imageLibrary === 'gd') {
- return $this->renderImageByGD($code);
- } elseif ($imageLibrary === 'imagick') {
- return $this->renderImageByImagick($code);
- } else {
- throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported");
- }
- }
-
-
-
- protected function renderImageByGD($code)
- {
- $image = imagecreatetruecolor($this->width, $this->height);
-
- $backColor = imagecolorallocate(
- $image,
- (int) ($this->backColor % 0x1000000 / 0x10000),
- (int) ($this->backColor % 0x10000 / 0x100),
- $this->backColor % 0x100
- );
- imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
- imagecolordeallocate($image, $backColor);
-
- if ($this->transparent) {
- imagecolortransparent($image, $backColor);
- }
-
- $foreColor = imagecolorallocate(
- $image,
- (int) ($this->foreColor % 0x1000000 / 0x10000),
- (int) ($this->foreColor % 0x10000 / 0x100),
- $this->foreColor % 0x100
- );
-
- $length = strlen($code);
- $box = imagettfbbox(30, 0, $this->fontFile, $code);
- $w = $box[4] - $box[0] + $this->offset * ($length - 1);
- $h = $box[1] - $box[5];
- $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
- $x = 10;
- $y = round($this->height * 27 / 40);
- for ($i = 0; $i < $length; ++$i) {
- $fontSize = (int) (rand(26, 32) * $scale * 0.8);
- $angle = rand(-10, 10);
- $letter = $code[$i];
- $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
- $x = $box[2] + $this->offset;
- }
-
- imagecolordeallocate($image, $foreColor);
-
- ob_start();
- imagepng($image);
- imagedestroy($image);
-
- return ob_get_clean();
- }
-
-
-
- protected function renderImageByImagick($code)
- {
- $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
- $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));
-
- $image = new \Imagick();
- $image->newImage($this->width, $this->height, $backColor);
-
- $draw = new \ImagickDraw();
- $draw->setFont($this->fontFile);
- $draw->setFontSize(30);
- $fontMetrics = $image->queryFontMetrics($draw, $code);
-
- $length = strlen($code);
- $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
- $h = (int) $fontMetrics['textHeight'] - 8;
- $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
- $x = 10;
- $y = round($this->height * 27 / 40);
- for ($i = 0; $i < $length; ++$i) {
- $draw = new \ImagickDraw();
- $draw->setFont($this->fontFile);
- $draw->setFontSize((int) (rand(26, 32) * $scale * 0.8));
- $draw->setFillColor($foreColor);
- $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]);
- $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
- $x += (int) $fontMetrics['textWidth'] + $this->offset;
- }
-
- $image->setImageFormat('png');
- return $image->getImageBlob();
- }
-
-
-
- protected function setHttpHeaders()
- {
- Yii::$app->getResponse()->getHeaders()
- ->set('Pragma', 'public')
- ->set('Expires', '0')
- ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
- ->set('Content-Transfer-Encoding', 'binary')
- ->set('Content-type', 'image/png');
- }
- }
|