CCaptcha.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. /**
  3. * CCaptcha 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. * CCaptcha renders a CAPTCHA image element.
  12. *
  13. * CCaptcha is used together with {@link CCaptchaAction} to provide {@link http://en.wikipedia.org/wiki/Captcha CAPTCHA}
  14. * - a way of preventing site spam.
  15. *
  16. * The image element rendered by CCaptcha will display a CAPTCHA image generated
  17. * by an action of class {@link CCaptchaAction} belonging to the current controller.
  18. * By default, the action ID should be 'captcha', which can be changed by setting {@link captchaAction}.
  19. *
  20. * CCaptcha may also render a button next to the CAPTCHA image. Clicking on the button
  21. * will change the CAPTCHA image to be a new one in an AJAX way.
  22. *
  23. * If {@link clickableImage} is set true, clicking on the CAPTCHA image
  24. * will refresh the CAPTCHA.
  25. *
  26. * A {@link CCaptchaValidator} may be used to validate that the user enters
  27. * a verification code matching the code displayed in the CAPTCHA image.
  28. *
  29. * When combining CCaptcha with CActiveForm or CForm, make sure ajaxValidation is disabled. Performing ajax validation causes
  30. * your Captcha to be refreshed, rendering the code invalid on the next validation attempt.
  31. *
  32. * @author Qiang Xue <qiang.xue@gmail.com>
  33. * @package system.web.widgets.captcha
  34. * @since 1.0
  35. */
  36. class CCaptcha extends CWidget
  37. {
  38. /**
  39. * @var string the ID of the action that should provide CAPTCHA image. Defaults to 'captcha',
  40. * meaning the 'captcha' action of the current controller. This property may also
  41. * be in the format of 'ControllerID/ActionID'. Underneath, this property is used
  42. * by {@link CController::createUrl} to create the URL that would serve the CAPTCHA image.
  43. * The action has to be of {@link CCaptchaAction}.
  44. */
  45. public $captchaAction='captcha';
  46. /**
  47. * @var boolean whether to display a button next to the CAPTCHA image. Clicking on the button
  48. * will cause the CAPTCHA image to be changed to a new one. Defaults to true.
  49. */
  50. public $showRefreshButton=true;
  51. /**
  52. * @var boolean whether to allow clicking on the CAPTCHA image to refresh the CAPTCHA letters.
  53. * Defaults to false. Hint: you may want to set {@link showRefreshButton} to false if you set
  54. * this property to be true because they serve for the same purpose.
  55. * To enhance accessibility, you may set {@link imageOptions} to provide hints to end-users that
  56. * the image is clickable.
  57. */
  58. public $clickableImage=false;
  59. /**
  60. * @var string the label for the refresh button. Defaults to 'Get a new code'.
  61. */
  62. public $buttonLabel;
  63. /**
  64. * @var string the type of the refresh button. This should be either 'link' or 'button'.
  65. * The former refers to hyperlink button while the latter a normal push button.
  66. * Defaults to 'link'.
  67. */
  68. public $buttonType='link';
  69. /**
  70. * @var array HTML attributes to be applied to the rendered image element.
  71. */
  72. public $imageOptions=array();
  73. /**
  74. * @var array HTML attributes to be applied to the rendered refresh button element.
  75. */
  76. public $buttonOptions=array();
  77. /**
  78. * Renders the widget.
  79. */
  80. public function run()
  81. {
  82. if(self::checkRequirements('imagick') || self::checkRequirements('gd'))
  83. {
  84. $this->renderImage();
  85. $this->registerClientScript();
  86. }
  87. else
  88. throw new CException(Yii::t('yii','GD with FreeType or ImageMagick PHP extensions are required.'));
  89. }
  90. /**
  91. * Renders the CAPTCHA image.
  92. */
  93. protected function renderImage()
  94. {
  95. if(!isset($this->imageOptions['id']))
  96. $this->imageOptions['id']=$this->getId();
  97. $url=$this->getController()->createUrl($this->captchaAction,array('v'=>uniqid()));
  98. $alt=isset($this->imageOptions['alt'])?$this->imageOptions['alt']:'';
  99. echo CHtml::image($url,$alt,$this->imageOptions);
  100. }
  101. /**
  102. * Registers the needed client scripts.
  103. */
  104. public function registerClientScript()
  105. {
  106. $cs=Yii::app()->clientScript;
  107. $id=$this->imageOptions['id'];
  108. $url=$this->getController()->createUrl($this->captchaAction,array(CCaptchaAction::REFRESH_GET_VAR=>true));
  109. $js="";
  110. if($this->showRefreshButton)
  111. {
  112. // reserve a place in the registered script so that any enclosing button js code appears after the captcha js
  113. $cs->registerScript('Yii.CCaptcha#'.$id,'// dummy');
  114. $label=$this->buttonLabel===null?Yii::t('yii','Get a new code'):$this->buttonLabel;
  115. $options=$this->buttonOptions;
  116. if(isset($options['id']))
  117. $buttonID=$options['id'];
  118. else
  119. $buttonID=$options['id']=$id.'_button';
  120. if($this->buttonType==='button')
  121. $html=CHtml::button($label, $options);
  122. else
  123. $html=CHtml::link($label, $url, $options);
  124. $js="jQuery('#$id').after(".CJSON::encode($html).");";
  125. $selector="#$buttonID";
  126. }
  127. if($this->clickableImage)
  128. $selector=isset($selector) ? "$selector, #$id" : "#$id";
  129. if(!isset($selector))
  130. return;
  131. $js.="
  132. jQuery(document).on('click', '$selector', function(){
  133. jQuery.ajax({
  134. url: ".CJSON::encode($url).",
  135. dataType: 'json',
  136. cache: false,
  137. success: function(data) {
  138. jQuery('#$id').attr('src', data['url']);
  139. jQuery('body').data('{$this->captchaAction}.hash', [data['hash1'], data['hash2']]);
  140. }
  141. });
  142. return false;
  143. });
  144. ";
  145. $cs->registerScript('Yii.CCaptcha#'.$id,$js);
  146. }
  147. /**
  148. * Checks if specified graphic extension support is loaded.
  149. * @param string $extension name to be checked. Possible values are 'gd', 'imagick' and null.
  150. * Default value is null meaning that both extensions will be checked. This parameter
  151. * is available since 1.1.13.
  152. * @return boolean true if ImageMagick extension with PNG support or GD with FreeType support is loaded,
  153. * otherwise false
  154. * @since 1.1.5
  155. */
  156. public static function checkRequirements($extension=null)
  157. {
  158. if(extension_loaded('imagick'))
  159. {
  160. $imagick=new Imagick();
  161. $imagickFormats=$imagick->queryFormats('PNG');
  162. }
  163. if(extension_loaded('gd'))
  164. {
  165. $gdInfo=gd_info();
  166. }
  167. if($extension===null)
  168. {
  169. if(isset($imagickFormats) && in_array('PNG',$imagickFormats))
  170. return true;
  171. if(isset($gdInfo) && $gdInfo['FreeType Support'])
  172. return true;
  173. }
  174. elseif($extension=='imagick' && isset($imagickFormats) && in_array('PNG',$imagickFormats))
  175. return true;
  176. elseif($extension=='gd' && isset($gdInfo) && $gdInfo['FreeType Support'])
  177. return true;
  178. return false;
  179. }
  180. }