Browse Source

'captcha' package removed

tags/3.0.0-alpha1
Paul Klimov 7 years ago
parent
commit
0cb91006d5
  1. 152
      framework/captcha/Captcha.php
  2. 191
      framework/captcha/CaptchaAction.php
  3. 33
      framework/captcha/CaptchaAsset.php
  4. 117
      framework/captcha/CaptchaValidator.php
  5. 84
      framework/captcha/Driver.php
  6. 36
      framework/captcha/DriverInterface.php
  7. 82
      framework/captcha/GdDriver.php
  8. 67
      framework/captcha/ImagickDriver.php
  9. 11
      framework/captcha/SpicyRice.md
  10. BIN
      framework/captcha/SpicyRice.ttf
  11. 60
      framework/captcha/VerifyCodeGeneratorTrait.php
  12. 69
      framework/captcha/assets/yii.captcha.js
  13. 86
      tests/framework/captcha/CaptchaActionTest.php
  14. 43
      tests/framework/captcha/CaptchaTest.php
  15. 41
      tests/framework/captcha/GdDriverTest.php
  16. 43
      tests/framework/captcha/ImagickDriverTest.php
  17. 27
      tests/framework/captcha/VerifyCodeGeneratorTraitTest.php

152
framework/captcha/Captcha.php

@ -1,152 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\widgets\InputWidget;
/**
* Captcha renders a CAPTCHA image and an input field that takes user-entered verification code.
*
* Captcha is used together with [[CaptchaAction]] to provide [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) - a way
* of preventing website spamming.
*
* The image element rendered by Captcha will display a CAPTCHA image generated by
* an action whose route is specified by [[captchaAction]]. This action must be an instance of [[CaptchaAction]].
*
* When the user clicks on the CAPTCHA image, it will cause the CAPTCHA image
* to be refreshed with a new CAPTCHA.
*
* You may use [[\yii\captcha\CaptchaValidator]] to validate the user input matches
* the current CAPTCHA verification code.
*
* The following example shows how to use this widget with a model attribute:
*
* ```php
* echo Captcha::widget([
* 'model' => $model,
* 'attribute' => 'captcha',
* ]);
* ```
*
* The following example will use the name property instead:
*
* ```php
* echo Captcha::widget([
* 'name' => 'captcha',
* ]);
* ```
*
* You can also use this widget in an [[\yii\widgets\ActiveForm|ActiveForm]] using the [[\yii\widgets\ActiveField::widget()|widget()]]
* method, for example like this:
*
* ```php
* <?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::class, [
* // configure additional widget properties here
* ]) ?>
* ```
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Captcha extends InputWidget
{
/**
* @var string|array the route of the action that generates the CAPTCHA images.
* The action represented by this route must be an action of [[CaptchaAction]].
* Please refer to [[\yii\helpers\Url::toRoute()]] for acceptable formats.
*/
public $captchaAction = '/site/captcha';
/**
* @var array HTML attributes to be applied to the CAPTCHA image tag.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $imageOptions = [];
/**
* @var string the template for arranging the CAPTCHA image tag and the text input tag.
* In this template, the token `{image}` will be replaced with the actual image tag,
* while `{input}` will be replaced with the text input tag.
*/
public $template = '{image} {input}';
/**
* @var array the HTML attributes for the input tag.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $options = ['class' => 'form-control'];
/**
* Initializes the widget.
*/
public function init()
{
parent::init();
if (!isset($this->imageOptions['id'])) {
$this->imageOptions['id'] = $this->options['id'] . '-image';
}
}
/**
* Renders the widget.
*/
public function run()
{
$this->registerClientScript();
$input = $this->renderInputHtml('text');
$route = $this->captchaAction;
if (is_array($route)) {
$route['v'] = uniqid();
} else {
$route = [$route, 'v' => uniqid()];
}
$image = Html::img($route, $this->imageOptions);
return strtr($this->template, [
'{input}' => $input,
'{image}' => $image,
]);
}
/**
* Registers the needed JavaScript.
*/
public function registerClientScript()
{
$options = $this->getClientOptions();
$options = empty($options) ? '' : Json::htmlEncode($options);
$id = $this->imageOptions['id'];
$view = $this->getView();
CaptchaAsset::register($view);
$view->registerJs("jQuery('#$id').yiiCaptcha($options);");
}
/**
* Returns the options for the captcha JS widget.
* @return array the options
*/
protected function getClientOptions()
{
$route = $this->captchaAction;
if (is_array($route)) {
$route[CaptchaAction::REFRESH_GET_VAR] = 1;
} else {
$route = [$route, CaptchaAction::REFRESH_GET_VAR => 1];
}
$options = [
'refreshUrl' => Url::toRoute($route),
'hashKey' => 'yiiCaptcha/' . trim($route[0], '/'),
];
return $options;
}
}

