Overview

Packages

  • application
    • commands
    • components
      • actions
      • filters
      • leftWidget
      • permissions
      • sortableWidget
      • util
      • webupdater
      • x2flow
        • actions
        • triggers
      • X2GridView
      • X2Settings
    • controllers
    • models
      • embedded
    • modules
      • accounts
        • controllers
        • models
      • actions
        • controllers
        • models
      • calendar
        • controllers
        • models
      • charts
        • models
      • contacts
        • controllers
        • models
      • docs
        • components
        • controllers
        • models
      • groups
        • controllers
        • models
      • marketing
        • components
        • controllers
        • models
      • media
        • controllers
        • models
      • mobile
        • components
      • opportunities
        • controllers
        • models
      • products
        • controllers
        • models
      • quotes
        • controllers
        • models
      • services
        • controllers
        • models
      • template
        • models
      • users
        • controllers
        • models
      • workflow
        • controllers
        • models
      • x2Leads
        • controllers
        • models
  • Net
  • None
  • PHP
  • system
    • base
    • caching
      • dependencies
    • collections
    • console
    • db
      • ar
      • schema
        • cubrid
        • mssql
        • mysql
        • oci
        • pgsql
        • sqlite
    • i18n
      • gettext
    • logging
    • test
    • utils
    • validators
    • web
      • actions
      • auth
      • filters
      • form
      • helpers
      • renderers
      • services
      • widgets
        • captcha
        • pagers
  • Text
    • Highlighter
  • zii
    • behaviors
    • widgets
      • grid
      • jui

Classes

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