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.

367 lines
12KB

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