PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/components/com_uniform/libraries/3rd-party/securimage/securimage.php

https://gitlab.com/Yishagerew/GDA
PHP | 2412 lines | 1473 code | 214 blank | 725 comment | 224 complexity | 34242af9d60ff732114d2c6dcf665241 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MIT

Large files files are truncated, but you can click here to view the full file

  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. {
  569. foreach ($options as $prop => $val)
  570. {
  571. if ($prop == 'captchaId')
  572. {
  573. Securimage::$_captchaId = $val;
  574. $this->use_database = true;
  575. }
  576. else if ($prop == 'use_sqlite_db')
  577. {
  578. trigger_error("The use_sqlite_db option is deprecated, use 'use_database' instead", E_USER_NOTICE);
  579. }
  580. else
  581. {
  582. $this->$prop = $val;
  583. }
  584. }
  585. }
  586. $this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
  587. $this->text_color = $this->initColor($this->text_color, '#616161');
  588. $this->line_color = $this->initColor($this->line_color, '#616161');
  589. $this->noise_color = $this->initColor($this->noise_color, '#616161');
  590. $this->signature_color = $this->initColor($this->signature_color, '#616161');
  591. if (is_null($this->ttf_file))
  592. {
  593. $this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
  594. }
  595. $this->signature_font = $this->ttf_file;
  596. if (is_null($this->wordlist_file))
  597. {
  598. $this->wordlist_file = $this->securimage_path . '/words/words.txt';
  599. }
  600. if (is_null($this->database_file))
  601. {
  602. $this->database_file = $this->securimage_path . '/database/securimage.sq3';
  603. }
  604. if (is_null($this->audio_path))
  605. {
  606. $this->audio_path = $this->securimage_path . '/audio/en/';
  607. }
  608. if (is_null($this->audio_noise_path))
  609. {
  610. $this->audio_noise_path = $this->securimage_path . '/audio/noise/';
  611. }
  612. if (is_null($this->audio_use_noise))
  613. {
  614. $this->audio_use_noise = true;
  615. }
  616. if (is_null($this->degrade_audio))
  617. {
  618. $this->degrade_audio = true;
  619. }
  620. if (is_null($this->code_length) || (int) $this->code_length < 1)
  621. {
  622. $this->code_length = 6;
  623. }
  624. if (is_null($this->perturbation) || !is_numeric($this->perturbation))
  625. {
  626. $this->perturbation = 0.75;
  627. }
  628. if (is_null($this->namespace) || !is_string($this->namespace))
  629. {
  630. $this->namespace = 'default';
  631. }
  632. if (is_null($this->no_exit))
  633. {
  634. $this->no_exit = false;
  635. }
  636. if (is_null($this->no_session))
  637. {
  638. $this->no_session = false;
  639. }
  640. if (is_null($this->send_headers))
  641. {
  642. $this->send_headers = false;
  643. }
  644. if ($this->no_session != true)
  645. {
  646. // Initialize session or attach to existing
  647. if (session_id() == '')
  648. { // no session has been started yet, which is needed for validation
  649. if (!is_null($this->session_name) && trim($this->session_name) != '')
  650. {
  651. session_name(trim($this->session_name)); // set session name if provided
  652. }
  653. session_start();
  654. }
  655. }
  656. }
  657. /**
  658. * Return the absolute path to the Securimage directory
  659. * @return string The path to the securimage base directory
  660. */
  661. public static function getPath()
  662. {
  663. return dirname(__FILE__);
  664. }
  665. /**
  666. * Generate a new captcha ID or retrieve the current ID
  667. *
  668. * @param $new bool If true, generates a new challenge and returns and ID
  669. * @param $options array Additional options to be passed to Securimage.
  670. * Must include database options if not set directly in securimage.php
  671. *
  672. * @return null|string Returns null if no captcha id set and new was false, or string captcha ID
  673. */
  674. public static function getCaptchaId($new = true, array $options = array())
  675. {
  676. if (is_null($new) || (bool) $new == true)
  677. {
  678. $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true));
  679. $opts = array('no_session' => true, 'use_database' => true);
  680. if (sizeof($options) > 0)
  681. $opts = array_merge($options, $opts);
  682. $si = new self($opts);
  683. Securimage::$_captchaId = $id;
  684. $si->createCode();
  685. return $id;
  686. }
  687. else
  688. {
  689. return Securimage::$_captchaId;
  690. }
  691. }
  692. /**
  693. * Validate a captcha code input against a captcha ID
  694. *
  695. * @param string $id The captcha ID to check
  696. * @param string $value The captcha value supplied by the user
  697. * @param array $options Array of options to construct Securimage with.
  698. * Options must include database options if they are not set in securimage.php
  699. *
  700. * @see Securimage::$database_driver
  701. * @return bool true if the code was valid for the given captcha ID, false if not or if database failed to open
  702. */
  703. public static function checkByCaptchaId($id, $value, array $options = array())
  704. {
  705. $opts = array('captchaId' => $id, 'no_session' => true, 'use_database' => true);
  706. if (sizeof($options) > 0)
  707. $opts = array_merge($options, $opts);
  708. $si = new self($opts);
  709. if ($si->openDatabase())
  710. {
  711. $code = $si->getCodeFromDatabase();
  712. if (is_array($code))
  713. {
  714. $si->code = $code['code'];
  715. $si->code_display = $code['code_disp'];
  716. }
  717. if ($si->check($value))
  718. {
  719. $si->clearCodeFromDatabase();
  720. return true;
  721. }
  722. else
  723. {
  724. return false;
  725. }
  726. }
  727. else
  728. {
  729. return false;
  730. }
  731. }
  732. /**
  733. * Used to serve a captcha image to the browser
  734. * @param string $background_image The path to the background image to use
  735. * <code>
  736. * $img = new Securimage();
  737. * $img->code_length = 6;
  738. * $img->num_lines = 5;
  739. * $img->noise_level = 5;
  740. *
  741. * $img->show(); // sends the image to browser
  742. * exit;
  743. * </code>
  744. */
  745. public function show($background_image = '')
  746. {
  747. set_error_handler(array(&$this, 'errorHandler'));
  748. if ($background_image != '' && is_readable($background_image))
  749. {
  750. $this->bgimg = $background_image;
  751. }
  752. $this->doImage();
  753. }
  754. /**
  755. * Check a submitted code against the stored value
  756. * @param string $code The captcha code to check
  757. * <code>
  758. * $code = $_POST['code'];
  759. * $img = new Securimage();
  760. * if ($img->check($code) == true) {
  761. * $captcha_valid = true;
  762. * } else {
  763. * $captcha_valid = false;
  764. * }
  765. * </code>
  766. */
  767. public function check($code)
  768. {
  769. $this->code_entered = $code;
  770. $this->validate();
  771. return $this->correct_code;
  772. }
  773. /**
  774. * Output a wav file of the captcha code to the browser
  775. *
  776. * <code>
  777. * $img = new Securimage();
  778. * $img->outputAudioFile(); // outputs a wav file to the browser
  779. * exit;
  780. * </code>
  781. */
  782. public function outputAudioFile()
  783. {
  784. set_error_handler(array(&$this, 'errorHandler'));
  785. require_once dirname(__FILE__) . '/WavFile.php';
  786. try
  787. {
  788. $audio = $this->getAudibleCode();
  789. }
  790. catch (Exception $ex)
  791. {
  792. if (($fp = @fopen(dirname(__FILE__) . '/si.error_log', 'a+')) !== false)
  793. {
  794. fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n");
  795. fclose($fp);
  796. }
  797. $audio = $this->audioError();
  798. }
  799. if ($this->canSendHeaders() || $this->send_headers == false)
  800. {
  801. if ($this->send_headers)
  802. {
  803. $uniq = md5(uniqid(microtime()));
  804. header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.wav\"");
  805. header('Cache-Control: no-store, no-cache, must-revalidate');
  806. header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
  807. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
  808. header('Content-type: audio/x-wav');
  809. if (extension_loaded('zlib'))
  810. {
  811. ini_set('zlib.output_compression', true); // compress output if supported by browser
  812. }
  813. else
  814. {
  815. header('Content-Length: ' . strlen($audio));
  816. }
  817. }
  818. echo $audio;
  819. }
  820. else
  821. {
  822. echo '<hr /><strong>' . 'Failed to generate audio file, content has already been ' . 'output.<br />This is most likely due to misconfiguration or ' . 'a PHP error was sent to the browser.</strong>';
  823. }
  824. restore_error_handler();
  825. if (!$this->no_exit)
  826. exit;
  827. }
  828. /**
  829. * Return the code from the session or sqlite database if used. If none exists yet, an empty string is returned
  830. *
  831. * @param $array bool True to receive an array containing the code and properties
  832. * @return array|string Array if $array = true, otherwise a string containing the code
  833. */
  834. public function getCode($array = false, $returnExisting = false)
  835. {
  836. $code = '';
  837. $time = 0;
  838. $disp = 'error';
  839. if ($returnExisting && strlen($this->code) > 0)
  840. {
  841. if ($array)
  842. {
  843. return array('code' => $this->code, 'display' => $this->code_display, 'code_display' => $this->code_display, 'time' => 0);
  844. }
  845. else
  846. {
  847. return $this->code;
  848. }
  849. }
  850. if ($this->no_session != true)
  851. {
  852. if (isset($_SESSION['securimage_code_value'][$this->namespace]) && trim($_SESSION['securimage_code_value'][$this->namespace]) != '')
  853. {
  854. if ($this->isCodeExpired($_SESSION['securimage_code_ctime'][$this->namespace]) == false)
  855. {
  856. $code = $_SESSION['securimage_code_value'][$this->namespace];
  857. $time = $_SESSION['securimage_code_ctime'][$this->namespace];
  858. $disp = $_SESSION['securimage_code_disp'] [$this->namespace];
  859. }
  860. }
  861. }
  862. if (empty($code) && $this->use_database)
  863. {
  864. // no code in session - may mean user has cookies turned off
  865. $this->openDatabase();
  866. $code = $this->getCodeFromDatabase();
  867. }
  868. else
  869. { /* no code stored in session or sqlite database, validation will fail */
  870. }
  871. if ($array == true)
  872. {
  873. return array('code' => $code, 'ctime' => $time, 'display' => $disp);
  874. }
  875. else
  876. {
  877. return $code;
  878. }
  879. }
  880. /**
  881. * The main image drawing routing, responsible for constructing the entire image and serving it
  882. */
  883. protected function doImage()
  884. {
  885. if (($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor'))
  886. {
  887. $imagecreate = 'imagecreatetruecolor';
  888. }
  889. else
  890. {
  891. $imagecreate = 'imagecreate';
  892. }
  893. $this->im = $imagecreate($this->image_width, $this->image_height);
  894. $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
  895. $this->allocateColors();
  896. imagepalettecopy($this->tmpimg, $this->im);
  897. $this->setBackground();
  898. $code = '';
  899. if ($this->getCaptchaId(false) !== null)
  900. {
  901. // a captcha Id was supplied
  902. // check to see if a display_value for the captcha image was set
  903. if (is_string($this->display_value) && strlen($this->display_value) > 0)
  904. {
  905. $this->code_display = $this->display_value;
  906. $this->code = ($this->case_sensitive)?$this->display_value:strtolower($this->display_value);
  907. $code = $this->code;
  908. }
  909. else if ($this->openDatabase())
  910. {
  911. // no display_value, check the database for existing captchaId
  912. $code = $this->getCodeFromDatabase();
  913. // got back a result from the database with a valid code for captchaId
  914. if (is_array($code))
  915. {
  916. $this->code = $code['code'];
  917. $this->code_display = $code['code_disp'];
  918. $code = $code['code'];
  919. }
  920. }
  921. }
  922. if ($code == '')
  923. {
  924. // if the code was not set using display_value or was not found in
  925. // the database, create a new code
  926. $this->createCode();
  927. }
  928. if ($this->noise_level > 0)
  929. {
  930. $this->drawNoise();
  931. }
  932. $this->drawWord();
  933. if ($this->perturbation > 0 && is_readable($this->ttf_file))
  934. {
  935. $this->distortedCopy();
  936. }
  937. if ($this->num_lines > 0)
  938. {
  939. $this->drawLines();
  940. }
  941. if (trim($this->image_signature) != '')
  942. {
  943. $this->addSignature();
  944. }
  945. $this->output();
  946. }
  947. /**
  948. * Allocate the colors to be used for the image
  949. */
  950. protected function allocateColors()
  951. {
  952. // allocate bg color first for imagecreate
  953. $this->gdbgcolor = imagecolorallocate($this->im, $this->image_bg_color->r, $this->image_bg_color->g, $this->image_bg_color->b);
  954. $alpha = intval($this->text_transparency_percentage / 100 * 127);
  955. if ($this->use_transparent_text == true)
  956. {
  957. $this->gdtextcolor = imagecolorallocatealpha($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b, $alpha);
  958. $this->gdlinecolor = imagecolorallocatealpha($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b, $alpha);
  959. $this->gdnoisecolor = imagecolorallocatealpha($this->im, $this->noise_color->r, $this->noise_color->g, $this->noise_color->b, $alpha);
  960. }
  961. else
  962. {
  963. $this->gdtextcolor = imagecolorallocate($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b);
  964. $this->gdlinecolor = imagecolorallocate($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b);
  965. $this->gdnoisecolor = imagecolorallocate($this->im, $this->noise_color->r, $this->noise_color->g, $this->noise_color->b);
  966. }
  967. $this->gdsignaturecolor = imagecolorallocate($this->im, $this->signature_color->r, $this->signature_color->g, $this->signature_color->b);
  968. }
  969. /**
  970. * The the background color, or background image to be used
  971. */
  972. protected function setBackground()
  973. {
  974. // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color
  975. imagefilledrectangle($this->im, 0, 0, $this->image_width, $this->image_height, $this->gdbgcolor);
  976. imagefilledrectangle($this->tmpimg, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $this->gdbgcolor);
  977. if ($this->bgimg == '')
  978. {
  979. if ($this->background_directory != null && is_dir($this->background_directory) && is_readable($this->background_directory))
  980. {
  981. $img = $this->getBackgroundFromDirectory();
  982. if ($img != false)
  983. {
  984. $this->bgimg = $img;
  985. }
  986. }
  987. }
  988. if ($this->bgimg == '')
  989. {
  990. return;
  991. }
  992. $dat = @getimagesize($this->bgimg);
  993. if ($dat == false)
  994. {
  995. return;
  996. }
  997. switch ($dat[2])
  998. {
  999. case 1:
  1000. $newim = @imagecreatefromgif($this->bgimg);
  1001. break;
  1002. case 2:
  1003. $newim = @imagecreatefromjpeg($this->bgimg);
  1004. break;
  1005. case 3:
  1006. $newim = @imagecreatefrompng($this->bgimg);
  1007. break;
  1008. default:
  1009. return;
  1010. }
  1011. if (!$newim)
  1012. return;
  1013. imagecopyresized($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height, imagesx($newim), imagesy($newim));
  1014. }
  1015. /**
  1016. * Scan the directory for a background image to use
  1017. */
  1018. protected function getBackgroundFromDirectory()
  1019. {
  1020. $images = array();
  1021. if (($dh = opendir($this->background_directory)) !== false)
  1022. {
  1023. while (($file = readdir($dh)) !== false)
  1024. {
  1025. if (preg_match('/(jpg|gif|png)$/i', $file))
  1026. $images[] = $file;
  1027. }
  1028. closedir($dh);
  1029. if (sizeof($images) > 0)
  1030. {
  1031. return rtrim($this->background_directory, '/') . '/' . $images[mt_rand(0, sizeof($images) - 1)];
  1032. }
  1033. }
  1034. return false;
  1035. }
  1036. /**
  1037. * Generates the code or math problem and saves the value to the session
  1038. */
  1039. public function createCode()
  1040. {
  1041. $this->code = false;
  1042. switch ($this->captcha_type)
  1043. {
  1044. case self::SI_CAPTCHA_MATHEMATIC:
  1045. {
  1046. do
  1047. {
  1048. $signs = array('+', '-', 'x');
  1049. $left = mt_rand(1, 10);
  1050. $right = mt_rand(1, 5);
  1051. $sign = $signs[mt_rand(0, 2)];
  1052. switch ($sign)
  1053. {
  1054. case 'x':
  1055. $c = $left * $right;
  1056. break;
  1057. case '-':
  1058. $c = $left - $right;
  1059. break;
  1060. default:
  1061. $c = $left + $right;
  1062. break;
  1063. }
  1064. } while ($c <= 0); // no negative #'s or 0
  1065. $this->code = $c;
  1066. $this->code_display = "$left $sign $right";
  1067. break;
  1068. }
  1069. case self::SI_CAPTCHA_WORDS:
  1070. $words = $this->readCodeFromFile(2);
  1071. $this->code = implode(' ', $words);
  1072. $this->code_display = $this->code;
  1073. break;
  1074. default:
  1075. {
  1076. if ($this->use_wordlist && is_readable($this->wordlist_file))
  1077. {
  1078. $this->code = $this->readCodeFromFile();
  1079. }
  1080. if ($this->code == false)
  1081. {
  1082. $this->code = $this->generateCode($this->code_length);
  1083. }
  1084. $this->code_display = $this->code;
  1085. $this->code = ($this->case_sensitive)?$this->code:strtolower($this->code);
  1086. } // default
  1087. }
  1088. $this->saveData();
  1089. }
  1090. /**
  1091. * Draws the captcha code on the image
  1092. */
  1093. protected function drawWord()
  1094. {
  1095. $width2 = $this->image_width * $this->iscale;
  1096. $height2 = $this->image_height * $this->iscale;
  1097. if (!is_readable($this->ttf_file))
  1098. {
  1099. imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor);
  1100. }
  1101. else
  1102. {
  1103. if ($this->perturbation > 0)
  1104. {
  1105. $font_size = $height2 * .4;
  1106. $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
  1107. $tx = $bb[4] - $bb[0];
  1108. $ty = $bb[5] - $bb[1];
  1109. $x = floor($width2 / 2 - $tx / 2 - $bb[0]);
  1110. $y = round($height2 / 2 - $ty / 2 - $bb[1]);
  1111. imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
  1112. }
  1113. else
  1114. {
  1115. $font_size = $this->image_height * .4;
  1116. $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
  1117. $tx = $bb[4] - $bb[0];
  1118. $ty = $bb[5] - $bb[1];
  1119. $x = floor($this->image_width / 2 - $tx / 2 - $bb[0]);
  1120. $y = round($this->image_height / 2 - $ty / 2 - $bb[1]);
  1121. imagettftext($this->im, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
  1122. }
  1123. }
  1124. // DEBUG
  1125. //$this->im = $this->tmpimg;
  1126. //$this->output();
  1127. }
  1128. /**
  1129. * Copies the captcha image to the final image with distortion applied
  1130. */
  1131. protected function distortedCopy()
  1132. {
  1133. $numpoles = 3; // distortion factor
  1134. // make array of poles AKA attractor points
  1135. for ($i = 0; $i < $numpoles; ++$i)
  1136. {
  1137. $px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8);
  1138. $py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
  1139. $rad[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
  1140. $tmp = ((-$this->frand()) * 0.15) - .15;
  1141. $amp[$i] = $this->perturbation * $tmp;
  1142. }
  1143. $bgCol = imagecolorat($this->tmpimg, 0, 0);
  1144. $width2 = $this->iscale * $this->image_width;
  1145. $height2 = $this->iscale * $this->image_height;
  1146. imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
  1147. // loop over $img pixels, take pixels from $tmpimg with distortion field
  1148. for ($ix = 0; $ix < $this->image_width; ++$ix)
  1149. {
  1150. for ($iy = 0; $iy < $this->image_height; ++$iy)
  1151. {
  1152. $x = $ix;
  1153. $y = $iy;
  1154. for ($i = 0; $i < $numpoles; ++$i)
  1155. {
  1156. $dx = $ix - $px[$i];
  1157. $dy = $iy - $py[$i];
  1158. if ($dx == 0 && $dy == 0)
  1159. {
  1160. continue;
  1161. }
  1162. $r = sqrt($dx * $dx + $dy * $dy);
  1163. if ($r > $rad[$i])
  1164. {
  1165. continue;
  1166. }
  1167. $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
  1168. $x += $dx * $rscale;
  1169. $y += $dy * $rscale;
  1170. }
  1171. $c = $bgCol;
  1172. $x *= $this->iscale;
  1173. $y *= $this->iscale;
  1174. if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2)
  1175. {
  1176. $c = imagecolorat($this->tmpimg, $x, $y);
  1177. }
  1178. if ($c != $bgCol)
  1179. { // only copy pixels of letters to preserve any background image
  1180. imagesetpixel($this->im, $ix, $iy, $c);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. /**
  1186. * Draws distorted lines on the image
  1187. */
  1188. protected function drawLines()
  1189. {
  1190. for ($line = 0; $line < $this->num_lines; ++$line)
  1191. {
  1192. $x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
  1193. $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
  1194. $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9);
  1195. $theta = ($this->frand() - 0.5) * M_PI * 0.7;
  1196. $w = $this->image_width;
  1197. $len = mt_rand($w * 0.4, $w * 0.7);
  1198. $lwid = mt_rand(0, 2);
  1199. $k = $this->frand() * 0.6 + 0.2;
  1200. $k = $k * $k * 0.5;
  1201. $phi = $this->frand() * 6.28;
  1202. $step = 0.5;
  1203. $dx = $step * cos($theta);
  1204. $dy = $step * sin($theta);
  1205. $n = $len / $step;
  1206. $amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
  1207. $x0 = $x - 0.5 * $len * cos($theta);
  1208. $y0 = $y - 0.5 * $len * sin($theta);
  1209. $ldx = round(-$dy * $lwid);
  1210. $ldy = round($dx * $lwid);
  1211. for ($i = 0; $i < $n; ++$i)
  1212. {
  1213. $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
  1214. $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
  1215. imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
  1216. }
  1217. }
  1218. }
  1219. /**
  1220. * Draws random noise on the image
  1221. */
  1222. protected function drawNoise()
  1223. {
  1224. if ($this->noise_level > 10)
  1225. {
  1226. $noise_level = 10;
  1227. }
  1228. else
  1229. {
  1230. $noise_level = $this->noise_level;
  1231. }
  1232. $t0 = microtime(true);
  1233. $noise_level *= 125; // an arbitrary number that works well on a 1-10 scale
  1234. $points = $this->image_width * $this->image_height * $this->iscale;
  1235. $height = $this->image_height * $this->iscale;
  1236. $width = $this->image_width * $this->iscale;
  1237. for ($i = 0; $i < $noise_level; ++$i)
  1238. {
  1239. $x = mt_rand(10, $width);
  1240. $y = mt_rand(10, $height);
  1241. $size = mt_rand(7, 10);
  1242. if ($x - $size <= 0 && $y - $size <= 0)
  1243. continue; // dont cover 0,0 since it is used by imagedistortedcopy
  1244. imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE);
  1245. }
  1246. $t1 = microtime(true);
  1247. $t = $t1 - $t0;
  1248. /*
  1249. // DEBUG
  1250. imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor);
  1251. header('content-type: image/png');
  1252. imagepng($this->tmpimg);
  1253. exit;
  1254. */
  1255. }
  1256. /**
  1257. * Print signature text on image
  1258. */
  1259. protected function addSignature()
  1260. {
  1261. $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
  1262. $textlen = $bbox[2] - $bbox[0];
  1263. $x = $this->image_width - $textlen - 5;
  1264. $y = $this->image_height - 3;
  1265. imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
  1266. }
  1267. /**
  1268. * Sends the appropriate image and cache headers and outputs image to the browser
  1269. */
  1270. protected function output()
  1271. {
  1272. if ($this->canSendHeaders() || $this->send_headers == false)
  1273. {
  1274. if ($this->send_headers)
  1275. {
  1276. // only send the content-type headers if no headers have been output
  1277. // this will ease debugging on misconfigured servers where warnings
  1278. // may have been output which break the image and prevent easily viewing
  1279. // source to see the error.
  1280. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  1281. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  1282. header("Cache-Control: no-store, no-cache, must-revalidate");
  1283. header("Cache-Control: post-check=0, pre-check=0", false);
  1284. header("Pragma: no-cache");
  1285. }
  1286. switch ($this->image_type)
  1287. {
  1288. case self::SI_IMAGE_JPEG:
  1289. if ($this->send_headers)
  1290. header("Content-Type: image/jpeg");
  1291. imagejpeg($this->im, null, 90);
  1292. break;
  1293. case self::SI_IMAGE_GIF:
  1294. if ($this->send_headers)
  1295. header("Content-Type: image/gif");
  1296. imagegif($this->im);
  1297. break;
  1298. default:
  1299. if ($this->send_headers)
  1300. header("Content-Type: image/png");
  1301. imagepng($this->im);
  1302. break;
  1303. }
  1304. }
  1305. else
  1306. {
  1307. echo '<hr /><strong>' . 'Failed to generate captcha image, content has already been ' . 'output.<br />This is most likely due to misconfiguration or ' . 'a PHP error was sent to the browser.</strong>';
  1308. }
  1309. imagedestroy($this->im);
  1310. restore_error_handler();
  1311. //if (!$this->no_exit) exit;
  1312. }
  1313. /**
  1314. * Gets the code and returns the binary audio file for the stored captcha code
  1315. *
  1316. * @return The audio representation of the captcha in Wav format
  1317. */
  1318. protected function getAudibleCode()
  1319. {
  1320. $letters = array();
  1321. $code = $this->getCode(true, true);
  1322. if ($code['code'] == '')
  1323. {
  1324. if (strlen($this->display_value) > 0)
  1325. {
  1326. $code = array('code' => $this->display_value, 'display' => $this->display_value);
  1327. }
  1328. else
  1329. {
  1330. $this->createCode();
  1331. $code = $this->getCode(true);
  1332. }
  1333. }
  1334. if (preg_match('/(\d+) (\+|-|x) (\d+)/i', $code['display'], $eq))
  1335. {
  1336. $math = true;
  1337. $left = $eq[1];
  1338. $sign = str_replace(array('+', '-', 'x'), array('plus', 'minus', 'times'), $eq[2]);
  1339. $right = $eq[3];
  1340. $letters = array($left, $sign, $right);
  1341. }
  1342. else
  1343. {
  1344. $math = false;
  1345. $length = strlen($code['display']);
  1346. for ($i = 0; $i < $length; ++$i)
  1347. {
  1348. $letter = $code['display']{$i};
  1349. $letters[] = $letter;
  1350. }
  1351. }
  1352. try
  1353. {
  1354. return $this->generateWAV($letters);
  1355. }
  1356. catch (Exception $ex)
  1357. {
  1358. throw $ex;
  1359. }
  1360. }
  1361. /**
  1362. * Gets a captcha code from a wordlist
  1363. */
  1364. protected function readCodeFromFile($numWords = 1)
  1365. {
  1366. $fp = fopen($this->wordlist_file, 'rb');
  1367. if (!$fp)
  1368. return false;
  1369. $fsize = filesize($this->wordlist_file);
  1370. if ($fsize < 128)
  1371. return false; // too small of a list to be effective
  1372. if ((int) $numWords < 1 || (int) $numWords > 5)
  1373. $numWords = 1;
  1374. $words = array();
  1375. $i = 0;
  1376. do
  1377. {
  1378. fseek($fp, mt_rand(0, $fsize - 64), SEEK_SET); // seek to a random position of file from 0 to filesize-64
  1379. $data = fread($fp, 64); // read a chunk from our random position
  1380. $data = preg_replace("/\r?\n/", "\n", $data);
  1381. $start = @strpos($data, "\n", mt_rand(0, 56)) + 1; // random start position
  1382. $end = @strpos($data, "\n", $start); // find end of word
  1383. if ($start === false)
  1384. {
  1385. // picked start position at end of file
  1386. continue;
  1387. }
  1388. else if ($end === false)
  1389. {
  1390. $end = strlen($data);
  1391. }
  1392. $word = strtolower(substr($data, $start, $end - $start)); // return a line of the file
  1393. $words[] = $word;
  1394. } while (++$i < $numWords);
  1395. fclose($fp);
  1396. if ($numWords < 2)
  1397. {
  1398. return $words[0];
  1399. }
  1400. else
  1401. {
  1402. return $words;
  1403. }
  1404. }
  1405. /**
  1406. * Generates a random captcha code from the set character set
  1407. */
  1408. protected function generateCode()
  1409. {
  1410. $code = '';
  1411. if (function_exists('mb_strlen'))
  1412. {
  1413. for ($i = 1, $cslen = mb_strlen($this->charset); $i <= $this->code_length; ++$i)
  1414. {
  1415. $code .= mb_substr($this->charset, mt_rand(0, $cslen - 1), 1, 'UTF-8');
  1416. }
  1417. }
  1418. else
  1419. {
  1420. for ($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i)
  1421. {
  1422. $code .= substr($this->charset, mt_rand(0, $cslen - 1), 1);
  1423. }
  1424. }
  1425. return $code;
  1426. }
  1427. /**
  1428. * Checks the entered code against the value stored in the session or sqlite database, handles case sensitivity
  1429. * Also clears the stored codes if the code was entered correctly to prevent re-use
  1430. */
  1431. protected function validate()
  1432. {
  1433. if (!is_string($this->code) || strlen($this->code) == 0)
  1434. {
  1435. $code = $this->getCode();
  1436. // returns stored code, or an empty string if no stored code was found
  1437. // checks the session and database if enabled
  1438. }
  1439. else
  1440. {
  1441. $code = $this->code;
  1442. }
  1443. if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code))
  1444. {
  1445. // case sensitive was set from securimage_show.php but not in class
  1446. // the code saved in the session has capitals so set case sensitive to true
  1447. $this->case_sensitive = true;
  1448. }
  1449. $code_entered = trim((($this->case_sensitive)?$this->code_entered:strtolower($this->code_entered)));
  1450. $this->correct_code = false;
  1451. if ($code != '')
  1452. {
  1453. if (strpos($code, ' ') !== false)
  1454. {
  1455. // for multi word captchas, remove more than once space from input
  1456. $code_entered = preg_replace('/\s+/', ' ', $code_entered);
  1457. $code_entered = strtolower($code_entered);
  1458. }
  1459. if ($code == $code_entered)
  1460. {
  1461. $this->correct_code = true;
  1462. if ($this->no_session != true)
  1463. {
  1464. $_SESSION['securimage_code_value'][$this->namespace] = '';
  1465. $_SESSION['securimage_code_ctime'][$this->namespace] = '';
  1466. }
  1467. $this->clearCodeFromDatabase();
  1468. }
  1469. }
  1470. }
  1471. /**
  1472. * Save data to session namespace and database if used
  1473. */
  1474. protected function saveData()
  1475. {
  1476. if ($this->no_session != true)
  1477. {
  1478. if (isset($_SESSION['securimage_code_value']) && is_scalar($_SESSION['securimage_code_value']))
  1479. {
  1480. // fix for migration from v2 - v3
  1481. unset($_SESSION['securimage_code_value']);
  1482. unset($_SESSION['securimage_code_ctime']);
  1483. }
  1484. $_SESSION['securimage_code_disp'] [$this->namespace] = $this->code_display;
  1485. $_SESSION['securimage_code_value'][$this->namespace] = $this->code;
  1486. $_SESSION['securimage_code_ctime'][$this->namespace] = time();
  1487. }
  1488. if ($this->use_database)
  1489. {
  1490. $this->saveCodeToDatabase();
  1491. }
  1492. }
  1493. /**
  1494. * Saves the code to the sqlite database
  1495. */
  1496. protected function saveCodeToDatabase()
  1497. {
  1498. $success = false;
  1499. $this->openDatabase();
  1500. if ($this->use_database && $this->pdo_conn)
  1501. {
  1502. $id = $this->getCaptchaId(false);
  1503. $ip = $_SERVER['REMOTE_ADDR'];
  1504. if (empty($id))
  1505. {
  1506. $id = $ip;
  1507. }
  1508. $time = time();
  1509. $code = $this->code;
  1510. $code_disp = $this->code_display;
  1511. // This is somewhat expensive in PDO Sqlite3 (when there is something to delete)
  1512. $this->clearCodeFromDatabase();
  1513. $query = "INSERT INTO {$this->database_table} (" . "id, code, code_display, namespace, created) " . "VALUES(?, ?, ?, ?, ?)";
  1514. $stmt = $this->pdo_conn->prepare($query);
  1515. $success = $stmt->execute(array($id, $code, $code_disp, $this->namespace, $time));
  1516. if (!$success)
  1517. {
  1518. $err = $stmt->errorInfo();
  1519. trigger_error("Failed to insert code into database. {$err[1]}: {$err[2]}", E_USER_WARNING);
  1520. }
  1521. }
  1522. return $success !== false;
  1523. }
  1524. /**
  1525. * Open sqlite database
  1526. */
  1527. protected function openDatabase()
  1528. {
  1529. $this->pdo_conn = false;
  1530. if ($this->use_database)
  1531. {
  1532. $pdo_extension = 'PDO_' . strtoupper($this->database_driver);
  1533. if (!extension_loaded($pdo_extension))
  1534. {
  1535. trigger_error("Database support is turned on in Securimage, but the chosen extension $pdo_extension is not loaded in PHP.", E_USER_WARNING);
  1536. return false;
  1537. }
  1538. }
  1539. if ($this->database_driver == self::SI_DRIVER_SQLITE3)
  1540. {
  1541. if (!file_exists($this->database_file))
  1542. {
  1543. $fp = fopen($this->database_file, 'w+');
  1544. if (!$fp)
  1545. {
  1546. $err = error_get_last();
  1547. trigger_error("Securimage failed to create SQLite3 database file '{$this->database_file}'. Reason: {$err['message']}", E_USER_WARNING);
  1548. return false;
  1549. }
  1550. fclose($fp);
  1551. chmod($this->database_file, 0666);
  1552. }
  1553. else if (!is_writeable($this->database_file))
  1554. {
  1555. 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);
  1556. return false;
  1557. }
  1558. }
  1559. $dsn = $this->getDsn();
  1560. try
  1561. {
  1562. $options = array();
  1563. $this->pdo_conn = new PDO($dsn, $this->database_user, $this->database_pass, $options);
  1564. }
  1565. catch (PDOException $pdoex)
  1566. {
  1567. trigger_error("Database connection failed: " . $pdoex->getMessage(), E_USER_WARNING);
  1568. return false;
  1569. }
  1570. try
  1571. {
  1572. if (!$this->checkTablesExist())
  1573. {
  1574. // create tables...
  1575. $this->createDatabaseTables();
  1576. }
  1577. }
  1578. catch (Exception $ex)
  1579. {
  1580. trigger_error($ex->getMessage(), E_USER_WARNING);
  1581. $this->pdo_conn = null;
  1582. return false;
  1583. }
  1584. if (mt_rand(0, 100) / 100.0 == 1.0)
  1585. {
  1586. $this->purgeOldCodesFromDatabase();
  1587. }
  1588. return $this->pdo_conn;
  1589. }
  1590. protected function getDsn()
  1591. {
  1592. $dsn = sprintf('%s:', $this->database_driver);
  1593. switch ($this->database_driver)
  1594. {
  1595. case self::SI_DRIVER_SQLITE3:
  1596. $dsn .= $this->database_file;
  1597. break;
  1598. case self::SI_DRIVER_MYSQL:
  1599. case self::SI_DRIVER_PGSQL:
  1600. $dsn .= sprintf('host=%s;dbname=%s', $this->database_host, $this->database_name);
  1601. break;
  1602. }
  1603. return $dsn;
  1604. }
  1605. protected function checkTablesExist()
  1606. {
  1607. $table = $this->pdo_conn->quote($this->database_table);
  1608. switch ($this->database_driver)
  1609. {
  1610. case self::SI_DRIVER_SQLITE3:
  1611. // query row count for sqlite, PRAGMA queries seem to return no
  1612. // rowCount using PDO even if there are rows returned
  1613. $query = "SELECT COUNT(id) FROM $table";
  1614. break;
  1615. case self::SI_DRIVER_MYSQL:
  1616. $query = "SHOW TABLES LIKE $table";
  1617. break;
  1618. ca

Large files files are truncated, but you can click here to view the full file