191
framework/captcha/CaptchaAction.php

@ -1,191 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use Yii;
use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\di\Instance;
use yii\helpers\Url;
use yii\web\Response;
/**
* CaptchaAction renders a CAPTCHA image.
*
* CaptchaAction is used together with [[Captcha]] and [[\yii\captcha\CaptchaValidator]]
* to provide the [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) feature.
*
* You should configure [[driver]] with the actual CAPTCHA rendering driver to be used.
* Note that different drivers may require different libraries or PHP extension installed.
* Please refer to the particular driver class for details.
*
* Using CAPTCHA involves the following steps:
*
* 1. Override [[\yii\web\Controller::actions()]] and register an action of class CaptchaAction with ID 'captcha'
* 2. In the form model, declare an attribute to store user-entered verification code, and declare the attribute
* to be validated by the 'captcha' validator.
* 3. In the controller view, insert a [[Captcha]] widget in the form.
*
* @property string $verifyCode The verification code. This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class CaptchaAction extends Action
{
/**
* The name of the GET parameter indicating whether the CAPTCHA image should be regenerated.
*/
const REFRESH_GET_VAR = 'refresh';
/**
* @var int how many times should the same CAPTCHA be displayed. Defaults to 3.
* A value less than or equal to 0 means the test is unlimited.
*/
public $testLimit = 3;
/**
* @var string the fixed verification code. When this property is set,
* [[getVerifyCode()]] will always return the value of this property.
* This is mainly used in automated tests where we want to be able to reproduce
* the same verification code each time we run the tests.
* If not set, it means the verification code will be randomly generated.
*/
public $fixedVerifyCode;
/**
* @var DriverInterface|array|string the driver to be used for CAPTCHA rendering. It could be either an instance
* of [[DriverInterface]] or its DI compatible configuration.
* For example:
*
* ```php
* [
* 'class' => \yii\captcha\ImagickDriver::class,
* // 'backColor' => 0xFFFFFF,
* // 'foreColor' => 0x2040A0,
* ]
* ```
*
* After the action object is created, if you want to change this property, you should assign it
* with a [[DriverInterface]] object only.
* @since 2.1.0
*/
public $driver;
/**
* Initializes the action.
* @throws InvalidConfigException if the font file does not exist.
*/
public function init()
{
parent::init();
$this->driver = Instance::ensure($this->driver, DriverInterface::class);
}
/**
* Runs the action.
*/
public function run()
{
if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
// AJAX request for regenerating code
$code = $this->getVerifyCode(true);
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'hash1' => $this->generateValidationHash($code),
'hash2' => $this->generateValidationHash(strtolower($code)),
// we add a random 'v' parameter so that FireFox can refresh the image
// when src attribute of image tag is changed
'url' => Url::to([$this->id, 'v' => uniqid()]),
];
}
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
return $this->driver->renderImage($this->getVerifyCode());
}
/**
* Generates a hash code that can be used for client-side validation.
* @param string $code the CAPTCHA code
* @return string a hash code generated from the CAPTCHA code
*/
public function generateValidationHash($code)
{
for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) {
$h += ord($code[$i]);
}
return $h;
}
/**
* Gets the verification code.
* @param bool $regenerate whether the verification code should be regenerated.
* @return string the verification code.
*/
public function getVerifyCode($regenerate = false)
{
if ($this->fixedVerifyCode !== null) {
return $this->fixedVerifyCode;
}
$session = Yii::$app->getSession();
$session->open();
$name = $this->getSessionKey();
if ($session->get($name) === null || $regenerate) {
$session->set($name, $this->driver->generateVerifyCode());
$session->set($name . 'count', 1);
}
return $session->get($name);
}
/**
* Validates the input to see if it matches the generated code.
* @param string $input user input
* @param bool $caseSensitive whether the comparison should be case-sensitive
* @return bool whether the input is valid
*/
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;
}
/**
* Returns the session variable name used to store verification code.
* @return string the session variable name
*/
protected function getSessionKey()
{
return '__captcha/' . $this->getUniqueId();
}
/**
* Sets the HTTP headers needed by image response.
*/
protected function setHttpHeaders()
{
$response = Yii::$app->getResponse();
$response->setHeader('Pragma', 'public');
$response->setHeader('Expires', '0');
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-type', $this->driver->getImageMimeType());
}
}

