Написал небольшой класс для приложения на Yii2, который расширяет стандартный yii\captcha\CaptchaAction. С его помощью мы сможем использовать captcha, в сгенерированном тексте которой будет прописано математическое выражение, вместо обычного текста. Для успешной отправки формы требуется ввести ответ на математическое выражение.

Список доступных операций:
1) Вычитание.
2) Сложение.
3) Умножение.
По умолчанию будут генерироваться изображения с операцией сложения или вычитания случайным образом.
Исходный код:
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
| <?php
namespace app\components\actions;
use yii\captcha\CaptchaAction;
use yii\base\InvalidConfigException;
/**
* Class implements advanced captcha action with mathematical expressions. Based on [[yii\captcha\CaptchaAction]].
* @see yii\captcha\CaptchaAction
* @link https://github.com/samdark/yii2-cookbook/blob/master/book/forms-captcha.md
* @author long399 <long399@mail.ru>
*/
class MathCaptchaAction extends CaptchaAction
{
/** @var int minimal value for generating code */
public $minLength = 0;
/** @var int maximal value for generating code */
public $maxLength = 100;
/** @var array operations list for captcha */
public $operations = ['+', '-'];
/** @var array available operarations list for captcha */
const AVAILABLE_OPERATIONS = ['+', '-', '*'];
/**
* {@inheritDoc}
* @see \yii\captcha\CaptchaAction::init()
*/
public function init()
{
parent::init();
if (!is_array($this->operations)) {
throw new InvalidConfigException('The "operations" property must be an array.');
}
foreach($this->operations as $operation) {
if (!in_array($operation, self::AVAILABLE_OPERATIONS)) {
throw new InvalidConfigException(
'The "operations" property may contains only ['.implode(', ', self::AVAILABLE_OPERATIONS).'] operations.'
);
}
}
}
/**
* {@inheritdoc}
*/
protected function generateVerifyCode()
{
return mt_rand((int)$this->minLength, (int)$this->maxLength);
}
/**
* {@inheritdoc}
*/
protected function renderImage($code)
{
return parent::renderImage($this->getText($code));
}
/**
* Get mathematical expression for image rendering.
* @param string $code
* @return string
*/
protected function getText($code)
{
$code = (int)$code;
$rand = mt_rand(min(1, $code - 1), max(1, $code - 1));
$operation = mt_rand(0, count($this->operations) - 1);
switch($this->operations[$operation]) {
case '+': return ($code - $rand).' + '.$rand;
case '-': return ($code + $rand).' - '.$rand;
case '*':
$sign = mt_rand(0, 1); // operation sign for subexpression
$whole = (int)($code / $rand);
switch ($sign) {
case 0: // plus
$reminder = $code % $rand;
break;
case 1: // minus
$whole++;
$reminder = $whole * $rand - $code;
}
$str = $whole.' * '.$rand;
if ($reminder) $str .= ($sign == 1 ? ' - ' : ' + ').$reminder;
return $str;
}
}
} |
|
Применение:
controller:
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
| public function actions()
{
return [
...
'captcha' => [
'class' => \app\components\actions\MathCaptchaAction::class,
'fixedVerifyCode' => YII_ENV_TEST ? '399' : null,
'minLength' => 0,
'maxLength' => 1000,
],
...
];
} |
|
model:
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
| class MyModel extends \yii\db\ActiveRecord
{
public $captcha;
...
public function rules()
{
return [
...
['captcha', 'captcha', 'captchaAction' => '/site/captcha'],
...
];
}
...
} |
|
view:
| PHP | 1
2
3
4
5
6
| ...
echo $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::class, [
'captchaAction' => "/site/captcha",
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]);
... |
|
Если вы, например, захотите использовать только выражения с операцией вычитания, тогда вам нужно задать соответствующим образом свойство operations в описании действия в контроллере:
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
| public function actions()
{
return [
...
'captcha' => [
'class' => \app\components\actions\MathCaptchaAction::class,
'fixedVerifyCode' => YII_ENV_TEST ? '399' : null,
'minLength' => 0,
'maxLength' => 1000,
'operations' => ['-'],
],
...
];
} |
|
Выражения с умножением:
Если вы, захотите использовать также выражения с операцией умножения, тогда вам нужно задать соответствующим образом свойство operations в описании действия в контроллере:
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
| public function actions()
{
return [
...
'captcha' => [
'class' => \app\components\actions\MathCaptchaAction::class,
'fixedVerifyCode' => YII_ENV_TEST ? '399' : null,
'minLength' => 0,
'maxLength' => 1000,
'operations' => ['+', '-', '*'],
],
...
];
} |
|
Для операции умножения могут быть сгенерированы выражения трех видов:
1) Выражение с умножением.

2) Выражение с умножением и сложением.

3) Выражение с умножением и вычитанием.

Ссылка на репозиторий.
|