|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181 |
- <?php
-
-
- namespace yii\captcha;
-
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\helpers\Url;
- use yii\helpers\Html;
- use yii\helpers\Json;
- use yii\widgets\InputWidget;
-
-
- class Captcha extends InputWidget
- {
-
-
- public $captchaAction = 'site/captcha';
-
-
- public $imageOptions = [];
-
-
- public $template = '{image} {input}';
-
-
- public $options = ['class' => 'form-control'];
-
-
-
-
- public function init()
- {
- parent::init();
-
- static::checkRequirements();
-
- if (!isset($this->imageOptions['id'])) {
- $this->imageOptions['id'] = $this->options['id'] . '-image';
- }
- }
-
-
-
- public function run()
- {
- $this->registerClientScript();
- if ($this->hasModel()) {
- $input = Html::activeTextInput($this->model, $this->attribute, $this->options);
- } else {
- $input = Html::textInput($this->name, $this->value, $this->options);
- }
- $route = $this->captchaAction;
- if (is_array($route)) {
- $route['v'] = uniqid();
- } else {
- $route = [$route, 'v' => uniqid()];
- }
- $image = Html::img($route, $this->imageOptions);
- echo strtr($this->template, [
- '{input}' => $input,
- '{image}' => $image,
- ]);
- }
-
-
-
- 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);");
- }
-
-
-
- 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;
- }
-
-
-
- public static function checkRequirements()
- {
- if (extension_loaded('imagick')) {
- $imagickFormats = (new \Imagick())->queryFormats('PNG');
- if (in_array('PNG', $imagickFormats, true)) {
- return 'imagick';
- }
- }
- if (extension_loaded('gd')) {
- $gdInfo = gd_info();
- if (!empty($gdInfo['FreeType Support'])) {
- return 'gd';
- }
- }
- throw new InvalidConfigException('Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required.');
- }
- }
|