33
framework/captcha/CaptchaAsset.php

@ -1,33 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use yii\web\AssetBundle;
use yii\jquery\YiiAsset;
/**
* This asset bundle provides the javascript files needed for the [[Captcha]] widget.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class CaptchaAsset extends AssetBundle
{
/**
* {@inheritdoc}
*/
public $sourcePath = '@yii/captcha/assets';
/**
* {@inheritdoc}
*/
public $js = ['yii.captcha.js',];
/**
* {@inheritdoc}
*/
public $depends = [YiiAsset::class];
}

117
framework/captcha/CaptchaValidator.php

@ -1,117 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use Yii;
use yii\base\InvalidConfigException;
use yii\validators\ValidationAsset;
use yii\validators\Validator;
/**
* CaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
*
* CaptchaValidator should be used together with [[CaptchaAction]].
*
* Note that once CAPTCHA validation succeeds, a new CAPTCHA will be generated automatically. As a result,
* CAPTCHA validation should not be used in AJAX validation mode because it may fail the validation
* even if a user enters the same code as shown in the CAPTCHA image which is actually different from the latest CAPTCHA code.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class CaptchaValidator extends Validator
{
/**
* @var bool whether to skip this validator if the input is empty.
*/
public $skipOnEmpty = false;
/**
* @var bool whether the comparison is case sensitive. Defaults to false.
*/
public $caseSensitive = false;
/**
* @var string the route of the controller action that renders the CAPTCHA image.
*/
public $captchaAction = 'site/captcha';
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = Yii::t('yii', 'The verification code is incorrect.');
}
}
/**
* {@inheritdoc}
*/
protected function validateValue($value)
{
$captcha = $this->createCaptchaAction();
$valid = !is_array($value) && $captcha->validate($value, $this->caseSensitive);
return $valid ? null : [$this->message, []];
}
/**
* Creates the CAPTCHA action object from the route specified by [[captchaAction]].
* @return \yii\captcha\CaptchaAction the action object
* @throws InvalidConfigException
*/
public function createCaptchaAction()
{
$ca = Yii::$app->createController($this->captchaAction);
if ($ca !== false) {
/* @var $controller \yii\base\Controller */
[$controller, $actionID] = $ca;
$action = $controller->createAction($actionID);
if ($action !== null) {
return $action;
}
}
throw new InvalidConfigException('Invalid CAPTCHA action ID: ' . $this->captchaAction);
}
/**
* {@inheritdoc}
*/
public function clientValidateAttribute($model, $attribute, $view)
{
ValidationAsset::register($view);
$options = $this->getClientOptions($model, $attribute);
return 'yii.validation.captcha(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
}
/**
* {@inheritdoc}
*/
public function getClientOptions($model, $attribute)
{
$captcha = $this->createCaptchaAction();
$code = $captcha->getVerifyCode(false);
$hash = $captcha->generateValidationHash($this->caseSensitive ? $code : strtolower($code));
$options = [
'hash' => $hash,
'hashKey' => 'yiiCaptcha/' . $captcha->getUniqueId(),
'caseSensitive' => $this->caseSensitive,
'message' => Yii::$app->getI18n()->format($this->message, [
'attribute' => $model->getAttributeLabel($attribute),
], Yii::$app->language),
];
if ($this->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
}
}

84
framework/captcha/Driver.php

