CCaptchaAction.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. /**
  3. * CCaptchaAction class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CCaptchaAction renders a CAPTCHA image.
  12. *
  13. * CCaptchaAction is used together with {@link CCaptcha} and {@link CCaptchaValidator}
  14. * to provide the {@link http://en.wikipedia.org/wiki/Captcha CAPTCHA} feature.
  15. *
  16. * You must configure properties of CCaptchaAction to customize the appearance of
  17. * the generated image.
  18. *
  19. * Note, CCaptchaAction requires PHP GD2 extension.
  20. *
  21. * Using CAPTCHA involves the following steps:
  22. * <ol>
  23. * <li>Override {@link CController::actions()} and register an action of class CCaptchaAction with ID 'captcha'.</li>
  24. * <li>In the form model, declare an attribute to store user-entered verification code, and declare the attribute
  25. * to be validated by the 'captcha' validator.</li>
  26. * <li>In the controller view, insert a {@link CCaptcha} widget in the form.</li>
  27. * </ol>
  28. *
  29. * @property string $verifyCode The verification code.
  30. *
  31. * @author Qiang Xue <qiang.xue@gmail.com>
  32. * @package system.web.widgets.captcha
  33. * @since 1.0
  34. */
  35. class CCaptchaAction extends CAction
  36. {
  37. /**
  38. * The name of the GET parameter indicating whether the CAPTCHA image should be regenerated.
  39. */
  40. const REFRESH_GET_VAR='refresh';
  41. /**
  42. * Prefix to the session variable name used by the action.
  43. */
  44. const SESSION_VAR_PREFIX='Yii.CCaptchaAction.';
  45. /**
  46. * @var integer how many times should the same CAPTCHA be displayed. Defaults to 3.
  47. * A value less than or equal to 0 means the test is unlimited (available since version 1.1.2).
  48. */
  49. public $testLimit = 3;
  50. /**
  51. * @var integer the width of the generated CAPTCHA image. Defaults to 120.
  52. */
  53. public $width = 120;
  54. /**
  55. * @var integer the height of the generated CAPTCHA image. Defaults to 50.
  56. */
  57. public $height = 50;
  58. /**
  59. * @var integer padding around the text. Defaults to 2.
  60. */
  61. public $padding = 2;
  62. /**
  63. * @var integer the background color. For example, 0x55FF00.
  64. * Defaults to 0xFFFFFF, meaning white color.
  65. */
  66. public $backColor = 0xFFFFFF;
  67. /**
  68. * @var integer the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
  69. */
  70. public $foreColor = 0x2040A0;
  71. /**
  72. * @var boolean whether to use transparent background. Defaults to false.
  73. */
  74. public $transparent = false;
  75. /**
  76. * @var integer the minimum length for randomly generated word. Defaults to 6.
  77. */
  78. public $minLength = 6;
  79. /**
  80. * @var integer the maximum length for randomly generated word. Defaults to 7.
  81. */
  82. public $maxLength = 7;
  83. /**
  84. * @var integer the offset between characters. Defaults to -2. You can adjust this property
  85. * in order to decrease or increase the readability of the captcha.
  86. * @since 1.1.7
  87. **/
  88. public $offset = -2;
  89. /**
  90. * @var string the TrueType font file. Defaults to SpicyRice.ttf which is provided with the Yii release.
  91. * Note that non-free Duality.ttf has been changed to open/free SpicyRice.ttf since 1.1.14.
  92. */
  93. public $fontFile;
  94. /**
  95. * @var string the fixed verification code. When this is property is set,
  96. * {@link getVerifyCode} will always return this value.
  97. * This is mainly used in automated tests where we want to be able to reproduce
  98. * the same verification code each time we run the tests.
  99. * Defaults to null, meaning the verification code will be randomly generated.
  100. * @since 1.1.4
  101. */
  102. public $fixedVerifyCode;
  103. /**
  104. * @var string the graphic extension that will be used to draw CAPTCHA image. Possible values
  105. * are 'gd', 'imagick' and null. Null value means that fallback mode will be used: ImageMagick
  106. * is preferred over GD. Default value is null.
  107. * @since 1.1.13
  108. */
  109. public $backend;
  110. /**
  111. * Runs the action.
  112. */
  113. public function run()
  114. {
  115. if(isset($_GET[self::REFRESH_GET_VAR])) // AJAX request for regenerating code
  116. {
  117. $code=$this->getVerifyCode(true);
  118. echo CJSON::encode(array(
  119. 'hash1'=>$this->generateValidationHash($code),
  120. 'hash2'=>$this->generateValidationHash(strtolower($code)),
  121. // we add a random 'v' parameter so that FireFox can refresh the image
  122. // when src attribute of image tag is changed
  123. 'url'=>$this->getController()->createUrl($this->getId(),array('v' => uniqid())),
  124. ));
  125. }
  126. else
  127. $this->renderImage($this->getVerifyCode());
  128. Yii::app()->end();
  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. * @since 1.1.7
  135. */
  136. public function generateValidationHash($code)
  137. {
  138. for($h=0,$i=strlen($code)-1;$i>=0;--$i)
  139. $h+=ord($code[$i]);
  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. $session = Yii::app()->session;
  152. $session->open();
  153. $name = $this->getSessionKey();
  154. if($session[$name] === null || $regenerate)
  155. {
  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()->session;
  172. $session->open();
  173. $name = $this->getSessionKey() . 'count';
  174. $session[$name] = $session[$name] + 1;
  175. if($session[$name] > $this->testLimit && $this->testLimit > 0)
  176. $this->getVerifyCode(true);
  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. if($this->minLength < 3)
  188. $this->minLength = 3;
  189. if($this->maxLength > 20)
  190. $this->maxLength = 20;
  191. $length = mt_rand($this->minLength,$this->maxLength);
  192. $letters = 'bcdfghjklmnpqrstvwxyz';
  193. $vowels = 'aeiou';
  194. $code = '';
  195. for($i = 0; $i < $length; ++$i)
  196. {
  197. if($i % 2 && mt_rand(0,10) > 2 || !($i % 2) && mt_rand(0,10) > 9)
  198. $code.=$vowels[mt_rand(0,4)];
  199. else
  200. $code.=$letters[mt_rand(0,20)];
  201. }
  202. return $code;
  203. }
  204. /**
  205. * Returns the session variable name used to store verification code.
  206. * @return string the session variable name
  207. */
  208. protected function getSessionKey()
  209. {
  210. return self::SESSION_VAR_PREFIX . Yii::app()->getId() . '.' . $this->getController()->getUniqueId() . '.' . $this->getId();
  211. }
  212. /**
  213. * Renders the CAPTCHA image based on the code using library specified in the {@link $backend} property.
  214. * @param string $code the verification code
  215. */
  216. protected function renderImage($code)
  217. {
  218. if($this->backend===null && CCaptcha::checkRequirements('imagick') || $this->backend==='imagick')
  219. $this->renderImageImagick($code);
  220. else if($this->backend===null && CCaptcha::checkRequirements('gd') || $this->backend==='gd')
  221. $this->renderImageGD($code);
  222. }
  223. /**
  224. * Renders the CAPTCHA image based on the code using GD library.
  225. * @param string $code the verification code
  226. * @since 1.1.13
  227. */
  228. protected function renderImageGD($code)
  229. {
  230. $image = imagecreatetruecolor($this->width,$this->height);
  231. $backColor = imagecolorallocate($image,
  232. (int)($this->backColor % 0x1000000 / 0x10000),
  233. (int)($this->backColor % 0x10000 / 0x100),
  234. $this->backColor % 0x100);
  235. imagefilledrectangle($image,0,0,$this->width,$this->height,$backColor);
  236. imagecolordeallocate($image,$backColor);
  237. if($this->transparent)
  238. imagecolortransparent($image,$backColor);
  239. $foreColor = imagecolorallocate($image,
  240. (int)($this->foreColor % 0x1000000 / 0x10000),
  241. (int)($this->foreColor % 0x10000 / 0x100),
  242. $this->foreColor % 0x100);
  243. if($this->fontFile === null)
  244. $this->fontFile = dirname(__FILE__).DIRECTORY_SEPARATOR.'SpicyRice.ttf';
  245. $length = strlen($code);
  246. $box = imagettfbbox(30,0,$this->fontFile,$code);
  247. $w = $box[4] - $box[0] + $this->offset * ($length - 1);
  248. $h = $box[1] - $box[5];
  249. $scale = min(($this->width - $this->padding * 2) / $w,($this->height - $this->padding * 2) / $h);
  250. $x = 10;
  251. $y = round($this->height * 27 / 40);
  252. for($i = 0; $i < $length; ++$i)
  253. {
  254. $fontSize = (int)(rand(26,32) * $scale * 0.8);
  255. $angle = rand(-10,10);
  256. $letter = $code[$i];
  257. $box = imagettftext($image,$fontSize,$angle,$x,$y,$foreColor,$this->fontFile,$letter);
  258. $x = $box[2] + $this->offset;
  259. }
  260. imagecolordeallocate($image,$foreColor);
  261. header('Pragma: public');
  262. header('Expires: 0');
  263. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  264. header('Content-Transfer-Encoding: binary');
  265. header("Content-Type: image/png");
  266. imagepng($image);
  267. imagedestroy($image);
  268. }
  269. /**
  270. * Renders the CAPTCHA image based on the code using ImageMagick library.
  271. * @param string $code the verification code
  272. * @since 1.1.13
  273. */
  274. protected function renderImageImagick($code)
  275. {
  276. $backColor=$this->transparent ? new ImagickPixel('transparent') : new ImagickPixel(sprintf('#%06x',$this->backColor));
  277. $foreColor=new ImagickPixel(sprintf('#%06x',$this->foreColor));
  278. $image=new Imagick();
  279. $image->newImage($this->width,$this->height,$backColor);
  280. if($this->fontFile===null)
  281. $this->fontFile=dirname(__FILE__).DIRECTORY_SEPARATOR.'SpicyRice.ttf';
  282. $draw=new ImagickDraw();
  283. $draw->setFont($this->fontFile);
  284. $draw->setFontSize(30);
  285. $fontMetrics=$image->queryFontMetrics($draw,$code);
  286. $length=strlen($code);
  287. $w=(int)($fontMetrics['textWidth'])-8+$this->offset*($length-1);
  288. $h=(int)($fontMetrics['textHeight'])-8;
  289. $scale=min(($this->width-$this->padding*2)/$w,($this->height-$this->padding*2)/$h);
  290. $x=10;
  291. $y=round($this->height*27/40);
  292. for($i=0; $i<$length; ++$i)
  293. {
  294. $draw=new ImagickDraw();
  295. $draw->setFont($this->fontFile);
  296. $draw->setFontSize((int)(rand(26,32)*$scale*0.8));
  297. $draw->setFillColor($foreColor);
  298. $image->annotateImage($draw,$x,$y,rand(-10,10),$code[$i]);
  299. $fontMetrics=$image->queryFontMetrics($draw,$code[$i]);
  300. $x+=(int)($fontMetrics['textWidth'])+$this->offset;
  301. }
  302. header('Pragma: public');
  303. header('Expires: 0');
  304. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  305. header('Content-Transfer-Encoding: binary');
  306. header("Content-Type: image/png");
  307. $image->setImageFormat('png');
  308. echo $image->getImageBlob();
  309. }
  310. }