2
// error_reporting(E_ALL); ini_set('display_errors', 1); // uncomment this line for debugging
5
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
6
* File: securimage.php<br />
8
* Copyright (c) 2011, Drew Phillips
11
* Redistribution and use in source and binary forms, with or without modification,
12
* are permitted provided that the following conditions are met:
14
* - Redistributions of source code must retain the above copyright notice,
15
* this list of conditions and the following disclaimer.
16
* - Redistributions in binary form must reproduce the above copyright notice,
17
* this list of conditions and the following disclaimer in the documentation
18
* and/or other materials provided with the distribution.
20
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
* POSSIBILITY OF SUCH DAMAGE.
32
* Any modifications to the library should be indicated clearly in the source code
33
* to inform users that the changes are not a part of the original software.<br /><br />
35
* If you found this script useful, please take a quick moment to rate it.<br />
36
* http://www.hotscripts.com/rate/49400.html Thanks.
38
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
39
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
40
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
41
* @copyright 2011 Drew Phillips
42
* @author Drew Phillips <drew@drew-phillips.com>
43
* @version 3.0 (October 2011)
52
- Rewrite class using PHP5 OOP
53
- Remove support for GD fonts, require FreeType
54
- Remove support for multi-color codes
55
- Add option to make codes case-sensitive
56
- Add namespaces to support multiple captchas on a single page or page specific captchas
57
- Add option to show simple math problems instead of codes
58
- Remove support for mp3 files due to vulnerability in decoding mp3 audio files
59
- Create new flash file to stream wav files instead of mp3
60
- Changed to BSD license
63
- Fix pathing to make integration into libraries easier (Nathan Phillip Brink ohnobinki@ohnopublishing.net)
66
- Add support for browsers with cookies disabled (requires php5, sqlite) maps users to md5 hashed ip addresses and md5 hashed codes for security
67
- Add fallback to gd fonts if ttf support is not enabled or font file not found (Mike Challis http://www.642weather.com/weather/scripts.php)
68
- Check for previous definition of image type constants (Mike Challis)
69
- Fix mime type settings for audio output
70
- Fixed color allocation issues with multiple colors and background images, consolidate allocation to one function
71
- Ability to let codes expire after a given length of time
72
- Allow HTML color codes to be passed to Securimage_Color (suggested by Mike Challis)
75
- Add mathematical distortion to characters (using code from HKCaptcha)
76
- Improved session support
77
- Added Securimage_Color class for easier color definitions
78
- Add distortion to audio output to prevent binary comparison attack (proposed by Sven "SavageTiger" Hagemann [insecurity.nl])
79
- Flash button to stream mp3 audio (Douglas Walsh www.douglaswalsh.net)
80
- Audio output is mp3 format by default
81
- Change font to AlteHaasGrotesk by yann le coroller
85
- Ability to output audible codes in mp3 format to stream from flash
88
- Error reading from wordlist in some cases caused words to be cut off 1 letter short
91
- Removed shadow_text from code which could cause an undefined property error due to removal from previous version
94
- Audible CAPTCHA Code wav files
95
- Create codes from a word list instead of random strings
98
- Added the ability to use a selected character set, rather than a-z0-9 only.
99
- Added the multi-color text option to use different colors for each letter.
100
- Switched to automatic session handling instead of using files for code storage
101
- Added GD Font support if ttf support is not available. Can use internal GD fonts or load new ones.
102
- Added the ability to set line thickness
103
- Added option for drawing arced lines over letters
104
- Added ability to choose image type for output
110
* Securimage CAPTCHA Class.
113
* @package Securimage
114
* @subpackage classes
115
* @author Drew Phillips <drew@drew-phillips.com>
120
// All of the public variables below are securimage options
121
// They can be passed as an array to the Securimage constructor, set below,
122
// or set from securimage_show.php and securimage_play.php
125
* Renders captcha as a JPEG image
128
const SI_IMAGE_JPEG = 1;
130
* Renders captcha as a PNG image (default)
133
const SI_IMAGE_PNG = 2;
135
* Renders captcha as a GIF image
138
const SI_IMAGE_GIF = 3;
141
* Create a normal alphanumeric captcha
144
const SI_CAPTCHA_STRING = 0;
146
* Create a captcha consisting of a simple math problem
149
const SI_CAPTCHA_MATHEMATIC = 1;
152
* The width of the captcha image
155
public $image_width = 300;
157
* The height of the captcha image
160
public $image_height = 80;
162
* The type of the image, default = png
165
public $image_type = self::SI_IMAGE_PNG;
168
* The background color of the captcha
169
* @var Securimage_Color
171
public $image_bg_color = '#ffffff';
173
* The color of the captcha text
174
* @var Securimage_Color
176
public $text_color = '#707070';
178
* The color of the lines over the captcha
179
* @var Securimage_Color
181
public $line_color = '#707070';
183
* The color of the noise that is drawn
184
* @var Securimage_Color
186
public $noise_color = '#707070';
189
* How transparent to make the text 0 = completely opaque, 100 = invisible
192
public $text_transparency_percentage = 50;
194
* Whether or not to draw the text transparently, true = use transparency, false = no transparency
197
public $use_transparent_text = false;
200
* The length of the captcha code
203
public $code_length = 6;
205
* Whether the captcha should be case sensitive (not recommended, use only for maximum protection)
208
public $case_sensitive = false;
210
* The character set to use for generating the captcha code
213
public $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
215
* How long in seconds a captcha remains valid, after this time it will not be accepted
218
public $expiry_time = 900;
221
* The session name securimage should use, only set this if your application uses a custom session name
222
* It is recommended to set this value below so it is used by all securimage scripts
225
public $session_name = null;
228
* true to use the wordlist file, false to generate random captcha codes
231
public $use_wordlist = false;
234
* The level of distortion, 0.75 = normal, 1.0 = very high distortion
237
public $perturbation = 0.75;
239
* How many lines to draw over the captcha code to increase security
242
public $num_lines = 8;
244
* The level of noise (random dots) to place on the image, 0-10
247
public $noise_level = 0;
250
* The signature text to draw on the bottom corner of the image
253
public $image_signature = '';
255
* The color of the signature text
256
* @var Securimage_Color
258
public $signature_color = '#707070';
260
* The path to the ttf font file to use for the signature text, defaults to $ttf_file (AHGBold.ttf)
263
public $signature_font;
266
* Use an SQLite database to store data (for users that do not support cookies)
269
public $use_sqlite_db = false;
272
* The type of captcha to create, either alphanumeric, or a math problem<br />
273
* Securimage::SI_CAPTCHA_STRING or Securimage::SI_CAPTCHA_MATHEMATIC
276
public $captcha_type = self::SI_CAPTCHA_STRING;
279
* The captcha namespace, use this if you have multiple forms on a single page, blank if you do not use multiple forms on one page
283
* // in securimage_show.php (create one show script for each form)
284
* $img->namespace = 'contact_form';
286
* // in form validator
287
* $img->namespace = 'contact_form';
288
* if ($img->check($code) == true) {
296
* The font file to use to draw the captcha code, leave blank for default font AHGBold.ttf
301
* The path to the wordlist file to use, leave blank for default words/words.txt
304
public $wordlist_file;
306
* The directory to scan for background images, if set a random background will be chosen from this folder
309
public $background_directory;
311
* The path to the SQLite database file to use, if $use_sqlite_database = true, should be chmod 666
314
public $sqlite_database;
316
* The path to the securimage audio directory, can be set in securimage_play.php
319
* $img->audio_path = '/home/yoursite/public_html/securimage/audio/';
329
protected $iscale = 5;
331
protected $securimage_path = null;
334
protected $code_display;
336
protected $captcha_code;
337
protected $sqlite_handle;
339
protected $gdbgcolor;
340
protected $gdtextcolor;
341
protected $gdlinecolor;
342
protected $gdsignaturecolor;
345
* Create a new securimage object, pass options to set in the constructor.<br />
346
* This can be used to display a captcha, play an audible captcha, or validate an entry
347
* @param array $options
350
* 'text_color' => new Securimage_Color('#013020'),
351
* 'code_length' => 5,
353
* 'noise_level' => 3,
354
* 'font_file' => Securimage::getPath() . '/custom.ttf'
357
* $img = new Securimage($options);
360
public function __construct($options = array())
362
$this->securimage_path = dirname(__FILE__);
364
if (is_array($options) && sizeof($options) > 0) {
365
foreach($options as $prop => $val) {
370
$this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
371
$this->text_color = $this->initColor($this->text_color, '#616161');
372
$this->line_color = $this->initColor($this->line_color, '#616161');
373
$this->noise_color = $this->initColor($this->noise_color, '#616161');
374
$this->signature_color = $this->initColor($this->signature_color, '#616161');
376
if ($this->ttf_file == null) {
377
$this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
380
$this->signature_font = $this->ttf_file;
382
if ($this->wordlist_file == null) {
383
$this->wordlist_file = $this->securimage_path . '/words/words.txt';
386
if ($this->sqlite_database == null) {
387
$this->sqlite_database = $this->securimage_path . '/database/securimage.sqlite';
390
if ($this->audio_path == null) {
391
$this->audio_path = $this->securimage_path . '/audio/';
394
if ($this->code_length == null || $this->code_length < 1) {
395
$this->code_length = 6;
398
if ($this->perturbation == null || !is_numeric($this->perturbation)) {
399
$this->perturbation = 0.75;
402
if ($this->namespace == null || !is_string($this->namespace)) {
403
$this->namespace = 'default';
406
// Initialize session or attach to existing
407
if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
408
if ($this->session_name != null && trim($this->session_name) != '') {
409
session_name(trim($this->session_name)); // set session name if provided
416
* Return the absolute path to the Securimage directory
417
* @return string The path to the securimage base directory
419
public static function getPath()
421
return dirname(__FILE__);
425
* Used to serve a captcha image to the browser
426
* @param string $background_image The path to the background image to use
428
* $img = new Securimage();
429
* $img->code_length = 6;
430
* $img->num_lines = 5;
431
* $img->noise_level = 5;
433
* $img->show(); // sends the image to browser
437
public function show($background_image = '')
439
if($background_image != '' && is_readable($background_image)) {
440
$this->bgimg = $background_image;
447
* Check a submitted code against the stored value
448
* @param string $code The captcha code to check
450
* $code = $_POST['code'];
451
* $img = new Securimage();
452
* if ($img->check($code) == true) {
453
* $captcha_valid = true;
455
* $captcha_valid = false;
459
public function check($code)
461
$this->code_entered = $code;
463
return $this->correct_code;
467
* Output a wav file of the captcha code to the browser
470
* $img = new Securimage();
471
* $img->outputAudioFile(); // outputs a wav file to the browser
475
public function outputAudioFile()
477
$ext = 'wav'; // force wav - mp3 is insecure
479
header("Content-Disposition: attachment; filename=\"securimage_audio.{$ext}\"");
480
header('Cache-Control: no-store, no-cache, must-revalidate');
481
header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
482
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
483
header('Content-type: audio/x-wav');
485
$audio = $this->getAudibleCode($ext);
487
header('Content-Length: ' . strlen($audio));
494
* The main image drawing routing, responsible for constructing the entire image and serving it
496
protected function doImage()
498
if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) {
499
$imagecreate = 'imagecreatetruecolor';
501
$imagecreate = 'imagecreate';
504
$this->im = $imagecreate($this->image_width, $this->image_height);
505
$this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
507
$this->allocateColors();
508
imagepalettecopy($this->tmpimg, $this->im);
510
$this->setBackground();
514
if ($this->noise_level > 0) {
520
if ($this->perturbation > 0 && is_readable($this->ttf_file)) {
521
$this->distortedCopy();
524
if ($this->num_lines > 0) {
528
if (trim($this->image_signature) != '') {
529
$this->addSignature();
536
* Allocate the colors to be used for the image
538
protected function allocateColors()
540
// allocate bg color first for imagecreate
541
$this->gdbgcolor = imagecolorallocate($this->im,
542
$this->image_bg_color->r,
543
$this->image_bg_color->g,
544
$this->image_bg_color->b);
546
$alpha = intval($this->text_transparency_percentage / 100 * 127);
548
if ($this->use_transparent_text == true) {
549
$this->gdtextcolor = imagecolorallocatealpha($this->im,
550
$this->text_color->r,
551
$this->text_color->g,
552
$this->text_color->b,
554
$this->gdlinecolor = imagecolorallocatealpha($this->im,
555
$this->line_color->r,
556
$this->line_color->g,
557
$this->line_color->b,
559
$this->gdnoisecolor = imagecolorallocatealpha($this->im,
560
$this->noise_color->r,
561
$this->noise_color->g,
562
$this->noise_color->b,
565
$this->gdtextcolor = imagecolorallocate($this->im,
566
$this->text_color->r,
567
$this->text_color->g,
568
$this->text_color->b);
569
$this->gdlinecolor = imagecolorallocate($this->im,
570
$this->line_color->r,
571
$this->line_color->g,
572
$this->line_color->b);
573
$this->gdnoisecolor = imagecolorallocate($this->im,
574
$this->noise_color->r,
575
$this->noise_color->g,
576
$this->noise_color->b);
579
$this->gdsignaturecolor = imagecolorallocate($this->im,
580
$this->signature_color->r,
581
$this->signature_color->g,
582
$this->signature_color->b);
587
* The the background color, or background image to be used
589
protected function setBackground()
591
// set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color
592
imagefilledrectangle($this->im, 0, 0,
593
$this->image_width, $this->image_height,
595
imagefilledrectangle($this->tmpimg, 0, 0,
596
$this->image_width * $this->iscale, $this->image_height * $this->iscale,
599
if ($this->bgimg == '') {
600
if ($this->background_directory != null &&
601
is_dir($this->background_directory) &&
602
is_readable($this->background_directory))
604
$img = $this->getBackgroundFromDirectory();
611
if ($this->bgimg == '') {
615
$dat = @getimagesize($this->bgimg);
621
case 1: $newim = @imagecreatefromgif($this->bgimg); break;
622
case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
623
case 3: $newim = @imagecreatefrompng($this->bgimg); break;
629
imagecopyresized($this->im, $newim, 0, 0, 0, 0,
630
$this->image_width, $this->image_height,
631
imagesx($newim), imagesy($newim));
635
* Scan the directory for a background image to use
637
protected function getBackgroundFromDirectory()
641
if ( ($dh = opendir($this->background_directory)) !== false) {
642
while (($file = readdir($dh)) !== false) {
643
if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
648
if (sizeof($images) > 0) {
649
return rtrim($this->background_directory, '/') . '/' . $images[rand(0, sizeof($images)-1)];
657
* Generates the code or math problem and saves the value to the session
659
protected function createCode()
663
switch($this->captcha_type) {
664
case self::SI_CAPTCHA_MATHEMATIC:
666
$signs = array('+', '-', 'x');
669
$sign = $signs[rand(0, 2)];
672
case 'x': $c = $left * $right; break;
673
case '-': $c = $left - $right; break;
674
default: $c = $left + $right; break;
678
$this->code_display = "$left $sign $right";
684
if ($this->use_wordlist && is_readable($this->wordlist_file)) {
685
$this->code = $this->readCodeFromFile();
688
if ($this->code == false) {
689
$this->code = $this->generateCode($this->code_length);
692
$this->code_display = $this->code;
693
$this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code);
701
* Draws the captcha code on the image
703
protected function drawWord()
705
$width2 = $this->image_width * $this->iscale;
706
$height2 = $this->image_height * $this->iscale;
708
if (!is_readable($this->ttf_file)) {
709
imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor);
711
if ($this->perturbation > 0) {
712
$font_size = $height2 * .4;
713
$bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
714
$tx = $bb[4] - $bb[0];
715
$ty = $bb[5] - $bb[1];
716
$x = floor($width2 / 2 - $tx / 2 - $bb[0]);
717
$y = round($height2 / 2 - $ty / 2 - $bb[1]);
719
imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
721
$font_size = $this->image_height * .4;
722
$bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
723
$tx = $bb[4] - $bb[0];
724
$ty = $bb[5] - $bb[1];
725
$x = floor($this->image_width / 2 - $tx / 2 - $bb[0]);
726
$y = round($this->image_height / 2 - $ty / 2 - $bb[1]);
728
imagettftext($this->im, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
733
//$this->im = $this->tmpimg;
739
* Copies the captcha image to the final image with distortion applied
741
protected function distortedCopy()
743
$numpoles = 3; // distortion factor
744
// make array of poles AKA attractor points
745
for ($i = 0; $i < $numpoles; ++ $i) {
746
$px[$i] = rand($this->image_width * 0.2, $this->image_width * 0.8);
747
$py[$i] = rand($this->image_height * 0.2, $this->image_height * 0.8);
748
$rad[$i] = rand($this->image_height * 0.2, $this->image_height * 0.8);
749
$tmp = ((- $this->frand()) * 0.15) - .15;
750
$amp[$i] = $this->perturbation * $tmp;
753
$bgCol = imagecolorat($this->tmpimg, 0, 0);
754
$width2 = $this->iscale * $this->image_width;
755
$height2 = $this->iscale * $this->image_height;
756
imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
757
// loop over $img pixels, take pixels from $tmpimg with distortion field
758
for ($ix = 0; $ix < $this->image_width; ++ $ix) {
759
for ($iy = 0; $iy < $this->image_height; ++ $iy) {
762
for ($i = 0; $i < $numpoles; ++ $i) {
765
if ($dx == 0 && $dy == 0) {
768
$r = sqrt($dx * $dx + $dy * $dy);
772
$rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
779
if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
780
$c = imagecolorat($this->tmpimg, $x, $y);
782
if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
783
imagesetpixel($this->im, $ix, $iy, $c);
790
* Draws distorted lines on the image
792
protected function drawLines()
794
for ($line = 0; $line < $this->num_lines; ++ $line) {
795
$x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
796
$x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
797
$y = rand($this->image_height * 0.1, $this->image_height * 0.9);
799
$theta = ($this->frand() - 0.5) * M_PI * 0.7;
800
$w = $this->image_width;
801
$len = rand($w * 0.4, $w * 0.7);
804
$k = $this->frand() * 0.6 + 0.2;
806
$phi = $this->frand() * 6.28;
808
$dx = $step * cos($theta);
809
$dy = $step * sin($theta);
811
$amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
812
$x0 = $x - 0.5 * $len * cos($theta);
813
$y0 = $y - 0.5 * $len * sin($theta);
815
$ldx = round(- $dy * $lwid);
816
$ldy = round($dx * $lwid);
818
for ($i = 0; $i < $n; ++ $i) {
819
$x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
820
$y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
821
imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
827
* Draws random noise on the image
829
protected function drawNoise()
831
if ($this->noise_level > 10) {
834
$noise_level = $this->noise_level;
837
$t0 = microtime(true);
839
$noise_level *= 125; // an arbitrary number that works well on a 1-10 scale
841
$points = $this->image_width * $this->image_height * $this->iscale;
842
$height = $this->image_height * $this->iscale;
843
$width = $this->image_width * $this->iscale;
844
for ($i = 0; $i < $noise_level; ++$i) {
845
$x = rand(10, $width);
846
$y = rand(10, $height);
848
if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy
849
imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE);
852
$t1 = microtime(true);
858
imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor);
859
header('content-type: image/png');
860
imagepng($this->tmpimg);
866
* Print signature text on image
868
protected function addSignature()
870
if ($this->use_gd_font) {
871
imagestring($this->im, 5, $this->image_width - (strlen($this->image_signature) * 10), $this->image_height - 20, $this->image_signature, $this->gdsignaturecolor);
874
$bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
875
$textlen = $bbox[2] - $bbox[0];
876
$x = $this->image_width - $textlen - 5;
877
$y = $this->image_height - 3;
879
imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
884
* Sends the appropriate image and cache headers and outputs image to the browser
886
protected function output()
888
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
889
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
890
header("Cache-Control: no-store, no-cache, must-revalidate");
891
header("Cache-Control: post-check=0, pre-check=0", false);
892
header("Pragma: no-cache");
894
switch ($this->image_type) {
895
case self::SI_IMAGE_JPEG:
896
header("Content-Type: image/jpeg");
897
imagejpeg($this->im, null, 90);
899
case self::SI_IMAGE_GIF:
900
header("Content-Type: image/gif");
904
header("Content-Type: image/png");
909
imagedestroy($this->im);
914
* Gets the code and returns the binary audio file for the stored captcha code
915
* @param string $format WAV only
917
protected function getAudibleCode($format = 'wav')
919
// override any format other than wav for now
920
// this is due to security issues with MP3 files
924
$code = $this->getCode();
928
$code = $this->getCode();
931
for($i = 0; $i < strlen($code); ++$i) {
932
$letters[] = $code{$i};
935
if ($format == 'mp3') {
936
return $this->generateMP3($letters);
938
return $this->generateWAV($letters);
943
* Gets a captcha code from a wordlist
945
protected function readCodeFromFile()
947
$fp = @fopen($this->wordlist_file, 'rb');
948
if (!$fp) return false;
950
$fsize = filesize($this->wordlist_file);
951
if ($fsize < 128) return false; // too small of a list to be effective
953
fseek($fp, rand(0, $fsize - 64), SEEK_SET); // seek to a random position of file from 0 to filesize-64
954
$data = fread($fp, 64); // read a chunk from our random position
956
$data = preg_replace("/\r?\n/", "\n", $data);
958
$start = @strpos($data, "\n", rand(0, 56)) + 1; // random start position
959
$end = @strpos($data, "\n", $start); // find end of word
961
if ($start === false) {
963
} else if ($end === false) {
964
$end = strlen($data);
967
return strtolower(substr($data, $start, $end - $start)); // return a line of the file
971
* Generates a random captcha code from the set character set
973
protected function generateCode()
977
for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) {
978
$code .= $this->charset{rand(0, $cslen - 1)};
981
//return 'testing'; // debug, set the code to given string
987
* Checks the entered code against the value stored in the session or sqlite database, handles case sensitivity
988
* Also clears the stored codes if the code was entered correctly to prevent re-use
990
protected function validate()
992
$code = $this->getCode();
993
// returns stored code, or an empty string if no stored code was found
994
// checks the session and sqlite database if enabled
996
if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) {
997
// case sensitive was set from securimage_show.php but not in class
998
// the code saved in the session has capitals so set case sensitive to true
999
$this->case_sensitive = true;
1002
$code_entered = trim( (($this->case_sensitive) ? $this->code_entered
1003
: strtolower($this->code_entered))
1005
$this->correct_code = false;
1008
if ($code == $code_entered) {
1009
$this->correct_code = true;
1010
$_SESSION['securimage_code_value'][$this->namespace] = '';
1011
$_SESSION['securimage_code_ctime'][$this->namespace] = '';
1012
$this->clearCodeFromDatabase();
1018
* Return the code from the session or sqlite database if used. If none exists yet, an empty string is returned
1020
protected function getCode()
1024
if (isset($_SESSION['securimage_code_value'][$this->namespace]) &&
1025
trim($_SESSION['securimage_code_value'][$this->namespace]) != '') {
1026
if ($this->isCodeExpired(
1027
$_SESSION['securimage_code_ctime'][$this->namespace]) == false) {
1028
$code = $_SESSION['securimage_code_value'][$this->namespace];
1030
} else if ($this->use_sqlite_db == true && function_exists('sqlite_open')) {
1031
// no code in session - may mean user has cookies turned off
1032
$this->openDatabase();
1033
$code = $this->getCodeFromDatabase();
1034
} else { /* no code stored in session or sqlite database, validation will fail */ }
1040
* Save data to session namespace and database if used
1042
protected function saveData()
1044
$_SESSION['securimage_code_value'][$this->namespace] = $this->code;
1045
$_SESSION['securimage_code_ctime'][$this->namespace] = time();
1047
$this->saveCodeToDatabase();
1051
* Saves the code to the sqlite database
1053
protected function saveCodeToDatabase()
1057
$this->openDatabase();
1059
if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
1060
$ip = $_SERVER['REMOTE_ADDR'];
1062
$code = $_SESSION['securimage_code_value'][$this->namespace]; // if cookies are disabled the session still exists at this point
1063
$success = sqlite_query($this->sqlite_handle,
1064
"INSERT OR REPLACE INTO codes(ip, code, namespace, created)
1065
VALUES('$ip', '$code', '{$this->namespace}', $time)");
1068
return $success !== false;
1072
* Open sqlite database
1074
protected function openDatabase()
1076
$this->sqlite_handle = false;
1078
if ($this->use_sqlite_db && function_exists('sqlite_open')) {
1079
$this->sqlite_handle = sqlite_open($this->sqlite_database, 0666, $error);
1081
if ($this->sqlite_handle !== false) {
1082
$res = sqlite_query($this->sqlite_handle, "PRAGMA table_info(codes)");
1083
if (sqlite_num_rows($res) == 0) {
1084
sqlite_query($this->sqlite_handle, "CREATE TABLE codes (ip VARCHAR(32) PRIMARY KEY, code VARCHAR(32) NOT NULL, namespace VARCHAR(32) NOT NULL, created INTEGER)");
1088
return $this->sqlite_handle != false;
1091
return $this->sqlite_handle;
1095
* Get a code from the sqlite database for ip address
1097
protected function getCodeFromDatabase()
1101
if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
1102
$ip = $_SERVER['REMOTE_ADDR'];
1103
$ns = sqlite_escape_string($this->namespace);
1105
$res = sqlite_query($this->sqlite_handle, "SELECT * FROM codes WHERE ip = '$ip' AND namespace = '$ns'");
1106
if ($res && sqlite_num_rows($res) > 0) {
1107
$res = sqlite_fetch_array($res);
1109
if ($this->isCodeExpired($res['created']) == false) {
1110
$code = $res['code'];
1118
* Remove an entered code from the database
1120
protected function clearCodeFromDatabase()
1122
if (is_resource($this->sqlite_handle)) {
1123
$ip = $_SERVER['REMOTE_ADDR'];
1124
$ns = sqlite_escape_string($this->namespace);
1126
sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE ip = '$ip' AND namespace = '$ns'");
1131
* Deletes old codes from sqlite database
1133
protected function purgeOldCodesFromDatabase()
1135
if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
1137
$limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time;
1139
sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE $now - created > $limit");
1144
* Checks to see if the captcha code has expired and cannot be used
1145
* @param unknown_type $creation_time
1147
protected function isCodeExpired($creation_time)
1151
if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) {
1153
} else if (time() - $creation_time < $this->expiry_time) {
1162
* Generate an MP3 audio file of the captcha image
1166
protected function generateMP3()
1172
* Generate a wav file given the $letters in the code
1173
* @todo Add ability to merge 2 sound files together to have random background sounds
1174
* @param array $letters
1175
* @return string The binary contents of the wav file
1177
protected function generateWAV($letters)
1184
$out_bpersample = 0;
1186
$removeChunks = array('LIST', 'DISP', 'NOTE');
1188
for ($i = 0; $i < sizeof($letters); ++$i) {
1189
$letter = $letters[$i];
1190
$filename = $this->audio_path . strtoupper($letter) . '.wav';
1192
$data = @file_get_contents($filename);
1194
if ($data === false) {
1195
// echo "Failed to read $filename";
1196
return $this->audioError();
1199
$header = substr($data, 0, 36);
1200
$info = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/'
1201
.'VSubChunk1Size/vAudioFormat/vNumChannels/'
1202
.'VSampleRate/VByteRate/vBlockAlign/vBitsPerSample',
1205
$dataPos = strpos($data, 'data');
1206
$out_channels = $info['NumChannels'];
1207
$out_samplert = $info['SampleRate'];
1208
$out_bpersample = $info['BitsPerSample'];
1210
if ($dataPos === false) {
1211
// wav file with no data?
1212
// echo "Failed to find DATA segment in $filename";
1213
return $this->audioError();
1216
if ($info['AudioFormat'] != 1) {
1217
// only work with PCM audio
1218
// echo "$filename was not PCM audio, only PCM is supported";
1219
return $this->audioError();
1222
if ($info['SubChunk1Size'] != 16 && $info['SubChunk1Size'] != 18) {
1223
// probably unsupported extension
1224
// echo "Bad SubChunk1Size in $filename - Size was {$info['SubChunk1Size']}";
1225
return $this->audioError();
1228
if ($info['SubChunk1Size'] > 16) {
1229
$header .= substr($data, 36, $info['SubChunk1Size'] - 16);
1233
// create the final file's header, size will be adjusted later
1234
$out_data = $header . 'data';
1239
foreach($removeChunks as $chunk) {
1240
$chunkPos = strpos($data, $chunk);
1241
if ($chunkPos !== false) {
1242
$listSize = unpack('VSize', substr($data, $chunkPos + 4, 4));
1244
$data = substr($data, 0, $chunkPos) .
1245
substr($data, $chunkPos + 8 + $listSize['Size']);
1247
$removed += $listSize['Size'] + 8;
1251
$dataSize = unpack('VSubchunk2Size', substr($data, $dataPos + 4, 4));
1252
$dataSize['Subchunk2Size'] -= $removed;
1253
$out_data .= substr($data, $dataPos + 8, $dataSize['Subchunk2Size'] * ($out_bpersample / 8));
1254
$numSamples += $dataSize['Subchunk2Size'];
1257
$filesize = strlen($out_data);
1258
$chunkSize = $filesize - 8;
1259
$dataCSize = $numSamples;
1261
$out_data = substr_replace($out_data, pack('V', $chunkSize), 4, 4);
1262
$out_data = substr_replace($out_data, pack('V', $numSamples), 40 + ($info['SubChunk1Size'] - 16), 4);
1264
$this->scrambleAudioData($out_data, 'wav');
1270
* Randomizes the audio data to add noise and prevent binary recognition
1271
* @param string $data The binary audio file data
1272
* @param string $format The format of the sound file (wav only)
1274
protected function scrambleAudioData(&$data, $format)
1276
$start = strpos($data, 'data') + 4; // look for "data" indicator
1277
if ($start === false) $start = 44; // if not found assume 44 byte header
1279
$start += rand(1, 4); // randomize starting offset
1280
$datalen = strlen($data) - $start;
1283
for ($i = $start; $i < $datalen; $i += $step) {
1284
$ch = ord($data{$i});
1285
if ($ch == 0 || $ch == 255) continue;
1287
if ($ch < 16 || $ch > 239) {
1290
$ch += rand(-12, 12);
1293
if ($ch < 0) $ch = 0; else if ($ch > 255) $ch = 255;
1295
$data{$i} = chr($ch);
1304
* Return a wav file saying there was an error generating file
1306
* @return string The binary audio contents
1308
protected function audioError()
1310
return @file_get_contents(dirname(__FILE__) . '/audio/error.wav');
1315
return 0.0001 * rand(0,9999);
1319
* Convert an html color code to a Securimage_Color
1320
* @param string $color
1321
* @param Securimage_Color $default The defalt color to use if $color is invalid
1323
protected function initColor($color, $default)
1325
if ($color == null) {
1326
return new Securimage_Color($default);
1327
} else if (is_string($color)) {
1329
return new Securimage_Color($color);
1330
} catch(Exception $e) {
1331
return new Securimage_Color($default);
1333
} else if (is_array($color) && sizeof($color) == 3) {
1334
return new Securimage_Color($color[0], $color[1], $color[2]);
1336
return new Securimage_Color($default);
1343
* Color object for Securimage CAPTCHA
1347
* @package Securimage
1348
* @subpackage classes
1351
class Securimage_Color
1358
* Create a new Securimage_Color object.<br />
1359
* Constructor expects 1 or 3 arguments.<br />
1360
* When passing a single argument, specify the color using HTML hex format,<br />
1361
* when passing 3 arguments, specify each RGB component (from 0-255) individually.<br />
1362
* $color = new Securimage_Color('#0080FF') or <br />
1363
* $color = new Securimage_Color(0, 128, 255)
1365
* @param string $color
1368
public function __construct($color = '#ffffff')
1370
$args = func_get_args();
1372
if (sizeof($args) == 0) {
1376
} else if (sizeof($args) == 1) {
1377
// set based on html code
1378
if (substr($color, 0, 1) == '#') {
1379
$color = substr($color, 1);
1382
if (strlen($color) != 3 && strlen($color) != 6) {
1383
throw new InvalidArgumentException(
1384
'Invalid HTML color code passed to Securimage_Color'
1388
$this->constructHTML($color);
1389
} else if (sizeof($args) == 3) {
1390
$this->constructRGB($args[0], $args[1], $args[2]);
1392
throw new InvalidArgumentException(
1393
'Securimage_Color constructor expects 0, 1 or 3 arguments; ' . sizeof($args) . ' given'
1399
* Construct from an rgb triplet
1400
* @param int $red The red component, 0-255
1401
* @param int $green The green component, 0-255
1402
* @param int $blue The blue component, 0-255
1404
protected function constructRGB($red, $green, $blue)
1406
if ($red < 0) $red = 0;
1407
if ($red > 255) $red = 255;
1408
if ($green < 0) $green = 0;
1409
if ($green > 255) $green = 255;
1410
if ($blue < 0) $blue = 0;
1411
if ($blue > 255) $blue = 255;
1419
* Construct from an html hex color code
1420
* @param string $color
1422
protected function constructHTML($color)
1424
if (strlen($color) == 3) {
1425
$red = str_repeat(substr($color, 0, 1), 2);
1426
$green = str_repeat(substr($color, 1, 1), 2);
1427
$blue = str_repeat(substr($color, 2, 1), 2);
1429
$red = substr($color, 0, 2);
1430
$green = substr($color, 2, 2);
1431
$blue = substr($color, 4, 2);
1434
$this->r = hexdec($red);
1435
$this->g = hexdec($green);
1436
$this->b = hexdec($blue);