PageRenderTime 36ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/webui/securimage/securimage.php

https://bitbucket.org/jsuto/piler
PHP | 2212 lines | 1271 code | 214 blank | 727 comment | 242 complexity | 4229e91648e9fcfc60c763205a7ad5cf MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-3.0, GPL-3.0
  1. <?php
  2. // error_reporting(E_ALL); ini_set('display_errors', 1); // uncomment this line for debugging
  3. /**
  4. * Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
  5. * File: securimage.php<br />
  6. *
  7. * Copyright (c) 2013, Drew Phillips
  8. * All rights reserved.
  9. *
  10. * Redistribution and use in source and binary forms, with or without modification,
  11. * are permitted provided that the following conditions are met:
  12. *
  13. * - Redistributions of source code must retain the above copyright notice,
  14. * this list of conditions and the following disclaimer.
  15. * - Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  23. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. * POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. * Any modifications to the library should be indicated clearly in the source code
  32. * to inform users that the changes are not a part of the original software.<br /><br />
  33. *
  34. * If you found this script useful, please take a quick moment to rate it.<br />
  35. * http://www.hotscripts.com/rate/49400.html Thanks.
  36. *
  37. * @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
  38. * @link http://www.phpcaptcha.org/latest.zip Download Latest Version
  39. * @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
  40. * @copyright 2013 Drew Phillips
  41. * @author Drew Phillips <drew@drew-phillips.com>
  42. * @version 3.5.1 (June 21, 2013)
  43. * @package Securimage
  44. *
  45. */
  46. /**
  47. ChangeLog
  48. 3.5.1
  49. - Fix XSS vulnerability in example_form.php (discovered by Gjoko Krstic - <gjoko@zeroscience.mk>)
  50. 3.5
  51. - Release new version
  52. - MB string support for charlist
  53. - Modify audio file path to use language directories
  54. - Changed default captcha appearance
  55. 3.2RC4
  56. - Add MySQL, PostgreSQL, and SQLite3 support for database storage
  57. - Deprecate "use_sqlite_db" option and remove SQLite2/sqlite_* functions
  58. - Add new captcha type that displays 2 dictionary words on one image
  59. - Update examples
  60. 3.2RC3
  61. - Fix canSendHeaders() check which was breaking if a PHP startup error was issued
  62. 3.2RC2
  63. - Add error handler (https://github.com/dapphp/securimage/issues/15)
  64. - Fix flash examples to use the correct value name for audio parameter
  65. 3.2RC1
  66. - New audio captcha code. Faster, fully dynamic audio, full WAV support
  67. (Paul Voegler, Drew Phillips) <http://voegler.eu/pub/audio>
  68. - New Flash audio streaming button. User defined image and size supported
  69. - Additional options for customizing captcha (noise_level, send_headers,
  70. no_exit, no_session, display_value
  71. - Add captcha ID support. Uses sqlite and unique captcha IDs to track captchas,
  72. no session used
  73. - Add static methods for creating and validating captcha by ID
  74. - Automatic clearing of old codes from SQLite database
  75. 3.0.3Beta
  76. - Add improved mixing function to WavFile class (Paul Voegler)
  77. - Improve performance and security of captcha audio (Paul Voegler, Drew Phillips)
  78. - Add option to use random file as background noise in captcha audio
  79. - Add new securimage options for audio files
  80. 3.0.2Beta
  81. - Fix issue with session variables when upgrading from 2.0 - 3.0
  82. - Improve audio captcha, switch to use WavFile class, make mathematical captcha audio work
  83. 3.0.1
  84. - Bugfix: removed use of deprecated variable in addSignature method that would cause errors with display_errors on
  85. 3.0
  86. - Rewrite class using PHP5 OOP
  87. - Remove support for GD fonts, require FreeType
  88. - Remove support for multi-color codes
  89. - Add option to make codes case-sensitive
  90. - Add namespaces to support multiple captchas on a single page or page specific captchas
  91. - Add option to show simple math problems instead of codes
  92. - Remove support for mp3 files due to vulnerability in decoding mp3 audio files
  93. - Create new flash file to stream wav files instead of mp3
  94. - Changed to BSD license
  95. 2.0.2
  96. - Fix pathing to make integration into libraries easier (Nathan Phillip Brink ohnobinki@ohnopublishing.net)
  97. 2.0.1
  98. - Add support for browsers with cookies disabled (requires php5, sqlite) maps users to md5 hashed ip addresses and md5 hashed codes for security
  99. - 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)
  100. - Check for previous definition of image type constants (Mike Challis)
  101. - Fix mime type settings for audio output
  102. - Fixed color allocation issues with multiple colors and background images, consolidate allocation to one function
  103. - Ability to let codes expire after a given length of time
  104. - Allow HTML color codes to be passed to Securimage_Color (suggested by Mike Challis)
  105. 2.0.0
  106. - Add mathematical distortion to characters (using code from HKCaptcha)
  107. - Improved session support
  108. - Added Securimage_Color class for easier color definitions
  109. - Add distortion to audio output to prevent binary comparison attack (proposed by Sven "SavageTiger" Hagemann [insecurity.nl])
  110. - Flash button to stream mp3 audio (Douglas Walsh www.douglaswalsh.net)
  111. - Audio output is mp3 format by default
  112. - Change font to AlteHaasGrotesk by yann le coroller
  113. - Some code cleanup
  114. 1.0.4 (unreleased)
  115. - Ability to output audible codes in mp3 format to stream from flash
  116. 1.0.3.1
  117. - Error reading from wordlist in some cases caused words to be cut off 1 letter short
  118. 1.0.3
  119. - Removed shadow_text from code which could cause an undefined property error due to removal from previous version
  120. 1.0.2
  121. - Audible CAPTCHA Code wav files
  122. - Create codes from a word list instead of random strings
  123. 1.0
  124. - Added the ability to use a selected character set, rather than a-z0-9 only.
  125. - Added the multi-color text option to use different colors for each letter.
  126. - Switched to automatic session handling instead of using files for code storage
  127. - Added GD Font support if ttf support is not available. Can use internal GD fonts or load new ones.
  128. - Added the ability to set line thickness
  129. - Added option for drawing arced lines over letters
  130. - Added ability to choose image type for output
  131. */
  132. /**
  133. * Securimage CAPTCHA Class.
  134. *
  135. * @version 3.5
  136. * @package Securimage
  137. * @subpackage classes
  138. * @author Drew Phillips <drew@drew-phillips.com>
  139. *
  140. */
  141. class Securimage
  142. {
  143. // All of the public variables below are securimage options
  144. // They can be passed as an array to the Securimage constructor, set below,
  145. // or set from securimage_show.php and securimage_play.php
  146. /**
  147. * Renders captcha as a JPEG image
  148. * @var int
  149. */
  150. const SI_IMAGE_JPEG = 1;
  151. /**
  152. * Renders captcha as a PNG image (default)
  153. * @var int
  154. */
  155. const SI_IMAGE_PNG = 2;
  156. /**
  157. * Renders captcha as a GIF image
  158. * @var int
  159. */
  160. const SI_IMAGE_GIF = 3;
  161. /**
  162. * Create a normal alphanumeric captcha
  163. * @var int
  164. */
  165. const SI_CAPTCHA_STRING = 0;
  166. /**
  167. * Create a captcha consisting of a simple math problem
  168. * @var int
  169. */
  170. const SI_CAPTCHA_MATHEMATIC = 1;
  171. /**
  172. * Create a word based captcha using 2 words
  173. * @var int
  174. */
  175. const SI_CAPTCHA_WORDS = 2;
  176. /**
  177. * MySQL option identifier for database storage option
  178. *
  179. * @var string
  180. */
  181. const SI_DRIVER_MYSQL = 'mysql';
  182. /**
  183. * PostgreSQL option identifier for database storage option
  184. *
  185. * @var string
  186. */
  187. const SI_DRIVER_PGSQL = 'pgsql';
  188. /**
  189. * SQLite option identifier for database storage option
  190. *
  191. * @var string
  192. */
  193. const SI_DRIVER_SQLITE3 = 'sqlite';
  194. /*%*********************************************************************%*/
  195. // Properties
  196. /**
  197. * The width of the captcha image
  198. * @var int
  199. */
  200. public $image_width = 215;
  201. /**
  202. * The height of the captcha image
  203. * @var int
  204. */
  205. public $image_height = 80;
  206. /**
  207. * The type of the image, default = png
  208. * @var int
  209. */
  210. public $image_type = self::SI_IMAGE_PNG;
  211. /**
  212. * The background color of the captcha
  213. * @var Securimage_Color
  214. */
  215. public $image_bg_color = '#ffffff';
  216. /**
  217. * The color of the captcha text
  218. * @var Securimage_Color
  219. */
  220. public $text_color = '#707070';
  221. /**
  222. * The color of the lines over the captcha
  223. * @var Securimage_Color
  224. */
  225. public $line_color = '#707070';
  226. /**
  227. * The color of the noise that is drawn
  228. * @var Securimage_Color
  229. */
  230. public $noise_color = '#707070';
  231. /**
  232. * How transparent to make the text 0 = completely opaque, 100 = invisible
  233. * @var int
  234. */
  235. public $text_transparency_percentage = 20;
  236. /**
  237. * Whether or not to draw the text transparently, true = use transparency, false = no transparency
  238. * @var bool
  239. */
  240. public $use_transparent_text = true;
  241. /**
  242. * The length of the captcha code
  243. * @var int
  244. */
  245. public $code_length = 6;
  246. /**
  247. * Whether the captcha should be case sensitive (not recommended, use only for maximum protection)
  248. * @var bool
  249. */
  250. public $case_sensitive = false;
  251. /**
  252. * The character set to use for generating the captcha code
  253. * @var string
  254. */
  255. public $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
  256. /**
  257. * How long in seconds a captcha remains valid, after this time it will not be accepted
  258. * @var unknown_type
  259. */
  260. public $expiry_time = 900;
  261. /**
  262. * The session name securimage should use, only set this if your application uses a custom session name
  263. * It is recommended to set this value below so it is used by all securimage scripts
  264. * @var string
  265. */
  266. public $session_name = null;
  267. /**
  268. * true to use the wordlist file, false to generate random captcha codes
  269. * @var bool
  270. */
  271. public $use_wordlist = false;
  272. /**
  273. * The level of distortion, 0.75 = normal, 1.0 = very high distortion
  274. * @var double
  275. */
  276. public $perturbation = 0.85;
  277. /**
  278. * How many lines to draw over the captcha code to increase security
  279. * @var int
  280. */
  281. public $num_lines = 5;
  282. /**
  283. * The level of noise (random dots) to place on the image, 0-10
  284. * @var int
  285. */
  286. public $noise_level = 2;
  287. /**
  288. * The signature text to draw on the bottom corner of the image
  289. * @var string
  290. */
  291. public $image_signature = '';
  292. /**
  293. * The color of the signature text
  294. * @var Securimage_Color
  295. */
  296. public $signature_color = '#707070';
  297. /**
  298. * The path to the ttf font file to use for the signature text, defaults to $ttf_file (AHGBold.ttf)
  299. * @var string
  300. */
  301. public $signature_font;
  302. /**
  303. * DO NOT USE!!!
  304. * Use an SQLite database to store data (for users that do not support cookies)
  305. * @var bool
  306. * @see Securimage::$use_sqlite_db
  307. * @deprecated 3.2RC4
  308. */
  309. public $use_sqlite_db = false;
  310. /**
  311. * Use a database backend for code storage.
  312. * Provides a fallback to users with cookies disabled.
  313. * Required when using captcha IDs.
  314. *
  315. * @see Securimage::$database_driver
  316. * @var bool
  317. */
  318. public $use_database = false;
  319. /**
  320. * Database driver to use for database support.
  321. * Allowable values: 'mysql', 'pgsql', 'sqlite'.
  322. * Default: sqlite
  323. *
  324. * @var string
  325. */
  326. public $database_driver = self::SI_DRIVER_SQLITE3;
  327. /**
  328. * Database host to connect to when using mysql or postgres
  329. * On Linux use "localhost" for Unix domain socket, otherwise uses TCP/IP
  330. * Does not apply to SQLite
  331. *
  332. * @var string
  333. */
  334. public $database_host = 'localhost';
  335. /**
  336. * Database username for connection (mysql, postgres only)
  337. * Default is an empty string
  338. *
  339. * @var string
  340. */
  341. public $database_user = '';
  342. /**
  343. * Database password for connection (mysql, postgres only)
  344. * Default is empty string
  345. *
  346. * @var string
  347. */
  348. public $database_pass = '';
  349. /**
  350. * Name of the database to select (mysql, postgres only)
  351. *
  352. * @see Securimage::$database_file for SQLite
  353. * @var string
  354. */
  355. public $database_name = '';
  356. /**
  357. * Database table where captcha codes are stored
  358. * Note: Securimage will attempt to create this table for you if it does
  359. * not exist. If the table cannot be created, an E_USER_WARNING is emitted.
  360. *
  361. * @var string
  362. */
  363. public $database_table = 'captcha_codes';
  364. /**
  365. * Fully qualified path to the database file when using SQLite3.
  366. * This value is only used when $database_driver == sqlite3 and does
  367. * not apply when no database is used, or when using MySQL or PostgreSQL.
  368. *
  369. * @var string
  370. */
  371. public $database_file;
  372. /**
  373. * The type of captcha to create, either alphanumeric, or a math problem<br />
  374. * Securimage::SI_CAPTCHA_STRING or Securimage::SI_CAPTCHA_MATHEMATIC
  375. * @var int
  376. */
  377. public $captcha_type = self::SI_CAPTCHA_STRING; // or self::SI_CAPTCHA_MATHEMATIC;
  378. /**
  379. * The captcha namespace, use this if you have multiple forms on a single page, blank if you do not use multiple forms on one page
  380. * @var string
  381. * <code>
  382. * <?php
  383. * // in securimage_show.php (create one show script for each form)
  384. * $img->namespace = 'contact_form';
  385. *
  386. * // in form validator
  387. * $img->namespace = 'contact_form';
  388. * if ($img->check($code) == true) {
  389. * echo "Valid!";
  390. * }
  391. * </code>
  392. */
  393. public $namespace;
  394. /**
  395. * The font file to use to draw the captcha code, leave blank for default font AHGBold.ttf
  396. * @var string
  397. */
  398. public $ttf_file;
  399. /**
  400. * The path to the wordlist file to use, leave blank for default words/words.txt
  401. * @var string
  402. */
  403. public $wordlist_file;
  404. /**
  405. * The directory to scan for background images, if set a random background will be chosen from this folder
  406. * @var string
  407. */
  408. public $background_directory;
  409. /**
  410. * The path to the SQLite database file to use, if $use_sqlite_database = true, should be chmod 666
  411. * @deprecated 3.2RC4
  412. * @var string
  413. */
  414. public $sqlite_database;
  415. /**
  416. * The path to the securimage audio directory, can be set in securimage_play.php
  417. * @var string
  418. * <code>
  419. * $img->audio_path = '/home/yoursite/public_html/securimage/audio/en/';
  420. * </code>
  421. */
  422. public $audio_path;
  423. /**
  424. * The path to the directory containing audio files that will be selected
  425. * randomly and mixed with the captcha audio.
  426. *
  427. * @var string
  428. */
  429. public $audio_noise_path;
  430. /**
  431. * Whether or not to mix background noise files into captcha audio (true = mix, false = no)
  432. * Mixing random background audio with noise can help improve security of audio captcha.
  433. * Default: securimage/audio/noise
  434. *
  435. * @since 3.0.3
  436. * @see Securimage::$audio_noise_path
  437. * @var bool
  438. */
  439. public $audio_use_noise;
  440. /**
  441. * The method and threshold (or gain factor) used to normalize the mixing with background noise.
  442. * See http://www.voegler.eu/pub/audio/ for more information.
  443. *
  444. * Valid: <ul>
  445. * <li> >= 1 - Normalize by multiplying by the threshold (boost - positive gain). <br />
  446. * A value of 1 in effect means no normalization (and results in clipping). </li>
  447. * <li> <= -1 - Normalize by dividing by the the absolute value of threshold (attenuate - negative gain). <br />
  448. * A factor of 2 (-2) is about 6dB reduction in volume.</li>
  449. * <li> [0, 1) - (open inverval - not including 1) - The threshold
  450. * above which amplitudes are comressed logarithmically. <br />
  451. * e.g. 0.6 to leave amplitudes up to 60% "as is" and compress above. </li>
  452. * <li> (-1, 0) - (open inverval - not including -1 and 0) - The threshold
  453. * above which amplitudes are comressed linearly. <br />
  454. * e.g. -0.6 to leave amplitudes up to 60% "as is" and compress above. </li></ul>
  455. *
  456. * Default: 0.6
  457. *
  458. * @since 3.0.4
  459. * @var float
  460. */
  461. public $audio_mix_normalization = 0.6;
  462. /**
  463. * Whether or not to degrade audio by introducing random noise (improves security of audio captcha)
  464. * Default: true
  465. *
  466. * @since 3.0.3
  467. * @var bool
  468. */
  469. public $degrade_audio;
  470. /**
  471. * Minimum delay to insert between captcha audio letters in milliseconds
  472. *
  473. * @since 3.0.3
  474. * @var float
  475. */
  476. public $audio_gap_min = 0;
  477. /**
  478. * Maximum delay to insert between captcha audio letters in milliseconds
  479. *
  480. * @since 3.0.3
  481. * @var float
  482. */
  483. public $audio_gap_max = 600;
  484. /**
  485. * Captcha ID if using static captcha
  486. * @var string Unique captcha id
  487. */
  488. protected static $_captchaId = null;
  489. protected $im;
  490. protected $tmpimg;
  491. protected $bgimg;
  492. protected $iscale = 5;
  493. public $securimage_path = null;
  494. /**
  495. * The captcha challenge value (either the case-sensitive/insensitive word captcha, or the solution to the math captcha)
  496. *
  497. * @var string Captcha challenge value
  498. */
  499. protected $code;
  500. /**
  501. * The display value of the captcha to draw on the image (the word captcha, or the math equation to present to the user)
  502. *
  503. * @var string Captcha display value to draw on the image
  504. */
  505. protected $code_display;
  506. /**
  507. * A value that can be passed to the constructor that can be used to generate a captcha image with a given value
  508. * This value does not get stored in the session or database and is only used when calling Securimage::show().
  509. * If a display_value was passed to the constructor and the captcha image is generated, the display_value will be used
  510. * as the string to draw on the captcha image. Used only if captcha codes are generated and managed by a 3rd party app/library
  511. *
  512. * @var string Captcha code value to display on the image
  513. */
  514. public $display_value;
  515. /**
  516. * Captcha code supplied by user [set from Securimage::check()]
  517. *
  518. * @var string
  519. */
  520. protected $captcha_code;
  521. /**
  522. * Flag that can be specified telling securimage not to call exit after generating a captcha image or audio file
  523. *
  524. * @var bool If true, script will not terminate; if false script will terminate (default)
  525. */
  526. protected $no_exit;
  527. /**
  528. * Flag indicating whether or not a PHP session should be started and used
  529. *
  530. * @var bool If true, no session will be started; if false, session will be started and used to store data (default)
  531. */
  532. protected $no_session;
  533. /**
  534. * Flag indicating whether or not HTTP headers will be sent when outputting captcha image/audio
  535. *
  536. * @var bool If true (default) headers will be sent, if false, no headers are sent
  537. */
  538. protected $send_headers;
  539. /**
  540. * PDO connection when a database is used
  541. *
  542. * @var resource
  543. */
  544. protected $pdo_conn;
  545. // gd color resources that are allocated for drawing the image
  546. protected $gdbgcolor;
  547. protected $gdtextcolor;
  548. protected $gdlinecolor;
  549. protected $gdsignaturecolor;
  550. /**
  551. * Create a new securimage object, pass options to set in the constructor.<br />
  552. * This can be used to display a captcha, play an audible captcha, or validate an entry
  553. * @param array $options
  554. * <code>
  555. * $options = array(
  556. * 'text_color' => new Securimage_Color('#013020'),
  557. * 'code_length' => 5,
  558. * 'num_lines' => 5,
  559. * 'noise_level' => 3,
  560. * 'font_file' => Securimage::getPath() . '/custom.ttf'
  561. * );
  562. *
  563. * $img = new Securimage($options);
  564. * </code>
  565. */
  566. public function __construct($options = array())
  567. {
  568. $this->securimage_path = dirname(__FILE__);
  569. if (is_array($options) && sizeof($options) > 0) {
  570. foreach($options as $prop => $val) {
  571. if ($prop == 'captchaId') {
  572. Securimage::$_captchaId = $val;
  573. $this->use_database = true;
  574. } else if ($prop == 'use_sqlite_db') {
  575. trigger_error("The use_sqlite_db option is deprecated, use 'use_database' instead", E_USER_NOTICE);
  576. } else {
  577. $this->$prop = $val;
  578. }
  579. }
  580. }
  581. $this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
  582. $this->text_color = $this->initColor($this->text_color, '#616161');
  583. $this->line_color = $this->initColor($this->line_color, '#616161');
  584. $this->noise_color = $this->initColor($this->noise_color, '#616161');
  585. $this->signature_color = $this->initColor($this->signature_color, '#616161');
  586. if (is_null($this->ttf_file)) {
  587. $this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
  588. }
  589. $this->signature_font = $this->ttf_file;
  590. if (is_null($this->wordlist_file)) {
  591. $this->wordlist_file = $this->securimage_path . '/words/words.txt';
  592. }
  593. if (is_null($this->database_file)) {
  594. $this->database_file = $this->securimage_path . '/database/securimage.sq3';
  595. }
  596. if (is_null($this->audio_path)) {
  597. $this->audio_path = $this->securimage_path . '/audio/en/';
  598. }
  599. if (is_null($this->audio_noise_path)) {
  600. $this->audio_noise_path = $this->securimage_path . '/audio/noise/';
  601. }
  602. if (is_null($this->audio_use_noise)) {
  603. $this->audio_use_noise = true;
  604. }
  605. if (is_null($this->degrade_audio)) {
  606. $this->degrade_audio = true;
  607. }
  608. if (is_null($this->code_length) || (int)$this->code_length < 1) {
  609. $this->code_length = 6;
  610. }
  611. if (is_null($this->perturbation) || !is_numeric($this->perturbation)) {
  612. $this->perturbation = 0.75;
  613. }
  614. if (is_null($this->namespace) || !is_string($this->namespace)) {
  615. $this->namespace = 'default';
  616. }
  617. if (is_null($this->no_exit)) {
  618. $this->no_exit = false;
  619. }
  620. if (is_null($this->no_session)) {
  621. $this->no_session = false;
  622. }
  623. if (is_null($this->send_headers)) {
  624. $this->send_headers = true;
  625. }
  626. if ($this->no_session != true) {
  627. // Initialize session or attach to existing
  628. if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
  629. if (!is_null($this->session_name) && trim($this->session_name) != '') {
  630. session_name(trim($this->session_name)); // set session name if provided
  631. }
  632. session_start();
  633. }
  634. }
  635. }
  636. /**
  637. * Return the absolute path to the Securimage directory
  638. * @return string The path to the securimage base directory
  639. */
  640. public static function getPath()
  641. {
  642. return dirname(__FILE__);
  643. }
  644. /**
  645. * Generate a new captcha ID or retrieve the current ID
  646. *
  647. * @param $new bool If true, generates a new challenge and returns and ID
  648. * @param $options array Additional options to be passed to Securimage.
  649. * Must include database options if not set directly in securimage.php
  650. *
  651. * @return null|string Returns null if no captcha id set and new was false, or string captcha ID
  652. */
  653. public static function getCaptchaId($new = true, array $options = array())
  654. {
  655. if (is_null($new) || (bool)$new == true) {
  656. $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true));
  657. $opts = array('no_session' => true,
  658. 'use_database' => true);
  659. if (sizeof($options) > 0) $opts = array_merge($options, $opts);
  660. $si = new self($opts);
  661. Securimage::$_captchaId = $id;
  662. $si->createCode();
  663. return $id;
  664. } else {
  665. return Securimage::$_captchaId;
  666. }
  667. }
  668. /**
  669. * Validate a captcha code input against a captcha ID
  670. *
  671. * @param string $id The captcha ID to check
  672. * @param string $value The captcha value supplied by the user
  673. * @param array $options Array of options to construct Securimage with.
  674. * Options must include database options if they are not set in securimage.php
  675. *
  676. * @see Securimage::$database_driver
  677. * @return bool true if the code was valid for the given captcha ID, false if not or if database failed to open
  678. */
  679. public static function checkByCaptchaId($id, $value, array $options = array())
  680. {
  681. $opts = array('captchaId' => $id,
  682. 'no_session' => true,
  683. 'use_database' => true);
  684. if (sizeof($options) > 0) $opts = array_merge($options, $opts);
  685. $si = new self($opts);
  686. if ($si->openDatabase()) {
  687. $code = $si->getCodeFromDatabase();
  688. if (is_array($code)) {
  689. $si->code = $code['code'];
  690. $si->code_display = $code['code_disp'];
  691. }
  692. if ($si->check($value)) {
  693. $si->clearCodeFromDatabase();
  694. return true;
  695. } else {
  696. return false;
  697. }
  698. } else {
  699. return false;
  700. }
  701. }
  702. /**
  703. * Used to serve a captcha image to the browser
  704. * @param string $background_image The path to the background image to use
  705. * <code>
  706. * $img = new Securimage();
  707. * $img->code_length = 6;
  708. * $img->num_lines = 5;
  709. * $img->noise_level = 5;
  710. *
  711. * $img->show(); // sends the image to browser
  712. * exit;
  713. * </code>
  714. */
  715. public function show($background_image = '')
  716. {
  717. set_error_handler(array(&$this, 'errorHandler'));
  718. if($background_image != '' && is_readable($background_image)) {
  719. $this->bgimg = $background_image;
  720. }
  721. $this->doImage();
  722. }
  723. /**
  724. * Check a submitted code against the stored value
  725. * @param string $code The captcha code to check
  726. * <code>
  727. * $code = $_POST['code'];
  728. * $img = new Securimage();
  729. * if ($img->check($code) == true) {
  730. * $captcha_valid = true;
  731. * } else {
  732. * $captcha_valid = false;
  733. * }
  734. * </code>
  735. */
  736. public function check($code)
  737. {
  738. $this->code_entered = $code;
  739. $this->validate();
  740. return $this->correct_code;
  741. }
  742. /**
  743. * Output a wav file of the captcha code to the browser
  744. *
  745. * <code>
  746. * $img = new Securimage();
  747. * $img->outputAudioFile(); // outputs a wav file to the browser
  748. * exit;
  749. * </code>
  750. */
  751. public function outputAudioFile()
  752. {
  753. set_error_handler(array(&$this, 'errorHandler'));
  754. require_once dirname(__FILE__) . '/WavFile.php';
  755. try {
  756. $audio = $this->getAudibleCode();
  757. } catch (Exception $ex) {
  758. if (($fp = @fopen(dirname(__FILE__) . '/si.error_log', 'a+')) !== false) {
  759. fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n");
  760. fclose($fp);
  761. }
  762. $audio = $this->audioError();
  763. }
  764. if ($this->canSendHeaders() || $this->send_headers == false) {
  765. if ($this->send_headers) {
  766. $uniq = md5(uniqid(microtime()));
  767. header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.wav\"");
  768. header('Cache-Control: no-store, no-cache, must-revalidate');
  769. header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
  770. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
  771. header('Content-type: audio/x-wav');
  772. if (extension_loaded('zlib')) {
  773. ini_set('zlib.output_compression', true); // compress output if supported by browser
  774. } else {
  775. header('Content-Length: ' . strlen($audio));
  776. }
  777. }
  778. echo $audio;
  779. } else {
  780. echo '<hr /><strong>'
  781. .'Failed to generate audio file, content has already been '
  782. .'output.<br />This is most likely due to misconfiguration or '
  783. .'a PHP error was sent to the browser.</strong>';
  784. }
  785. restore_error_handler();
  786. if (!$this->no_exit) exit;
  787. }
  788. /**
  789. * Return the code from the session or sqlite database if used. If none exists yet, an empty string is returned
  790. *
  791. * @param $array bool True to receive an array containing the code and properties
  792. * @return array|string Array if $array = true, otherwise a string containing the code
  793. */
  794. public function getCode($array = false, $returnExisting = false)
  795. {
  796. $code = '';
  797. $time = 0;
  798. $disp = 'error';
  799. if ($returnExisting && strlen($this->code) > 0) {
  800. if ($array) {
  801. return array('code' => $this->code,
  802. 'display' => $this->code_display,
  803. 'code_display' => $this->code_display,
  804. 'time' => 0);
  805. } else {
  806. return $this->code;
  807. }
  808. }
  809. if ($this->no_session != true) {
  810. if (isset($_SESSION['securimage_code_value'][$this->namespace]) &&
  811. trim($_SESSION['securimage_code_value'][$this->namespace]) != '') {
  812. if ($this->isCodeExpired(
  813. $_SESSION['securimage_code_ctime'][$this->namespace]) == false) {
  814. $code = $_SESSION['securimage_code_value'][$this->namespace];
  815. $time = $_SESSION['securimage_code_ctime'][$this->namespace];
  816. $disp = $_SESSION['securimage_code_disp'] [$this->namespace];
  817. }
  818. }
  819. }
  820. if (empty($code) && $this->use_database) {
  821. // no code in session - may mean user has cookies turned off
  822. $this->openDatabase();
  823. $code = $this->getCodeFromDatabase();
  824. } else { /* no code stored in session or sqlite database, validation will fail */ }
  825. if ($array == true) {
  826. return array('code' => $code, 'ctime' => $time, 'display' => $disp);
  827. } else {
  828. return $code;
  829. }
  830. }
  831. /**
  832. * The main image drawing routing, responsible for constructing the entire image and serving it
  833. */
  834. protected function doImage()
  835. {
  836. if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) {
  837. $imagecreate = 'imagecreatetruecolor';
  838. } else {
  839. $imagecreate = 'imagecreate';
  840. }
  841. $this->im = $imagecreate($this->image_width, $this->image_height);
  842. $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
  843. $this->allocateColors();
  844. imagepalettecopy($this->tmpimg, $this->im);
  845. $this->setBackground();
  846. $code = '';
  847. if ($this->getCaptchaId(false) !== null) {
  848. // a captcha Id was supplied
  849. // check to see if a display_value for the captcha image was set
  850. if (is_string($this->display_value) && strlen($this->display_value) > 0) {
  851. $this->code_display = $this->display_value;
  852. $this->code = ($this->case_sensitive) ?
  853. $this->display_value :
  854. strtolower($this->display_value);
  855. $code = $this->code;
  856. } else if ($this->openDatabase()) {
  857. // no display_value, check the database for existing captchaId
  858. $code = $this->getCodeFromDatabase();
  859. // got back a result from the database with a valid code for captchaId
  860. if (is_array($code)) {
  861. $this->code = $code['code'];
  862. $this->code_display = $code['code_disp'];
  863. $code = $code['code'];
  864. }
  865. }
  866. }
  867. if ($code == '') {
  868. // if the code was not set using display_value or was not found in
  869. // the database, create a new code
  870. $this->createCode();
  871. }
  872. if ($this->noise_level > 0) {
  873. $this->drawNoise();
  874. }
  875. $this->drawWord();
  876. if ($this->perturbation > 0 && is_readable($this->ttf_file)) {
  877. $this->distortedCopy();
  878. }
  879. if ($this->num_lines > 0) {
  880. $this->drawLines();
  881. }
  882. if (trim($this->image_signature) != '') {
  883. $this->addSignature();
  884. }
  885. $this->output();
  886. }
  887. /**
  888. * Allocate the colors to be used for the image
  889. */
  890. protected function allocateColors()
  891. {
  892. // allocate bg color first for imagecreate
  893. $this->gdbgcolor = imagecolorallocate($this->im,
  894. $this->image_bg_color->r,
  895. $this->image_bg_color->g,
  896. $this->image_bg_color->b);
  897. $alpha = intval($this->text_transparency_percentage / 100 * 127);
  898. if ($this->use_transparent_text == true) {
  899. $this->gdtextcolor = imagecolorallocatealpha($this->im,
  900. $this->text_color->r,
  901. $this->text_color->g,
  902. $this->text_color->b,
  903. $alpha);
  904. $this->gdlinecolor = imagecolorallocatealpha($this->im,
  905. $this->line_color->r,
  906. $this->line_color->g,
  907. $this->line_color->b,
  908. $alpha);
  909. $this->gdnoisecolor = imagecolorallocatealpha($this->im,
  910. $this->noise_color->r,
  911. $this->noise_color->g,
  912. $this->noise_color->b,
  913. $alpha);
  914. } else {
  915. $this->gdtextcolor = imagecolorallocate($this->im,
  916. $this->text_color->r,
  917. $this->text_color->g,
  918. $this->text_color->b);
  919. $this->gdlinecolor = imagecolorallocate($this->im,
  920. $this->line_color->r,
  921. $this->line_color->g,
  922. $this->line_color->b);
  923. $this->gdnoisecolor = imagecolorallocate($this->im,
  924. $this->noise_color->r,
  925. $this->noise_color->g,
  926. $this->noise_color->b);
  927. }
  928. $this->gdsignaturecolor = imagecolorallocate($this->im,
  929. $this->signature_color->r,
  930. $this->signature_color->g,
  931. $this->signature_color->b);
  932. }
  933. /**
  934. * The the background color, or background image to be used
  935. */
  936. protected function setBackground()
  937. {
  938. // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color
  939. imagefilledrectangle($this->im, 0, 0,
  940. $this->image_width, $this->image_height,
  941. $this->gdbgcolor);
  942. imagefilledrectangle($this->tmpimg, 0, 0,
  943. $this->image_width * $this->iscale, $this->image_height * $this->iscale,
  944. $this->gdbgcolor);
  945. if ($this->bgimg == '') {
  946. if ($this->background_directory != null &&
  947. is_dir($this->background_directory) &&
  948. is_readable($this->background_directory))
  949. {
  950. $img = $this->getBackgroundFromDirectory();
  951. if ($img != false) {
  952. $this->bgimg = $img;
  953. }
  954. }
  955. }
  956. if ($this->bgimg == '') {
  957. return;
  958. }
  959. $dat = @getimagesize($this->bgimg);
  960. if($dat == false) {
  961. return;
  962. }
  963. switch($dat[2]) {
  964. case 1: $newim = @imagecreatefromgif($this->bgimg); break;
  965. case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
  966. case 3: $newim = @imagecreatefrompng($this->bgimg); break;
  967. default: return;
  968. }
  969. if(!$newim) return;
  970. imagecopyresized($this->im, $newim, 0, 0, 0, 0,
  971. $this->image_width, $this->image_height,
  972. imagesx($newim), imagesy($newim));
  973. }
  974. /**
  975. * Scan the directory for a background image to use
  976. */
  977. protected function getBackgroundFromDirectory()
  978. {
  979. $images = array();
  980. if ( ($dh = opendir($this->background_directory)) !== false) {
  981. while (($file = readdir($dh)) !== false) {
  982. if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
  983. }
  984. closedir($dh);
  985. if (sizeof($images) > 0) {
  986. return rtrim($this->background_directory, '/') . '/' . $images[mt_rand(0, sizeof($images)-1)];
  987. }
  988. }
  989. return false;
  990. }
  991. /**
  992. * Generates the code or math problem and saves the value to the session
  993. */
  994. public function createCode()
  995. {
  996. $this->code = false;
  997. switch($this->captcha_type) {
  998. case self::SI_CAPTCHA_MATHEMATIC:
  999. {
  1000. do {
  1001. $signs = array('+', '-', 'x');
  1002. $left = mt_rand(1, 10);
  1003. $right = mt_rand(1, 5);
  1004. $sign = $signs[mt_rand(0, 2)];
  1005. switch($sign) {
  1006. case 'x': $c = $left * $right; break;
  1007. case '-': $c = $left - $right; break;
  1008. default: $c = $left + $right; break;
  1009. }
  1010. } while ($c <= 0); // no negative #'s or 0
  1011. $this->code = $c;
  1012. $this->code_display = "$left $sign $right";
  1013. break;
  1014. }
  1015. case self::SI_CAPTCHA_WORDS:
  1016. $words = $this->readCodeFromFile(2);
  1017. $this->code = implode(' ', $words);
  1018. $this->code_display = $this->code;
  1019. break;
  1020. default:
  1021. {
  1022. if ($this->use_wordlist && is_readable($this->wordlist_file)) {
  1023. $this->code = $this->readCodeFromFile();
  1024. }
  1025. if ($this->code == false) {
  1026. $this->code = $this->generateCode($this->code_length);
  1027. }
  1028. $this->code_display = $this->code;
  1029. $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code);
  1030. } // default
  1031. }
  1032. $this->saveData();
  1033. }
  1034. /**
  1035. * Draws the captcha code on the image
  1036. */
  1037. protected function drawWord()
  1038. {
  1039. $width2 = $this->image_width * $this->iscale;
  1040. $height2 = $this->image_height * $this->iscale;
  1041. if (!is_readable($this->ttf_file)) {
  1042. imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor);
  1043. } else {
  1044. if ($this->perturbation > 0) {
  1045. $font_size = $height2 * .4;
  1046. $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
  1047. $tx = $bb[4] - $bb[0];
  1048. $ty = $bb[5] - $bb[1];
  1049. $x = floor($width2 / 2 - $tx / 2 - $bb[0]);
  1050. $y = round($height2 / 2 - $ty / 2 - $bb[1]);
  1051. imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
  1052. } else {
  1053. $font_size = $this->image_height * .4;
  1054. $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
  1055. $tx = $bb[4] - $bb[0];
  1056. $ty = $bb[5] - $bb[1];
  1057. $x = floor($this->image_width / 2 - $tx / 2 - $bb[0]);
  1058. $y = round($this->image_height / 2 - $ty / 2 - $bb[1]);
  1059. imagettftext($this->im, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
  1060. }
  1061. }
  1062. // DEBUG
  1063. //$this->im = $this->tmpimg;
  1064. //$this->output();
  1065. }
  1066. /**
  1067. * Copies the captcha image to the final image with distortion applied
  1068. */
  1069. protected function distortedCopy()
  1070. {
  1071. $numpoles = 3; // distortion factor
  1072. // make array of poles AKA attractor points
  1073. for ($i = 0; $i < $numpoles; ++ $i) {
  1074. $px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8);
  1075. $py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
  1076. $rad[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
  1077. $tmp = ((- $this->frand()) * 0.15) - .15;
  1078. $amp[$i] = $this->perturbation * $tmp;
  1079. }
  1080. $bgCol = imagecolorat($this->tmpimg, 0, 0);
  1081. $width2 = $this->iscale * $this->image_width;
  1082. $height2 = $this->iscale * $this->image_height;
  1083. imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
  1084. // loop over $img pixels, take pixels from $tmpimg with distortion field
  1085. for ($ix = 0; $ix < $this->image_width; ++ $ix) {
  1086. for ($iy = 0; $iy < $this->image_height; ++ $iy) {
  1087. $x = $ix;
  1088. $y = $iy;
  1089. for ($i = 0; $i < $numpoles; ++ $i) {
  1090. $dx = $ix - $px[$i];
  1091. $dy = $iy - $py[$i];
  1092. if ($dx == 0 && $dy == 0) {
  1093. continue;
  1094. }
  1095. $r = sqrt($dx * $dx + $dy * $dy);
  1096. if ($r > $rad[$i]) {
  1097. continue;
  1098. }
  1099. $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
  1100. $x += $dx * $rscale;
  1101. $y += $dy * $rscale;
  1102. }
  1103. $c = $bgCol;
  1104. $x *= $this->iscale;
  1105. $y *= $this->iscale;
  1106. if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
  1107. $c = imagecolorat($this->tmpimg, $x, $y);
  1108. }
  1109. if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
  1110. imagesetpixel($this->im, $ix, $iy, $c);
  1111. }
  1112. }
  1113. }
  1114. }
  1115. /**
  1116. * Draws distorted lines on the image
  1117. */
  1118. protected function drawLines()
  1119. {
  1120. for ($line = 0; $line < $this->num_lines; ++ $line) {
  1121. $x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
  1122. $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
  1123. $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9);
  1124. $theta = ($this->frand() - 0.5) * M_PI * 0.7;
  1125. $w = $this->image_width;
  1126. $len = mt_rand($w * 0.4, $w * 0.7);
  1127. $lwid = mt_rand(0, 2);
  1128. $k = $this->frand() * 0.6 + 0.2;
  1129. $k = $k * $k * 0.5;
  1130. $phi = $this->frand() * 6.28;
  1131. $step = 0.5;
  1132. $dx = $step * cos($theta);
  1133. $dy = $step * sin($theta);
  1134. $n = $len / $step;
  1135. $amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
  1136. $x0 = $x - 0.5 * $len * cos($theta);
  1137. $y0 = $y - 0.5 * $len * sin($theta);
  1138. $ldx = round(- $dy * $lwid);
  1139. $ldy = round($dx * $lwid);
  1140. for ($i = 0; $i < $n; ++ $i) {
  1141. $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
  1142. $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
  1143. imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
  1144. }
  1145. }
  1146. }
  1147. /**
  1148. * Draws random noise on the image
  1149. */
  1150. protected function drawNoise()
  1151. {
  1152. if ($this->noise_level > 10) {
  1153. $noise_level = 10;
  1154. } else {
  1155. $noise_level = $this->noise_level;
  1156. }
  1157. $t0 = microtime(true);
  1158. $noise_level *= 125; // an arbitrary number that works well on a 1-10 scale
  1159. $points = $this->image_width * $this->image_height * $this->iscale;
  1160. $height = $this->image_height * $this->iscale;
  1161. $width = $this->image_width * $this->iscale;
  1162. for ($i = 0; $i < $noise_level; ++$i) {
  1163. $x = mt_rand(10, $width);
  1164. $y = mt_rand(10, $height);
  1165. $size = mt_rand(7, 10);
  1166. if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy
  1167. imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE);
  1168. }
  1169. $t1 = microtime(true);
  1170. $t = $t1 - $t0;
  1171. /*
  1172. // DEBUG
  1173. imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor);
  1174. header('content-type: image/png');
  1175. imagepng($this->tmpimg);
  1176. exit;
  1177. */
  1178. }
  1179. /**
  1180. * Print signature text on image
  1181. */
  1182. protected function addSignature()
  1183. {
  1184. $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
  1185. $textlen = $bbox[2] - $bbox[0];
  1186. $x = $this->image_width - $textlen - 5;
  1187. $y = $this->image_height - 3;
  1188. imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
  1189. }
  1190. /**
  1191. * Sends the appropriate image and cache headers and outputs image to the browser
  1192. */
  1193. protected function output()
  1194. {
  1195. if ($this->canSendHeaders() || $this->send_headers == false) {
  1196. if ($this->send_headers) {
  1197. // only send the content-type headers if no headers have been output
  1198. // this will ease debugging on misconfigured servers where warnings
  1199. // may have been output which break the image and prevent easily viewing
  1200. // source to see the error.
  1201. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  1202. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  1203. header("Cache-Control: no-store, no-cache, must-revalidate");
  1204. header("Cache-Control: post-check=0, pre-check=0", false);
  1205. header("Pragma: no-cache");
  1206. }
  1207. switch ($this->image_type) {
  1208. case self::SI_IMAGE_JPEG:
  1209. if ($this->send_headers) header("Content-Type: image/jpeg");
  1210. imagejpeg($this->im, null, 90);
  1211. break;
  1212. case self::SI_IMAGE_GIF:
  1213. if ($this->send_headers) header("Content-Type: image/gif");
  1214. imagegif($this->im);
  1215. break;
  1216. default:
  1217. if ($this->send_headers) header("Content-Type: image/png");
  1218. imagepng($this->im);
  1219. break;
  1220. }
  1221. } else {
  1222. echo '<hr /><strong>'
  1223. .'Failed to generate captcha image, content has already been '
  1224. .'output.<br />This is most likely due to misconfiguration or '
  1225. .'a PHP error was sent to the browser.</strong>';
  1226. }
  1227. imagedestroy($this->im);
  1228. restore_error_handler();
  1229. if (!$this->no_exit) exit;
  1230. }
  1231. /**
  1232. * Gets the code and returns the binary audio file for the stored captcha code
  1233. *
  1234. * @return The audio representation of the captcha in Wav format
  1235. */
  1236. protected function getAudibleCode()
  1237. {
  1238. $letters = array();
  1239. $code = $this->getCode(true, true);
  1240. if ($code['code'] == '') {
  1241. if (strlen($this->display_value) > 0) {
  1242. $code = array('code' => $this->display_value, 'display' => $this->display_value);
  1243. } else {
  1244. $this->createCode();
  1245. $code = $this->getCode(true);
  1246. }
  1247. }
  1248. if (preg_match('/(\d+) (\+|-|x) (\d+)/i', $code['display'], $eq)) {
  1249. $math = true;
  1250. $left = $eq[1];
  1251. $sign = str_replace(array('+', '-', 'x'), array('plus', 'minus', 'times'), $eq[2]);
  1252. $right = $eq[3];
  1253. $letters = array($left, $sign, $right);
  1254. } else {
  1255. $math = false;
  1256. $length = strlen($code['display']);
  1257. for($i = 0; $i < $length; ++$i) {
  1258. $letter = $code['display']{$i};
  1259. $letters[] = $letter;
  1260. }
  1261. }
  1262. try {
  1263. return $this->generateWAV($letters);
  1264. } catch(Exception $ex) {
  1265. throw $ex;
  1266. }
  1267. }
  1268. /**
  1269. * Gets a captcha code from a wordlist
  1270. */
  1271. protected function readCodeFromFile($numWords = 1)
  1272. {
  1273. $fp = fopen($this->wordlist_file, 'rb');
  1274. if (!$fp) return false;
  1275. $fsize = filesize($this->wordlist_file);
  1276. if ($fsize < 128) return false; // too small of a list to be effective
  1277. if ((int)$numWords < 1 || (int)$numWords > 5) $numWords = 1;
  1278. $words = array();
  1279. $i = 0;
  1280. do {
  1281. fseek($fp, mt_rand(0, $fsize - 64), SEEK_SET); // seek to a random position of file from 0 to filesize-64
  1282. $data = fread($fp, 64); // read a chunk from our random position
  1283. $data = preg_replace("/\r?\n/", "\n", $data);
  1284. $start = @strpos($data, "\n", mt_rand(0, 56)) + 1; // random start position
  1285. $end = @strpos($data, "\n", $start); // find end of word
  1286. if ($start === false) {
  1287. // picked start position at end of file
  1288. continue;
  1289. } else if ($end === false) {
  1290. $end = strlen($data);
  1291. }
  1292. $word = strtolower(substr($data, $start, $end - $start)); // return a line of the file
  1293. $words[] = $word;
  1294. } while (++$i < $numWords);
  1295. fclose($fp);
  1296. if ($numWords < 2) {
  1297. return $words[0];
  1298. } else {
  1299. return $words;
  1300. }
  1301. }
  1302. /**
  1303. * Generates a random captcha code from the set character set
  1304. */
  1305. protected function generateCode()
  1306. {
  1307. $code = '';
  1308. if (function_exists('mb_strlen')) {
  1309. for($i = 1, $cslen = mb_strlen($this->charset); $i <= $this->code_length; ++$i) {
  1310. $code .= mb_substr($this->charset, mt_rand(0, $cslen - 1), 1, 'UTF-8');
  1311. }
  1312. } else {
  1313. for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) {
  1314. $code .= substr($this->charset, mt_rand(0, $cslen - 1), 1);
  1315. }
  1316. }
  1317. return $code;
  1318. }
  1319. /**
  1320. * Checks the entered code against the value stored in the session or sqlite database, handles case sensitivity
  1321. * Also clears the stored codes if the code was entered correctly to prevent re-use
  1322. */
  1323. protected function validate()
  1324. {
  1325. if (!is_string($this->code) || strlen($this->code) == 0) {
  1326. $code = $this->getCode();
  1327. // returns stored code, or an empty string if no stored code was found
  1328. // checks the session and database if enabled
  1329. } else {
  1330. $code = $this->code;
  1331. }
  1332. if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) {
  1333. // case sensitive was set from securimage_show.php but not in class
  1334. // the code saved in the session has capitals so set case sensitive to true
  1335. $this->case_sensitive = true;
  1336. }
  1337. $code_entered = trim( (($this->case_sensitive) ? $this->code_entered
  1338. : strtolower($this->code_entered))
  1339. );
  1340. $this->correct_code = false;
  1341. if ($code != '') {
  1342. if (strpos($code, ' ') !== false) {
  1343. // for multi word captchas, remove more than once space from input
  1344. $code_entered = preg_replace('/\s+/', ' ', $code_entered);
  1345. $code_entered = strtolower($code_entered);
  1346. }
  1347. if ($code == $code_entered) {
  1348. $this->correct_code = true;
  1349. if ($this->no_session != true) {
  1350. $_SESSION['securimage_code_value'][$this->namespace] = '';
  1351. $_SESSION['securimage_code_ctime'][$this->namespace] = '';
  1352. }
  1353. $this->clearCodeFromDatabase();
  1354. }
  1355. }
  1356. }
  1357. /**
  1358. * Save data to session namespace and database if used
  1359. */
  1360. protected function saveData()
  1361. {
  1362. if ($this->no_session != true) {
  1363. if (isset($_SESSION['securimage_code_value']) && is_scalar($_SESSION['securimage_code_value'])) {
  1364. // fix for migration from v2 - v3
  1365. unset($_SESSION['securimage_code_value']);
  1366. unset($_SESSION['securimage_code_ctime']);
  1367. }
  1368. $_SESSION['securimage_code_disp'] [$this->namespace] = $this->code_display;
  1369. $_SESSION['securimage_code_value'][$this->namespace] = $this->code;
  1370. $_SESSION['securimage_code_ctime'][$this->namespace] = time();
  1371. }
  1372. if ($this->use_database) {
  1373. $this->saveCodeToDatabase();
  1374. }
  1375. }
  1376. /**
  1377. * Saves the code to the sqlite database
  1378. */
  1379. protected function saveCodeToDatabase()
  1380. {
  1381. $success = false;
  1382. $this->openDatabase();
  1383. if ($this->use_database && $this->pdo_conn) {
  1384. $id = $this->getCaptchaId(false);
  1385. $ip = $_SERVER['REMOTE_ADDR'];
  1386. if (empty($id)) {
  1387. $id = $ip;
  1388. }
  1389. $time = time();
  1390. $code = $this->code;
  1391. $code_disp = $this->code_display;
  1392. // This is somewhat expensive in PDO Sqlite3 (when there is something to delete)
  1393. $this->clearCodeFromDatabase();
  1394. $query = "INSERT INTO {$this->database_table} ("
  1395. ."id, code, code_display, namespace, created) "
  1396. ."VALUES(?, ?, ?, ?, ?)";
  1397. $stmt = $this->pdo_conn->prepare($query);
  1398. $success = $stmt->execute(array($id, $code, $code_disp, $this->namespace, $time));
  1399. if (!$success) {
  1400. $err = $stmt->errorInfo();
  1401. trigger_error("Failed to insert code into database. {$err[1]}: {$err[2]}", E_USER_WARNING);
  1402. }
  1403. }
  1404. return $success !== false;
  1405. }
  1406. /**
  1407. * Open sqlite database
  1408. */
  1409. protected function openDatabase()
  1410. {
  1411. $this->pdo_conn = false;
  1412. if ($this->use_database) {
  1413. $pdo_extension = 'PDO_' . strtoupper($this->database_driver);
  1414. if (!extension_loaded($pdo_extension)) {
  1415. trigger_error("Database support is turned on in Securimage, but the chosen extension $pdo_extension is not loaded in PHP.", E_USER_WARNING);
  1416. return false;
  1417. }
  1418. }
  1419. if ($this->database_driver == self::SI_DRIVER_SQLITE3) {
  1420. if (!file_exists($this->database_file)) {
  1421. $fp = fopen($this->database_file, 'w+');
  1422. if (!$fp) {
  1423. $err = error_get_last();
  1424. trigger_error("Securimage failed to create SQLite3 database file '{$this->database_file}'. Reason: {$err['message']}", E_USER_WARNING);
  1425. return false;
  1426. }
  1427. fclose($fp);
  1428. chmod($this->database_file, 0666);
  1429. } else if (!is_writeable($this->database_file)) {
  1430. trigger_error("Securimage does not have read/write access to database file '{$this->database_file}. Make sure permissions are 0666 and writeable by user '" . get_current_user() . "'", E_USER_WARNING);
  1431. return false;
  1432. }
  1433. }
  1434. $dsn = $this->getDsn();
  1435. try {
  1436. $options = array();
  1437. $this->pdo_conn = new PDO($dsn, $this->database_user, $this->database_pass, $options);
  1438. } catch (PDOException $pdoex) {
  1439. trigger_error("Database connection failed: " . $pdoex->getMessage(), E_USER_WARNING);
  1440. return false;
  1441. }
  1442. try {
  1443. if (!$this->checkTablesExist()) {
  1444. // create tables...
  1445. $this->createDatabaseTables();
  1446. }
  1447. } catch (Exception $ex) {
  1448. trigger_error($ex->getMessage(), E_USER_WARNING);
  1449. $this->pdo_conn = null;
  1450. return false;
  1451. }
  1452. if (mt_rand(0, 100) / 100.0 == 1.0) {
  1453. $this->purgeOldCodesFromDatabase();
  1454. }
  1455. return $this->pdo_conn;
  1456. }
  1457. protected function getDsn()
  1458. {
  1459. $dsn = sprintf('%s:', $this->database_driver);
  1460. switch($this->database_driver) {
  1461. case self::SI_DRIVER_SQLITE3:
  1462. $dsn .= $this->database_file;
  1463. break;
  1464. case self::SI_DRIVER_MYSQL:
  1465. case self::SI_DRIVER_PGSQL:
  1466. $dsn .= sprintf('host=%s;dbname=%s',
  1467. $this->database_host,
  1468. $this->database_name);
  1469. break;
  1470. }
  1471. return $dsn;
  1472. }
  1473. protected function checkTablesExist()
  1474. {
  1475. $table = $this->pdo_conn->quote($this->database_table);
  1476. switch($this->database_driver) {
  1477. case self::SI_DRIVER_SQLITE3:
  1478. // query row count for sqlite, PRAGMA queries seem to return no
  1479. // rowCount using PDO even if there are rows returned
  1480. $query = "SELECT COUNT(id) FROM $table";
  1481. break;
  1482. case self::SI_DRIVER_MYSQL:
  1483. $query = "SHOW TABLES LIKE $table";
  1484. break;
  1485. case self::SI_DRIVER_PGSQL:
  1486. $query = "SELECT * FROM information_schema.columns WHERE table_name = $table;";
  1487. break;
  1488. }
  1489. $result = $this->pdo_conn->query($query);
  1490. if (!$result) {
  1491. $err = $this->pdo_conn->errorInfo();
  1492. if ($this->database_driver == self::SI_DRIVER_SQLITE3 &&
  1493. $err[1] === 1 && strpos($err[2], 'no such table') !== false)
  1494. {
  1495. return false;
  1496. }
  1497. throw new Exception("Failed to check tables: {$err[0]} - {$err[1]}: {$err[2]}");
  1498. } else if ($this->database_driver == self::SI_DRIVER_SQLITE3) {
  1499. // successful here regardless of row count for sqlite
  1500. return true;
  1501. } else if ($result->rowCount() == 0) {
  1502. return false;
  1503. } else {
  1504. return true;
  1505. }
  1506. }
  1507. protected function createDatabaseTables()
  1508. {
  1509. $queries = array();
  1510. switch($this->database_driver) {
  1511. case self::SI_DRIVER_SQLITE3:
  1512. $queries[] = "CREATE TABLE \"{$this->database_table}\" (
  1513. id VARCHAR(40),
  1514. namespace VARCHAR(32) NOT NULL,
  1515. code VARCHAR(32) NOT NULL,
  1516. code_display VARCHAR(32) NOT NULL,
  1517. created INTEGER NOT NULL,
  1518. PRIMARY KEY(id, namespace)
  1519. )";
  1520. $queries[] = "CREATE INDEX ndx_created ON {$this->database_table} (created)";
  1521. break;
  1522. case self::SI_DRIVER_MYSQL:
  1523. $queries[] = "CREATE TABLE `{$this->database_table}` (
  1524. `id` VARCHAR(40) NOT NULL,
  1525. `namespace` VARCHAR(32) NOT NULL,
  1526. `code` VARCHAR(32) NOT NULL,
  1527. `code_display` VARCHAR(32) NOT NULL,
  1528. `created` INT NOT NULL,
  1529. PRIMARY KEY(id, namespace),
  1530. INDEX(created)
  1531. )";
  1532. break;
  1533. case self::SI_DRIVER_PGSQL:
  1534. $queries[] = "CREATE TABLE {$this->database_table} (
  1535. id character varying(40) NOT NULL,
  1536. namespace character varying(32) NOT NULL,
  1537. code character varying(32) NOT NULL,
  1538. code_display character varying(32) NOT NULL,
  1539. created integer NOT NULL,
  1540. CONSTRAINT pkey_id_namespace PRIMARY KEY (id, namespace)
  1541. )";
  1542. $queries[] = "CREATE INDEX ndx_created ON {$this->database_table} (created);";
  1543. break;
  1544. }
  1545. $this->pdo_conn->beginTransaction();
  1546. foreach($queries as $query) {
  1547. $result = $this->pdo_conn->query($query);
  1548. if (!$result) {
  1549. $err = $this->pdo_conn->errorInfo();
  1550. trigger_error("Failed to create table. {$err[1]}: {$err[2]}", E_USER_WARNING);
  1551. $this->pdo_conn->rollBack();
  1552. $this->pdo_conn = false;
  1553. return false;
  1554. }
  1555. }
  1556. $this->pdo_conn->commit();
  1557. return true;
  1558. }
  1559. /**
  1560. * Get a code from the sqlite database for ip address/captchaId.
  1561. *
  1562. * @return string|array Empty string if no code was found or has expired,
  1563. * otherwise returns the stored captcha code. If a captchaId is set, this
  1564. * returns an array with indices "code" and "code_disp"
  1565. */
  1566. protected function getCodeFromDatabase()
  1567. {
  1568. $code = '';
  1569. if ($this->use_database == true && $this->pdo_conn) {
  1570. if (Securimage::$_captchaId !== null) {
  1571. $query = "SELECT * FROM {$this->database_table} WHERE id = ?";
  1572. $stmt = $this->pdo_conn->prepare($query);
  1573. $result = $stmt->execute(array(Securimage::$_captchaId));
  1574. } else {
  1575. $ip = $_SERVER['REMOTE_ADDR'];
  1576. $ns = $this->namespace;
  1577. // ip is stored in id column when no captchaId
  1578. $query = "SELECT * FROM {$this->database_table} WHERE id = ? AND namespace = ?";
  1579. $stmt = $this->pdo_conn->prepare($query);
  1580. $result = $stmt->execute(array($ip, $ns));
  1581. }
  1582. if (!$result) {
  1583. $err = $this->pdo_conn->errorInfo();
  1584. trigger_error("Failed to select code from database. {$err[0]}: {$err[1]}", E_USER_WARNING);
  1585. } else {
  1586. if ( ($row = $stmt->fetch()) !== false ) {
  1587. if (false == $this->isCodeExpired($row['created'])) {
  1588. if (Securimage::$_captchaId !== null) {
  1589. // return an array when using captchaId
  1590. $code = array('code' => $row['code'],
  1591. 'code_disp' => $row['code_display']);
  1592. } else {
  1593. $code = $row['code'];
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. return $code;
  1600. }
  1601. /**
  1602. * Remove an entered code from the database
  1603. */
  1604. protected function clearCodeFromDatabase()
  1605. {
  1606. if ($this->pdo_conn) {
  1607. $ip = $_SERVER['REMOTE_ADDR'];
  1608. $ns = $this->pdo_conn->quote($this->namespace);
  1609. $id = Securimage::$_captchaId;
  1610. if (empty($id)) {
  1611. $id = $ip; // if no captchaId set, IP address is captchaId.
  1612. }
  1613. $id = $this->pdo_conn->quote($id);
  1614. $query = sprintf("DELETE FROM %s WHERE id = %s AND namespace = %s",
  1615. $this->database_table, $id, $ns);
  1616. $result = $this->pdo_conn->query($query);
  1617. if (!$result) {
  1618. trigger_error("Failed to delete code from database.", E_USER_WARNING);
  1619. }
  1620. }
  1621. }
  1622. /**
  1623. * Deletes old codes from sqlite database
  1624. */
  1625. protected function purgeOldCodesFromDatabase()
  1626. {
  1627. if ($this->use_database && $this->pdo_conn) {
  1628. $now = time();
  1629. $limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time;
  1630. $query = sprintf("DELETE FROM %s WHERE %s - created > %s",
  1631. $this->database_table,
  1632. $this->pdo_conn->quote($now, PDO::PARAM_INT),
  1633. $this->pdo_conn->quote($limit, PDO::PARAM_INT));
  1634. $result = $this->pdo_conn->query($query);
  1635. }
  1636. }
  1637. /**
  1638. * Checks to see if the captcha code has expired and cannot be used
  1639. * @param unknown_type $creation_time
  1640. */
  1641. protected function isCodeExpired($creation_time)
  1642. {
  1643. $expired = true;
  1644. if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) {
  1645. $expired = false;
  1646. } else if (time() - $creation_time < $this->expiry_time) {
  1647. $expired = false;
  1648. }
  1649. return $expired;
  1650. }
  1651. /**
  1652. * Generate a wav file given the $letters in the code
  1653. * @todo Add ability to merge 2 sound files together to have random background sounds
  1654. * @param array $letters
  1655. * @return string The binary contents of the wav file
  1656. */
  1657. protected function generateWAV($letters)
  1658. {
  1659. $wavCaptcha = new WavFile();
  1660. $first = true; // reading first wav file
  1661. foreach ($letters as $letter) {
  1662. $letter = strtoupper($letter);
  1663. try {
  1664. $l = new WavFile($this->audio_path . '/' . $letter . '.wav');
  1665. if ($first) {
  1666. // set sample rate, bits/sample, and # of channels for file based on first letter
  1667. $wavCaptcha->setSampleRate($l->getSampleRate())
  1668. ->setBitsPerSample($l->getBitsPerSample())
  1669. ->setNumChannels($l->getNumChannels());
  1670. $first = false;
  1671. }
  1672. // append letter to the captcha audio
  1673. $wavCaptcha->appendWav($l);
  1674. // random length of silence between $audio_gap_min and $audio_gap_max
  1675. if ($this->audio_gap_max > 0 && $this->audio_gap_max > $this->audio_gap_min) {
  1676. $wavCaptcha->insertSilence( mt_rand($this->audio_gap_min, $this->audio_gap_max) / 1000.0 );
  1677. }
  1678. } catch (Exception $ex) {
  1679. // failed to open file, or the wav file is broken or not supported
  1680. // 2 wav files were not compatible, different # channels, bits/sample, or sample rate
  1681. throw $ex;
  1682. }
  1683. }
  1684. /********* Set up audio filters *****************************/
  1685. $filters = array();
  1686. if ($this->audio_use_noise == true) {
  1687. // use background audio - find random file
  1688. $noiseFile = $this->getRandomNoiseFile();
  1689. if ($noiseFile !== false && is_readable($noiseFile)) {
  1690. try {
  1691. $wavNoise = new WavFile($noiseFile, false);
  1692. } catch(Exception $ex) {
  1693. throw $ex;
  1694. }
  1695. // start at a random offset from the beginning of the wavfile
  1696. // in order to add more randomness
  1697. $randOffset = 0;
  1698. if ($wavNoise->getNumBlocks() > 2 * $wavCaptcha->getNumBlocks()) {
  1699. $randBlock = mt_rand(0, $wavNoise->getNumBlocks() - $wavCaptcha->getNumBlocks());
  1700. $wavNoise->readWavData($randBlock * $wavNoise->getBlockAlign(), $wavCaptcha->getNumBlocks() * $wavNoise->getBlockAlign());
  1701. } else {
  1702. $wavNoise->readWavData();
  1703. $randOffset = mt_rand(0, $wavNoise->getNumBlocks() - 1);
  1704. }
  1705. $mixOpts = array('wav' => $wavNoise,
  1706. 'loop' => true,
  1707. 'blockOffset' => $randOffset);
  1708. $filters[WavFile::FILTER_MIX] = $mixOpts;
  1709. $filters[WavFile::FILTER_NORMALIZE] = $this->audio_mix_normalization;
  1710. }
  1711. }
  1712. if ($this->degrade_audio == true) {
  1713. // add random noise.
  1714. // any noise level below 95% is intensely distorted and not pleasant to the ear
  1715. $filters[WavFile::FILTER_DEGRADE] = mt_rand(95, 98) / 100.0;
  1716. }
  1717. if (!empty($filters)) {
  1718. $wavCaptcha->filter($filters); // apply filters to captcha audio
  1719. }
  1720. return $wavCaptcha->__toString();
  1721. }
  1722. public function getRandomNoiseFile()
  1723. {
  1724. $return = false;
  1725. if ( ($dh = opendir($this->audio_noise_path)) !== false ) {
  1726. $list = array();
  1727. while ( ($file = readdir($dh)) !== false ) {
  1728. if ($file == '.' || $file == '..') continue;
  1729. if (strtolower(substr($file, -4)) != '.wav') continue;
  1730. $list[] = $file;
  1731. }
  1732. closedir($dh);
  1733. if (sizeof($list) > 0) {
  1734. $file = $list[array_rand($list, 1)];
  1735. $return = $this->audio_noise_path . DIRECTORY_SEPARATOR . $file;
  1736. }
  1737. }
  1738. return $return;
  1739. }
  1740. /**
  1741. * Return a wav file saying there was an error generating file
  1742. *
  1743. * @return string The binary audio contents
  1744. */
  1745. protected function audioError()
  1746. {
  1747. return @file_get_contents(dirname(__FILE__) . '/audio/en/error.wav');
  1748. }
  1749. /**
  1750. * Checks to see if headers can be sent and if any error has been output to the browser
  1751. *
  1752. * @return bool true if headers haven't been sent and no output/errors will break audio/images, false if unsafe
  1753. */
  1754. protected function canSendHeaders()
  1755. {
  1756. if (headers_sent()) {
  1757. // output has been flushed and headers have already been sent
  1758. return false;
  1759. } else if (strlen((string)ob_get_contents()) > 0) {
  1760. // headers haven't been sent, but there is data in the buffer that will break image and audio data
  1761. return false;
  1762. }
  1763. return true;
  1764. }
  1765. /**
  1766. * Return a random float between 0 and 0.9999
  1767. *
  1768. * @return float Random float between 0 and 0.9999
  1769. */
  1770. function frand()
  1771. {
  1772. return 0.0001 * mt_rand(0,9999);
  1773. }
  1774. /**
  1775. * Convert an html color code to a Securimage_Color
  1776. * @param string $color
  1777. * @param Securimage_Color $default The defalt color to use if $color is invalid
  1778. */
  1779. protected function initColor($color, $default)
  1780. {
  1781. if ($color == null) {
  1782. return new Securimage_Color($default);
  1783. } else if (is_string($color)) {
  1784. try {
  1785. return new Securimage_Color($color);
  1786. } catch(Exception $e) {
  1787. return new Securimage_Color($default);
  1788. }
  1789. } else if (is_array($color) && sizeof($color) == 3) {
  1790. return new Securimage_Color($color[0], $color[1], $color[2]);
  1791. } else {
  1792. return new Securimage_Color($default);
  1793. }
  1794. }
  1795. /**
  1796. * Error handler used when outputting captcha image or audio.
  1797. * This error handler helps determine if any errors raised would
  1798. * prevent captcha image or audio from displaying. If they have
  1799. * no effect on the output buffer or headers, true is returned so
  1800. * the script can continue processing.
  1801. * See https://github.com/dapphp/securimage/issues/15
  1802. *
  1803. * @param int $errno
  1804. * @param string $errstr
  1805. * @param string $errfile
  1806. * @param int $errline
  1807. * @param array $errcontext
  1808. * @return boolean true if handled, false if PHP should handle
  1809. */
  1810. public function errorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array())
  1811. {
  1812. // get the current error reporting level
  1813. $level = error_reporting();
  1814. // if error was supressed or $errno not set in current error level
  1815. if ($level == 0 || ($level & $errno) == 0) {
  1816. return true;
  1817. }
  1818. return false;
  1819. }
  1820. }
  1821. /**
  1822. * Color object for Securimage CAPTCHA
  1823. *
  1824. * @version 3.0
  1825. * @since 2.0
  1826. * @package Securimage
  1827. * @subpackage classes
  1828. *
  1829. */
  1830. class Securimage_Color
  1831. {
  1832. public $r;
  1833. public $g;
  1834. public $b;
  1835. /**
  1836. * Create a new Securimage_Color object.<br />
  1837. * Constructor expects 1 or 3 arguments.<br />
  1838. * When passing a single argument, specify the color using HTML hex format,<br />
  1839. * when passing 3 arguments, specify each RGB component (from 0-255) individually.<br />
  1840. * $color = new Securimage_Color('#0080FF') or <br />
  1841. * $color = new Securimage_Color(0, 128, 255)
  1842. *
  1843. * @param string $color
  1844. * @throws Exception
  1845. */
  1846. public function __construct($color = '#ffffff')
  1847. {
  1848. $args = func_get_args();
  1849. if (sizeof($args) == 0) {
  1850. $this->r = 255;
  1851. $this->g = 255;
  1852. $this->b = 255;
  1853. } else if (sizeof($args) == 1) {
  1854. // set based on html code
  1855. if (substr($color, 0, 1) == '#') {
  1856. $color = substr($color, 1);
  1857. }
  1858. if (strlen($color) != 3 && strlen($color) != 6) {
  1859. throw new InvalidArgumentException(
  1860. 'Invalid HTML color code passed to Securimage_Color'
  1861. );
  1862. }
  1863. $this->constructHTML($color);
  1864. } else if (sizeof($args) == 3) {
  1865. $this->constructRGB($args[0], $args[1], $args[2]);
  1866. } else {
  1867. throw new InvalidArgumentException(
  1868. 'Securimage_Color constructor expects 0, 1 or 3 arguments; ' . sizeof($args) . ' given'
  1869. );
  1870. }
  1871. }
  1872. /**
  1873. * Construct from an rgb triplet
  1874. * @param int $red The red component, 0-255
  1875. * @param int $green The green component, 0-255
  1876. * @param int $blue The blue component, 0-255
  1877. */
  1878. protected function constructRGB($red, $green, $blue)
  1879. {
  1880. if ($red < 0) $red = 0;
  1881. if ($red > 255) $red = 255;
  1882. if ($green < 0) $green = 0;
  1883. if ($green > 255) $green = 255;
  1884. if ($blue < 0) $blue = 0;
  1885. if ($blue > 255) $blue = 255;
  1886. $this->r = $red;
  1887. $this->g = $green;
  1888. $this->b = $blue;
  1889. }
  1890. /**
  1891. * Construct from an html hex color code
  1892. * @param string $color
  1893. */
  1894. protected function constructHTML($color)
  1895. {
  1896. if (strlen($color) == 3) {
  1897. $red = str_repeat(substr($color, 0, 1), 2);
  1898. $green = str_repeat(substr($color, 1, 1), 2);
  1899. $blue = str_repeat(substr($color, 2, 1), 2);
  1900. } else {
  1901. $red = substr($color, 0, 2);
  1902. $green = substr($color, 2, 2);
  1903. $blue = substr($color, 4, 2);
  1904. }
  1905. $this->r = hexdec($red);
  1906. $this->g = hexdec($green);
  1907. $this->b = hexdec($blue);
  1908. }
  1909. }