@ -1,84 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
/**
* Driver is the base class for CAPTCHA rendering driver classes.
*
* By configuring the properties of Driver, you may customize the appearance of
* the generated CAPTCHA images, such as the font color, the background color, etc.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.1.0
*/
abstract class Driver extends Component implements DriverInterface
{
use VerifyCodeGeneratorTrait;
/**
* @var int the width of the generated CAPTCHA image. Defaults to 120.
*/
public $width = 120;
/**
* @var int the height of the generated CAPTCHA image. Defaults to 50.
*/
public $height = 50;
/**
* @var int padding around the text. Defaults to 2.
*/
public $padding = 2;
/**
* @var int the offset between characters. Defaults to -2. You can adjust this property
* in order to decrease or increase the readability of the captcha.
*/
public $offset = -2;
/**
* @var int the background color. For example, 0x55FF00.
* Defaults to 0xFFFFFF, meaning white color.
*/
public $backColor = 0xFFFFFF;
/**
* @var int the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
*/
public $foreColor = 0x2040A0;
/**
* @var bool whether to use transparent background. Defaults to false.
*/
public $transparent = false;
/**
* @var string the TrueType font file. This can be either a file path or [path alias](guide:concept-aliases).
*/
public $fontFile = '@yii/captcha/SpicyRice.ttf';
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
$this->fontFile = Yii::getAlias($this->fontFile);
if (!is_file($this->fontFile)) {
throw new InvalidConfigException("The font file does not exist: {$this->fontFile}");
}
}
/**
* {@inheritdoc}
*/
public function getImageMimeType()
{
return 'image/png';
}
}

36
framework/captcha/DriverInterface.php

@ -1,36 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
/**
* DriverInterface defines the common interface to be implemented by CAPTCHA rendering drivers.
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.1.0
*/
interface DriverInterface
{
/**
* Generates new CAPTCHA code.
* @return string CAPTCHA code.
*/
public function generateVerifyCode();
/**
* Renders the CAPTCHA image.
* @param string $code CAPTCHA code
* @return string image binary source.
*/
public function renderImage($code);
/**
* Returns image MIME type for the content generated by [[renderImage()]].
* @return string image MIME type.
*/
public function getImageMimeType();
}

82
framework/captcha/GdDriver.php

@ -1,82 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use yii\base\InvalidConfigException;
/**
* GdDriver renders the CAPTCHA image based on the code using [GD](http://php.net/manual/en/book.image.php) library.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.1.0
*/
class GdDriver extends Driver
{
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if (!extension_loaded('gd') || (($gdInfo = gd_info()) && empty($gdInfo['FreeType Support']))) {
throw new InvalidConfigException('GD PHP extension with FreeType support is required.');
}
}
/**
* {@inheritdoc}
*/
public function renderImage($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) (random_int(26, 32) * $scale * 0.8);
$angle = random_int(-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();
}
}

67
framework/captcha/ImagickDriver.php

@ -1,67 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
use yii\base\InvalidConfigException;
/**
* ImagickDriver renders the CAPTCHA image based on the code using [ImageMagick](http://php.net/manual/en/book.imagick.php) library.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.1.0
*/
class ImagickDriver extends Driver
{
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if (!extension_loaded('imagick') || !in_array('PNG', (new \Imagick())->queryFormats('PNG'), true)) {
throw new InvalidConfigException('ImageMagick PHP extension with PNG support is required.');
}
}
/**
* {@inheritdoc}
*/
public function renderImage($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) (random_int(26, 32) * $scale * 0.8));
$draw->setFillColor($foreColor);
$image->annotateImage($draw, $x, $y, random_int(-10, 10), $code[$i]);
$fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
$x += (int) $fontMetrics['textWidth'] + $this->offset;
}
$image->setImageFormat('png');
return $image->getImageBlob();
}
}

11
framework/captcha/SpicyRice.md

