noalyss  Version-6.7.2
 All Data Structures Namespaces Files Functions Variables Enumerations
securimage.php
Go to the documentation of this file.
00001 <?php
00002 
00003 /**
00004  * Project:     Securimage: A PHP class for creating and managing form CAPTCHA images<br />
00005  * File:        securimage.php<br />
00006  *
00007  * This library is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or any later version.<br /><br />
00011  *
00012  * This library is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.<br /><br />
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with this library; if not, write to the Free Software
00019  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA<br /><br />
00020  *
00021  * Any modifications to the library should be indicated clearly in the source code
00022  * to inform users that the changes are not a part of the original software.<br /><br />
00023  *
00024  * If you found this script useful, please take a quick moment to rate it.<br />
00025  * http://www.hotscripts.com/rate/49400.html  Thanks.
00026  *
00027  * @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
00028  * @link http://www.phpcaptcha.org/latest.zip Download Latest Version
00029  * @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
00030  * @copyright 2009 Drew Phillips
00031  * @author Drew Phillips <drew@drew-phillips.com>
00032  * @version 2.0.1 BETA (December 6th, 2009)
00033  * @package Securimage
00034  *
00035  */
00036 
00037 /**
00038  ChangeLog
00039 
00040  2.0.1
00041  - Add support for browsers with cookies disabled (requires php5, sqlite) maps users to md5 hashed ip addresses and md5 hashed codes for security
00042  - 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)
00043  - Check for previous definition of image type constants (Mike Challis)
00044  - Fix mime type settings for audio output
00045  - Fixed color allocation issues with multiple colors and background images, consolidate allocation to one function
00046  - Ability to let codes expire after a given length of time
00047  - Allow HTML color codes to be passed to Securimage_Color (suggested by Mike Challis)
00048 
00049  2.0.0
00050  - Add mathematical distortion to characters (using code from HKCaptcha)
00051  - Improved session support
00052  - Added Securimage_Color class for easier color definitions
00053  - Add distortion to audio output to prevent binary comparison attack (proposed by Sven "SavageTiger" Hagemann [insecurity.nl])
00054  - Flash button to stream mp3 audio (Douglas Walsh www.douglaswalsh.net)
00055  - Audio output is mp3 format by default
00056  - Change font to AlteHaasGrotesk by yann le coroller
00057  - Some code cleanup 
00058 
00059  1.0.4 (unreleased)
00060  - Ability to output audible codes in mp3 format to stream from flash
00061 
00062  1.0.3.1
00063  - Error reading from wordlist in some cases caused words to be cut off 1 letter short
00064 
00065  1.0.3
00066  - Removed shadow_text from code which could cause an undefined property error due to removal from previous version
00067 
00068  1.0.2
00069  - Audible CAPTCHA Code wav files
00070  - Create codes from a word list instead of random strings
00071 
00072  1.0
00073  - Added the ability to use a selected character set, rather than a-z0-9 only.
00074  - Added the multi-color text option to use different colors for each letter.
00075  - Switched to automatic session handling instead of using files for code storage
00076  - Added GD Font support if ttf support is not available.  Can use internal GD fonts or load new ones.
00077  - Added the ability to set line thickness
00078  - Added option for drawing arced lines over letters
00079  - Added ability to choose image type for output
00080 
00081  */
00082 
00083 /**
00084  * Output images in JPEG format
00085  */
00086 if (!defined('SI_IMAGE_JPEG'))
00087   define('SI_IMAGE_JPEG', 1);
00088 /**
00089  * Output images in PNG format
00090  */
00091 if (!defined('SI_IMAGE_PNG'))
00092   define('SI_IMAGE_PNG',  2);
00093 /**
00094  * Output images in GIF format (not recommended)
00095  * Must have GD >= 2.0.28!
00096  */
00097 if (!defined('SI_IMAGE_GIF'))
00098   define('SI_IMAGE_GIF',  3);
00099 
00100 /**
00101  * Securimage CAPTCHA Class.
00102  *
00103  * @package    Securimage
00104  * @subpackage classes
00105  *
00106  */
00107 class Securimage {
00108 
00109         /**
00110          * The desired width of the CAPTCHA image.
00111          *
00112          * @var int
00113          */
00114         var $image_width;
00115 
00116         /**
00117          * The desired width of the CAPTCHA image.
00118          *
00119          * @var int
00120          */
00121         var $image_height;
00122 
00123         /**
00124          * The image format for output.<br />
00125          * Valid options: SI_IMAGE_PNG, SI_IMAGE_JPG, SI_IMAGE_GIF
00126          *
00127          * @var int
00128          */
00129         var $image_type;
00130 
00131         /**
00132          * The length of the code to generate.
00133          *
00134          * @var int
00135          */
00136         var $code_length;
00137 
00138         /**
00139          * The character set for individual characters in the image.<br />
00140          * Letters are converted to uppercase.<br />
00141          * The font must support the letters or there may be problematic substitutions.
00142          *
00143          * @var string
00144          */
00145         var $charset;
00146 
00147         /**
00148          * Create codes using this word list
00149          *
00150          * @var string  The path to the word list to use for creating CAPTCHA codes
00151          */
00152         var $wordlist_file;
00153 
00154         /**
00155          * Use wordlist of not
00156          *
00157          * @var bool true to use wordlist file, false to use random code
00158          */
00159         var $use_wordlist = false;
00160 
00161         /**
00162          * Note: Use of GD fonts is not recommended as many distortion features are not available<br />
00163          * The GD font to use.<br />
00164          * Internal gd fonts can be loaded by their number.<br />
00165          * Alternatively, a file path can be given and the font will be loaded from file.
00166          *
00167          * @var mixed
00168          */
00169         var $gd_font_file;
00170 
00171         /**
00172          * The approximate size of the font in pixels.<br />
00173          * This does not control the size of the font because that is determined by the GD font itself.<br />
00174          * This is used to aid the calculations of positioning used by this class.<br />
00175          *
00176          * @var int
00177          */
00178         var $gd_font_size;
00179 
00180         /**
00181          * Use a gd font instead of TTF
00182          *
00183          * @var bool true for gd font, false for TTF
00184          */
00185         var $use_gd_font;
00186 
00187         // Note: These font options below do not apply if you set $use_gd_font to true with the exception of $text_color
00188 
00189         /**
00190          * The path to the TTF font file to load.
00191          *
00192          * @var string
00193          */
00194         var $ttf_file;
00195 
00196         /**
00197          * How much to distort image, higher = more distortion.<br />
00198          * Distortion is only available when using TTF fonts.<br />
00199          *
00200          * @var float
00201          */
00202         var $perturbation;
00203 
00204         /**
00205          * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
00206          * Higher values represent a counter-clockwise rotation.<br />
00207          * For example, a value of 90 would result in bottom-to-top reading text.<br />
00208          * This value along with maximum angle distance do not need to be very high with perturbation
00209          *
00210          * @var int
00211          */
00212         var $text_angle_minimum;
00213 
00214         /**
00215          * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
00216          * Higher values represent a counter-clockwise rotation.<br />
00217          * For example, a value of 90 would result in bottom-to-top reading text.
00218          *
00219          * @var int
00220          */
00221         var $text_angle_maximum;
00222 
00223         /**
00224          * The X-Position on the image where letter drawing will begin.<br />
00225          * This value is in pixels from the left side of the image.
00226          *
00227          * @var int
00228          * @deprecated 2.0
00229          */
00230         var $text_x_start;
00231 
00232         /**
00233          * The background color for the image as a Securimage_Color.<br />
00234          *
00235          * @var Securimage_Color
00236          */
00237         var $image_bg_color;
00238 
00239         /**
00240          * Scan this directory for gif, jpg, and png files to use as background images.<br />
00241          * A random image file will be picked each time.<br />
00242          * Change from null to the full path to your directory.<br />
00243          * i.e. var $background_directory = $_SERVER['DOCUMENT_ROOT'] . '/securimage/backgrounds';
00244          * Make sure not to pass a background image to the show function, otherwise this directive is ignored.
00245          *
00246          * @var string
00247          */
00248         var $background_directory = null; //'./backgrounds';
00249 
00250         /**
00251          * The text color to use for drawing characters as a Securimage_Color.<br />
00252          * This value is ignored if $use_multi_text is set to true.<br />
00253          * Make sure this contrasts well with the background color or image.<br />
00254          *
00255          * @see Securimage::$use_multi_text
00256          * @var Securimage_Color
00257          */
00258         var $text_color;
00259 
00260         /**
00261          * Set to true to use multiple colors for each character.
00262          *
00263          * @see Securimage::$multi_text_color
00264          * @var boolean
00265          */
00266         var $use_multi_text;
00267 
00268         /**
00269          * Array of Securimage_Colors which will be randomly selected for each letter.<br />
00270          *
00271          * @var array
00272          */
00273         var $multi_text_color;
00274 
00275         /**
00276          * Set to true to make the characters appear transparent.
00277          *
00278          * @see Securimage::$text_transparency_percentage
00279          * @var boolean
00280          */
00281         var $use_transparent_text;
00282 
00283         /**
00284          * The percentage of transparency, 0 to 100.<br />
00285          * A value of 0 is completely opaque, 100 is completely transparent (invisble)
00286          *
00287          * @see Securimage::$use_transparent_text
00288          * @var int
00289          */
00290         var $text_transparency_percentage;
00291 
00292 
00293         // Line options
00294         /**
00295         * Draw vertical and horizontal lines on the image.
00296         *
00297         * @see Securimage::$line_color
00298         * @see Securimage::$draw_lines_over_text
00299         * @var boolean
00300         */
00301         var $num_lines;
00302 
00303         /**
00304          * Color of lines drawn over text
00305          *
00306          * @var string
00307          */
00308         var $line_color;
00309 
00310         /**
00311          * Draw the lines over the text.<br />
00312          * If fales lines will be drawn before putting the text on the image.
00313          *
00314          * @var boolean
00315          */
00316         var $draw_lines_over_text;
00317 
00318         /**
00319          * Text to write at the bottom corner of captcha image
00320          * 
00321          * @since 2.0
00322          * @var string Signature text
00323          */
00324         var $image_signature;
00325         
00326         /**
00327          * Color to use for writing signature text
00328          * 
00329          * @since 2.0
00330          * @var Securimage_Color
00331          */
00332         var $signature_color;
00333 
00334         /**
00335          * Full path to the WAV files to use to make the audio files, include trailing /.<br />
00336          * Name Files  [A-Z0-9].wav
00337          *
00338          * @since 1.0.1
00339          * @var string
00340          */
00341         var $audio_path;
00342 
00343         /**
00344          * Type of audio file to generate (mp3 or wav)
00345          *
00346          * @var string
00347          */
00348         var $audio_format;
00349 
00350         /**
00351          * The session name to use if not the default.  Blank for none
00352          *
00353          * @see http://php.net/session_name
00354          * @since 2.0
00355          * @var string
00356          */
00357         var $session_name = '';
00358         
00359         /**
00360          * The amount of time in seconds that a code remains valid.<br />
00361          * Any code older than this number will be considered invalid even if entered correctly.<br />
00362          * Any non-numeric or value less than 1 disables this functionality.
00363          * 
00364          * @var int
00365          */
00366         var $expiry_time;
00367         
00368         /**
00369          * Path to the file to use for storing codes for users.<br />
00370          * THIS FILE MUST ABSOLUTELY NOT BE ACCESSIBLE FROM A WEB BROWSER!!<br />
00371          * Put this file in a directory below the web root or one that is restricted (i.e. an apache .htaccess file with deny from all)<br />
00372          * If you cannot meet those requirements your forms may not be completely protected.<br />
00373          * You could obscure the database file name but this is also not recommended.
00374          * 
00375          * @var string
00376          */
00377         var $sqlite_database;
00378         
00379         /**
00380          * Use an SQLite database for storing codes as a backup to sessions.<br />
00381          * Note: Sessions will still be used 
00382          */
00383         var $use_sqlite_db;
00384 
00385 
00386         //END USER CONFIGURATION
00387         //There should be no need to edit below unless you really know what you are doing.
00388 
00389         /**
00390          * The gd image resource.
00391          *
00392          * @access private
00393          * @var resource
00394          */
00395         var $im;
00396 
00397         /**
00398          * Temporary image for rendering
00399          *
00400          * @access private
00401          * @var resource
00402          */
00403         var $tmpimg;
00404 
00405         /**
00406          * Internal scale factor for anti-alias @hkcaptcha
00407          *
00408          * @access private
00409          * @since 2.0
00410          * @var int
00411          */
00412         var $iscale; // internal scale factor for anti-alias @hkcaptcha
00413 
00414         /**
00415          * The background image resource
00416          *
00417          * @access private
00418          * @var resource
00419          */
00420         var $bgimg;
00421 
00422         /**
00423          * The code generated by the script
00424          *
00425          * @access private
00426          * @var string
00427          */
00428         var $code;
00429 
00430         /**
00431          * The code that was entered by the user
00432          *
00433          * @access private
00434          * @var string
00435          */
00436         var $code_entered;
00437 
00438         /**
00439          * Whether or not the correct code was entered
00440          *
00441          * @access private
00442          * @var boolean
00443          */
00444         var $correct_code;
00445         
00446         /**
00447          * Handle to SQLite database
00448          *
00449          * @access private
00450          * @var resource
00451          */
00452         var $sqlite_handle;
00453         
00454         /**
00455          * Color resource for image line color
00456          * 
00457          * @access private
00458          * @var int
00459          */
00460         var $gdlinecolor;
00461         
00462         /**
00463          * Array of colors for multi colored codes
00464          * 
00465          * @access private
00466          * @var array
00467          */
00468         var $gdmulticolor;
00469         
00470         /**
00471          * Color resource for image font color
00472          * 
00473          * @access private
00474          * @var int
00475          */
00476         var $gdtextcolor;
00477         
00478         /**
00479          * Color resource for image signature color
00480          * 
00481          * @access private
00482          * @var int
00483          */
00484         var $gdsignaturecolor;
00485         
00486         /**
00487          * Color resource for image background color
00488          * 
00489          * @access private
00490          * @var int
00491          */
00492         var $gdbgcolor;
00493         
00494 
00495         /**
00496          * Class constructor.<br />
00497          * Because the class uses sessions, this will attempt to start a session if there is no previous one.<br />
00498          * If you do not start a session before calling the class, the constructor must be called before any
00499          * output is sent to the browser.
00500          *
00501          * <code>
00502          *   $securimage = new Securimage();
00503          * </code>
00504          *
00505          */
00506         function Securimage()
00507         {
00508                 // Initialize session or attach to existing
00509                 if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
00510                         if (trim($this->session_name) != '') {
00511                                 session_name($this->session_name); // set session name if provided
00512                         }
00513                         session_start();
00514                 }
00515 
00516                 // Set Default Values
00517                 $this->image_width   = 230;
00518                 $this->image_height  = 80;
00519                 $this->image_type    = SI_IMAGE_PNG;
00520 
00521                 $this->code_length   = 6;
00522                 $this->charset       = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
00523                 $this->wordlist_file = './words/words.txt';
00524                 $this->use_wordlist  = false;
00525 
00526                 $this->gd_font_file  = 'gdfonts/automatic.gdf';
00527                 $this->use_gd_font   = false;
00528                 $this->gd_font_size  = 24;
00529                 $this->text_x_start  = 15;
00530 
00531                 $this->ttf_file      = './AHGBold.ttf';
00532 
00533                 $this->perturbation       = 0.75;
00534                 $this->iscale             = 5;
00535                 $this->text_angle_minimum = 0;
00536                 $this->text_angle_maximum = 0;
00537 
00538                 $this->image_bg_color   = new Securimage_Color(0xff, 0xff, 0xff);
00539     $this->text_color       = new Securimage_Color(0x3d, 0x3d, 0x3d);
00540                 $this->multi_text_color = array(new Securimage_Color(0x0, 0x20, 0xCC),
00541                                                                                                                                                 new Securimage_Color(0x0, 0x30, 0xEE),
00542                                                                                                                                                 new Securimage_color(0x0, 0x40, 0xCC),
00543                                                                                                                                                 new Securimage_Color(0x0, 0x50, 0xEE),
00544                                                                                                                                                 new Securimage_Color(0x0, 0x60, 0xCC));
00545                 $this->use_multi_text   = false;
00546 
00547                 $this->use_transparent_text         = false;
00548                 $this->text_transparency_percentage = 30;
00549 
00550                 $this->num_lines            = 10;
00551                 $this->line_color           = new Securimage_Color(0x3d, 0x3d, 0x3d);
00552                 $this->draw_lines_over_text = true;
00553 
00554                 $this->image_signature = '';
00555                 $this->signature_color = new Securimage_Color(0x20, 0x50, 0xCC);
00556                 $this->signature_font  = './AHGBold.ttf';
00557 
00558                 $this->audio_path   = './audio/';
00559                 $this->audio_format = 'mp3';
00560                 $this->session_name = '';
00561                 $this->expiry_time  = 900;
00562                 
00563                 $this->sqlite_database = 'database/securimage.sqlite';
00564                 $this->use_sqlite_db   = false;
00565                 
00566                 $this->sqlite_handle = false;
00567         }
00568 
00569         /**
00570          * Generate a code and output the image to the browser.
00571          *
00572          * <code>
00573          *   <?php
00574          *   include 'securimage.php';
00575          *   $securimage = new Securimage();
00576          *   $securimage->show('bg.jpg');
00577          *   ?>
00578          * </code>
00579          *
00580          * @param string $background_image  The path to an image to use as the background for the CAPTCHA
00581          */
00582         function show($background_image = "")
00583         {
00584                 if($background_image != "" && is_readable($background_image)) {
00585                         $this->bgimg = $background_image;
00586                 }
00587 
00588                 $this->doImage();
00589         }
00590 
00591         /**
00592          * Validate the code entered by the user.
00593          *
00594          * <code>
00595          *   $code = $_POST['code'];
00596          *   if ($securimage->check($code) == false) {
00597          *     die("Sorry, the code entered did not match.");
00598          *   } else {
00599          *     $valid = true;
00600          *   }
00601          * </code>
00602          * @param string $code  The code the user entered
00603          * @return boolean  true if the code was correct, false if not
00604          */
00605         function check($code)
00606         {
00607                 $this->code_entered = $code;
00608                 $this->validate();
00609                 return $this->correct_code;
00610         }
00611 
00612         /**
00613          * Output audio file with HTTP headers to browser
00614          * 
00615          * <code>
00616          *   $sound = new Securimage();
00617          *   $sound->audio_format = 'mp3';
00618          *   $sound->outputAudioFile();
00619          * </code>
00620          * 
00621          * @since 2.0
00622          */
00623         function outputAudioFile()
00624         {
00625                 if (strtolower($this->audio_format) == 'wav') {
00626                         header('Content-type: audio/x-wav');
00627                         $ext = 'wav';
00628                 } else {
00629                         header('Content-type: audio/mpeg'); // default to mp3
00630                         $ext = 'mp3';
00631                 }
00632 
00633                 header("Content-Disposition: attachment; filename=\"securimage_audio.{$ext}\"");
00634                 header('Cache-Control: no-store, no-cache, must-revalidate');
00635                 header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
00636                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
00637 
00638                 $audio = $this->getAudibleCode($ext);
00639 
00640                 header('Content-Length: ' . strlen($audio));
00641 
00642                 echo $audio;
00643                 exit;
00644         }
00645 
00646         /**
00647          * Generate and output the image
00648          *
00649          * @access private
00650          *
00651          */
00652         function doImage()
00653         {
00654                 if ($this->use_gd_font == true) {
00655                         $this->iscale = 1;
00656                 }
00657                 if($this->use_transparent_text == true || $this->bgimg != "") {
00658                         $this->im     = imagecreatetruecolor($this->image_width, $this->image_height);
00659                         $this->tmpimg = imagecreatetruecolor($this->image_width * $this->iscale, $this->image_height * $this->iscale);
00660 
00661                 } else { //no transparency
00662                         $this->im     = imagecreate($this->image_width, $this->image_height);
00663                         $this->tmpimg = imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
00664                 }
00665                 
00666                 $this->allocateColors();
00667                 imagepalettecopy($this->tmpimg, $this->im);
00668 
00669                 $this->setBackground();
00670 
00671                 $this->createCode();
00672 
00673                 if (!$this->draw_lines_over_text && $this->num_lines > 0) $this->drawLines();
00674 
00675                 $this->drawWord();
00676                 if ($this->use_gd_font == false && is_readable($this->ttf_file)) $this->distortedCopy();
00677 
00678                 if ($this->draw_lines_over_text && $this->num_lines > 0) $this->drawLines();
00679 
00680                 if (trim($this->image_signature) != '') $this->addSignature();
00681 
00682                 $this->output();
00683 
00684         }
00685         
00686         /**
00687          * Allocate all colors that will be used in the CAPTCHA image
00688          * 
00689          * @since 2.0.1
00690          * @access private
00691          */
00692         function allocateColors()
00693         {
00694                 // allocate bg color first for imagecreate
00695                 $this->gdbgcolor = imagecolorallocate($this->im, $this->image_bg_color->r, $this->image_bg_color->g, $this->image_bg_color->b);
00696                 
00697                 $alpha = intval($this->text_transparency_percentage / 100 * 127);
00698                 
00699                 if ($this->use_transparent_text == true) {
00700       $this->gdtextcolor = imagecolorallocatealpha($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b, $alpha);
00701       $this->gdlinecolor = imagecolorallocatealpha($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b, $alpha);
00702                 } else {
00703                         $this->gdtextcolor = imagecolorallocate($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b);
00704       $this->gdlinecolor = imagecolorallocate($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b);
00705                 }
00706     
00707     $this->gdsignaturecolor = imagecolorallocate($this->im, $this->signature_color->r, $this->signature_color->g, $this->signature_color->b);
00708     
00709     if ($this->use_multi_text == true) {
00710         $this->gdmulticolor = array();
00711         
00712         foreach($this->multi_text_color as $color) {
00713                 if ($this->use_transparent_text == true) {
00714                   $this->gdmulticolor[] = imagecolorallocatealpha($this->im, $color->r, $color->g, $color->b, $alpha);
00715                 } else {
00716                         $this->gdmulticolor[] = imagecolorallocate($this->im, $color->r, $color->g, $color->b);
00717                 }
00718         }
00719     }
00720         }
00721 
00722         /**
00723          * Set the background of the CAPTCHA image
00724          *
00725          * @access private
00726          *
00727          */
00728         function setBackground()
00729         {
00730                 imagefilledrectangle($this->im, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $this->gdbgcolor);
00731     imagefilledrectangle($this->tmpimg, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $this->gdbgcolor);
00732     
00733                 if ($this->bgimg == '') {
00734                         if ($this->background_directory != null && is_dir($this->background_directory) && is_readable($this->background_directory)) {
00735                                 $img = $this->getBackgroundFromDirectory();
00736                                 if ($img != false) {
00737                                         $this->bgimg = $img;
00738                                 }
00739                         }
00740                 }
00741 
00742                 $dat = @getimagesize($this->bgimg);
00743                 if($dat == false) { 
00744                         return;
00745                 }
00746 
00747                 switch($dat[2]) {
00748                         case 1:  $newim = @imagecreatefromgif($this->bgimg); break;
00749                         case 2:  $newim = @imagecreatefromjpeg($this->bgimg); break;
00750                         case 3:  $newim = @imagecreatefrompng($this->bgimg); break;
00751                         case 15: $newim = @imagecreatefromwbmp($this->bgimg); break;
00752                         case 16: $newim = @imagecreatefromxbm($this->bgimg); break;
00753                         default: return;
00754                 }
00755 
00756                 if(!$newim) return;
00757 
00758                 imagecopyresized($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height, imagesx($newim), imagesy($newim));
00759         }
00760 
00761         /**
00762          * Return the full path to a random gif, jpg, or png from the background directory.
00763          *
00764          * @access private
00765          * @see Securimage::$background_directory
00766          * @return mixed  false if none found, string $path if found
00767          */
00768         function getBackgroundFromDirectory()
00769         {
00770                 $images = array();
00771 
00772                 if ($dh = opendir($this->background_directory)) {
00773                         while (($file = readdir($dh)) !== false) {
00774                                 if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
00775                         }
00776 
00777                         closedir($dh);
00778 
00779                         if (sizeof($images) > 0) {
00780                                 return rtrim($this->background_directory, '/') . '/' . $images[rand(0, sizeof($images)-1)];
00781                         }
00782                 }
00783 
00784                 return false;
00785         }
00786 
00787         /**
00788          * Draw random curvy lines over the image<br />
00789          * Modified code from HKCaptcha
00790          *
00791          * @since 2.0
00792          * @access private
00793          *
00794          */
00795         function drawLines()
00796         {
00797                 for ($line = 0; $line < $this->num_lines; ++$line) {
00798                         $x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
00799                         $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
00800                         $y = rand($this->image_height * 0.1, $this->image_height * 0.9);
00801                          
00802                         $theta = ($this->frand()-0.5) * M_PI * 0.7;
00803                         $w = $this->image_width;
00804                         $len = rand($w * 0.4, $w * 0.7);
00805                         $lwid = rand(0, 2);
00806                          
00807                         $k = $this->frand() * 0.6 + 0.2;
00808                         $k = $k * $k * 0.5;
00809                         $phi = $this->frand() * 6.28;
00810                         $step = 0.5;
00811                         $dx = $step * cos($theta);
00812                         $dy = $step * sin($theta);
00813                         $n = $len / $step;
00814                         $amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
00815                         $x0 = $x - 0.5 * $len * cos($theta);
00816                         $y0 = $y - 0.5 * $len * sin($theta);
00817                          
00818                         $ldx = round(-$dy * $lwid);
00819                         $ldy = round($dx * $lwid);
00820                          
00821                         for ($i = 0; $i < $n; ++$i) {
00822                                 $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
00823                                 $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
00824                                 imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
00825                         }
00826                 }
00827         }
00828 
00829         /**
00830          * Draw the CAPTCHA code over the image
00831          *
00832          * @access private
00833          *
00834          */
00835         function drawWord()
00836         {
00837                 $width2 = $this->image_width * $this->iscale;
00838                 $height2 = $this->image_height * $this->iscale;
00839                  
00840                 if ($this->use_gd_font == true || !is_readable($this->ttf_file)) {
00841                         if (!is_int($this->gd_font_file)) { //is a file name
00842                                 $font = @imageloadfont($this->gd_font_file);
00843                                 if ($font == false) {
00844                                         trigger_error("Failed to load GD Font file {$this->gd_font_file} ", E_USER_WARNING);
00845                                         return;
00846                                 }
00847                         } else { //gd font identifier
00848                                 $font = $this->gd_font_file;
00849                         }
00850 
00851                         imagestring($this->im, $font, $this->text_x_start, ($this->image_height / 2) - ($this->gd_font_size / 2), $this->code, $this->gdtextcolor);
00852                 } else { //ttf font
00853                         $font_size = $height2 * .35;
00854                         $bb = imagettfbbox($font_size, 0, $this->ttf_file, $this->code);
00855                         $tx = $bb[4] - $bb[0];
00856                         $ty = $bb[5] - $bb[1];
00857                         $x  = floor($width2 / 2 - $tx / 2 - $bb[0]);
00858                         $y  = round($height2 / 2 - $ty / 2 - $bb[1]);
00859 
00860                         $strlen = strlen($this->code);
00861                         if (!is_array($this->multi_text_color)) $this->use_multi_text = false;
00862 
00863 
00864                         if ($this->use_multi_text == false && $this->text_angle_minimum == 0 && $this->text_angle_maximum == 0) { // no angled or multi-color characters
00865                                 imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code);
00866                         } else {
00867                                 for($i = 0; $i < $strlen; ++$i) {
00868                                         $angle = rand($this->text_angle_minimum, $this->text_angle_maximum);
00869                                         $y = rand($y - 5, $y + 5);
00870                                         if ($this->use_multi_text == true) {
00871                                                 $font_color = $this->gdmulticolor[rand(0, sizeof($this->gdmulticolor) - 1)];
00872                                         } else {
00873                                                 $font_color = $this->gdtextcolor;
00874                                         }
00875                                         
00876                                         $ch = $this->code{$i};
00877                                          
00878                                         imagettftext($this->tmpimg, $font_size, $angle, $x, $y, $font_color, $this->ttf_file, $ch);
00879                                          
00880                                         // estimate character widths to increment $x without creating spaces that are too large or too small
00881                                         // these are best estimates to align text but may vary between fonts
00882                                         // for optimal character widths, do not use multiple text colors or character angles and the complete string will be written by imagettftext
00883                                         if (strpos('abcdeghknopqsuvxyz', $ch) !== false) {
00884                                                 $min_x = $font_size - ($this->iscale * 6);
00885                                                 $max_x = $font_size - ($this->iscale * 6);
00886                                         } else if (strpos('ilI1', $ch) !== false) {
00887                                                 $min_x = $font_size / 5;
00888                                                 $max_x = $font_size / 3;
00889                                         } else if (strpos('fjrt', $ch) !== false) {
00890                                                 $min_x = $font_size - ($this->iscale * 12);
00891                                                 $max_x = $font_size - ($this->iscale * 12);
00892                                         } else if ($ch == 'wm') {
00893                                                 $min_x = $font_size;
00894                                                 $max_x = $font_size + ($this->iscale * 3);
00895                                         } else { // numbers, capitals or unicode
00896                                                 $min_x = $font_size + ($this->iscale * 2);
00897                                                 $max_x = $font_size + ($this->iscale * 5);
00898                                         }
00899                                          
00900                                         $x += rand($min_x, $max_x);
00901                                 } //for loop
00902                         } // angled or multi-color
00903                 } //else ttf font
00904                 //$this->im = $this->tmpimg;
00905                 //$this->output();
00906         } //function
00907 
00908         /**
00909          * Warp text from temporary image onto final image.<br />
00910          * Modified for securimage
00911          *
00912          * @access private
00913          * @since 2.0
00914          * @author Han-Kwang Nienhuys modified
00915          * @copyright Han-Kwang Neinhuys
00916          *
00917          */
00918         function distortedCopy()
00919         {
00920                 $numpoles = 3; // distortion factor
00921                  
00922                 // make array of poles AKA attractor points
00923                 for ($i = 0; $i < $numpoles; ++$i) {
00924                         $px[$i]  = rand($this->image_width * 0.3, $this->image_width * 0.7);
00925                         $py[$i]  = rand($this->image_height * 0.3, $this->image_height * 0.7);
00926                         $rad[$i] = rand($this->image_width * 0.4, $this->image_width * 0.7);
00927                         $tmp     = -$this->frand() * 0.15 - 0.15;
00928                         $amp[$i] = $this->perturbation * $tmp;
00929                 }
00930                  
00931                 $bgCol   = imagecolorat($this->tmpimg, 0, 0);
00932                 $width2  = $this->iscale * $this->image_width;
00933                 $height2 = $this->iscale * $this->image_height;
00934                  
00935                 imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
00936                  
00937                 // loop over $img pixels, take pixels from $tmpimg with distortion field
00938                 for ($ix = 0; $ix < $this->image_width; ++$ix) {
00939                         for ($iy = 0; $iy < $this->image_height; ++$iy) {
00940                                 $x = $ix;
00941                                 $y = $iy;
00942                                         
00943                                 for ($i = 0; $i < $numpoles; ++$i) {
00944                                         $dx = $ix - $px[$i];
00945                                         $dy = $iy - $py[$i];
00946                                         if ($dx == 0 && $dy == 0) continue;
00947 
00948                                         $r = sqrt($dx * $dx + $dy * $dy);
00949                                         if ($r > $rad[$i]) continue;
00950 
00951                                         $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
00952                                         $x += $dx * $rscale;
00953                                         $y += $dy * $rscale;
00954                                 }
00955                                         
00956                                 $c = $bgCol;
00957                                 $x *= $this->iscale;
00958                                 $y *= $this->iscale;
00959 
00960                                 if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
00961                                         $c = imagecolorat($this->tmpimg, $x, $y);
00962                                 }
00963 
00964                                 if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
00965                                         imagesetpixel($this->im, $ix, $iy, $c);
00966                                 }
00967                         }
00968                 }
00969         }
00970 
00971         /**
00972          * Create a code and save to the session
00973          *
00974          * @access private
00975          * @since 1.0.1
00976          *
00977          */
00978         function createCode()
00979         {
00980                 $this->code = false;
00981 
00982                 if ($this->use_wordlist && is_readable($this->wordlist_file)) {
00983                         $this->code = $this->readCodeFromFile();
00984                 }
00985 
00986                 if ($this->code == false) {
00987                         $this->code = $this->generateCode($this->code_length);
00988                 }
00989                 
00990                 $this->saveData();
00991         }
00992 
00993         /**
00994          * Generate a code
00995          *
00996          * @access private
00997          * @param int $len  The code length
00998          * @return string
00999          */
01000         function generateCode($len)
01001         {
01002                 $code = '';
01003 
01004                 for($i = 1, $cslen = strlen($this->charset); $i <= $len; ++$i) {
01005                         $code .= $this->charset{rand(0, $cslen - 1)};
01006                 }
01007                 return $code;
01008         }
01009 
01010         /**
01011          * Reads a word list file to get a code
01012          *
01013          * @access private
01014          * @since 1.0.2
01015          * @return mixed  false on failure, a word on success
01016          */
01017         function readCodeFromFile()
01018         {
01019                 $fp = @fopen($this->wordlist_file, 'rb');
01020                 if (!$fp) return false;
01021 
01022                 $fsize = filesize($this->wordlist_file);
01023                 if ($fsize < 32) return false; // too small of a list to be effective
01024 
01025                 if ($fsize < 128) {
01026                         $max = $fsize; // still pretty small but changes the range of seeking
01027                 } else {
01028                         $max = 128;
01029                 }
01030 
01031                 fseek($fp, rand(0, $fsize - $max), SEEK_SET);
01032                 $data = fread($fp, 128); // read a random 128 bytes from file
01033                 fclose($fp);
01034                 $data = preg_replace("/\r?\n/", "\n", $data);
01035 
01036                 $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
01037                 $end   = strpos($data, "\n", $start);           // find end of word
01038 
01039                 return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
01040         }
01041 
01042         /**
01043          * Output image to the browser
01044          *
01045          * @access private
01046          *
01047          */
01048         function output()
01049         {
01050                 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
01051                 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
01052                 header("Cache-Control: no-store, no-cache, must-revalidate");
01053                 header("Cache-Control: post-check=0, pre-check=0", false);
01054                 header("Pragma: no-cache");
01055 
01056                 switch($this->image_type)
01057                 {
01058                         case SI_IMAGE_JPEG:
01059                                 header("Content-Type: image/jpeg");
01060                                 imagejpeg($this->im, null, 90);
01061                                 break;
01062 
01063                         case SI_IMAGE_GIF:
01064                                 header("Content-Type: image/gif");
01065                                 imagegif($this->im);
01066                                 break;
01067 
01068                         default:
01069                                 header("Content-Type: image/png");
01070                                 imagepng($this->im);
01071                                 break;
01072                 }
01073 
01074                 imagedestroy($this->im);
01075                 exit;
01076         }
01077 
01078         /**
01079          * Get WAV or MP3 file data of the spoken code.<br />
01080          * This is appropriate for output to the browser as audio/x-wav or audio/mpeg
01081          *
01082          * @since 1.0.1
01083          * @return string  WAV or MP3 data
01084          *
01085          */
01086         function getAudibleCode($format = 'wav')
01087         {
01088                 $letters = array();
01089                 $code    = $this->getCode();
01090 
01091                 if ($code == '') {
01092                         $this->createCode();
01093                         $code = $this->getCode();
01094                 }
01095 
01096                 for($i = 0; $i < strlen($code); ++$i) {
01097                         $letters[] = $code{$i};
01098                 }
01099 
01100                 if ($format == 'mp3') {
01101                         return $this->generateMP3($letters);
01102                 } else {
01103                         return $this->generateWAV($letters);
01104                 }
01105         }
01106 
01107         /**
01108          * Set the path to the audio directory.<br />
01109          *
01110          * @since 1.0.4
01111          * @return bool true if the directory exists and is readble, false if not
01112          */
01113         function setAudioPath($audio_directory)
01114         {
01115                 if (is_dir($audio_directory) && is_readable($audio_directory)) {
01116                         $this->audio_path = $audio_directory;
01117                         return true;
01118                 } else {
01119                         return false;
01120                 }
01121         }
01122 
01123         /**
01124          * Save the code in the session
01125          *
01126          * @access private
01127          *
01128          */
01129         function saveData()
01130         {
01131                 $_SESSION['securimage_code_value'] = strtolower($this->code);
01132                 $_SESSION['securimage_code_ctime'] = time();
01133                 
01134                 $this->saveCodeToDatabase();
01135         }
01136 
01137         /**
01138          * Validate the code to the user code
01139          *
01140          * @access private
01141          *
01142          */
01143         function validate()
01144         {
01145                 // retrieve code from session, if no code exists check sqlite database if supported.
01146                 
01147                 if (isset($_SESSION['securimage_code_value']) && trim($_SESSION['securimage_code_value']) != '') {
01148                         if ($this->isCodeExpired($_SESSION['securimage_code_ctime']) == false) { 
01149                           $code = $_SESSION['securimage_code_value'];
01150                         }
01151                 } else if ($this->use_sqlite_db == true && function_exists('sqlite_open')) { // no code in session - may mean user has cookies turned off
01152                         $this->openDatabase();
01153                         $code = $this->getCodeFromDatabase();
01154                 } else {
01155                         // session code invalid or non-existant and code not found in sqlite db or sqlite is not available
01156                         $code = '';
01157                 }
01158                 
01159                 $code               = trim(strtolower($code));
01160                 $code_entered       = trim(strtolower($this->code_entered));
01161                 $this->correct_code = false;
01162                 
01163                 if ($code != '') {
01164                         if ($code == $code_entered) {
01165                           $this->correct_code = true;
01166                           $_SESSION['securimage_code_value'] = '';
01167                           $_SESSION['securimage_code_ctime'] = '';
01168                           $this->clearCodeFromDatabase();
01169                   }
01170                 }
01171         }
01172 
01173         /**
01174          * Get the captcha code
01175          *
01176          * @since 1.0.1
01177          * @return string
01178          */
01179         function getCode()
01180         {
01181                 if (isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value'])) {
01182                         return strtolower($_SESSION['securimage_code_value']);
01183                 } else {
01184                         if ($this->sqlite_handle == false) $this->openDatabase();
01185                         
01186                         return $this->getCodeFromDatabase(); // attempt to get from database, returns empty string if sqlite is not available or disabled
01187                 }
01188         }
01189 
01190         /**
01191          * Check if the user entered code was correct
01192          *
01193          * @access private
01194          * @return boolean
01195          */
01196         function checkCode()
01197         {
01198                 return $this->correct_code;
01199         }
01200 
01201         /**
01202          * Generate a wav file by concatenating individual files
01203          *
01204          * @since 1.0.1
01205          * @access private
01206          * @param array $letters  Array of letters to build a file from
01207          * @return string  WAV file data
01208          */
01209         function generateWAV($letters)
01210         {
01211                 $data_len    = 0;
01212                 $files       = array();
01213                 $out_data    = '';
01214 
01215                 foreach ($letters as $letter) {
01216                         $filename = $this->audio_path . strtoupper($letter) . '.wav';
01217 
01218                         $fp = fopen($filename, 'rb');
01219 
01220                         $file = array();
01221 
01222                         $data = fread($fp, filesize($filename)); // read file in
01223 
01224                         $header = substr($data, 0, 36);
01225                         $body   = substr($data, 44);
01226 
01227 
01228                         $data = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/VSubChunk1Size/vAudioFormat/vNumChannels/VSampleRate/VByteRate/vBlockAlign/vBitsPerSample', $header);
01229 
01230                         $file['sub_chunk1_id']   = $data['SubChunk1ID'];
01231                         $file['bits_per_sample'] = $data['BitsPerSample'];
01232                         $file['channels']        = $data['NumChannels'];
01233                         $file['format']          = $data['AudioFormat'];
01234                         $file['sample_rate']     = $data['SampleRate'];
01235                         $file['size']            = $data['ChunkSize'] + 8;
01236                         $file['data']            = $body;
01237 
01238                         if ( ($p = strpos($file['data'], 'LIST')) !== false) {
01239                                 // If the LIST data is not at the end of the file, this will probably break your sound file
01240                                 $info         = substr($file['data'], $p + 4, 8);
01241                                 $data         = unpack('Vlength/Vjunk', $info);
01242                                 $file['data'] = substr($file['data'], 0, $p);
01243                                 $file['size'] = $file['size'] - (strlen($file['data']) - $p);
01244                         }
01245 
01246                         $files[] = $file;
01247                         $data    = null;
01248                         $header  = null;
01249                         $body    = null;
01250 
01251                         $data_len += strlen($file['data']);
01252 
01253                         fclose($fp);
01254                 }
01255 
01256                 $out_data = '';
01257                 for($i = 0; $i < sizeof($files); ++$i) {
01258                         if ($i == 0) { // output header
01259                                 $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(' '));
01260 
01261                                 $out_data .= pack('VvvVVvv',
01262                                 16,
01263                                 $files[$i]['format'],
01264                                 $files[$i]['channels'],
01265                                 $files[$i]['sample_rate'],
01266                                 $files[$i]['sample_rate'] * (($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8),
01267                                 ($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8,
01268                                 $files[$i]['bits_per_sample'] );
01269 
01270                                 $out_data .= pack('C4', ord('d'), ord('a'), ord('t'), ord('a'));
01271 
01272                                 $out_data .= pack('V', $data_len);
01273                         }
01274 
01275                         $out_data .= $files[$i]['data'];
01276                 }
01277 
01278                 $this->scrambleAudioData($out_data, 'wav');
01279                 return $out_data;
01280         }
01281 
01282         /**
01283          * Randomly modify the audio data to scramble sound and prevent binary recognition.<br />
01284          * Take care not to "break" the audio file by leaving the header data intact.
01285          *
01286          * @since 2.0
01287          * @access private
01288          * @param $data Sound data in mp3 of wav format
01289          */
01290         function scrambleAudioData(&$data, $format)
01291         {
01292                 if ($format == 'wav') {
01293                         $start = strpos($data, 'data') + 4; // look for "data" indicator
01294                         if ($start === false) $start = 44;  // if not found assume 44 byte header
01295                 } else { // mp3
01296                         $start = 4; // 4 byte (32 bit) frame header
01297                 }
01298                  
01299                 $start  += rand(1, 64); // randomize starting offset
01300                 $datalen = strlen($data) - $start - 256; // leave last 256 bytes unchanged
01301                  
01302                 for ($i = $start; $i < $datalen; $i += 64) {
01303                         $ch = ord($data{$i});
01304                         if ($ch < 9 || $ch > 119) continue;
01305 
01306                         $data{$i} = chr($ch + rand(-8, 8));
01307                 }
01308         }
01309 
01310         /**
01311          * Generate an mp3 file by concatenating individual files
01312          * @since 1.0.4
01313          * @access private
01314          * @param array $letters  Array of letters to build a file from
01315          * @return string  MP3 file data
01316          */
01317         function generateMP3($letters)
01318         {
01319                 $data_len    = 0;
01320                 $files       = array();
01321                 $out_data    = '';
01322 
01323                 foreach ($letters as $letter) {
01324                         $filename = $this->audio_path . strtoupper($letter) . '.mp3';
01325 
01326                         $fp   = fopen($filename, 'rb');
01327                         $data = fread($fp, filesize($filename)); // read file in
01328 
01329                         $this->scrambleAudioData($data, 'mp3');
01330                         $out_data .= $data;
01331 
01332                         fclose($fp);
01333                 }
01334 
01335 
01336                 return $out_data;
01337         }
01338 
01339         /**
01340          * Generate random number less than 1
01341          * @since 2.0
01342          * @access private
01343          * @return float
01344          */
01345         function frand()
01346         {
01347                 return 0.0001*rand(0,9999);
01348         }
01349 
01350         /**
01351          * Print signature text on image
01352          *
01353          * @since 2.0
01354          * @access private
01355          *
01356          */
01357         function addSignature()
01358         {
01359                 if ($this->use_gd_font) {
01360                         imagestring($this->im, 5, $this->image_width - (strlen($this->image_signature) * 10), $this->image_height - 20, $this->image_signature, $this->gdsignaturecolor);
01361                 } else {
01362                          
01363                         $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
01364                         $textlen = $bbox[2] - $bbox[0];
01365                         $x = $this->image_width - $textlen - 5;
01366                         $y = $this->image_height - 3;
01367                          
01368                         imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
01369                 }
01370         }
01371         
01372         /**
01373          * Get hashed IP address of remote user
01374          * 
01375          * @access private
01376          * @since 2.0.1
01377          * @return string
01378          */
01379         function getIPHash()
01380         {
01381                 return strtolower(md5($_SERVER['REMOTE_ADDR']));
01382         }
01383         
01384         /**
01385          * Open SQLite database
01386          * 
01387          * @access private
01388          * @since 2.0.1
01389          * @return bool true if database was opened successfully
01390          */
01391         function openDatabase()
01392         {
01393                 $this->sqlite_handle = false;
01394                 
01395                 if ($this->use_sqlite_db && function_exists('sqlite_open')) {
01396                         $this->sqlite_handle = sqlite_open($this->sqlite_database, 0666, $error);
01397                         
01398                         if ($this->sqlite_handle !== false) {
01399                                 $res = sqlite_query($this->sqlite_handle, "PRAGMA table_info(codes)");
01400                                 if (sqlite_num_rows($res) == 0) {
01401                                   sqlite_query($this->sqlite_handle, "CREATE TABLE codes (iphash VARCHAR(32) PRIMARY KEY, code VARCHAR(32) NOT NULL, created INTEGER)");
01402                                 }
01403                         }
01404                         
01405                         return $this->sqlite_handle != false;
01406                 }
01407                 
01408                 return $this->sqlite_handle;
01409         }
01410         
01411         /**
01412          * Save captcha code to sqlite database
01413          * 
01414          * @access private
01415          * @since 2.0.1
01416          * @return bool true if code was saved, false if not
01417          */
01418         function saveCodeToDatabase()
01419         {
01420                 $success = false;
01421                 
01422                 $this->openDatabase();
01423                 
01424                 if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
01425                         $ip = $this->getIPHash();
01426                         $time = time();
01427                         $code = $_SESSION['securimage_code_value']; // hash code for security - if cookies are disabled the session still exists at this point
01428                         $success = sqlite_query($this->sqlite_handle, "INSERT OR REPLACE INTO codes(iphash, code, created) VALUES('$ip', '$code', $time)");
01429                 }
01430                 
01431                 return $success !== false;
01432         }
01433         
01434         /**
01435          * Get stored captcha code from sqlite database based on ip address hash
01436          * 
01437          * @access private
01438          * @since 2.0.1
01439          * @return string captcha code
01440          */
01441         function getCodeFromDatabase()
01442         {
01443     $code = '';
01444 
01445     if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
01446         $ip = $this->getIPHash();
01447         
01448         $res = sqlite_query($this->sqlite_handle, "SELECT * FROM codes WHERE iphash = '$ip'");
01449         if ($res && sqlite_num_rows($res) > 0) {
01450                 $res = sqlite_fetch_array($res);
01451                 
01452                 if ($this->isCodeExpired($res['created']) == false) {
01453                         $code = $res['code'];
01454                 }
01455         }
01456     }
01457     
01458     return $code;
01459         }
01460         
01461         /**
01462          * Delete a code from the database by ip address hash
01463          * 
01464          * @access private
01465          * @since 2.0.1
01466          */
01467         function clearCodeFromDatabase()
01468         {
01469                 if ($this->sqlite_handle !== false) {
01470                         $ip = $this->getIPHash();
01471                         
01472                         sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE iphash = '$ip'");
01473                 }
01474         }
01475         
01476         /**
01477          * Purge codes over a day old from database
01478          * 
01479          * @access private
01480          * @since 2.0.1
01481          */
01482         function purgeOldCodesFromDatabase()
01483         {
01484                 if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
01485                         $now   = time();
01486                         $limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time;
01487                         
01488                         sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE $now - created > $limit");
01489                 }
01490         }
01491         
01492         /**
01493          * Check a code to see if it is expired based on creation time
01494          * 
01495          * @access private
01496          * @since 2.0.1
01497          * @param $creation_time unix timestamp of code creation time
01498          * @return bool true if code has expired, false if not
01499          */
01500         function isCodeExpired($creation_time)
01501         {
01502                 $expired = true;
01503                 
01504                 if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) {
01505                         $expired = false;
01506                 } else if (time() - $creation_time < $this->expiry_time) {
01507                         $expired = false;
01508                 }
01509                 
01510                 return $expired;
01511         }
01512         
01513 } /* class Securimage */
01514 
01515 
01516 /**
01517  * Color object for Securimage CAPTCHA
01518  *
01519  * @since 2.0
01520  * @package Securimage
01521  * @subpackage classes
01522  *
01523  */
01524 class Securimage_Color {
01525         /**
01526          * Red component: 0-255
01527          *
01528          * @var int
01529          */
01530         var $r;
01531         /**
01532          * Green component: 0-255
01533          *
01534          * @var int
01535          */
01536         var $g;
01537         /**
01538          * Blue component: 0-255
01539          *
01540          * @var int
01541          */
01542         var $b;
01543 
01544         /**
01545          * Create a new Securimage_Color object.<br />
01546          * Specify the red, green, and blue components using their HTML hex code equivalent.<br />
01547          * Example: The code for the HTML color #4A203C is:<br />
01548          * $color = new Securimage_Color(0x4A, 0x20, 0x3C);
01549          *
01550          * @param $red Red component 0-255
01551          * @param $green Green component 0-255
01552          * @param $blue Blue component 0-255
01553          */
01554         function Securimage_Color($red, $green = null, $blue = null)
01555         {
01556                 if ($green == null && $blue == null && preg_match('/^#[a-f0-9]{3,6}$/i', $red)) {
01557                         $col = substr($red, 1);
01558                         if (strlen($col) == 3) {
01559                                 $red   = str_repeat(substr($col, 0, 1), 2);
01560                                 $green = str_repeat(substr($col, 1, 1), 2);
01561                                 $blue  = str_repeat(substr($col, 2, 1), 2);
01562                         } else {
01563                                 $red   = substr($col, 0, 2);
01564                                 $green = substr($col, 2, 2);
01565                                 $blue  = substr($col, 4, 2); 
01566                         }
01567                         
01568                         $red   = hexdec($red);
01569                         $green = hexdec($green);
01570                         $blue  = hexdec($blue);
01571                 } else {
01572                         if ($red < 0) $red       = 0;
01573                         if ($red > 255) $red     = 255;
01574                         if ($green < 0) $green   = 0;
01575                         if ($green > 255) $green = 255;
01576                         if ($blue < 0) $blue     = 0;
01577                         if ($blue > 255) $blue   = 255;
01578                 }
01579 
01580                 $this->r = $red;
01581                 $this->g = $green;
01582                 $this->b = $blue;
01583         }
01584 }
 All Data Structures Namespaces Files Functions Variables Enumerations