PageRenderTime 58ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/yiisoft/yii2/captcha/CaptchaAction.php

https://gitlab.com/Griffolion/Game-Embargo-Tracker
PHP | 352 lines | 192 code | 34 blank | 126 comment | 24 complexity | ddd1eee02a3cf4352e12e7fdfc17fd09 MD5 | raw file
  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. return json_encode([
  117. 'hash1' => $this->generateValidationHash($code),
  118. 'hash2' => $this->generateValidationHash(strtolower($code)),
  119. // we add a random 'v' parameter so that FireFox can refresh the image
  120. // when src attribute of image tag is changed
  121. 'url' => Url::to([$this->id, 'v' => uniqid()]),
  122. ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  123. } else {
  124. $this->setHttpHeaders();
  125. Yii::$app->response->format = Response::FORMAT_RAW;
  126. return $this->renderImage($this->getVerifyCode());
  127. }
  128. }
  129. /**
  130. * Generates a hash code that can be used for client side validation.
  131. * @param string $code the CAPTCHA code
  132. * @return string a hash code generated from the CAPTCHA code
  133. */
  134. public function generateValidationHash($code)
  135. {
  136. for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) {
  137. $h += ord($code[$i]);
  138. }
  139. return $h;
  140. }
  141. /**
  142. * Gets the verification code.
  143. * @param boolean $regenerate whether the verification code should be regenerated.
  144. * @return string the verification code.
  145. */
  146. public function getVerifyCode($regenerate = false)
  147. {
  148. if ($this->fixedVerifyCode !== null) {
  149. return $this->fixedVerifyCode;
  150. }
  151. $session = Yii::$app->getSession();
  152. $session->open();
  153. $name = $this->getSessionKey();
  154. if ($session[$name] === null || $regenerate) {
  155. $session[$name] = $this->generateVerifyCode();
  156. $session[$name . 'count'] = 1;
  157. }
  158. return $session[$name];
  159. }
  160. /**
  161. * Validates the input to see if it matches the generated code.
  162. * @param string $input user input
  163. * @param boolean $caseSensitive whether the comparison should be case-sensitive
  164. * @return boolean whether the input is valid
  165. */
  166. public function validate($input, $caseSensitive)
  167. {
  168. $code = $this->getVerifyCode();
  169. $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0;
  170. $session = Yii::$app->getSession();
  171. $session->open();
  172. $name = $this->getSessionKey() . 'count';
  173. $session[$name] = $session[$name] + 1;
  174. if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {
  175. $this->getVerifyCode(true);
  176. }
  177. return $valid;
  178. }
  179. /**
  180. * Generates a new verification code.
  181. * @return string the generated verification code
  182. */
  183. protected function generateVerifyCode()
  184. {
  185. if ($this->minLength > $this->maxLength) {
  186. $this->maxLength = $this->minLength;
  187. }
  188. if ($this->minLength < 3) {
  189. $this->minLength = 3;
  190. }
  191. if ($this->maxLength > 20) {
  192. $this->maxLength = 20;
  193. }
  194. $length = mt_rand($this->minLength, $this->maxLength);
  195. $letters = 'bcdfghjklmnpqrstvwxyz';
  196. $vowels = 'aeiou';
  197. $code = '';
  198. for ($i = 0; $i < $length; ++$i) {
  199. if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
  200. $code .= $vowels[mt_rand(0, 4)];
  201. } else {
  202. $code .= $letters[mt_rand(0, 20)];
  203. }
  204. }
  205. return $code;
  206. }
  207. /**
  208. * Returns the session variable name used to store verification code.
  209. * @return string the session variable name
  210. */
  211. protected function getSessionKey()
  212. {
  213. return '__captcha/' . $this->getUniqueId();
  214. }
  215. /**
  216. * Renders the CAPTCHA image.
  217. * @param string $code the verification code
  218. * @return string image contents
  219. */
  220. protected function renderImage($code)
  221. {
  222. if (Captcha::checkRequirements() === 'gd') {
  223. return $this->renderImageByGD($code);
  224. } else {
  225. return $this->renderImageByImagick($code);
  226. }
  227. }
  228. /**
  229. * Renders the CAPTCHA image based on the code using GD library.
  230. * @param string $code the verification code
  231. * @return string image contents in PNG format.
  232. */
  233. protected function renderImageByGD($code)
  234. {
  235. $image = imagecreatetruecolor($this->width, $this->height);
  236. $backColor = imagecolorallocate(
  237. $image,
  238. (int) ($this->backColor % 0x1000000 / 0x10000),
  239. (int) ($this->backColor % 0x10000 / 0x100),
  240. $this->backColor % 0x100
  241. );
  242. imagefilledrectangle($image, 0, 0, $this->width, $this->height, $backColor);
  243. imagecolordeallocate($image, $backColor);
  244. if ($this->transparent) {
  245. imagecolortransparent($image, $backColor);
  246. }
  247. $foreColor = imagecolorallocate(
  248. $image,
  249. (int) ($this->foreColor % 0x1000000 / 0x10000),
  250. (int) ($this->foreColor % 0x10000 / 0x100),
  251. $this->foreColor % 0x100
  252. );
  253. $length = strlen($code);
  254. $box = imagettfbbox(30, 0, $this->fontFile, $code);
  255. $w = $box[4] - $box[0] + $this->offset * ($length - 1);
  256. $h = $box[1] - $box[5];
  257. $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
  258. $x = 10;
  259. $y = round($this->height * 27 / 40);
  260. for ($i = 0; $i < $length; ++$i) {
  261. $fontSize = (int) (rand(26, 32) * $scale * 0.8);
  262. $angle = rand(-10, 10);
  263. $letter = $code[$i];
  264. $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
  265. $x = $box[2] + $this->offset;
  266. }
  267. imagecolordeallocate($image, $foreColor);
  268. ob_start();
  269. imagepng($image);
  270. imagedestroy($image);
  271. return ob_get_clean();
  272. }
  273. /**
  274. * Renders the CAPTCHA image based on the code using ImageMagick library.
  275. * @param string $code the verification code
  276. * @return string image contents in PNG format.
  277. */
  278. protected function renderImageByImagick($code)
  279. {
  280. $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . dechex($this->backColor));
  281. $foreColor = new \ImagickPixel('#' . dechex($this->foreColor));
  282. $image = new \Imagick();
  283. $image->newImage($this->width, $this->height, $backColor);
  284. $draw = new \ImagickDraw();
  285. $draw->setFont($this->fontFile);
  286. $draw->setFontSize(30);
  287. $fontMetrics = $image->queryFontMetrics($draw, $code);
  288. $length = strlen($code);
  289. $w = (int) ($fontMetrics['textWidth']) - 8 + $this->offset * ($length - 1);
  290. $h = (int) ($fontMetrics['textHeight']) - 8;
  291. $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
  292. $x = 10;
  293. $y = round($this->height * 27 / 40);
  294. for ($i = 0; $i < $length; ++$i) {
  295. $draw = new \ImagickDraw();
  296. $draw->setFont($this->fontFile);
  297. $draw->setFontSize((int) (rand(26, 32) * $scale * 0.8));
  298. $draw->setFillColor($foreColor);
  299. $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]);
  300. $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
  301. $x += (int) ($fontMetrics['textWidth']) + $this->offset;
  302. }
  303. $image->setImageFormat('png');
  304. return $image->getImageBlob();
  305. }
  306. /**
  307. * Sets the HTTP headers needed by image response.
  308. */
  309. protected function setHttpHeaders()
  310. {
  311. Yii::$app->getResponse()->getHeaders()
  312. ->set('Pragma', 'public')
  313. ->set('Expires', '0')
  314. ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
  315. ->set('Content-Transfer-Encoding', 'binary')
  316. ->set('Content-type', 'image/png');
  317. }
  318. }