CaptchaAction.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\captcha;
  8. use Yii;
  9. use yii\base\Action;
  10. use yii\base\InvalidConfigException;
  11. use yii\helpers\Url;
  12. use yii\web\Response;
  13. /**
  14. * CaptchaAction renders a CAPTCHA image.
  15. *
  16. * CaptchaAction is used together with [[Captcha]] and [[\yii\captcha\CaptchaValidator]]
  17. * to provide the [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) feature.
  18. *
  19. * By configuring the properties of CaptchaAction, you may customize the appearance of
  20. * the generated CAPTCHA images, such as the font color, the background color, etc.
  21. *
  22. * Note that CaptchaAction requires either GD2 extension or ImageMagick PHP extension.
  23. *
  24. * Using CAPTCHA involves the following steps:
  25. *
  26. * 1. Override [[\yii\web\Controller::actions()]] and register an action of class CaptchaAction with ID 'captcha'
  27. * 2. In the form model, declare an attribute to store user-entered verification code, and declare the attribute
  28. * to be validated by the 'captcha' validator.
  29. * 3. In the controller view, insert a [[Captcha]] widget in the form.
  30. *
  31. * @property string $verifyCode The verification code. This property is read-only.
  32. *
  33. * @author Qiang Xue <qiang.xue@gmail.com>
  34. * @since 2.0
  35. */
  36. class CaptchaAction extends Action
  37. {
  38. /**
  39. * The name of the GET parameter indicating whether the CAPTCHA image should be regenerated.
  40. */
  41. const REFRESH_GET_VAR = 'refresh';
  42. /**
  43. * @var int how many times should the same CAPTCHA be displayed. Defaults to 3.
  44. * A value less than or equal to 0 means the test is unlimited (available since version 1.1.2).
  45. */
  46. public $testLimit = 3;
  47. /**
  48. * @var int the width of the generated CAPTCHA image. Defaults to 120.
  49. */
  50. public $width = 120;
  51. /**
  52. * @var int the height of the generated CAPTCHA image. Defaults to 50.
  53. */
  54. public $height = 50;
  55. /**
  56. * @var int padding around the text. Defaults to 2.
  57. */
  58. public $padding = 2;
  59. /**
  60. * @var int the background color. For example, 0x55FF00.
  61. * Defaults to 0xFFFFFF, meaning white color.
  62. */
  63. public $backColor = 0xFFFFFF;
  64. /**
  65. * @var int the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
  66. */
  67. public $foreColor = 0x2040A0;
  68. /**
  69. * @var bool whether to use transparent background. Defaults to false.
  70. */
  71. public $transparent = false;
  72. /**
  73. * @var int the minimum length for randomly generated word. Defaults to 6.
  74. */
  75. public $minLength = 6;
  76. /**
  77. * @var int the maximum length for randomly generated word. Defaults to 7.
  78. */
  79. public $maxLength = 7;
  80. /**
  81. * @var int the offset between characters. Defaults to -2. You can adjust this property
  82. * in order to decrease or increase the readability of the captcha.
  83. */
  84. public $offset = -2;
  85. /**
  86. * @var string the TrueType font file. This can be either a file path or [path alias](guide:concept-aliases).
  87. */
  88. public $fontFile = '@yii/captcha/SpicyRice.ttf';
  89. /**
  90. * @var string the fixed verification code. When this property is set,
  91. * [[getVerifyCode()]] will always return the value of this property.
  92. * This is mainly used in automated tests where we want to be able to reproduce
  93. * the same verification code each time we run the tests.
  94. * If not set, it means the verification code will be randomly generated.
  95. */
  96. public $fixedVerifyCode;
  97. /**
  98. * @var string the rendering library to use. Currently supported only 'gd' and 'imagick'.
  99. * If not set, library will be determined automatically.
  100. * @since 2.0.7
  101. */
  102. public $imageLibrary;
  103. /**
  104. * Initializes the action.
  105. * @throws InvalidConfigException if the font file does not exist.
  106. */
  107. public function init()
  108. {
  109. $this->fontFile = Yii::getAlias($this->fontFile);
  110. if (!is_file($this->fontFile)) {
  111. throw new InvalidConfigException("The font file does not exist: {$this->fontFile}");
  112. }
  113. }
  114. /**
  115. * Runs the action.
  116. */
  117. public function run()
  118. {
  119. if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
  120. // AJAX request for regenerating code
  121. $code = $this->getVerifyCode(true);
  122. Yii::$app->response->format = Response::FORMAT_JSON;
  123. return [
  124. 'hash1' => $this->generateValidationHash($code),
  125. 'hash2' => $this->generateValidationHash(strtolower($code)),
  126. // we add a random 'v' parameter so that FireFox can refresh the image
  127. // when src attribute of image tag is changed
  128. 'url' => Url::to([$this->id, 'v' => uniqid('', true)]),
  129. ];
  130. }
  131. $this->setHttpHeaders();
  132. Yii::$app->response->format = Response::FORMAT_RAW;
  133. return $this->renderImage($this->getVerifyCode());
  134. }
  135. /**
  136. * Generates a hash code that can be used for client-side validation.
  137. * @param string $code the CAPTCHA code
  138. * @return string a hash code generated from the CAPTCHA code
  139. */
  140. public function generateValidationHash($code)
  141. {
  142. for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) {
  143. $h += ord($code[$i]);
  144. }
  145. return $h;
  146. }
  147. /**
  148. * Gets the verification code.
  149. * @param bool $regenerate whether the verification code should be regenerated.
  150. * @return string the verification code.
  151. */
  152. public function getVerifyCode($regenerate = false)
  153. {
  154. if ($this->fixedVerifyCode !== null) {
  155. return $this->fixedVerifyCode;
  156. }
  157. $session = Yii::$app->getSession();
  158. $session->open();
  159. $name = $this->getSessionKey();
  160. if ($session[$name] === null || $regenerate) {
  161. $session[$name] = $this->generateVerifyCode();
  162. $session[$name . 'count'] = 1;
  163. }
  164. return $session[$name];
  165. }
  166. /**
  167. * Validates the input to see if it matches the generated code.
  168. * @param string $input user input
  169. * @param bool $caseSensitive whether the comparison should be case-sensitive
  170. * @return bool whether the input is valid
  171. */
  172. public function validate($input, $caseSensitive)
  173. {
  174. $code = $this->getVerifyCode();
  175. $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0;
  176. $session = Yii::$app->getSession();
  177. $session->open();
  178. $name = $this->getSessionKey() . 'count';
  179. $session[$name] += 1;
  180. if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {
  181. $this->getVerifyCode(true);
  182. }
  183. return $valid;
  184. }
  185. /**
  186. * Generates a new verification code.
  187. * @return string the generated verification code
  188. */
  189. protected function generateVerifyCode()
  190. {
  191. if ($this->minLength > $this->maxLength) {
  192. $this->maxLength = $this->minLength;
  193. }
  194. if ($this->minLength < 3) {
  195. $this->minLength = 3;
  196. }
  197. if ($this->maxLength > 20) {
  198. $this->maxLength = 20;
  199. }
  200. $length = mt_rand($this->minLength, $this->maxLength);
  201. $letters = 'bcdfghjklmnpqrstvwxyz';
  202. $vowels = 'aeiou';
  203. $code = '';
  204. for ($i = 0; $i < $length; ++$i) {
  205. if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
  206. $code .= $vowels[mt_rand(0, 4)];
  207. } else {
  208. $code .= $letters[mt_rand(0, 20)];
  209. }
  210. }
  211. return $code;
  212. }
  213. /**
  214. * Returns the session variable name used to store verification code.
  215. * @return string the session variable name
  216. */
  217. protected function getSessionKey()
  218. {
  219. return '__captcha/' . $this->getUniqueId();
  220. }
  221. /**
  222. * Renders the CAPTCHA image.
  223. * @param string $code the verification code
  224. * @return string image contents
  225. * @throws InvalidConfigException if imageLibrary is not supported
  226. */
  227. protected function renderImage($code)
  228. {
  229. if (isset($this->imageLibrary)) {
  230. $imageLibrary = $this->imageLibrary;
  231. } else {
  232. $imageLibrary = Captcha::checkRequirements();
  233. }
  234. if ($imageLibrary === 'gd') {
  235. return $this->renderImageByGD($code);
  236. } elseif ($imageLibrary === 'imagick') {
  237. return $this->renderImageByImagick($code);
  238. }
  239. throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported");
  240. }
  241. /**
  242. * Renders the CAPTCHA image based on the code using GD library.
  243. * @param string $code the verification code
  244. * @return string image contents in PNG format.
  245. */
  246. protected function renderImageByGD($code)
  247. {
  248. $image = imagecreatetruecolor($this->width, $this->height);
  249. $backColor = imagecolorallocate(
  250. $image,
  251. (int) ($this->backColor % 0x1000000 / 0x10000),
  252. (int) ($this->backColor % 0x10000 / 0x100),
  253. $this->backColor % 0x100
  254. );
  255. imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
  256. imagecolordeallocate($image, $backColor);
  257. if ($this->transparent) {
  258. imagecolortransparent($image, $backColor);
  259. }
  260. $foreColor = imagecolorallocate(
  261. $image,
  262. (int) ($this->foreColor % 0x1000000 / 0x10000),
  263. (int) ($this->foreColor % 0x10000 / 0x100),
  264. $this->foreColor % 0x100
  265. );
  266. $length = strlen($code);
  267. $box = imagettfbbox(30, 0, $this->fontFile, $code);
  268. $w = $box[4] - $box[0] + $this->offset * ($length - 1);
  269. $h = $box[1] - $box[5];
  270. $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
  271. $x = 10;
  272. $y = round($this->height * 27 / 40);
  273. for ($i = 0; $i < $length; ++$i) {
  274. $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);
  275. $angle = mt_rand(-10, 10);
  276. $letter = $code[$i];
  277. $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
  278. $x = $box[2] + $this->offset;
  279. }
  280. imagecolordeallocate($image, $foreColor);
  281. ob_start();
  282. imagepng($image);
  283. imagedestroy($image);
  284. return ob_get_clean();
  285. }
  286. /**
  287. * Renders the CAPTCHA image based on the code using ImageMagick library.
  288. * @param string $code the verification code
  289. * @return string image contents in PNG format.
  290. */
  291. protected function renderImageByImagick($code)
  292. {
  293. $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
  294. $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));
  295. $image = new \Imagick();
  296. $image->newImage($this->width, $this->height, $backColor);
  297. $draw = new \ImagickDraw();
  298. $draw->setFont($this->fontFile);
  299. $draw->setFontSize(30);
  300. $fontMetrics = $image->queryFontMetrics($draw, $code);
  301. $length = strlen($code);
  302. $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
  303. $h = (int) $fontMetrics['textHeight'] - 8;
  304. $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
  305. $x = 10;
  306. $y = round($this->height * 27 / 40);
  307. for ($i = 0; $i < $length; ++$i) {
  308. $draw = new \ImagickDraw();
  309. $draw->setFont($this->fontFile);
  310. $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));
  311. $draw->setFillColor($foreColor);
  312. $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);
  313. $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
  314. $x += (int) $fontMetrics['textWidth'] + $this->offset;
  315. }
  316. $image->setImageFormat('png');
  317. return $image->getImageBlob();
  318. }
  319. /**
  320. * Sets the HTTP headers needed by image response.
  321. */
  322. protected function setHttpHeaders()
  323. {
  324. Yii::$app->getResponse()->getHeaders()
  325. ->set('Pragma', 'public')
  326. ->set('Expires', '0')
  327. ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
  328. ->set('Content-Transfer-Encoding', 'binary')
  329. ->set('Content-type', 'image/png');
  330. }
  331. }