/securimage.php
PHP | 3801 lines | 2126 code | 414 blank | 1261 comment | 385 complexity | 10a63003b27d0c7d825e7dacd4df34e9 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- // error_reporting(E_ALL); ini_set('display_errors', 1); // uncomment this line for debugging
- /**
- * Project: Securimage: A PHP class dealing with CAPTCHA images, audio, and validation
- * File: securimage.php
- *
- * Copyright (c) 2018, Drew Phillips
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * - Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Any modifications to the library should be indicated clearly in the source code
- * to inform users that the changes are not a part of the original software.
- *
- * @link https://www.phpcaptcha.org Securimage Homepage
- * @link https://www.phpcaptcha.org/latest.zip Download Latest Version
- * @link https://github.com/dapphp/securimage GitHub page
- * @link https://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
- * @copyright 2018 Drew Phillips
- * @author Drew Phillips <drew@drew-phillips.com>
- * @version 3.6.8 (May 2020)
- * @package Securimage
- *
- */
- /**
- ChangeLog
- 3.6.8
- - Ability to fix open_basedir warning by setting Securimage::$lame_binary_path = ''; (#63)
- - Fix division by zero if captcha length is 1 (#88)
- - Add options to getCaptchaHtml input_required (#82) and js_url (#95)
- - PHP 7.3/7.4 compat fixes (#101)
- - Project status: https://github.com/dapphp/securimage/issues/99
- - Improve handling of multi-byte wordlists (#87)
- 3.6.7
- - Merge changes from 4.0.1-nextgen
- - Increase captcha difficulty
- - Add setting "use_text_angles". Enable to select a random angle and step value and draw each character at an angle in a step like fashion
- - Add setting "use_random_spaces". Enable to insert 1-3 spaces between a random group of letters some of the time
- - Add setting "use_random_baseline". Enable to draw letters at a random height instead of centered. Each character's baseline is a step up or down from the previous (not totally random)
- - Add setting "use_random_boxes". Enable to draw a bounding box around one or more characters at random
- - Improve performance of captcha generation when using distortion (perturbation) and noise (noise_level)
- - Enable image anti-aliasing
- - Make all text functions multibyte safe when using UTF-8 or other encodings for charsets and wordlists (using mbstring)
- 3.6.6
- - Not critical: Fix potential HTML injection in example form via HTTP_USER_AGENT (CVE-2017-14077)
- 3.6.5
- - Fix regex in replaceElements in securimage.js
- - Update examples
- - Exclude certain examples from Git autogenerated archives
- 3.6.4
- - Fix XSS vulnerability in example_form.ajax.php (Discovered by RedTeam. advisory rt-sa-2016-002)
- - Update example_form.ajax.php to use Securimage::getCaptchaHtml()
- 3.6.3
- - Add support for multibyte wordlist files
- - Fix code generation issues with UTF-8 charsets
- - Add parameter to getCaptchaHtml() method to control display components of captcha HTML
- - Fix database audio storage issue with multiple namespaces
- 3.6.2
- - Support HTTP range requests with audio playback (iOS requirement)
- - Add optional config.inc.php for storing global configuration settings
- 3.6.1
- - Fix copyElement bug in securimage.js for IE Flash fallback
- 3.6
- - Implement CAPTCHA audio using HTML5 <audio> with optional Flash fallback
- - Support MP3 audio using LAME MP3 Encoder (Internet Explorer 9+ does not support WAV format in <audio> tags)
- - Add getCaptchaHtml() options to support full framework integration (ruifil)
- 3.5.4
- - Fix email validation code in example form files
- - Fix backslashes in getCaptchaHtml for img attribute on Windows systems
- 3.5.3
- - Add options for audio button to getCaptchaHtml(), fix urlencoding of flash parameters that was breaking button
- 3.5.2
- - Add Securimage::getCaptchaHtml() for getting automatically generated captcha html code
- - Option for using SoX to add effects to captcha audio to make identification by neural networks more difficult
- - Add setNamespace() method
- - Add getTimeToSolve() method
- - Add session_status() check so session still starts if one had previously been opened and closed
- - Add .htaccess file to audio directory to deny access; update audio files
- - Option to skip checking of database tables during connection
- - Add composer.json to package, submit to packagist
- - Add font_ratio variable to determine size of font (github.com/wilkor)
- - Add hint if sqlite3 database is not writeable. Improve database error handling, add example database options to securimage_play.php
- - Fixed issue regarding database storage and math captcha breaking audio output (github.com/SoftwareAndOutsourcing)
- 3.5.1
- - Fix XSS vulnerability in example_form.php (discovered by Gjoko Krstic - <gjoko@zeroscience.mk>)
- 3.5
- - Release new version
- - MB string support for charlist
- - Modify audio file path to use language directories
- - Changed default captcha appearance
- 3.2RC4
- - Add MySQL, PostgreSQL, and SQLite3 support for database storage
- - Deprecate "use_sqlite_db" option and remove SQLite2/sqlite_* functions
- - Add new captcha type that displays 2 dictionary words on one image
- - Update examples
- 3.2RC3
- - Fix canSendHeaders() check which was breaking if a PHP startup error was issued
- 3.2RC2
- - Add error handler (https://github.com/dapphp/securimage/issues/15)
- - Fix flash examples to use the correct value name for audio parameter
- 3.2RC1
- - New audio captcha code. Faster, fully dynamic audio, full WAV support
- (Paul Voegler, Drew Phillips) <http://voegler.eu/pub/audio>
- - New Flash audio streaming button. User defined image and size supported
- - Additional options for customizing captcha (noise_level, send_headers,
- no_exit, no_session, display_value
- - Add captcha ID support. Uses sqlite and unique captcha IDs to track captchas,
- no session used
- - Add static methods for creating and validating captcha by ID
- - Automatic clearing of old codes from SQLite database
- 3.0.3Beta
- - Add improved mixing function to WavFile class (Paul Voegler)
- - Improve performance and security of captcha audio (Paul Voegler, Drew Phillips)
- - Add option to use random file as background noise in captcha audio
- - Add new securimage options for audio files
- 3.0.2Beta
- - Fix issue with session variables when upgrading from 2.0 - 3.0
- - Improve audio captcha, switch to use WavFile class, make mathematical captcha audio work
- 3.0.1
- - Bugfix: removed use of deprecated variable in addSignature method that would cause errors with display_errors on
- 3.0
- - Rewrite class using PHP5 OOP
- - Remove support for GD fonts, require FreeType
- - Remove support for multi-color codes
- - Add option to make codes case-sensitive
- - Add namespaces to support multiple captchas on a single page or page specific captchas
- - Add option to show simple math problems instead of codes
- - Remove support for mp3 files due to vulnerability in decoding mp3 audio files
- - Create new flash file to stream wav files instead of mp3
- - Changed to BSD license
- 2.0.2
- - Fix pathing to make integration into libraries easier (Nathan Phillip Brink ohnobinki@ohnopublishing.net)
- 2.0.1
- - Add support for browsers with cookies disabled (requires php5, sqlite) maps users to md5 hashed ip addresses and md5 hashed codes for security
- - 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)
- - Check for previous definition of image type constants (Mike Challis)
- - Fix mime type settings for audio output
- - Fixed color allocation issues with multiple colors and background images, consolidate allocation to one function
- - Ability to let codes expire after a given length of time
- - Allow HTML color codes to be passed to Securimage_Color (suggested by Mike Challis)
- 2.0.0
- - Add mathematical distortion to characters (using code from HKCaptcha)
- - Improved session support
- - Added Securimage_Color class for easier color definitions
- - Add distortion to audio output to prevent binary comparison attack (proposed by Sven "SavageTiger" Hagemann [insecurity.nl])
- - Flash button to stream mp3 audio (Douglas Walsh www.douglaswalsh.net)
- - Audio output is mp3 format by default
- - Change font to AlteHaasGrotesk by yann le coroller
- - Some code cleanup
- 1.0.4 (unreleased)
- - Ability to output audible codes in mp3 format to stream from flash
- 1.0.3.1
- - Error reading from wordlist in some cases caused words to be cut off 1 letter short
- 1.0.3
- - Removed shadow_text from code which could cause an undefined property error due to removal from previous version
- 1.0.2
- - Audible CAPTCHA Code wav files
- - Create codes from a word list instead of random strings
- 1.0
- - Added the ability to use a selected character set, rather than a-z0-9 only.
- - Added the multi-color text option to use different colors for each letter.
- - Switched to automatic session handling instead of using files for code storage
- - Added GD Font support if ttf support is not available. Can use internal GD fonts or load new ones.
- - Added the ability to set line thickness
- - Added option for drawing arced lines over letters
- - Added ability to choose image type for output
- */
- /**
- * Securimage CAPTCHA Class.
- *
- * A class for creating and validating secure CAPTCHA images and audio.
- *
- * The class contains many options regarding appearance, security, storage of
- * captcha data and image/audio generation options.
- *
- * @package Securimage
- * @subpackage classes
- * @author Drew Phillips <drew@drew-phillips.com>
- *
- */
- class Securimage
- {
- // All of the public variables below are securimage options
- // They can be passed as an array to the Securimage constructor, set below,
- // or set from securimage_show.php and securimage_play.php
- /**
- * Constant for rendering captcha as a JPEG image
- * @var int
- */
- const SI_IMAGE_JPEG = 1;
- /**
- * Constant for rendering captcha as a PNG image (default)
- * @var int
- */
- const SI_IMAGE_PNG = 2;
- /**
- * Constant for rendering captcha as a GIF image
- * @var int
- */
- const SI_IMAGE_GIF = 3;
- /**
- * Constant for generating a normal alphanumeric captcha based on the
- * character set
- *
- * @see Securimage::$charset charset property
- * @var int
- */
- const SI_CAPTCHA_STRING = 0;
- /**
- * Constant for generating a captcha consisting of a simple math problem
- *
- * @var int
- */
- const SI_CAPTCHA_MATHEMATIC = 1;
- /**
- * Constant for generating a word based captcha using 2 words from a list
- *
- * @var int
- */
- const SI_CAPTCHA_WORDS = 2;
- /**
- * MySQL option identifier for database storage option
- *
- * @var string
- */
- const SI_DRIVER_MYSQL = 'mysql';
- /**
- * PostgreSQL option identifier for database storage option
- *
- * @var string
- */
- const SI_DRIVER_PGSQL = 'pgsql';
- /**
- * SQLite option identifier for database storage option
- *
- * @var string
- */
- const SI_DRIVER_SQLITE3 = 'sqlite';
- /**
- * getCaptchaHtml() display constant for HTML Captcha Image
- *
- * @var integer
- */
- const HTML_IMG = 1;
- /**
- * getCaptchaHtml() display constant for HTML5 Audio code
- *
- * @var integer
- */
- const HTML_AUDIO = 2;
- /**
- * getCaptchaHtml() display constant for Captcha Input text box
- *
- * @var integer
- */
- const HTML_INPUT = 4;
- /**
- * getCaptchaHtml() display constant for Captcha Text HTML label
- *
- * @var integer
- */
- const HTML_INPUT_LABEL = 8;
- /**
- * getCaptchaHtml() display constant for HTML Refresh button
- *
- * @var integer
- */
- const HTML_ICON_REFRESH = 16;
- /**
- * getCaptchaHtml() display constant for all HTML elements (default)
- *
- * @var integer
- */
- const HTML_ALL = 0xffffffff;
- /*%*********************************************************************%*/
- // Properties
- /**
- * The width of the captcha image
- * @var int
- */
- public $image_width = 215;
- /**
- * The height of the captcha image
- * @var int
- */
- public $image_height = 80;
- /**
- * Font size is calculated by image height and this ratio. Leave blank for
- * default ratio of 0.4.
- *
- * Valid range: 0.1 - 0.99.
- *
- * Depending on image_width, values > 0.6 are probably too large and
- * values < 0.3 are too small.
- *
- * @var float
- */
- public $font_ratio;
- /**
- * The type of the image, default = png
- *
- * @see Securimage::SI_IMAGE_PNG SI_IMAGE_PNG
- * @see Securimage::SI_IMAGE_JPEG SI_IMAGE_JPEG
- * @see Securimage::SI_IMAGE_GIF SI_IMAGE_GIF
- * @var int
- */
- public $image_type = self::SI_IMAGE_PNG;
- /**
- * The background color of the captcha
- * @var Securimage_Color|string
- */
- public $image_bg_color = '#ffffff';
- /**
- * The color of the captcha text
- * @var Securimage_Color|string
- */
- public $text_color = '#707070';
- /**
- * The color of the lines over the captcha
- * @var Securimage_Color|string
- */
- public $line_color = '#707070';
- /**
- * The color of the noise that is drawn
- * @var Securimage_Color|string
- */
- public $noise_color = '#707070';
- /**
- * How transparent to make the text.
- *
- * 0 = completely opaque, 100 = invisible
- *
- * @var int
- */
- public $text_transparency_percentage = 20;
- /**
- * Whether or not to draw the text transparently.
- *
- * true = use transparency, false = no transparency
- *
- * @var bool
- */
- public $use_transparent_text = true;
- /**
- * The length of the captcha code
- * @var int
- */
- public $code_length = 6;
- /**
- * Display random spaces in the captcha text on the image
- *
- * @var bool true to insert random spacing between groups of letters
- */
- public $use_random_spaces = false;
- /**
- * Draw each character at an angle with random starting angle and increase/decrease per character
- * @var bool true to use random angles, false to draw each character normally
- */
- public $use_text_angles = false;
- /**
- * Instead of centering text vertically in the image, the baseline of each character is
- * randomized in such a way that the next character is drawn slightly higher or lower than
- * the previous in a step-like fashion.
- *
- * @var bool true to use random baselines, false to center text in image
- */
- public $use_random_baseline = false;
- /**
- * Draw a bounding box around some characters at random. 20% of the time, random boxes
- * may be drawn around 0 or more characters on the image.
- *
- * @var bool true to randomly draw boxes around letters, false not to
- */
- public $use_random_boxes = false;
- /**
- * Whether the captcha should be case sensitive or not.
- *
- * Not recommended, use only for maximum protection.
- *
- * @var bool
- */
- public $case_sensitive = false;
- /**
- * The character set to use for generating the captcha code
- * @var string
- */
- public $charset = 'abcdefghijkmnopqrstuvwxzyABCDEFGHJKLMNPQRSTUVWXZY0123456789';
- /**
- * How long in seconds a captcha remains valid, after this time it will be
- * considered incorrect.
- *
- * @var int
- */
- public $expiry_time = 900;
- /**
- * The session name securimage should use.
- *
- * Only use if your application uses a custom session name (e.g. Joomla).
- * It is recommended to set this value here so it is used by all securimage
- * scripts (i.e. securimage_show.php)
- *
- * @var string
- */
- public $session_name = null;
- /**
- * true to use the wordlist file, false to generate random captcha codes
- * @var bool
- */
- public $use_wordlist = false;
- /**
- * The level of distortion.
- *
- * 0.75 = normal, 1.0 = very high distortion
- *
- * @var double
- */
- public $perturbation = 0.85;
- /**
- * How many lines to draw over the captcha code to increase security
- * @var int
- */
- public $num_lines = 5;
- /**
- * The level of noise (random dots) to place on the image, 0-10
- * @var int
- */
- public $noise_level = 2;
- /**
- * The signature text to draw on the bottom corner of the image
- * @var string
- */
- public $image_signature = '';
- /**
- * The color of the signature text
- * @var Securimage_Color|string
- */
- public $signature_color = '#707070';
- /**
- * The path to the ttf font file to use for the signature text.
- * Defaults to $ttf_file (AHGBold.ttf)
- *
- * @see Securimage::$ttf_file
- * @var string
- */
- public $signature_font;
- /**
- * No longer used.
- *
- * Use an SQLite database to store data (for users that do not support cookies)
- *
- * @var bool
- * @see Securimage::$database_driver database_driver property
- * @deprecated 3.2RC4
- */
- public $use_sqlite_db = false;
- /**
- * Use a database backend for code storage.
- * Provides a fallback to users with cookies disabled.
- * Required when using captcha IDs.
- *
- * @see Securimage::$database_driver
- * @var bool
- */
- public $use_database = false;
- /**
- * Whether or not to skip checking if Securimage tables exist when using a
- * database.
- *
- * Turn this to true once database functionality is working to improve
- * performance.
- *
- * @var bool true to not check if captcha_codes tables are set up, false
- * to check (and create if necessary)
- */
- public $skip_table_check = false;
- /**
- * Database driver to use for database support.
- * Allowable values: *mysql*, *pgsql*, *sqlite*.
- * Default: sqlite
- *
- * @var string
- */
- public $database_driver = self::SI_DRIVER_SQLITE3;
- /**
- * Database host to connect to when using mysql or postgres
- *
- * On Linux use "localhost" for Unix domain socket, otherwise uses TCP/IP
- *
- * Does not apply to SQLite
- *
- * @var string
- */
- public $database_host = 'localhost';
- /**
- * Database username for connection (mysql, postgres only)
- * Default is an empty string
- *
- * @var string
- */
- public $database_user = '';
- /**
- * Database password for connection (mysql, postgres only)
- * Default is empty string
- *
- * @var string
- */
- public $database_pass = '';
- /**
- * Name of the database to select (mysql, postgres only)
- *
- * @see Securimage::$database_file for SQLite
- * @var string
- */
- public $database_name = '';
- /**
- * Database table where captcha codes are stored
- *
- * Note: Securimage will attempt to create this table for you if it does
- * not exist. If the table cannot be created, an E_USER_WARNING is emitted
- *
- * @var string
- */
- public $database_table = 'captcha_codes';
- /**
- * Fully qualified path to the database file when using SQLite3.
- *
- * This value is only used when $database_driver == sqlite and does
- * not apply when no database is used, or when using MySQL or PostgreSQL.
- *
- * On *nix, file must have permissions of 0666.
- *
- * **Make sure the directory containing this file is NOT web accessible**
- *
- * @var string
- */
- public $database_file;
- /**
- * The type of captcha to create.
- *
- * Either alphanumeric based on *charset*, a simple math problem, or an
- * image consisting of 2 words from the word list.
- *
- * @see Securimage::SI_CAPTCHA_STRING SI_CAPTCHA_STRING
- * @see Securimage::SI_CAPTCHA_MATHEMATIC SI_CAPTCHA_MATHEMATIC
- * @see Securimage::SI_CAPTCHA_WORDS SI_CAPTCHA_WORDS
- * @see Securimage::$charset charset property
- * @see Securimage::$wordlist_file wordlist_file property
- * @var int
- */
- public $captcha_type = self::SI_CAPTCHA_STRING; // or self::SI_CAPTCHA_MATHEMATIC, or self::SI_CAPTCHA_WORDS;
- /**
- * The captcha namespace used for having multiple captchas on a page or
- * to separate captchas from differen forms on your site.
- * Example:
- *
- * <?php
- * // use <img src="securimage_show.php?namespace=contact_form">
- * // or manually in securimage_show.php
- * $img->setNamespace('contact_form');
- *
- * // in form validator
- * $img->setNamespace('contact_form');
- * if ($img->check($code) == true) {
- * echo "Valid!";
- * }
- *
- * @var string
- */
- public $namespace;
- /**
- * The TTF font file to use to draw the captcha code.
- *
- * Leave blank for default font AHGBold.ttf
- *
- * @var string
- */
- public $ttf_file;
- /**
- * The path to the wordlist file to use.
- *
- * Leave blank for default words/words.txt
- *
- * @var string
- */
- public $wordlist_file;
- /**
- * Character encoding of the wordlist file.
- * Requires PHP Multibyte String (mbstring) support.
- * Allows word list to contain characters other than US-ASCII (requires compatible TTF font).
- *
- * @var string The character encoding (e.g. UTF-8, UTF-7, EUC-JP, GB2312)
- * @see http://php.net/manual/en/mbstring.supported-encodings.php
- * @since 3.6.3
- */
- public $wordlist_file_encoding = null;
- /**
- * The directory to scan for background images, if set a random background
- * will be chosen from this folder
- *
- * @var string
- */
- public $background_directory;
- /**
- * No longer used
- *
- * The path to the SQLite database file to use
- *
- * @deprecated 3.2RC4
- * @see Securimage::$database_file database_file property
- * @var string
- */
- public $sqlite_database;
- /**
- * The path to the audio files to be used for audio captchas.
- *
- * Can also be set in securimage_play.php
- *
- * Example:
- *
- * $img->audio_path = '/home/yoursite/public_html/securimage/audio/en/';
- *
- * @var string
- */
- public $audio_path;
- /**
- * Use SoX (The Swiss Army knife of audio manipulation) for audio effects
- * and processing.
- *
- * Using SoX should make it more difficult for bots to solve audio captchas
- *
- * @see Securimage::$sox_binary_path sox_binary_path property
- * @var bool true to use SoX, false to use PHP
- */
- public $audio_use_sox = false;
- /**
- * The path to the SoX binary on your system
- *
- * @var string
- */
- public $sox_binary_path = '/usr/bin/sox';
- /**
- * The path to the lame (mp3 encoder) binary on your system
- * Static so that Securimage::getCaptchaHtml() has access to this value.
- *
- * @since 3.6
- * @var string
- */
- public static $lame_binary_path = '/usr/bin/lame';
- /**
- * The path to the directory containing audio files that will be selected
- * randomly and mixed with the captcha audio.
- *
- * @var string
- */
- public $audio_noise_path;
- /**
- * Whether or not to mix background noise files into captcha audio
- *
- * Mixing random background audio with noise can help improve security of
- * audio captcha.
- *
- * Default: securimage/audio/noise
- *
- * @since 3.0.3
- * @see Securimage::$audio_noise_path audio_noise_path property
- * @var bool true = mix, false = no
- */
- public $audio_use_noise;
- /**
- * The method and threshold (or gain factor) used to normalize the mixing
- * with background noise.
- *
- * See http://www.voegler.eu/pub/audio/ for more information.
- *
- * Default: 0.6
- *
- * Valid:
- * >= 1
- * Normalize by multiplying by the threshold (boost - positive gain).
- * A value of 1 in effect means no normalization (and results in clipping).
- *
- * <= -1
- * Normalize by dividing by the the absolute value of threshold (attenuate - negative gain).
- * A factor of 2 (-2) is about 6dB reduction in volume.
- *
- * [0, 1) (open inverval - not including 1)
- * The threshold above which amplitudes are comressed logarithmically.
- * e.g. 0.6 to leave amplitudes up to 60% "as is" and compressabove.
- *
- * (-1, 0) (open inverval - not including -1 and 0)
- * The threshold above which amplitudes are comressed linearly.
- * e.g. -0.6 to leave amplitudes up to 60% "as is" and compress above.
- *
- * @since 3.0.4
- * @var float
- */
- public $audio_mix_normalization = 0.8;
- /**
- * Whether or not to degrade audio by introducing random noise.
- *
- * Current research shows this may not increase the security of audible
- * captchas.
- *
- * Default: true
- *
- * @since 3.0.3
- * @var bool
- */
- public $degrade_audio;
- /**
- * Minimum delay to insert between captcha audio letters in milliseconds
- *
- * @since 3.0.3
- * @var float
- */
- public $audio_gap_min = 0;
- /**
- * Maximum delay to insert between captcha audio letters in milliseconds
- *
- * @since 3.0.3
- * @var float
- */
- public $audio_gap_max = 3000;
- /**
- * The file path for logging errors from audio (default __DIR__)
- *
- * @var string|null
- */
- public $log_path = null;
- /**
- * The name of the log file for logging audio errors
- *
- * @var string|null (defualt si_error.log)
- */
- public $log_file = null;
- /**
- * Captcha ID if using static captcha
- * @var string Unique captcha id
- */
- protected static $_captchaId = null;
- /**
- * The GD image resource of the captcha image
- *
- * @var resource
- */
- protected $im;
- /**
- * A temporary GD image resource of the captcha image for distortion
- *
- * @var resource
- */
- protected $tmpimg;
- /**
- * The background image GD resource
- * @var string
- */
- protected $bgimg;
- /**
- * Scale factor for magnification of distorted captcha image
- *
- * @var int
- */
- protected $iscale = 2;
- /**
- * Absolute path to securimage directory.
- *
- * This is calculated at runtime
- *
- * @var string
- */
- public $securimage_path = null;
- /**
- * The captcha challenge value.
- *
- * Either the case-sensitive/insensitive word captcha, or the solution to
- * the math captcha.
- *
- * @var string|bool Captcha challenge value
- */
- protected $code;
- /**
- * The display value of the captcha to draw on the image
- *
- * Either the word captcha or the math equation to present to the user
- *
- * @var string Captcha display value to draw on the image
- */
- protected $code_display;
- /**
- * Alternate text to draw as the captcha image text
- *
- * A value that can be passed to the constructor that can be used to
- * generate a captcha image with a given value.
- *
- * This value does not get stored in the session or database and is only
- * used when calling Securimage::show().
- *
- * If a display_value was passed to the constructor and the captcha image
- * is generated, the display_value will be used as the string to draw on
- * the captcha image.
- *
- * Used only if captcha codes are generated and managed by a 3rd party
- * app/library
- *
- * @var string Captcha code value to display on the image
- */
- public $display_value;
- /**
- * Captcha code supplied by user [set from Securimage::check()]
- *
- * @var string
- */
- protected $captcha_code;
- /**
- * Time (in seconds) that the captcha was solved in (correctly or incorrectly).
- *
- * This is from the time of code creation, to when validation was attempted.
- *
- * @var int
- */
- protected $_timeToSolve = 0;
- /**
- * Flag that can be specified telling securimage not to call exit after
- * generating a captcha image or audio file
- *
- * @var bool If true, script will not terminate; if false script will terminate (default)
- */
- protected $no_exit;
- /**
- * Flag indicating whether or not a PHP session should be started and used
- *
- * @var bool If true, no session will be started; if false, session will be started and used to store data (default)
- */
- protected $no_session;
- /**
- * Flag indicating whether or not HTTP headers will be sent when outputting
- * captcha image/audio
- *
- * @var bool If true (default) headers will be sent, if false, no headers are sent
- */
- protected $send_headers;
- /**
- * PDO connection when a database is used
- *
- * @var PDO|bool
- */
- protected $pdo_conn;
- /**
- * The GD color for the background color
- *
- * @var int
- */
- protected $gdbgcolor;
- /**
- * The GD color for the text color
- *
- * @var int
- */
- protected $gdtextcolor;
- /**
- * The GD color for the line color
- *
- * @var int
- */
- protected $gdlinecolor;
- /**
- * The GD color for the signature text color
- *
- * @var int
- */
- protected $gdsignaturecolor;
- /**
- * Create a new securimage object, pass options to set in the constructor.
- *
- * The object can then be used to display a captcha, play an audible captcha, or validate a submission.
- *
- * @param array $options Options to initialize the class. May be any class property.
- *
- * $options = array(
- * 'text_color' => new Securimage_Color('#013020'),
- * 'code_length' => 5,
- * 'num_lines' => 5,
- * 'noise_level' => 3,
- * 'font_file' => Securimage::getPath() . '/custom.ttf'
- * );
- *
- * $img = new Securimage($options);
- *
- */
- public function __construct($options = array())
- {
- $this->securimage_path = dirname(__FILE__);
- if (!is_array($options)) {
- trigger_error(
- '$options passed to Securimage::__construct() must be an array. ' .
- gettype($options) . ' given',
- E_USER_WARNING
- );
- $options = array();
- }
- if (function_exists('mb_internal_encoding')) {
- mb_internal_encoding('UTF-8');
- }
- // check for and load settings from custom config file
- $config_file = null;
- if (file_exists(dirname(__FILE__) . '/config.inc.php')) {
- $config_file = dirname(__FILE__) . '/config.inc.php';
- }
- if (isset($options['config_file']) && file_exists($options['config_file'])) {
- $config_file = $options['config_file'];
- }
- if ($config_file) {
- $settings = include $config_file;
- if (is_array($settings)) {
- $options = array_merge($settings, $options);
- }
- }
- if (is_array($options) && sizeof($options) > 0) {
- foreach($options as $prop => $val) {
- if ($prop == 'captchaId') {
- Securimage::$_captchaId = $val;
- $this->use_database = true;
- } else if ($prop == 'use_sqlite_db') {
- trigger_error("The use_sqlite_db option is deprecated, use 'use_database' instead", E_USER_NOTICE);
- } else {
- $this->$prop = $val;
- }
- }
- }
- $this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
- $this->text_color = $this->initColor($this->text_color, '#616161');
- $this->line_color = $this->initColor($this->line_color, '#616161');
- $this->noise_color = $this->initColor($this->noise_color, '#616161');
- $this->signature_color = $this->initColor($this->signature_color, '#616161');
- if (is_null($this->ttf_file)) {
- $this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
- }
- $this->signature_font = $this->ttf_file;
- if (is_null($this->wordlist_file)) {
- $this->wordlist_file = $this->securimage_path . '/words/words.txt';
- }
- if (is_null($this->database_file)) {
- $this->database_file = $this->securimage_path . '/database/securimage.sq3';
- }
- if (is_null($this->audio_path)) {
- $this->audio_path = $this->securimage_path . '/audio/en/';
- }
- if (is_null($this->audio_noise_path)) {
- $this->audio_noise_path = $this->securimage_path . '/audio/noise/';
- }
- if (is_null($this->audio_use_noise)) {
- $this->audio_use_noise = true;
- }
- if (is_null($this->degrade_audio)) {
- $this->degrade_audio = true;
- }
- if (is_null($this->code_length) || (int)$this->code_length < 1) {
- $this->code_length = 6;
- }
- if (is_null($this->perturbation) || !is_numeric($this->perturbation)) {
- $this->perturbation = 0.75;
- }
- if (is_null($this->namespace) || !is_string($this->namespace)) {
- $this->namespace = 'default';
- }
- if (is_null($this->no_exit)) {
- $this->no_exit = false;
- }
- if (is_null($this->no_session)) {
- $this->no_session = false;
- }
- if (is_null($this->send_headers)) {
- $this->send_headers = true;
- }
- if (is_null($this->log_path)) {
- $this->log_path = __DIR__;
- }
- if (is_null($this->log_file)) {
- $this->log_file = 'securimage.error_log';
- }
- if ($this->no_session != true) {
- // Initialize session or attach to existing
- if ( session_id() == '' || (function_exists('session_status') && PHP_SESSION_NONE == session_status()) ) { // no session has been started yet (or it was previousy closed), which is needed for validation
- if (!is_null($this->session_name) && trim($this->session_name) != '') {
- session_name(trim($this->session_name)); // set session name if provided
- }
- session_start();
- }
- }
- }
- /**
- * Return the absolute path to the Securimage directory.
- *
- * @return string The path to the securimage base directory
- */
- public static function getPath()
- {
- return dirname(__FILE__);
- }
- /**
- * Generate a new captcha ID or retrieve the current ID (if exists).
- *
- * @param bool $new If true, generates a new challenge and returns and ID. If false, the existing captcha ID is returned, or null if none exists.
- * @param array $options Additional options to be passed to Securimage.
- * $options must include database settings if they are not set directly in securimage.php
- *
- * @return null|string Returns null if no captcha id set and new was false, or the captcha ID
- */
- public static function getCaptchaId($new = true, array $options = array())
- {
- if (is_null($new) || (bool)$new == true) {
- $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true));
- $opts = array('no_session' => true,
- 'use_database' => true);
- if (sizeof($options) > 0) $opts = array_merge($options, $opts);
- $si = new self($opts);
- Securimage::$_captchaId = $id;
- $si->createCode();
- return $id;
- } else {
- return Securimage::$_captchaId;
- }
- }
- /**
- * Validate a captcha code input against a captcha ID
- *
- * @param string $id The captcha ID to check
- * @param string $value The captcha value supplied by the user
- * @param array $options Array of options to construct Securimage with.
- * Options must include database options if they are not set in securimage.php
- *
- * @see Securimage::$database_driver
- * @return bool true if the code was valid for the given captcha ID, false if not or if database failed to open
- */
- public static function checkByCaptchaId($id, $value, array $options = array())
- {
- $opts = array('captchaId' => $id,
- 'no_session' => true,
- 'use_database' => true);
- if (sizeof($options) > 0) $opts = array_merge($options, $opts);
- $si = new self($opts);
- if ($si->openDatabase()) {
- $code = $si->getCodeFromDatabase();
- if (is_array($code)) {
- $si->code = $code['code'];
- $si->code_display = $code['code_disp'];
- }
- if ($si->check($value)) {
- $si->clearCodeFromDatabase();
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
- /**
- * Generates a new challenge and serves a captcha image.
- *
- * Appropriate headers will be sent to the browser unless the *send_headers* option is false.
- *
- * @param string $background_image The absolute or relative path to the background image to use as the background of the captcha image.
- *
- * $img = new Securimage();
- * $img->code_length = 6;
- * $img->num_lines = 5;
- * $img->noise_level = 5;
- *
- * $img->show(); // sends the image and appropriate headers to browser
- * exit;
- */
- public function show($background_image = '')
- {
- set_error_handler(array(&$this, 'errorHandler'));
- if($background_image != '' && is_readable($background_image)) {
- $this->bgimg = $background_image;
- }
- $this->doImage();
- }
- /**
- * Checks a given code against the correct value from the session and/or database.
- *
- * @param string $code The captcha code to check
- *
- * $code = $_POST['code'];
- * $img = new Securimage();
- * if ($img->check($code) == true) {
- * $captcha_valid = true;
- * } else {
- * $captcha_valid = false;
- * }
- *
- * @return bool true if the given code was correct, false if not.
- */
- public function check($code)
- {
- if (!is_string($code)) {
- trigger_error("The \$code parameter passed to Securimage::check() must be a string, " . gettype($code) . " given", E_USER_NOTICE);
- $code = '';
- }
- $this->code_entered = $code;
- $this->validate();
- return $this->correct_code;
- }
- /**
- * Returns HTML code for displaying the captcha image, audio button, and form text input.
- *
- * Options can be specified to modify the output of the HTML. Accepted options:
- *
- * 'securimage_path':
- * Optional: The URI to where securimage is installed (e.g. /securimage)
- * 'show_image_url':
- * Path to the securimage_show.php script (useful when integrating with a framework or moving outside the securimage directory)
- * This will be passed as a urlencoded string to the <img> tag for outputting the captcha image
- * 'audio_play_url':
- * Same as show_image_url, except this indicates the URL of the audio playback script
- * 'image_id':
- * A string that sets the "id" attribute of the captcha image (default: captcha_image)
- * 'image_alt_text':
- * The alt text of the captcha image (default: CAPTCHA Image)
- * 'show_audio_button':
- * true/false Whether or not to show the audio button (default: true)
- * 'disable_flash_fallback':)
- * Allow only HTML5 audio and disable Flash fallback
- * 'show_refresh_button':
- * true/false Whether or not to show a button to refresh the image (default: true)
- * 'audio_icon_url':
- * URL to the image used for showing the HTML5 audio icon
- * 'js_url':
- * URL to the javascript file
- * 'icon_size':
- * Size (for both height & width) in pixels of the audio and refresh buttons
- * 'show_text_input':
- * true/false Whether or not to show the text input for the captcha (default: true)
- * 'refresh_alt_text':
- * Alt text for the refresh image (default: Refresh Image)
- * 'refresh_title_text':
- * Title text for the refresh image link (default: Refresh Image)
- * 'input_id':
- * A string that sets the "id" attribute of the captcha text input (default: captcha_code)
- * 'input_name':
- * A string that sets the "name" attribute of the captcha text input (default: same as input_id)
- * 'input_text':
- * A string that sets the text of the label for the captcha text input (default: Type the text:)
- * 'input_attributes':
- * An array of additional HTML tag attributes to pass to the text input tag (default: empty)
- * 'image_attributes':
- * An array of additional HTML tag attributes to pass to the captcha image tag (default: empty)
- * 'error_html':
- * Optional HTML markup to be shown above the text input field
- * 'namespace':
- * The optional captcha namespace to use for showing the image and playing back the audio. Namespaces are for using multiple captchas on the same page.
- *
- * @param array $options Array of options for modifying the HTML code.
- * @param int $parts Securiage::HTML_* constant controlling what component of the captcha HTML to display
- *
- * @return string The generated HTML code for displaying the captcha
- */
- public static function getCaptchaHtml($options = array(), $parts = Securimage::HTML_ALL)
- {
- static $javascript_init = false;
- if (!isset($options['securimage_path'])) {
- $docroot = (isset($_SERVER['DOCUMENT_ROOT'])) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME']));
- $docroot = realpath($docroot);
- $sipath = dirname(__FILE__);
- $securimage_path = str_replace($docroot, '', $sipath);
- } else {
- $securimage_path = $options['securimage_path'];
- }
- $show_image_url = (isset($options['show_image_url'])) ? $options['show_image_url'] : null;
- $image_id = (isset($options['image_id'])) ? $options['image_id'] : 'captcha_image';
- $image_alt = (isset($options['image_alt_text'])) ? $options['image_alt_text'] : 'CAPTCHA Image';
- $show_audio_btn = (isset($options['show_audio_button'])) ? (bool)$options['show_audio_button'] : true;
- $disable_flash_fbk = (isset($options['disable_flash_fallback'])) ? (bool)$options['disable_flash_fallback'] : false;
- $show_refresh_btn = (isset($options['show_refresh_button'])) ? (bool)$options['show_refresh_button'] : true;
- $refresh_icon_url = (isset($options['refresh_icon_url'])) ? $options['refresh_icon_url'] : null;
- $audio_but_bg_col = (isset($options['audio_button_bgcol'])) ? $options['audio_button_bgcol'] : '#ffffff';
- $audio_icon_url = (isset($options['audio_icon_url'])) ? $options['audio_icon_url'] : null;
- $loading_icon_url = (isset($options['loading_icon_url'])) ? $options['loading_icon_url'] : null;
- $icon_size = (isset($options['icon_size'])) ? $options['icon_size'] : 32;
- $audio_play_url = (isset($options['audio_play_url'])) ? $options['audio_play_url'] : null;
- $audio_swf_url = (isset($options['audio_swf_url'])) ? $options['audio_swf_url'] : null;
- $js_url = (isset($options['js_url'])) ? $options['js_url'] : null;
- $show_input = (isset($options['show_text_input'])) ? (bool)$options['show_text_input'] : true;
- $refresh_alt = (isset($options['refresh_alt_text'])) ? $options['refresh_alt_text'] : 'Refresh Image';
- $refresh_title = (isset($options['refresh_title_text'])) ? $options['refresh_title_text'] : 'Refresh Image';
- $input_text = (isset($options['input_text'])) ? $options['input_text'] : 'Type the text:';
- $input_id = (isset($options['input_id'])) ? $options['input_id'] : 'captcha_code';
- $input_name = (isset($options['input_name'])) ? $options['input_name'] : $input_id;
- $input_required = (isset($options['input_required'])) ? (bool)$options['input_required'] : true;
- $input_attrs = (isset($options['input_attributes'])) ? $options['input_attributes'] : array();
- $image_attrs = (isset($options['image_attributes'])) ? $options['image_attributes'] : array();
- $error_html = (isset($options['error_html'])) ? $options['error_html'] : null;
- $namespace = (isset($options['namespace'])) ? $options['namespace'] : '';
- $rand = md5(uniqid($_SERVER['REMOTE_PORT'], true));
- $securimage_path = rtrim($securimage_path, '/\\');
- $securimage_path = str_replace('\\', '/', $securimage_path);
- $image_attr = '';
- if (!is_array($image_attrs)) $image_attrs = array();
- if (!isset($image_attrs['style'])) $image_attrs['style'] = 'float: left; padding-right: 5px';
- $image_attrs['id'] = $image_id;
- $show_path = $securimage_path . '/securimage_show.php?';
- if ($show_image_url) {
- if (parse_url($show_image_url, PHP_URL_QUERY)) {
- $show_path = "{$show_image_url}&";
- } else {
- $show_path = "{$show_image_url}?";
- }
- }
- if (!empty($namespace)) {
- $show_path .= sprintf('namespace=%s&', $namespace);
- }
- $image_attrs['src'] = $show_path . $rand;
- $image_attrs['alt'] = $image_alt;
- foreach($image_attrs as $name => $val) {
- $image_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val));
- }
- $swf_path = $securimage_path . '/securimage_play.swf';
- $play_path = $securimage_path . '/securimage_play.php?';
- $icon_path = $securimage_path . '/images/audio_icon.png';
- $load_path = $securimage_path . '/images/loading.png';
- $js_path = $securimage_path . '/securimage.js';
- if (!empty($audio_icon_url)) {
- $icon_path = $audio_icon_url;
- }
- if (!empty($loading_icon_url)) {
- $load_path = $loading_icon_url;
- }
- if (!empty($audio_play_url)) {
- if (parse_url($audio_play_url, PHP_URL_QUERY)) {
- $play_path = "{$audio_play_url}&";
- } else {
- $play_path = "{$audio_play_url}?";
- }
- }
- if (!empty($namespace)) {
- $play_path .= sprintf('namespace=%s&', $namespace);
- }
- if (!empty($audio_swf_url)) {
- $swf_path = $audio_swf_url;
- }
- if (!empty($js_url)) {
- $js_path = $js_url;
- }
- $audio_obj = $image_id . '_audioObj';
- $html = '';
- if ( ($parts & Securimage::HTML_IMG) > 0) {
- $html .= sprintf('<img %s/>', $image_attr);
- }
- if ( ($parts & Securimage::HTML_AUDIO) > 0 && $show_audio_btn) {
- // html5 audio
- $html .= sprintf('<div id="%s_audio_div">', $image_id) . "\n" .
- sprintf('<audio id="%s_audio" preload="none" style="display: none">', $image_id) . "\n";
- // check for existence and executability of LAME binary
- // prefer mp3 over wav by sourcing it first, if available
- if (!empty(Securimage::$lame_binary_path) && is_executable(Securimage::$lame_binary_path)) {
- $html .= sprintf('<source id="%s_source_mp3" src="%sid=%s&format=mp3" type="audio/mpeg">', $image_id, $play_path, uniqid()) . "\n";
- }
- // output wav source
- $html .= sprintf('<source id="%s_source_wav" src="%sid=%s" type="audio/wav">', $image_id, $play_path, uniqid()) . "\n";
- // flash audio button
- if (!$disable_flash_fbk) {
- $html .= sprintf('<object type="application/x-shockwave-flash" data="%s?bgcol=%s&icon_file=%s&audio_file=%s" height="%d" width="%d">',
- htmlspecialchars($swf_path),
- urlencode($audio_but_bg_col),
- urlencode($icon_…
Large files files are truncated, but you can click here to view the full file