PageRenderTime 32ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/securimage/securimage.php

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