Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

CaptchaAction.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 integer 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 integer the width of the generated CAPTCHA image. Defaults to 120.
  49. */
  50. public $width = 120;
  51. /**
  52. * @var integer the height of the generated CAPTCHA image. Defaults to 50.
  53. */
  54. public $height = 50;
  55. /**
  56. * @var integer padding around the text. Defaults to 2.
  57. */
  58. public $padding = 2;
  59. /**
  60. * @var integer the background color. For example, 0x55FF00.
  61. * Defaults to 0xFFFFFF, meaning white color.
  62. */
  63. public $backColor = 0xFFFFFF;
  64. /**
  65. * @var integer the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
  66. */
  67. public $foreColor = 0x2040A0;
  68. /**
  69. * @var boolean whether to use transparent background. Defaults to false.
  70. */
  71. public $transparent = false;
  72. /**
  73. * @var integer the minimum length for randomly generated word. Defaults to 6.
  74. */
  75. public $minLength = 6;
  76. /**
  77. * @var integer the maximum length for randomly generated word. Defaults to 7.
  78. */
  79. public $maxLength = 7;
  80. /**
  81. * @var integer 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.
  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. * Initializes the action.
  99. * @throws InvalidConfigException if the font file does not exist.
  100. */
  101. public function init()
  102. {
  103. $this->fontFile = Yii::getAlias($this->fontFile);
  104. if (!is_file($this->fontFile)) {
  105. throw new InvalidConfigException("The font file does not exist: {$this->fontFile}");
  106. }
  107. }
  108. /**
  109. * Runs the action.
  110. */
  111. public function run()
  112. {
  113. if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
  114. // AJAX request for regenerating code
  115. $code = $this->getVerifyCode(true);
  116. Yii::$app->response->format = Response::FORMAT_JSON;
  117. return [
  118. 'hash1' => $this->generateValidationHash($code),
  119. 'hash2' => $this->generateValidationHash(strtolower($code)),
  120. // we add a random 'v' parameter so that FireFox can refresh the image
  121. // when src attribute of image tag is changed
  122. 'url' => Url::to([$this->id, 'v' => uniqid()]),
  123. ];
  124. } else {
  125. $this->setHttpHeaders();
  126. Yii::$app->response->format = Response::FORMAT_RAW;
  127. return $this->renderImage($this->getVerifyCode());
  128. }
  129. }
  130. /**
  131. * Generates a hash code that can be used for client side validation.
  132. * @param string $code the CAPTCHA code
  133. * @return string a hash code generated from the CAPTCHA code
  134. */
  135. public function generateValidationHash($code)
  136. {
  137. for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) {
  138. $h += ord($code[$i]);
  139. }
  140. return $h;
  141. }
  142. /**
  143. * Gets the verification code.
  144. * @param boolean $regenerate whether the verification code should be regenerated.
  145. * @return string the verification code.
  146. */
  147. public function getVerifyCode($regenerate = false)
  148. {
  149. if ($this->fixedVerifyCode !== null) {
  150. return $this->fixedVerifyCode;
  151. }
  152. $session = Yii::$app->getSession();
  153. $session->open();
  154. $name = $this->getSessionKey();
  155. if ($session[$name] === null || $regenerate) {
  156. $session[$name] = $this->generateVerifyCode();
  157. $session[$name . 'count'] = 1;
  158. }
  159. return $session[$name];
  160. }
  161. /**
  162. * Validates the input to see if it matches the generated code.
  163. * @param string $input user input
  164. * @param boolean $caseSensitive whether the comparison should be case-sensitive
  165. * @return boolean whether the input is valid
  166. */
  167. public function validate($input, $caseSensitive)
  168. {
  169. $code = $this->getVerifyCode();
  170. $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0;
  171. $session = Yii::$app->getSession();
  172. $session->open();
  173. $name = $this->getSessionKey() . 'count';
  174. $session[$name] = $session[$name] + 1;
  175. if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {
  176. $this->getVerifyCode(true);
  177. }
  178. return $valid;
  179. }
  180. /**
  181. * Generates a new verification code.
  182. * @return string the generated verification code
  183. */
  184. protected function generateVerifyCode()
  185. {
  186. if ($this->minLength > $this->maxLength) {
  187. $this->maxLength = $this->minLength;
  188. }
  189. if ($this->minLength < 3) {
  190. $this->minLength = 3;
  191. }
  192. if ($this->maxLength > 20) {
  193. $this->maxLength = 20;
  194. }
  195. $length = mt_rand($this->minLength, $this->maxLength);
  196. $letters = 'bcdfghjklmnpqrstvwxyz';
  197. $vowels = 'aeiou';
  198. $code = '';
  199. for ($i = 0; $i < $length; ++$i) {
  200. if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
  201. $code .= $vowels[mt_rand(0, 4)];
  202. } else {
  203. $code .= $letters[mt_rand(0, 20)];
  204. }
  205. }
  206. return $code;
  207. }
  208. /**
  209. * Returns the session variable name used to store verification code.
  210. * @return string the session variable name
  211. */
  212. protected function getSessionKey()
  213. {
  214. return '__captcha/' . $this->getUniqueId();
  215. }
  216. /**
  217. * Renders the CAPTCHA image.
  218. * @param string $code the verification code
  219. * @return string image contents
  220. */
  221. protected function renderImage($code)
  222. {
  223. if (Captcha::checkRequirements() === 'gd') {
  224. return $this->renderImageByGD($code);
  225. } else {
  226. return $this->renderImageByImagick($code);
  227. }
  228. }
  229. /**
  230. * Renders the CAPTCHA image based on the code using GD library.
  231. * @param string $code the verification code
  232. * @return string image contents in PNG format.
  233. */
  234. protected function renderImageByGD($code)
  235. {
  236. $image = imagecreatetruecolor($this->width, $this->height);
  237. $backColor = imagecolorallocate(
  238. $image,
  239. (int) ($this->backColor % 0x1000000 / 0x10000),
  240. (int) ($this->backColor % 0x10000 / 0x100),
  241. $this->backColor % 0x100
  242. );
  243. imagefilledrectangle($image, 0, 0, $this->width, $this->height, $backColor);
  244. imagecolordeallocate($image, $backColor);
  245. if ($this->transparent) {
  246. imagecolortransparent($image, $backColor);
  247. }
  248. $foreColor = imagecolorallocate(
  249. $image,
  250. (int) ($this->foreColor % 0x1000000 / 0x10000),
  251. (int) ($this->foreColor % 0x10000 / 0x100),
  252. $this->foreColor % 0x100
  253. );
  254. $length = strlen($code);
  255. $box = imagettfbbox(30, 0, $this->fontFile, $code);
  256. $w = $box[4] - $box[0] + $this->offset * ($length - 1);
  257. $h = $box[1] - $box[5];
  258. $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
  259. $x = 10;
  260. $y = round($this->height * 27 / 40);
  261. for ($i = 0; $i < $length; ++$i) {
  262. $fontSize = (int) (rand(26, 32) * $scale * 0.8);
  263. $angle = rand(-10, 10);
  264. $letter = $code[$i];
  265. $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
  266. $x = $box[2] + $this->offset;
  267. }
  268. imagecolordeallocate($image, $foreColor);
  269. ob_start();
  270. imagepng($image);
  271. imagedestroy($image);
  272. return ob_get_clean();
  273. }
  274. /**
  275. * Renders the CAPTCHA image based on the code using ImageMagick library.
  276. * @param string $code the verification code
  277. * @return string image contents in PNG format.
  278. */
  279. protected function renderImageByImagick($code)
  280. {
  281. $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . dechex($this->backColor));
  282. $foreColor = new \ImagickPixel('#' . dechex($this->foreColor));
  283. $image = new \Imagick();
  284. $image->newImage($this->width, $this->height, $backColor);
  285. $draw = new \ImagickDraw();
  286. $draw->setFont($this->fontFile);
  287. $draw->setFontSize(30);
  288. $fontMetrics = $image->queryFontMetrics($draw, $code);
  289. $length = strlen($code);
  290. $w = (int) ($fontMetrics['textWidth']) - 8 + $this->offset * ($length - 1);
  291. $h = (int) ($fontMetrics['textHeight']) - 8;
  292. $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
  293. $x = 10;
  294. $y = round($this->height * 27 / 40);
  295. for ($i = 0; $i < $length; ++$i) {
  296. $draw = new \ImagickDraw();
  297. $draw->setFont($this->fontFile);
  298. $draw->setFontSize((int) (rand(26, 32) * $scale * 0.8));
  299. $draw->setFillColor($foreColor);
  300. $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]);
  301. $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
  302. $x += (int) ($fontMetrics['textWidth']) + $this->offset;
  303. }
  304. $image->setImageFormat('png');
  305. return $image->getImageBlob();
  306. }
  307. /**
  308. * Sets the HTTP headers needed by image response.
  309. */
  310. protected function setHttpHeaders()
  311. {
  312. Yii::$app->getResponse()->getHeaders()
  313. ->set('Pragma', 'public')
  314. ->set('Expires', '0')
  315. ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
  316. ->set('Content-Transfer-Encoding', 'binary')
  317. ->set('Content-type', 'image/png');
  318. }
  319. }