@ -1,11 +0,0 @@
## Spicy Rice font
* **Author:** Brian J. Bonislawsky, Astigmatic (AOETI, Astigmatic One Eye Typographic Institute)
* **License:** SIL Open Font License (OFL), version 1.1, [notes and FAQ](http://scripts.sil.org/OFL)
## Links
* [Astigmatic](http://www.astigmatic.com/)
* [Google WebFonts](http://www.google.com/webfonts/specimen/Spicy+Rice)
* [fontsquirrel.com](http://www.fontsquirrel.com/fonts/spicy-rice)
* [fontspace.com](http://www.fontspace.com/astigmatic-one-eye-typographic-institute/spicy-rice)

BIN
framework/captcha/SpicyRice.ttf

Binary file not shown.

60
framework/captcha/VerifyCodeGeneratorTrait.php

@ -1,60 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\captcha;
/**
* VerifyCodeGeneratorTrait provides configurable implementation for [[DriverInterface::generateVerifyCode()]].
* This trait should be used at the class, which implements [[DriverInterface]].
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.1.0
*/
trait VerifyCodeGeneratorTrait
{
/**
* @var int the minimum length for randomly generated word. Defaults to 6.
*/
public $minLength = 6;
/**
* @var int the maximum length for randomly generated word. Defaults to 7.
*/
public $maxLength = 7;
/**
* Generates new CAPTCHA code.
* @return string CAPTCHA code.
*/
public 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 = random_int($this->minLength, $this->maxLength);
$letters = 'bcdfghjklmnpqrstvwxyz';
$vowels = 'aeiou';
$code = '';
for ($i = 0; $i < $length; ++$i) {
if ($i % 2 && random_int(0, 10) > 2 || !($i % 2) && random_int(0, 10) > 9) {
$code .= $vowels[random_int(0, 4)];
} else {
$code .= $letters[random_int(0, 20)];
}
}
return $code;
}
}

69
framework/captcha/assets/yii.captcha.js

@ -1,69 +0,0 @@
/**
* Yii Captcha widget.
*
* This is the JavaScript widget used by the yii\captcha\Captcha widget.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
(function ($) {
$.fn.yiiCaptcha = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist in jQuery.yiiCaptcha');
return false;
}
};
var defaults = {
refreshUrl: undefined,
hashKey: undefined
};
var methods = {
init: function (options) {
return this.each(function () {
var $e = $(this);
var settings = $.extend({}, defaults, options || {});
$e.data('yiiCaptcha', {
settings: settings
});
$e.on('click.yiiCaptcha', function () {
methods.refresh.apply($e);
return false;
});
});
},
refresh: function () {
var $e = this,
settings = this.data('yiiCaptcha').settings;
$.ajax({
url: $e.data('yiiCaptcha').settings.refreshUrl,
dataType: 'json',
cache: false,
success: function (data) {
$e.attr('src', data.url);
$('body').data(settings.hashKey, [data.hash1, data.hash2]);
}
});
},
destroy: function () {
this.off('.yiiCaptcha');
this.removeData('yiiCaptcha');
return this;
},
data: function () {
return this.data('yiiCaptcha');
}
};
})(window.jQuery);

86
tests/framework/captcha/CaptchaActionTest.php

@ -1,86 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\captcha;
use Yii;
use yii\captcha\CaptchaAction;
use yii\captcha\Driver;
use yii\web\Controller;
use yii\web\Response;
use yiiunit\TestCase;
class CaptchaActionTest extends TestCase
{
protected function setUp()
{
parent::setUp();
$this->mockWebApplication();
$_SERVER['REQUEST_URI'] = 'http://example.com/';
}
/**
* @param array $config controller config.
* @return Controller controller instance.
*/
protected function createController($config = [])
{
return Yii::$app->controller = new Controller('test', Yii::$app, $config);
}
public function testRun()
{
/* @var $driver Driver|\PHPUnit_Framework_MockObject_MockObject */
$driver = $this->getMockBuilder(Driver::class)
->setMethods(['renderImage'])
->getMock();
$driver->expects($this->any())
->method('renderImage')
->willReturn('test image binary');
$action = new CaptchaAction('test', $this->createController(), [
'driver' => $driver
]);
$response = $action->run();
$this->assertEquals('test image binary', $response);
/* @var $response Response */
$response = Yii::$app->response;
$this->assertEquals(Response::FORMAT_RAW, $response->format);
$this->assertEquals([$driver->getImageMimeType()], $response->getHeader('Content-type'));
$this->assertEquals(['binary'], $response->getHeader('Content-Transfer-Encoding'));
$this->assertEquals(['public'], $response->getHeader('Pragma'));
$this->assertEquals(['0'], $response->getHeader('Expires'));
$this->assertEquals(['must-revalidate, post-check=0, pre-check=0'], $response->getHeader('Cache-Control'));
}
public function testRunRefresh()
{
/* @var $driver Driver|\PHPUnit_Framework_MockObject_MockObject */
$driver = $this->getMockBuilder(Driver::class)
->getMockForAbstractClass();
$action = new CaptchaAction('test', $this->createController(), [
'driver' => $driver
]);
//var_dump($action->getVerifyCode(true));
Yii::$app->request->setQueryParams([CaptchaAction::REFRESH_GET_VAR => true]);
$response = $action->run();
$this->assertArrayHasKey('hash1', $response);
$this->assertArrayHasKey('hash2', $response);
$this->assertContains('/index.php?r=test%2Ftest', $response['url']);
/* @var $response Response */
$response = Yii::$app->response;
$this->assertEquals(Response::FORMAT_JSON, $response->format);
}
}

43
tests/framework/captcha/CaptchaTest.php

@ -1,43 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\captcha;
use yii\captcha\Captcha;
use yii\web\AssetManager;
use yii\jquery\JqueryAsset;
use yiiunit\TestCase;
class CaptchaTest extends TestCase
{
protected function setUp()
{
parent::setUp();
$this->mockWebApplication([
'components' => [
'assetManager' => [
'class' => AssetManager::class,
'bundles' => [
JqueryAsset::class => false,
],
],
],
]);
$_SERVER['REQUEST_URI'] = 'http://example.com/';
}
public function testRender()
{
$output = Captcha::widget([
'id' => 'test-id',
'name' => 'testInput',
]);
$this->assertContains('<img id="test-id-image" src="/index.php?r=site%2Fcaptcha', $output);
$this->assertContains('<input type="text" id="test-id" class="form-control" name="testInput">', $output);
}
}

41
tests/framework/captcha/GdDriverTest.php

@ -1,41 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\captcha;
use yii\captcha\GdDriver;
use yiiunit\TestCase;
class GdDriverTest extends TestCase
{
/**
* {@inheritdoc}
*/
protected function setUp()
{
if (!extension_loaded('gd') || ($gdInfo = gd_info() && empty($gdInfo['FreeType Support']))) {
$this->markTestSkipped('GD PHP extension with FreeType support is required.');
}
parent::setUp();
}
public function testRenderImage()
{
$driver = new GdDriver();
$driver->width = 222;
$driver->height = 111;
$imageBinary = $driver->renderImage('test');
$this->assertNotEmpty($imageBinary);
$size = getimagesizefromstring($imageBinary);
$this->assertEquals($driver->width, $size[0]);
$this->assertEquals($driver->height, $size[1]);
$this->assertEquals($driver->getImageMimeType(), $size['mime']);
}
}

43
tests/framework/captcha/ImagickDriverTest.php

@ -1,43 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\captcha;
use yii\captcha\ImagickDriver;
use yiiunit\TestCase;
class ImagickDriverTest extends TestCase
{
/**
* {@inheritdoc}
*/
protected function setUp()
{
if (!extension_loaded('imagick') || !in_array('PNG', (new \Imagick())->queryFormats('PNG'), true)) {
$this->markTestSkipped('GD PHP extension with FreeType support is required.');
}
parent::setUp();
}
public function testRenderImage()
{
$driver = new ImagickDriver();
$driver->width = 222;
$driver->height = 111;
$imageBinary = $driver->renderImage('test');
$this->assertNotEmpty($imageBinary);
$imagick = new \Imagick();
$imagick->readImageBlob($imageBinary);
$this->assertEquals($driver->width, $imagick->getImageWidth());
$this->assertEquals($driver->height, $imagick->getImageHeight());
$this->assertEquals($driver->getImageMimeType(), $imagick->getImageMimeType());
}
}

27
tests/framework/captcha/VerifyCodeGeneratorTraitTest.php

@ -1,27 +0,0 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\captcha;
use yii\captcha\Driver;
use yiiunit\TestCase;
class VerifyCodeGeneratorTraitTest extends TestCase
{
public function testGenerateVerifyCode()
{
/* @var $driver Driver */
$driver = $this->getMockBuilder(Driver::class)
->getMockForAbstractClass();
$this->assertNotEmpty($driver->generateVerifyCode());
$driver->minLength = 10;
$driver->maxLength = 10;
$this->assertEquals(10, strlen($driver->generateVerifyCode()));
}
}
Loading…
Cancel
Save