move code up one directory
[atutor.git] / include / securimage / securimage.php
1 <?php
2
3 /**
4  * Project:     Securimage: A PHP class for creating and managing form CAPTCHA images<br />
5  * File:        securimage.php<br />
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or any later version.<br /><br />
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.<br /><br />
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA<br /><br />
20  *
21  * Any modifications to the library should be indicated clearly in the source code
22  * to inform users that the changes are not a part of the original software.<br /><br />
23  *
24  * If you found this script useful, please take a quick moment to rate it.<br />
25  * http://www.hotscripts.com/rate/49400.html  Thanks.
26  *
27  * @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
28  * @link http://www.phpcaptcha.org/latest.zip Download Latest Version
29  * @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
30  * @copyright 2007 Drew Phillips
31  * @author drew010 <drew@drew-phillips.com>
32  * @version 1.0.3.1 (March 24, 2008)
33  * @package Securimage
34  *
35  */
36
37 /**
38   ChangeLog
39
40   1.0.3.1
41   - Error reading from wordlist in some cases caused words to be cut off 1 letter short
42
43   1.0.3
44   - Removed shadow_text from code which could cause an undefined property error due to removal from previous version
45
46   1.0.2
47   - Audible CAPTCHA Code wav files
48   - Create codes from a word list instead of random strings
49
50   1.0
51   - Added the ability to use a selected character set, rather than a-z0-9 only.
52   - Added the multi-color text option to use different colors for each letter.
53   - Switched to automatic session handling instead of using files for code storage
54   - Added GD Font support if ttf support is not available.  Can use internal GD fonts or load new ones.
55   - Added the ability to set line thickness
56   - Added option for drawing arced lines over letters
57   - Added ability to choose image type for output
58
59 */
60
61 /**
62  * Output images in JPEG format
63  */
64 define('SI_IMAGE_JPEG', 1);
65 /**
66  * Output images in PNG format
67  */
68 define('SI_IMAGE_PNG',  2);
69 /**
70  * Output images in GIF format
71  * Must have GD >= 2.0.28!
72  */
73 define('SI_IMAGE_GIF',  3);
74
75 /**
76  * Securimage CAPTCHA Class.
77  *
78  * @package    Securimage
79  * @subpackage classes
80  *
81  */
82 class Securimage {
83
84   /**
85    * The desired width of the CAPTCHA image.
86    *
87    * @var int
88    */
89   var $image_width = 175;
90
91   /**
92    * The desired width of the CAPTCHA image.
93    *
94    * @var int
95    */
96   var $image_height = 45;
97
98   /**
99    * The image format for output.<br />
100    * Valid options: SI_IMAGE_PNG, SI_IMAGE_JPG, SI_IMAGE_GIF
101    *
102    * @var int
103    */
104   var $image_type = SI_IMAGE_PNG;
105
106   /**
107    * The length of the code to generate.
108    *
109    * @var int
110    */
111   var $code_length = 4;
112
113   /**
114    * The character set for individual characters in the image.<br />
115    * Letters are converted to uppercase.<br />
116    * The font must support the letters or there may be problematic substitutions.
117    *
118    * @var string
119    */
120   var $charset = 'ABCDEFGHKLMNPRSTUVWYZ23456789';
121   //var $charset = '0123456789';
122
123   /**
124    * Create codes using this word list
125    *
126    * @var string  The path to the word list to use for creating CAPTCHA codes
127    */
128   var $wordlist_file = '../words/words.txt';
129
130   /**
131    * True to use a word list file instead of a random code
132    *
133    * @var bool
134    */
135   var $use_wordlist  = true;
136
137   /**
138    * Whether to use a GD font instead of a TTF font.<br />
139    * TTF offers more support and options, but use this if your PHP doesn't support TTF.<br />
140    *
141    * @var boolean
142    */
143   var $use_gd_font = false;
144
145   /**
146    * The GD font to use.<br />
147    * Internal gd fonts can be loaded by their number.<br />
148    * Alternatively, a file path can be given and the font will be loaded from file.
149    *
150    * @var mixed
151    */
152   var $gd_font_file = 'gdfonts/bubblebath.gdf';
153
154   /**
155    * The approximate size of the font in pixels.<br />
156    * This does not control the size of the font because that is determined by the GD font itself.<br />
157    * This is used to aid the calculations of positioning used by this class.<br />
158    *
159    * @var int
160    */
161   var $gd_font_size = 20;
162
163   // Note: These font options below do not apply if you set $use_gd_font to true with the exception of $text_color
164
165   /**
166    * The path to the TTF font file to load.
167    *
168    * @var string
169    */
170   var $ttf_file = "./elephant.ttf";
171
172   /**
173    * The font size.<br />
174    * Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2)<br />
175    *
176    * @var int
177    */
178   var $font_size = 24;
179
180   /**
181    * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
182    * Higher values represent a counter-clockwise rotation.<br />
183    * For example, a value of 90 would result in bottom-to-top reading text.
184    *
185    * @var int
186    */
187   var $text_angle_minimum = -20;
188
189   /**
190    * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
191    * Higher values represent a counter-clockwise rotation.<br />
192    * For example, a value of 90 would result in bottom-to-top reading text.
193    *
194    * @var int
195    */
196   var $text_angle_maximum = 20;
197
198   /**
199    * The X-Position on the image where letter drawing will begin.<br />
200    * This value is in pixels from the left side of the image.
201    *
202    * @var int
203    */
204   var $text_x_start = 8;
205
206   /**
207    * Letters can be spaced apart at random distances.<br />
208    * This is the minimum distance between two letters.<br />
209    * This should be <i>at least</i> as wide as a font character.<br />
210    * Small values can cause letters to be drawn over eachother.<br />
211    *
212    * @var int
213    */
214   var $text_minimum_distance = 30;
215
216   /**
217    * Letters can be spaced apart at random distances.<br />
218    * This is the maximum distance between two letters.<br />
219    * This should be <i>at least</i> as wide as a font character.<br />
220    * Small values can cause letters to be drawn over eachother.<br />
221    *
222    * @var int
223    */
224   var $text_maximum_distance = 33;
225
226   /**
227    * The background color for the image.<br />
228    * This should be specified in HTML hex format.<br />
229    * Make sure to include the preceding # sign!
230    *
231    * @var string
232    */
233   var $image_bg_color = "#e3daed";
234
235   /**
236    * The text color to use for drawing characters.<br />
237    * This value is ignored if $use_multi_text is set to true.<br />
238    * Make sure this contrasts well with the background color.<br />
239    * Specify the color in HTML hex format with preceding # sign
240    *
241    * @see Securimage::$use_multi_text
242    * @var string
243    */
244   var $text_color = "#ff0000";
245
246   /**
247    * Set to true to use multiple colors for each character.
248    *
249    * @see Securimage::$multi_text_color
250    * @var boolean
251    */
252   var $use_multi_text = true;
253
254   /**
255    * String of HTML hex colors to use.<br />
256    * Separate each possible color with commas.<br />
257    * Be sure to precede each value with the # sign.
258    *
259    * @var string
260    */
261   var $multi_text_color = "#0a68dd,#f65c47,#8d32fd";
262
263   /**
264    * Set to true to make the characters appear transparent.
265    *
266    * @see Securimage::$text_transparency_percentage
267    * @var boolean
268    */
269   var $use_transparent_text = true;
270
271   /**
272    * The percentage of transparency, 0 to 100.<br />
273    * A value of 0 is completely opaque, 100 is completely transparent (invisble)
274    *
275    * @see Securimage::$use_transparent_text
276    * @var int
277    */
278   var $text_transparency_percentage = 15;
279
280
281   // Line options
282   /**
283    * Draw vertical and horizontal lines on the image.
284    *
285    * @see Securimage::$line_color
286    * @see Securimage::$line_distance
287    * @see Securimage::$line_thickness
288    * @see Securimage::$draw_lines_over_text
289    * @var boolean
290    */
291   var $draw_lines = true;
292
293   /**
294    * The color of the lines drawn on the image.<br />
295    * Use HTML hex format with preceding # sign.
296    *
297    * @see Securimage::$draw_lines
298    * @var string
299    */
300   var $line_color = "#80BFFF";
301
302   /**
303    * How far apart to space the lines from eachother in pixels.
304    *
305    * @see Securimage::$draw_lines
306    * @var int
307    */
308   var $line_distance = 5;
309
310   /**
311    * How thick to draw the lines in pixels.<br />
312    * 1-3 is ideal depending on distance
313    *
314    * @see Securimage::$draw_lines
315    * @see Securimage::$line_distance
316    * @var int
317    */
318   var $line_thickness = 1;
319
320   /**
321    * Set to true to draw angled lines on the image in addition to the horizontal and vertical lines.
322    *
323    * @see Securimage::$draw_lines
324    * @var boolean
325    */
326   var $draw_angled_lines = false;
327
328   /**
329    * Draw the lines over the text.<br />
330    * If fales lines will be drawn before putting the text on the image.<br />
331    * This can make the image hard for humans to read depending on the line thickness and distance.
332    *
333    * @var boolean
334    */
335   var $draw_lines_over_text = false;
336
337   /**
338    * For added security, it is a good idea to draw arced lines over the letters to make it harder for bots to segment the letters.<br />
339    * Two arced lines will be drawn over the text on each side of the image.<br />
340    * This is currently expirimental and may be off in certain configurations.
341    *
342    * @var boolean
343    */
344   var $arc_linethrough = true;
345
346   /**
347    * The colors or color of the arced lines.<br />
348    * Use HTML hex notation with preceding # sign, and separate each value with a comma.<br />
349    * This should be similar to your font color for single color images.
350    *
351    * @var string
352    */
353   var $arc_line_colors = "#8080ff";
354
355   /**
356    * Full path to the WAV files to use to make the audio files, include trailing /.<br />
357    * Name Files  [A-Z0-9].wav
358    *
359    * @since 1.0.1
360    * @var string
361    */
362   var $audio_path = './audio/';
363
364
365   //END USER CONFIGURATION
366   //There should be no need to edit below unless you really know what you are doing.
367
368   /**
369    * The gd image resource.
370    *
371    * @access private
372    * @var resource
373    */
374   var $im;
375
376   /**
377    * The background image resource
378    *
379    * @access private
380    * @var resource
381    */
382   var $bgimg;
383
384   /**
385    * The code generated by the script
386    *
387    * @access private
388    * @var string
389    */
390   var $code;
391
392   /**
393    * The code that was entered by the user
394    *
395    * @access private
396    * @var string
397    */
398   var $code_entered;
399
400   /**
401    * Whether or not the correct code was entered
402    *
403    * @access private
404    * @var boolean
405    */
406   var $correct_code;
407
408   /**
409    * Class constructor.<br />
410    * Because the class uses sessions, this will attempt to start a session if there is no previous one.<br />
411    * If you do not start a session before calling the class, the constructor must be called before any
412    * output is sent to the browser.
413    *
414    * <code>
415    *   $securimage = new Securimage();
416    * </code>
417    *
418    */
419   function Securimage()
420   {
421     if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
422       session_start();
423     }
424   }
425
426   /**
427    * Generate a code and output the image to the browser.
428    *
429    * <code>
430    *   
431    *   include 'securimage.php';
432    *   $securimage = new Securimage();
433    *   $securimage->show('bg.jpg');
434    *   
435    * </code>
436    *
437    * @param string $background_image  The path to an image to use as the background for the CAPTCHA
438    */
439   function show($background_image = "")
440   {
441     if($background_image != "" && is_readable($background_image)) {
442       $this->bgimg = $background_image;
443     }
444
445     $this->doImage();
446   }
447
448   /**
449    * Validate the code entered by the user.
450    *
451    * <code>
452    *   $code = $_POST['code'];
453    *   if ($securimage->check($code) == false) {
454    *     die("Sorry, the code entered did not match.");
455    *   } else {
456    *     $valid = true;
457    *   }
458    * </code>
459    * @param string $code  The code the user entered
460    * @return boolean  true if the code was correct, false if not
461    */
462   function check($code)
463   {
464     $this->code_entered = $code;
465     $this->validate();
466     return $this->correct_code;
467   }
468
469   /**
470    * Generate and output the image
471    *
472    * @access private
473    *
474    */
475   function doImage()
476   {
477     if($this->use_transparent_text == true || $this->bgimg != "") {
478       $this->im = imagecreatetruecolor($this->image_width, $this->image_height);
479       $bgcolor = imagecolorallocate($this->im, hexdec(substr($this->image_bg_color, 1, 2)), hexdec(substr($this->image_bg_color, 3, 2)), hexdec(substr($this->image_bg_color, 5, 2)));
480       imagefilledrectangle($this->im, 0, 0, imagesx($this->im), imagesy($this->im), $bgcolor);
481     } else { //no transparency
482       $this->im = imagecreate($this->image_width, $this->image_height);
483       $bgcolor = imagecolorallocate($this->im, hexdec(substr($this->image_bg_color, 1, 2)), hexdec(substr($this->image_bg_color, 3, 2)), hexdec(substr($this->image_bg_color, 5, 2)));
484     }
485
486     if($this->bgimg != "") { $this->setBackground(); }
487
488     $this->createCode();
489
490     if (!$this->draw_lines_over_text && $this->draw_lines) $this->drawLines();
491
492     $this->drawWord();
493
494     if ($this->arc_linethrough == true) $this->arcLines();
495
496     if ($this->draw_lines_over_text && $this->draw_lines) $this->drawLines();
497
498     $this->output();
499
500   }
501
502   /**
503    * Set the background of the CAPTCHA image
504    *
505    * @access private
506    *
507    */
508   function setBackground()
509   {
510     $dat = @getimagesize($this->bgimg);
511     if($dat == false) { return; }
512
513     switch($dat[2]) {
514       case 1:  $newim = @imagecreatefromgif($this->bgimg); break;
515       case 2:  $newim = @imagecreatefromjpeg($this->bgimg); break;
516       case 3:  $newim = @imagecreatefrompng($this->bgimg); break;
517       case 15: $newim = @imagecreatefromwbmp($this->bgimg); break;
518       case 16: $newim = @imagecreatefromxbm($this->bgimg); break;
519       default: return;
520     }
521
522     if(!$newim) return;
523
524     imagecopy($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height);
525   }
526
527   /**
528    * Draw arced lines over the text
529    *
530    * @access private
531    *
532    */
533   function arcLines()
534   {
535     $colors = explode(',', $this->randomColor());
536     imagesetthickness($this->im, 3);
537
538     $color = $colors[rand(0, sizeof($colors) - 1)];
539     $linecolor = imagecolorallocate($this->im, hexdec(substr($color, 1, 2)), hexdec(substr($color, 3, 2)), hexdec(substr($color, 5, 2)));
540
541     $xpos   = $this->text_x_start + ($this->font_size * 2) + rand(-5, 5);
542     $width  = $this->image_width / 2.66 + rand(3, 10);
543     $height = $this->font_size * 2.14 - rand(3, 10);
544
545     if ( rand(0,100) % 2 == 0 ) {
546       $start = rand(0,66);
547       $ypos  = $this->image_height / 2 - rand(5, 15);
548       $xpos += rand(5, 15);
549     } else {
550       $start = rand(180, 246);
551       $ypos  = $this->image_height / 2 + rand(5, 15);
552     }
553
554     $end = $start + rand(75, 110);
555
556     imagearc($this->im, $xpos, $ypos, $width, $height, $start, $end, $linecolor);
557
558     $color = $colors[rand(0, sizeof($colors) - 1)];
559     $linecolor = imagecolorallocate($this->im, hexdec(substr($color, 1, 2)), hexdec(substr($color, 3, 2)), hexdec(substr($color, 5, 2)));
560
561     if ( rand(1,75) % 2 == 0 ) {
562       $start = rand(45, 111);
563       $ypos  = $this->image_height / 2 - rand(5, 15);
564       $xpos += rand(5, 15);
565     } else {
566       $start = rand(200, 250);
567       $ypos  = $this->image_height / 2 + rand(5, 15);
568     }
569
570     $end = $start + rand(75, 100);
571
572     imagearc($this->im, $this->image_width * .75, $ypos, $width, $height, $start, $end, $linecolor);
573   }
574
575   /**
576    * Draw lines on the image
577    *
578    * @access private
579    *
580    */
581   function drawLines()
582   {
583     $linecolor = imagecolorallocate($this->im, hexdec(substr($this->line_color, 1, 2)), hexdec(substr($this->line_color, 3, 2)), hexdec(substr($this->line_color, 5, 2)));
584     imagesetthickness($this->im, $this->line_thickness);
585
586     //vertical lines
587     for($x = 1; $x < $this->image_width; $x += $this->line_distance) {
588       imageline($this->im, $x, 0, $x, $this->image_height, $linecolor);
589     }
590
591     //horizontal lines
592     for($y = 11; $y < $this->image_height; $y += $this->line_distance) {
593       imageline($this->im, 0, $y, $this->image_width, $y, $linecolor);
594     }
595
596     if ($this->draw_angled_lines == true) {
597       for ($x = -($this->image_height); $x < $this->image_width; $x += $this->line_distance) {
598         imageline($this->im, $x, 0, $x + $this->image_height, $this->image_height, $linecolor);
599       }
600
601       for ($x = $this->image_width + $this->image_height; $x > 0; $x -= $this->line_distance) {
602         imageline($this->im, $x, 0, $x - $this->image_height, $this->image_height, $linecolor);
603       }
604     }
605   }
606
607   /**
608    * Draw the CAPTCHA code over the image
609    *
610    * @access private
611    *
612    */
613   function drawWord()
614   {
615     if ($this->use_gd_font == true) {
616       if (!is_int($this->gd_font_file)) { //is a file name
617         $font = @imageloadfont($this->gd_font_file);
618         if ($font == false) {
619           trigger_error("Failed to load GD Font file {$this->gd_font_file} ", E_USER_WARNING);
620           return;
621         }
622       } else { //gd font identifier
623         $font = $this->gd_font_file;
624       }
625
626       $color = imagecolorallocate($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)));
627       imagestring($this->im, $font, $this->text_x_start, ($this->image_height / 2) - ($this->gd_font_size / 2), $this->code, $color);
628
629     } else { //ttf font
630       if($this->use_transparent_text == true) {
631         $alpha = intval($this->text_transparency_percentage / 100 * 127);
632         $font_color = imagecolorallocatealpha($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)), $alpha);
633       } else { //no transparency
634         $font_color = imagecolorallocate($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)));
635       }
636
637       $x = $this->text_x_start;
638       $strlen = strlen($this->code);
639       $y_min = ($this->image_height / 2) + ($this->font_size / 2) - 2;
640       $y_max = ($this->image_height / 2) + ($this->font_size / 2) + 2;
641       $colors = explode(',', $this->multi_text_color);
642
643       for($i = 0; $i < $strlen; ++$i) {
644         $angle = rand($this->text_angle_minimum, $this->text_angle_maximum);
645         $y = rand($y_min, $y_max);
646         if ($this->use_multi_text == true) {
647           $idx = rand(0, sizeof($colors) - 1);
648           $r = substr($colors[$idx], 1, 2);
649           $g = substr($colors[$idx], 3, 2);
650           $b = substr($colors[$idx], 5, 2);
651           if($this->use_transparent_text == true) {
652             $font_color = imagecolorallocatealpha($this->im, "0x$r", "0x$g", "0x$b", $alpha);
653           } else {
654             $font_color = imagecolorallocate($this->im, "0x$r", "0x$g", "0x$b");
655           }
656         }
657                 /* Will check if the FreeType library is loaded, if not, use the default PHP fonts.
658                  * @customized by ATutor, Harris Wong
659                  */
660                 if (function_exists('imagettftext')) {
661                         @imagettftext($this->im, $this->font_size, $angle, $x, $y, $font_color, $this->ttf_file, $this->code{$i});
662                 } else {
663                         $this->arc_linethrough = false; //no arcline then,too hard to see with the built in fonts and limited size
664                         imagestring($this->im, 5, $x, $y-15, $this->code{$i}, $font_color);
665                 }
666
667         $x += rand($this->text_minimum_distance, $this->text_maximum_distance);
668       } //for loop
669     } //else ttf font
670   } //function
671
672   /**
673    * Create a code and save to the session
674    *
675    * @since 1.0.1
676    *
677    */
678   function createCode()
679   {
680     $this->code = false;
681
682     if ($this->use_wordlist && is_readable($this->wordlist_file)) {
683       $this->code = $this->readCodeFromFile();
684     }
685
686     if ($this->code == false) {
687       $this->code = $this->generateCode($this->code_length);
688     }
689
690     $this->saveData();
691   }
692
693   /**
694    * Generate a code
695    *
696    * @access private
697    * @param int $len  The code length
698    * @return string
699    */
700   function generateCode($len)
701   {
702     $code = '';
703
704     for($i = 1, $cslen = strlen($this->charset); $i <= $len; ++$i) {
705       $code .= strtoupper( $this->charset{rand(0, $cslen - 1)} );
706     }
707     return $code;
708   }
709
710   /**
711    * Reads a word list file to get a code
712    *
713    * @access private
714    * @since 1.0.2
715    * @return mixed  false on failure, a word on success
716    */
717   function readCodeFromFile()
718   {
719     $fp = @fopen($this->wordlist_file, 'rb');
720     if (!$fp) return false;
721
722     $fsize = filesize($this->wordlist_file);
723     if ($fsize < 32) return false; // too small of a list to be effective
724
725     if ($fsize < 128) {
726       $max = $fsize; // still pretty small but changes the range of seeking
727     } else {
728       $max = 128;
729     }
730
731     fseek($fp, rand(0, $fsize - $max), SEEK_SET);
732     $data = fread($fp, 128); // read a random 128 bytes from file
733     fclose($fp);
734     $data = preg_replace("/\r?\n/", "\n", $data);
735
736     $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
737     $end   = strpos($data, "\n", $start);           // find end of word
738
739     return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
740   }
741
742   /**
743    * Output image to the browser
744    *
745    * @access private
746    *
747    */
748   function output()
749   {
750     header("Expires: Sun, 1 Jan 2000 12:00:00 GMT");
751     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
752     header("Cache-Control: no-store, no-cache, must-revalidate");
753     header("Cache-Control: post-check=0, pre-check=0", false);
754     header("Pragma: no-cache");
755
756     switch($this->image_type)
757     {
758       case SI_IMAGE_JPEG:
759         header("Content-Type: image/jpeg");
760         imagejpeg($this->im, null, 90);
761         break;
762
763       case SI_IMAGE_GIF:
764         header("Content-Type: image/gif");
765         imagegif($this->im);
766         break;
767
768       default:
769         header("Content-Type: image/png");
770         imagepng($this->im);
771         break;
772     }
773
774     imagedestroy($this->im);
775   }
776
777   /**
778    * Get WAV file data of the spoken code.<br />
779    * This is appropriate for output to the browser as audio/x-wav
780    *
781    * @since 1.0.1
782    * @return string  WAV data
783    *
784    */
785   function getAudibleCode()
786   {
787     $letters = array();
788     $code    = $this->getCode();
789
790     if ($code == '') {
791       $this->createCode();
792       $code = $this->getCode();
793     }
794
795     for($i = 0; $i < strlen($code); ++$i) {
796       $letters[] = $code{$i};
797     }
798
799     return $this->generateWAV($letters);
800   }
801
802   /**
803    * Save the code in the session
804    *
805    * @access private
806    *
807    */
808   function saveData()
809   {
810     $_SESSION['securimage_code_value'] = strtolower($this->code);
811   }
812
813   /**
814    * Validate the code to the user code
815    *
816    * @access private
817    *
818    */
819   function validate()
820   {
821     if ( isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value']) ) {
822       if ( $_SESSION['securimage_code_value'] == strtolower(trim($this->code_entered)) ) {
823         $this->correct_code = true;
824         $_SESSION['securimage_code_value'] = '';
825       } else {
826         $this->correct_code = false;
827       }
828     } else {
829       $this->correct_code = false;
830     }
831   }
832
833   /**
834    * Get the captcha code
835    *
836    * @since 1.0.1
837    * @return string
838    */
839   function getCode()
840   {
841     if (isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value'])) {
842       return $_SESSION['securimage_code_value'];
843     } else {
844       return '';
845     }
846   }
847
848   /**
849    * Check if the user entered code was correct
850    *
851    * @access private
852    * @return boolean
853    */
854   function checkCode()
855   {
856     return $this->correct_code;
857   }
858
859   /**
860    * Generate a wav file by concatenating individual files
861    * @since 1.0.1
862    * @access private
863    * @param array $letters  Array of letters to build a file from
864    * @return string  WAV file data
865    */
866   function generateWAV($letters)
867   {
868     $first = true; // use first file to write the header...
869     $data_len    = 0;
870     $files       = array();
871     $out_data    = '';
872
873     foreach ($letters as $letter) {
874       $filename = $this->audio_path . strtoupper($letter) . '.wav';
875
876       $fp = fopen($filename, 'rb');
877
878       $file = array();
879
880       $data = fread($fp, filesize($filename)); // read file in
881
882       $header = substr($data, 0, 36);
883       $body   = substr($data, 44);
884
885
886       $data = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/VSubChunk1Size/vAudioFormat/vNumChannels/VSampleRate/VByteRate/vBlockAlign/vBitsPerSample', $header);
887
888       $file['sub_chunk1_id']   = $data['SubChunk1ID'];
889       $file['bits_per_sample'] = $data['BitsPerSample'];
890       $file['channels']        = $data['NumChannels'];
891       $file['format']          = $data['AudioFormat'];
892       $file['sample_rate']     = $data['SampleRate'];
893       $file['size']            = $data['ChunkSize'] + 8;
894       $file['data']            = $body;
895
896       if ( ($p = strpos($file['data'], 'LIST')) !== false) {
897         // If the LIST data is not at the end of the file, this will probably break your sound file
898         $info         = substr($file['data'], $p + 4, 8);
899         $data         = unpack('Vlength/Vjunk', $info);
900         $file['data'] = substr($file['data'], 0, $p);
901         $file['size'] = $file['size'] - (strlen($file['data']) - $p);
902       }
903
904       $files[] = $file;
905       $data    = null;
906       $header  = null;
907       $body    = null;
908
909       $data_len += strlen($file['data']);
910
911       fclose($fp);
912     }
913
914     $out_data = '';
915     for($i = 0; $i < sizeof($files); ++$i) {
916       if ($i == 0) { // output header
917         $out_data .= pack('C4VC8', ord('R'), ord('I'), ord('F'), ord('F'), $data_len + 36, ord('W'), ord('A'), ord('V'), ord('E'), ord('f'), ord('m'), ord('t'), ord(' '));
918
919         $out_data .= pack('VvvVVvv',
920                           16,
921                           $files[$i]['format'],
922                           $files[$i]['channels'],
923                           $files[$i]['sample_rate'],
924                           $files[$i]['sample_rate'] * (($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8),
925                           ($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8,
926                           $files[$i]['bits_per_sample'] );
927
928         $out_data .= pack('C4', ord('d'), ord('a'), ord('t'), ord('a'));
929
930         $out_data .= pack('V', $data_len);
931       }
932
933       $out_data .= $files[$i]['data'];
934     }
935
936     return $out_data;
937   }
938
939
940   /**
941    * Random color generation
942    * @return    a 6 digits color code string 
943    */
944   function randomColor(){
945           $str = '#';
946           for($i=0;$i<3;$i++){
947                   $str .= rand(0, 255);
948           }
949           return $str;
950   }
951
952 } /* class Securimage */
953
954 ?>