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

/src/apps/passport/libraries/securimage/securimage.php

https://github.com/42Team-itslove/passport
PHP | 1683 lines | 827 code | 221 blank | 635 comment | 202 complexity | 68a9f2af346e32c9f2e392d8de3199cb MD5 | raw file

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

  1. <?php
  2. /**
  3. * Securimage CAPTCHA Class.
  4. *
  5. * A class for creating and validating secure CAPTCHA images and audio.
  6. *
  7. * The class contains many options regarding appearance, security, storage of
  8. * captcha data and image/audio generation options.
  9. *
  10. * @version 3.5.2
  11. * @package Securimage
  12. * @subpackage classes
  13. * @author Drew Phillips <drew@drew-phillips.com>
  14. *
  15. */
  16. class Securimage
  17. {
  18. // All of the public variables below are securimage options
  19. // They can be passed as an array to the Securimage constructor, set below,
  20. // or set from securimage_show.php and securimage_play.php
  21. /**
  22. * Constant for rendering captcha as a JPEG image
  23. * @var int
  24. */
  25. const SI_IMAGE_JPEG = 1;
  26. /**
  27. * Constant for rendering captcha as a PNG image (default)
  28. * @var int
  29. */
  30. const SI_IMAGE_PNG = 2;
  31. /**
  32. * Constant for rendering captcha as a GIF image
  33. * @var int
  34. */
  35. const SI_IMAGE_GIF = 3;
  36. /**
  37. * Constant for generating a normal alphanumeric captcha based on the
  38. * character set
  39. *
  40. * @see Securimage::$charset charset property
  41. * @var int
  42. */
  43. const SI_CAPTCHA_STRING = 0;
  44. /**
  45. * Constant for generating a captcha consisting of a simple math problem
  46. *
  47. * @var int
  48. */
  49. const SI_CAPTCHA_MATHEMATIC = 1;
  50. /**
  51. * Constant for generating a word based captcha using 2 words from a list
  52. *
  53. * @var int
  54. */
  55. const SI_CAPTCHA_WORDS = 2;
  56. /*%*********************************************************************%*/
  57. // Properties
  58. /**
  59. * The width of the captcha image
  60. * @var int
  61. */
  62. public $image_width = 215;
  63. /**
  64. * The height of the captcha image
  65. * @var int
  66. */
  67. public $image_height = 80;
  68. /**
  69. * Font size is calculated by image height and this ratio. Leave blank for
  70. * default ratio of 0.4.
  71. *
  72. * Valid range: 0.1 - 0.99.
  73. *
  74. * Depending on image_width, values > 0.6 are probably too large and
  75. * values < 0.3 are too small.
  76. *
  77. * @var float
  78. */
  79. public $font_ratio;
  80. /**
  81. * The type of the image, default = png
  82. *
  83. * @see Securimage::SI_IMAGE_PNG SI_IMAGE_PNG
  84. * @see Securimage::SI_IMAGE_JPEG SI_IMAGE_JPEG
  85. * @see Securimage::SI_IMAGE_GIF SI_IMAGE_GIF
  86. * @var int
  87. */
  88. public $image_type = self::SI_IMAGE_PNG;
  89. /**
  90. * The background color of the captcha
  91. * @var Securimage_Color
  92. */
  93. public $image_bg_color = '#ffffff';
  94. /**
  95. * The color of the captcha text
  96. * @var Securimage_Color
  97. */
  98. public $text_color = '#707070';
  99. /**
  100. * The color of the lines over the captcha
  101. * @var Securimage_Color
  102. */
  103. public $line_color = '#707070';
  104. /**
  105. * The color of the noise that is drawn
  106. * @var Securimage_Color
  107. */
  108. public $noise_color = '#707070';
  109. /**
  110. * How transparent to make the text.
  111. *
  112. * 0 = completely opaque, 100 = invisible
  113. *
  114. * @var int
  115. */
  116. public $text_transparency_percentage = 20;
  117. /**
  118. * Whether or not to draw the text transparently.
  119. *
  120. * true = use transparency, false = no transparency
  121. *
  122. * @var bool
  123. */
  124. public $use_transparent_text = true;
  125. /**
  126. * The length of the captcha code
  127. * @var int
  128. */
  129. public $code_length = 6;
  130. /**
  131. * Whether the captcha should be case sensitive or not.
  132. *
  133. * Not recommended, use only for maximum protection.
  134. *
  135. * @var bool
  136. */
  137. public $case_sensitive = false;
  138. /**
  139. * The character set to use for generating the captcha code
  140. * @var string
  141. */
  142. public $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
  143. /**
  144. * How long in seconds a captcha remains valid, after this time it will be
  145. * considered incorrect.
  146. *
  147. * @var int
  148. */
  149. public $expiry_time = 900;
  150. /**
  151. * The session name securimage should use.
  152. *
  153. * Only use if your application uses a custom session name (e.g. Joomla).
  154. * It is recommended to set this value here so it is used by all securimage
  155. * scripts (i.e. securimage_show.php)
  156. *
  157. * @var string
  158. */
  159. public $session_name = null;
  160. /**
  161. * true to use the wordlist file, false to generate random captcha codes
  162. * @var bool
  163. */
  164. public $use_wordlist = false;
  165. /**
  166. * The level of distortion.
  167. *
  168. * 0.75 = normal, 1.0 = very high distortion
  169. *
  170. * @var double
  171. */
  172. public $perturbation = 0.85;
  173. /**
  174. * How many lines to draw over the captcha code to increase security
  175. * @var int
  176. */
  177. public $num_lines = 5;
  178. /**
  179. * The level of noise (random dots) to place on the image, 0-10
  180. * @var int
  181. */
  182. public $noise_level = 2;
  183. /**
  184. * The signature text to draw on the bottom corner of the image
  185. * @var string
  186. */
  187. public $image_signature = '';
  188. /**
  189. * The color of the signature text
  190. * @var Securimage_Color
  191. */
  192. public $signature_color = '#707070';
  193. /**
  194. * The path to the ttf font file to use for the signature text.
  195. * Defaults to $ttf_file (AHGBold.ttf)
  196. *
  197. * @see Securimage::$ttf_file
  198. * @var string
  199. */
  200. public $signature_font;
  201. /**
  202. * The type of captcha to create.
  203. *
  204. * Either alphanumeric based on *charset*, a simple math problem, or an
  205. * image consisting of 2 words from the word list.
  206. *
  207. * @see Securimage::SI_CAPTCHA_STRING SI_CAPTCHA_STRING
  208. * @see Securimage::SI_CAPTCHA_MATHEMATIC SI_CAPTCHA_MATHEMATIC
  209. * @see Securimage::SI_CAPTCHA_WORDS SI_CAPTCHA_WORDS
  210. * @see Securimage::$charset charset property
  211. * @see Securimage::$wordlist_file wordlist_file property
  212. * @var int
  213. */
  214. public $captcha_type = self::SI_CAPTCHA_STRING; // or self::SI_CAPTCHA_MATHEMATIC, or self::SI_CAPTCHA_WORDS;
  215. /**
  216. * The captcha namespace used for having multiple captchas on a page or
  217. * to separate captchas from differen forms on your site.
  218. * Example:
  219. *
  220. * <?php
  221. * // use <img src="securimage_show.php?namespace=contact_form">
  222. * // or manually in securimage_show.php
  223. * $img->setNamespace('contact_form');
  224. *
  225. * // in form validator
  226. * $img->setNamespace('contact_form');
  227. * if ($img->check($code) == true) {
  228. * echo "Valid!";
  229. * }
  230. *
  231. * @var string
  232. */
  233. public $namespace;
  234. /**
  235. * The TTF font file to use to draw the captcha code.
  236. *
  237. * Leave blank for default font AHGBold.ttf
  238. *
  239. * @var string
  240. */
  241. public $ttf_file;
  242. /**
  243. * The path to the wordlist file to use.
  244. *
  245. * Leave blank for default words/words.txt
  246. *
  247. * @var string
  248. */
  249. public $wordlist_file;
  250. /**
  251. * The directory to scan for background images, if set a random background
  252. * will be chosen from this folder
  253. *
  254. * @var string
  255. */
  256. public $background_directory;
  257. /**
  258. * Captcha ID if using static captcha
  259. * @var string Unique captcha id
  260. */
  261. protected static $_captchaId = null;
  262. /**
  263. * The GD image resource of the captcha image
  264. *
  265. * @var resource
  266. */
  267. protected $im;
  268. /**
  269. * A temporary GD image resource of the captcha image for distortion
  270. *
  271. * @var resource
  272. */
  273. protected $tmpimg;
  274. /**
  275. * The background image GD resource
  276. * @var resource
  277. */
  278. protected $bgimg;
  279. /**
  280. * Scale factor for magnification of distorted captcha image
  281. *
  282. * @var int
  283. */
  284. protected $iscale = 5;
  285. /**
  286. * Absolute path to securimage directory.
  287. *
  288. * This is calculated at runtime
  289. *
  290. * @var string
  291. */
  292. public $securimage_path = null;
  293. /**
  294. * The captcha challenge value.
  295. *
  296. * Either the case-sensitive/insensitive word captcha, or the solution to
  297. * the math captcha.
  298. *
  299. * @var string Captcha challenge value
  300. */
  301. protected $code;
  302. /**
  303. * The display value of the captcha to draw on the image
  304. *
  305. * Either the word captcha or the math equation to present to the user
  306. *
  307. * @var string Captcha display value to draw on the image
  308. */
  309. protected $code_display;
  310. /**
  311. * Alternate text to draw as the captcha image text
  312. *
  313. * A value that can be passed to the constructor that can be used to
  314. * generate a captcha image with a given value.
  315. *
  316. * This value does not get stored in the session or database and is only
  317. * used when calling Securimage::show().
  318. *
  319. * If a display_value was passed to the constructor and the captcha image
  320. * is generated, the display_value will be used as the string to draw on
  321. * the captcha image.
  322. *
  323. * Used only if captcha codes are generated and managed by a 3rd party
  324. * app/library
  325. *
  326. * @var string Captcha code value to display on the image
  327. */
  328. public $display_value;
  329. /**
  330. * Captcha code supplied by user [set from Securimage::check()]
  331. *
  332. * @var string
  333. */
  334. protected $captcha_code;
  335. /**
  336. * Time (in seconds) that the captcha was solved in (correctly or incorrectly).
  337. *
  338. * This is from the time of code creation, to when validation was attempted.
  339. *
  340. * @var int
  341. */
  342. protected $_timeToSolve = 0;
  343. /**
  344. * Flag that can be specified telling securimage not to call exit after
  345. * generating a captcha image or audio file
  346. *
  347. * @var bool If true, script will not terminate; if false script will terminate (default)
  348. */
  349. protected $no_exit;
  350. /**
  351. * Flag indicating whether or not HTTP headers will be sent when outputting
  352. * captcha image/audio
  353. *
  354. * @var bool If true (default) headers will be sent, if false, no headers are sent
  355. */
  356. protected $send_headers;
  357. /**
  358. * The GD color resource for the background color
  359. *
  360. * @var resource
  361. */
  362. protected $gdbgcolor;
  363. /**
  364. * The GD color resource for the text color
  365. *
  366. * @var resource
  367. */
  368. protected $gdtextcolor;
  369. /**
  370. * The GD color resource for the line color
  371. *
  372. * @var resource
  373. */
  374. protected $gdlinecolor;
  375. /**
  376. * The GD color resource for the signature text color
  377. *
  378. * @var resource
  379. */
  380. protected $gdsignaturecolor;
  381. /**
  382. * The Placon Session
  383. * @var
  384. */
  385. protected $session;
  386. /**
  387. * Create a new securimage object, pass options to set in the constructor.
  388. *
  389. * The object can then be used to display a captcha, play an audible captcha, or validate a submission.
  390. *
  391. * @param array $options Options to initialize the class. May be any class property.
  392. *
  393. * $options = array(
  394. * 'text_color' => new Securimage_Color('#013020'),
  395. * 'code_length' => 5,
  396. * 'num_lines' => 5,
  397. * 'noise_level' => 3,
  398. * 'font_file' => Securimage::getPath() . '/custom.ttf'
  399. * );
  400. *
  401. * $img = new Securimage($options);
  402. *
  403. */
  404. public function __construct($options = array())
  405. {
  406. $this->securimage_path = dirname(__FILE__);
  407. if (is_array($options) && sizeof($options) > 0) {
  408. foreach($options as $prop => $val) {
  409. if ($prop == 'captchaId') {
  410. Securimage::$_captchaId = $val;
  411. $this->use_database = true;
  412. } else if ($prop == 'use_sqlite_db') {
  413. trigger_error("The use_sqlite_db option is deprecated, use 'use_database' instead", E_USER_NOTICE);
  414. } else {
  415. $this->$prop = $val;
  416. }
  417. }
  418. }
  419. $this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
  420. $this->text_color = $this->initColor($this->text_color, '#616161');
  421. $this->line_color = $this->initColor($this->line_color, '#616161');
  422. $this->noise_color = $this->initColor($this->noise_color, '#616161');
  423. $this->signature_color = $this->initColor($this->signature_color, '#616161');
  424. if (is_null($this->ttf_file)) {
  425. $this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
  426. }
  427. $this->signature_font = $this->ttf_file;
  428. if (is_null($this->wordlist_file)) {
  429. $this->wordlist_file = $this->securimage_path . '/words/words.txt';
  430. }
  431. if (is_null($this->code_length) || (int)$this->code_length < 1) {
  432. $this->code_length = 6;
  433. }
  434. if (is_null($this->perturbation) || !is_numeric($this->perturbation)) {
  435. $this->perturbation = 0.75;
  436. }
  437. if (is_null($this->namespace) || !is_string($this->namespace)) {
  438. $this->namespace = 'default';
  439. }
  440. if (is_null($this->no_exit)) {
  441. $this->no_exit = false;
  442. }
  443. if (is_null($this->send_headers)) {
  444. $this->send_headers = true;
  445. }
  446. }
  447. /**
  448. * Return the absolute path to the Securimage directory.
  449. *
  450. * @return string The path to the securimage base directory
  451. */
  452. public static function getPath()
  453. {
  454. return dirname(__FILE__);
  455. }
  456. /**
  457. * Generate a new captcha ID or retrieve the current ID (if exists).
  458. *
  459. * @param bool $new If true, generates a new challenge and returns and ID. If false, the existing captcha ID is returned, or null if none exists.
  460. * @param array $options Additional options to be passed to Securimage.
  461. * $options must include database settings if they are not set directly in securimage.php
  462. *
  463. * @return null|string Returns null if no captcha id set and new was false, or the captcha ID
  464. */
  465. public static function getCaptchaId($new = true, array $options = array())
  466. {
  467. if (is_null($new) || (bool)$new == true) {
  468. $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true));
  469. $opts = array('no_session' => true,
  470. 'use_database' => true);
  471. if (sizeof($options) > 0) $opts = array_merge($options, $opts);
  472. $si = new self($opts);
  473. Securimage::$_captchaId = $id;
  474. $si->createCode();
  475. return $id;
  476. } else {
  477. return Securimage::$_captchaId;
  478. }
  479. }
  480. /**
  481. * Validate a captcha code input against a captcha ID
  482. *
  483. * @param string $id The captcha ID to check
  484. * @param string $value The captcha value supplied by the user
  485. * @param array $options Array of options to construct Securimage with.
  486. * Options must include database options if they are not set in securimage.php
  487. *
  488. * @see Securimage::$database_driver
  489. * @return bool true if the code was valid for the given captcha ID, false if not or if database failed to open
  490. */
  491. public static function checkByCaptchaId($id, $value, array $options = array())
  492. {
  493. $opts = array('captchaId' => $id,
  494. 'no_session' => true,
  495. 'use_database' => true);
  496. if (sizeof($options) > 0) $opts = array_merge($options, $opts);
  497. $si = new self($opts);
  498. }
  499. /**
  500. * Generates a new challenge and serves a captcha image.
  501. *
  502. * Appropriate headers will be sent to the browser unless the *send_headers* option is false.
  503. *
  504. * @param string $background_image The absolute or relative path to the background image to use as the background of the captcha image.
  505. *
  506. * $img = new Securimage();
  507. * $img->code_length = 6;
  508. * $img->num_lines = 5;
  509. * $img->noise_level = 5;
  510. *
  511. * $img->show(); // sends the image and appropriate headers to browser
  512. * exit;
  513. */
  514. public function show($background_image = '')
  515. {
  516. set_error_handler(array(&$this, 'errorHandler'));
  517. if($background_image != '' && is_readable($background_image)) {
  518. $this->bgimg = $background_image;
  519. }
  520. $this->doImage();
  521. }
  522. /**
  523. * Checks a given code against the correct value from the session and/or database.
  524. *
  525. * @param string $code The captcha code to check
  526. *
  527. * $code = $_POST['code'];
  528. * $img = new Securimage();
  529. * if ($img->check($code) == true) {
  530. * $captcha_valid = true;
  531. * } else {
  532. * $captcha_valid = false;
  533. * }
  534. *
  535. * @return bool true if the given code was correct, false if not.
  536. */
  537. public function check($code)
  538. {
  539. $this->code_entered = $code;
  540. $this->validate();
  541. return $this->correct_code;
  542. }
  543. /**
  544. * Get the time in seconds that it took to solve the captcha.
  545. *
  546. * @return int The time in seconds from when the code was created, to when it was solved
  547. */
  548. public function getTimeToSolve()
  549. {
  550. return $this->_timeToSolve;
  551. }
  552. /**
  553. * Set the namespace for the captcha being stored in the session or database.
  554. *
  555. * Namespaces are useful when multiple captchas need to be displayed on a single page.
  556. *
  557. * @param string $namespace Namespace value, String consisting of characters "a-zA-Z0-9_-"
  558. */
  559. public function setNamespace($namespace)
  560. {
  561. $namespace = preg_replace('/[^a-z0-9-_]/i', '', $namespace);
  562. $namespace = substr($namespace, 0, 64);
  563. if (!empty($namespace)) {
  564. $this->namespace = $namespace;
  565. } else {
  566. $this->namespace = 'default';
  567. }
  568. }
  569. /**
  570. * Return the code from the session or database (if configured). If none exists or was found, an empty string is returned.
  571. *
  572. * @param bool $array true to receive an array containing the code and properties, false to receive just the code.
  573. * @param bool $returnExisting If true, and the class property *code* is set, it will be returned instead of getting the code from the session or database.
  574. * @return array|string Return is an array if $array = true, otherwise a string containing the code
  575. */
  576. public function getCode($array = false, $returnExisting = false)
  577. {
  578. $code = array();
  579. $time = 0;
  580. $disp = 'error';
  581. if ($returnExisting && strlen($this->code) > 0) {
  582. if ($array) {
  583. return array(
  584. 'code' => $this->code,
  585. 'display' => $this->code_display,
  586. 'code_display' => $this->code_display,
  587. 'time' => 0);
  588. } else {
  589. return $this->code;
  590. }
  591. }
  592. if ($this->session->has('securimage') && isset($this->session->securimage[$this->namespace]) &&
  593. trim($this->session->securimage[$this->namespace]['code_value']) != '') {
  594. if ($this->isCodeExpired(
  595. $this->session->securimage[$this->namespace]['code_ctime'] == false)) {
  596. $code['code'] = $this->session->securimage[$this->namespace]['code_value'];
  597. $code['time'] = $this->session->securimage[$this->namespace]['code_ctime'];
  598. $code['display'] = $this->session->securimage[$this->namespace]['code_disp'];
  599. }
  600. }
  601. if ($array == true) {
  602. return $code;
  603. } else {
  604. return isset($code['code']) ? $code['code'] : false;
  605. }
  606. }
  607. /**
  608. * The main image drawing routing, responsible for constructing the entire image and serving it
  609. */
  610. protected function doImage()
  611. {
  612. if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) {
  613. $imagecreate = 'imagecreatetruecolor';
  614. } else {
  615. $imagecreate = 'imagecreate';
  616. }
  617. $this->im = $imagecreate($this->image_width, $this->image_height);
  618. $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
  619. $this->allocateColors();
  620. imagepalettecopy($this->tmpimg, $this->im);
  621. $this->setBackground();
  622. $code = '';
  623. if ($this->getCaptchaId(false) !== null) {
  624. // a captcha Id was supplied
  625. // check to see if a display_value for the captcha image was set
  626. if (is_string($this->display_value) && strlen($this->display_value) > 0) {
  627. $this->code_display = $this->display_value;
  628. $this->code = ($this->case_sensitive) ?
  629. $this->display_value :
  630. strtolower($this->display_value);
  631. $code = $this->code;
  632. }
  633. }
  634. if ($code == '') {
  635. // if the code was not set using display_value or was not found in
  636. // the database, create a new code
  637. $this->createCode();
  638. }
  639. if ($this->noise_level > 0) {
  640. $this->drawNoise();
  641. }
  642. $this->drawWord();
  643. if ($this->perturbation > 0 && is_readable($this->ttf_file)) {
  644. $this->distortedCopy();
  645. }
  646. if ($this->num_lines > 0) {
  647. $this->drawLines();
  648. }
  649. if (trim($this->image_signature) != '') {
  650. $this->addSignature();
  651. }
  652. $this->output();
  653. }
  654. /**
  655. * Allocate the colors to be used for the image
  656. */
  657. protected function allocateColors()
  658. {
  659. // allocate bg color first for imagecreate
  660. $this->gdbgcolor = imagecolorallocate($this->im,
  661. $this->image_bg_color->r,
  662. $this->image_bg_color->g,
  663. $this->image_bg_color->b);
  664. $alpha = intval($this->text_transparency_percentage / 100 * 127);
  665. if ($this->use_transparent_text == true) {
  666. $this->gdtextcolor = imagecolorallocatealpha($this->im,
  667. $this->text_color->r,
  668. $this->text_color->g,
  669. $this->text_color->b,
  670. $alpha);
  671. $this->gdlinecolor = imagecolorallocatealpha($this->im,
  672. $this->line_color->r,
  673. $this->line_color->g,
  674. $this->line_color->b,
  675. $alpha);
  676. $this->gdnoisecolor = imagecolorallocatealpha($this->im,
  677. $this->noise_color->r,
  678. $this->noise_color->g,
  679. $this->noise_color->b,
  680. $alpha);
  681. } else {
  682. $this->gdtextcolor = imagecolorallocate($this->im,
  683. $this->text_color->r,
  684. $this->text_color->g,
  685. $this->text_color->b);
  686. $this->gdlinecolor = imagecolorallocate($this->im,
  687. $this->line_color->r,
  688. $this->line_color->g,
  689. $this->line_color->b);
  690. $this->gdnoisecolor = imagecolorallocate($this->im,
  691. $this->noise_color->r,
  692. $this->noise_color->g,
  693. $this->noise_color->b);
  694. }
  695. $this->gdsignaturecolor = imagecolorallocate($this->im,
  696. $this->signature_color->r,
  697. $this->signature_color->g,
  698. $this->signature_color->b);
  699. }
  700. /**
  701. * The the background color, or background image to be used
  702. */
  703. protected function setBackground()
  704. {
  705. // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color
  706. imagefilledrectangle($this->im, 0, 0,
  707. $this->image_width, $this->image_height,
  708. $this->gdbgcolor);
  709. imagefilledrectangle($this->tmpimg, 0, 0,
  710. $this->image_width * $this->iscale, $this->image_height * $this->iscale,
  711. $this->gdbgcolor);
  712. if ($this->bgimg == '') {
  713. if ($this->background_directory != null &&
  714. is_dir($this->background_directory) &&
  715. is_readable($this->background_directory))
  716. {
  717. $img = $this->getBackgroundFromDirectory();
  718. if ($img != false) {
  719. $this->bgimg = $img;
  720. }
  721. }
  722. }
  723. if ($this->bgimg == '') {
  724. return;
  725. }
  726. $dat = @getimagesize($this->bgimg);
  727. if($dat == false) {
  728. return;
  729. }
  730. switch($dat[2]) {
  731. case 1: $newim = @imagecreatefromgif($this->bgimg); break;
  732. case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
  733. case 3: $newim = @imagecreatefrompng($this->bgimg); break;
  734. default: return;
  735. }
  736. if(!$newim) return;
  737. imagecopyresized($this->im, $newim, 0, 0, 0, 0,
  738. $this->image_width, $this->image_height,
  739. imagesx($newim), imagesy($newim));
  740. }
  741. /**
  742. * Scan the directory for a background image to use
  743. */
  744. protected function getBackgroundFromDirectory()
  745. {
  746. $images = array();
  747. if ( ($dh = opendir($this->background_directory)) !== false) {
  748. while (($file = readdir($dh)) !== false) {
  749. if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
  750. }
  751. closedir($dh);
  752. if (sizeof($images) > 0) {
  753. return rtrim($this->background_directory, '/') . '/' . $images[mt_rand(0, sizeof($images)-1)];
  754. }
  755. }
  756. return false;
  757. }
  758. /**
  759. * This method generates a new captcha code.
  760. *
  761. * Generates a random captcha code based on *charset*, math problem, or captcha from the wordlist and saves the value to the session and/or database.
  762. */
  763. public function createCode()
  764. {
  765. $this->code = false;
  766. switch($this->captcha_type) {
  767. case self::SI_CAPTCHA_MATHEMATIC:
  768. {
  769. do {
  770. $signs = array('+', '-', 'x');
  771. $left = mt_rand(1, 10);
  772. $right = mt_rand(1, 5);
  773. $sign = $signs[mt_rand(0, 2)];
  774. switch($sign) {
  775. case 'x': $c = $left * $right; break;
  776. case '-': $c = $left - $right; break;
  777. default: $c = $left + $right; break;
  778. }
  779. } while ($c <= 0); // no negative #'s or 0
  780. $this->code = $c;
  781. $this->code_display = "$left $sign $right";
  782. break;
  783. }
  784. case self::SI_CAPTCHA_WORDS:
  785. $words = $this->readCodeFromFile(2);
  786. $this->code = implode(' ', $words);
  787. $this->code_display = $this->code;
  788. break;
  789. default:
  790. {
  791. if ($this->use_wordlist && is_readable($this->wordlist_file)) {
  792. $this->code = $this->readCodeFromFile();
  793. }
  794. if ($this->code == false) {
  795. $this->code = $this->generateCode($this->code_length);
  796. }
  797. $this->code_display = $this->code;
  798. $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code);
  799. } // default
  800. }
  801. $this->saveData();
  802. }
  803. /**
  804. * Draws the captcha code on the image
  805. */
  806. protected function drawWord()
  807. {
  808. $width2 = $this->image_width * $this->iscale;
  809. $height2 = $this->image_height * $this->iscale;
  810. $ratio = ($this->font_ratio) ? $this->font_ratio : 0.4;
  811. if ((float)$ratio < 0.1 || (float)$ratio >= 1) {
  812. $ratio = 0.4;
  813. }
  814. if (!is_readable($this->ttf_file)) {
  815. imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor);
  816. } else {
  817. if ($this->perturbation > 0) {
  818. $font_size = $height2 * $ratio;
  819. $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
  820. $tx = $bb[4] - $bb[0];
  821. $ty = $bb[5] - $bb[1];
  822. $x = floor($width2 / 2 - $tx / 2 - $bb[0]);
  823. $y = round($height2 / 2 - $ty / 2 - $bb[1]);
  824. imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
  825. } else {
  826. $font_size = $this->image_height * $ratio;
  827. $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
  828. $tx = $bb[4] - $bb[0];
  829. $ty = $bb[5] - $bb[1];
  830. $x = floor($this->image_width / 2 - $tx / 2 - $bb[0]);
  831. $y = round($this->image_height / 2 - $ty / 2 - $bb[1]);
  832. imagettftext($this->im, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
  833. }
  834. }
  835. // DEBUG
  836. //$this->im = $this->tmpimg;
  837. //$this->output();
  838. }
  839. /**
  840. * Copies the captcha image to the final image with distortion applied
  841. */
  842. protected function distortedCopy()
  843. {
  844. $numpoles = 3; // distortion factor
  845. // make array of poles AKA attractor points
  846. for ($i = 0; $i < $numpoles; ++ $i) {
  847. $px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8);
  848. $py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
  849. $rad[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
  850. $tmp = ((- $this->frand()) * 0.15) - .15;
  851. $amp[$i] = $this->perturbation * $tmp;
  852. }
  853. $bgCol = imagecolorat($this->tmpimg, 0, 0);
  854. $width2 = $this->iscale * $this->image_width;
  855. $height2 = $this->iscale * $this->image_height;
  856. imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
  857. // loop over $img pixels, take pixels from $tmpimg with distortion field
  858. for ($ix = 0; $ix < $this->image_width; ++ $ix) {
  859. for ($iy = 0; $iy < $this->image_height; ++ $iy) {
  860. $x = $ix;
  861. $y = $iy;
  862. for ($i = 0; $i < $numpoles; ++ $i) {
  863. $dx = $ix - $px[$i];
  864. $dy = $iy - $py[$i];
  865. if ($dx == 0 && $dy == 0) {
  866. continue;
  867. }
  868. $r = sqrt($dx * $dx + $dy * $dy);
  869. if ($r > $rad[$i]) {
  870. continue;
  871. }
  872. $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
  873. $x += $dx * $rscale;
  874. $y += $dy * $rscale;
  875. }
  876. $c = $bgCol;
  877. $x *= $this->iscale;
  878. $y *= $this->iscale;
  879. if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
  880. $c = imagecolorat($this->tmpimg, $x, $y);
  881. }
  882. if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
  883. imagesetpixel($this->im, $ix, $iy, $c);
  884. }
  885. }
  886. }
  887. }
  888. /**
  889. * Draws distorted lines on the image
  890. */
  891. protected function drawLines()
  892. {
  893. for ($line = 0; $line < $this->num_lines; ++ $line) {
  894. $x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
  895. $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
  896. $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9);
  897. $theta = ($this->frand() - 0.5) * M_PI * 0.7;
  898. $w = $this->image_width;
  899. $len = mt_rand($w * 0.4, $w * 0.7);
  900. $lwid = mt_rand(0, 2);
  901. $k = $this->frand() * 0.6 + 0.2;
  902. $k = $k * $k * 0.5;
  903. $phi = $this->frand() * 6.28;
  904. $step = 0.5;
  905. $dx = $step * cos($theta);
  906. $dy = $step * sin($theta);
  907. $n = $len / $step;
  908. $amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
  909. $x0 = $x - 0.5 * $len * cos($theta);
  910. $y0 = $y - 0.5 * $len * sin($theta);
  911. $ldx = round(- $dy * $lwid);
  912. $ldy = round($dx * $lwid);
  913. for ($i = 0; $i < $n; ++ $i) {
  914. $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
  915. $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
  916. imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
  917. }
  918. }
  919. }
  920. /**
  921. * Draws random noise on the image
  922. */
  923. protected function drawNoise()
  924. {
  925. if ($this->noise_level > 10) {
  926. $noise_level = 10;
  927. } else {
  928. $noise_level = $this->noise_level;
  929. }
  930. $t0 = microtime(true);
  931. $noise_level *= 125; // an arbitrary number that works well on a 1-10 scale
  932. $points = $this->image_width * $this->image_height * $this->iscale;
  933. $height = $this->image_height * $this->iscale;
  934. $width = $this->image_width * $this->iscale;
  935. for ($i = 0; $i < $noise_level; ++$i) {
  936. $x = mt_rand(10, $width);
  937. $y = mt_rand(10, $height);
  938. $size = mt_rand(7, 10);
  939. if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy
  940. imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE);
  941. }
  942. $t1 = microtime(true);
  943. $t = $t1 - $t0;
  944. /*
  945. // DEBUG
  946. imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor);
  947. header('content-type: image/png');
  948. imagepng($this->tmpimg);
  949. exit;
  950. */
  951. }
  952. /**
  953. * Print signature text on image
  954. */
  955. protected function addSignature()
  956. {
  957. $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
  958. $textlen = $bbox[2] - $bbox[0];
  959. $x = $this->image_width - $textlen - 5;
  960. $y = $this->image_height - 3;
  961. imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
  962. }
  963. /**
  964. * Sends the appropriate image and cache headers and outputs image to the browser
  965. */
  966. protected function output()
  967. {
  968. if ($this->canSendHeaders() || $this->send_headers == false) {
  969. if ($this->send_headers) {
  970. // only send the content-type headers if no headers have been output
  971. // this will ease debugging on misconfigured servers where warnings
  972. // may have been output which break the image and prevent easily viewing
  973. // source to see the error.
  974. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  975. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  976. header("Cache-Control: no-store, no-cache, must-revalidate");
  977. header("Cache-Control: post-check=0, pre-check=0", false);
  978. header("Pragma: no-cache");
  979. }
  980. switch ($this->image_type) {
  981. case self::SI_IMAGE_JPEG:
  982. if ($this->send_headers) header("Content-Type: image/jpeg");
  983. imagejpeg($this->im, null, 90);
  984. break;
  985. case self::SI_IMAGE_GIF:
  986. if ($this->send_headers) header("Content-Type: image/gif");
  987. imagegif($this->im);
  988. break;
  989. default:
  990. if ($this->send_headers) header("Content-Type: image/png");
  991. imagepng($this->im);
  992. break;
  993. }
  994. } else {
  995. echo '<hr /><strong>'
  996. .'Failed to generate captcha image, content has already been '
  997. .'output.<br />This is most likely due to misconfiguration or '
  998. .'a PHP error was sent to the browser.</strong>';
  999. }
  1000. imagedestroy($this->im);
  1001. restore_error_handler();
  1002. if (!$this->no_exit) exit;
  1003. }
  1004. /**
  1005. * Gets a captcha code from a file containing a list of words.
  1006. *
  1007. * Seek to a random offset in the file and reads a block of data and returns a line from the file.
  1008. *
  1009. * @param int $numWords Number of words (lines) to read from the file
  1010. * @return string|array Returns a string if only one word is to be read, or an array of words
  1011. */
  1012. protected function readCodeFromFile($numWords = 1)
  1013. {
  1014. $fp = fopen($this->wordlist_file, 'rb');
  1015. if (!$fp) return false;
  1016. $fsize = filesize($this->wordlist_file);
  1017. if ($fsize < 128) return false; // too small of a list to be effective
  1018. if ((int)$numWords < 1 || (int)$numWords > 5) $numWords = 1;
  1019. $words = array();
  1020. $i = 0;
  1021. do {
  1022. fseek($fp, mt_rand(0, $fsize - 64), SEEK_SET); // seek to a random position of file from 0 to filesize-64
  1023. $data = fread($fp, 64); // read a chunk from our random position
  1024. $data = preg_replace("/\r?\n/", "\n", $data);
  1025. $start = @strpos($data, "\n", mt_rand(0, 56)) + 1; // random start position
  1026. $end = @strpos($data, "\n", $start); // find end of word
  1027. if ($start === false) {
  1028. // picked start position at end of file
  1029. continue;
  1030. } else if ($end === false) {
  1031. $end = strlen($data);
  1032. }
  1033. $word = strtolower(substr($data, $start, $end - $start)); // return a line of the file
  1034. $words[] = $word;
  1035. } while (++$i < $numWords);
  1036. fclose($fp);
  1037. if ($numWords < 2) {
  1038. return $words[0];
  1039. } else {
  1040. return $words;
  1041. }
  1042. }
  1043. /**
  1044. * Generates a random captcha code from the set character set
  1045. *
  1046. * @see Securimage::$charset Charset option
  1047. * @return string A randomly generated CAPTCHA code
  1048. */
  1049. protected function generateCode()
  1050. {
  1051. $code = '';
  1052. if (function_exists('mb_strlen')) {
  1053. for($i = 1, $cslen = mb_strlen($this->charset); $i <= $this->code_length; ++$i) {
  1054. $code .= mb_substr($this->charset, mt_rand(0, $cslen - 1), 1, 'UTF-8');
  1055. }
  1056. } else {
  1057. for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) {
  1058. $code .= substr($this->charset, mt_rand(0, $cslen - 1), 1);
  1059. }
  1060. }
  1061. return $code;
  1062. }
  1063. /**
  1064. * Validate a code supplied by the user
  1065. *
  1066. * Checks the entered code against the value stored in the session and/or database (if configured). Handles case sensitivity.
  1067. * Also removes the code from session/database if the code was entered correctly to prevent re-use attack.
  1068. *
  1069. * This function does not return a value.
  1070. *
  1071. * @see Securimage::$correct_code 'correct_code' property
  1072. */
  1073. protected function validate()
  1074. {
  1075. if (!is_string($this->code) || strlen($this->code) == 0) {
  1076. $code = $this->getCode(true);
  1077. // returns stored code, or an empty string if no stored code was found
  1078. // checks the session and database if enabled
  1079. } else {
  1080. $code = $this->code;
  1081. }
  1082. if (is_array($code)) {
  1083. if (!empty($code)) {
  1084. $ctime = $code['time'];
  1085. $code = $code['code'];
  1086. $this->_timeToSolve = time() - $ctime;
  1087. } else {
  1088. $code = '';
  1089. }
  1090. }
  1091. if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) {
  1092. // case sensitive was set from securimage_show.php but not in class
  1093. // the code saved in the session has capitals so set case sensitive to true
  1094. $this->case_sensitive = true;
  1095. }
  1096. $code_entered = trim( (($this->case_sensitive) ? $this->code_entered
  1097. : strtolower($this->code_entered))
  1098. );
  1099. $this->correct_code = false;
  1100. if ($code != '') {
  1101. if (strpos($code, ' ') !== false) {
  1102. // for multi word captchas, remove more than once space from input
  1103. $code_entered = preg_replace('/\s+/', ' ', $code_entered);
  1104. $code_entered = strtolower($code_entered);
  1105. }
  1106. if ((string)$code === (string)$code_entered) {
  1107. $this->correct_code = true;
  1108. if ($this->session->has('securimage')) {
  1109. $session_data = $this->session->securimage;
  1110. } else {
  1111. $session_data = array();
  1112. }
  1113. $session_data[$this->namespace] = array(
  1114. 'code_disp' => '',
  1115. 'code_value' => '',
  1116. 'code_ctime' => '',
  1117. );
  1118. $this->session->set('securimage', $session_data);
  1119. }
  1120. }
  1121. }
  1122. /**
  1123. * Save CAPTCHA data to session and database (if configured)
  1124. */
  1125. protected function saveData()
  1126. {
  1127. if ($this->session->has('securimage')) {
  1128. // fix for migration from v2 - v3
  1129. $this->session->remove('securimage');
  1130. }
  1131. if ($this->session->has('securimage')) {
  1132. $session_data = $this->session->securimage;
  1133. } else {
  1134. $session_data = array();
  1135. }
  1136. $session_data[$this->namespace] = array(
  1137. 'code_disp' => $this->code_display,
  1138. 'code_value' => $this->code,
  1139. 'code_ctime' => time(),
  1140. );
  1141. $this->session->set('securimage', $session_data);
  1142. }
  1143. /**
  1144. * Checks to see if the captcha code has expired and can no longer be used.
  1145. *
  1146. * @see Securimage::$expiry_time expiry_time
  1147. * @param int $creation_time The Unix timestamp of when the captcha code was created
  1148. * @return bool true if the code is expired, false if it is still valid
  1149. */
  1150. protected function isCodeExpired($creation_time)
  1151. {
  1152. $expired = true;
  1153. if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) {
  1154. $expired = false;
  1155. } else if (time() - $creation_time < $this->expiry_time) {
  1156. $expired = false;
  1157. }
  1158. return $expired;
  1159. }
  1160. /**
  1161. * Get a random effect or chain of effects to apply to a segment of the
  1162. * audio file.
  1163. *
  1164. * These effects should increase the randomness of the audio for
  1165. * a particular letter/number by modulating the signal. The SoX effects
  1166. * used are *bend*, *chorus*, *overdrive*, *pitch*, *reverb*, *tempo*, and
  1167. * *tremolo*.
  1168. *
  1169. * For each effect selected, random parameters are supplied to the effect.
  1170. *
  1171. * @param int $numEffects How many effects to chain together
  1172. * @return string A string of valid SoX effects and their respective options.
  1173. */
  1174. protected function getSoxEffectChain($numEffects = 2)
  1175. {
  1176. $effectsList = array('bend', 'chorus', 'overdrive', 'pitch', 'reverb', 'tempo', 'tremolo');
  1177. $effects = array_rand($effectsList, $numEffects);
  1178. $outEffects = array();
  1179. if (!is_array($effects)) $effects = array($effects);
  1180. foreach($effects as $effect) {
  1181. $effect = $effectsList[$effect];
  1182. switch($effect)
  1183. {
  1184. case 'bend':
  1185. $delay = mt_rand(0, 15) / 100.0;
  1186. $cents = mt_rand(-120, 120);
  1187. $dur = mt_rand(75, 400) / 100.0;
  1188. $outEffects[] = "$effect $delay,$cents,$dur";
  1189. break;
  1190. case 'chorus':
  1191. $gainIn = mt_rand(75, 90) / 100.0;
  1192. $gainOut = mt_rand(70, 95) / 100.0;
  1193. $chorStr = "$effect $gainIn $gainOut";
  1194. for ($i = 0; $i < mt_rand(2, 3); ++$i) {
  1195. $delay = mt_rand(20, 100);
  1196. $decay = mt_rand(10, 100) / 100.0;
  1197. $speed = mt_rand(20, 50) / 100.0;
  1198. $depth = mt_rand(150, 250) / 100.0;
  1199. $chorStr .= " $delay $decay $speed $depth -s";
  1200. }
  1201. $outEffects[] = $chorStr;
  1202. break;
  1203. case 'overdrive':
  1204. $gain = mt_rand(5, 25);
  1205. $color = mt_rand(20, 70);
  1206. $outEffects[] = "$effect $gain $color";
  1207. break;
  1208. case 'pitch':
  1209. $cents = mt_rand(-300, 300);
  1210. $outEffects[] = "$effect $cents";
  1211. break;
  1212. case 'reverb':
  1213. $reverberance = mt_rand(20, 80);
  1214. $damping = mt_rand(10, 80);
  1215. $scale = mt_rand(85, 100);
  1216. $depth = mt_rand(90, 100);
  1217. $predelay = mt_rand(0, 5);
  1218. $outEffects[] = "$effect $reverberance $damping $scale $depth $predelay";
  1219. break;
  1220. case 'tempo':
  1221. $factor = mt_rand(65, 135) / 100.0;
  1222. $outEffects[] = "$effect -s $factor";
  1223. break;
  1224. case 'tremolo':
  1225. $hz = mt_rand(10, 30);
  1226. $depth = mt_rand(40, 85);
  1227. $outEffects[] = "$effect $hz $depth";
  1228. break;
  1229. }
  1230. }
  1231. return implode(' ', $outEffects);
  1232. }
  1233. /**
  1234. * This function is not yet used.
  1235. *
  1236. * Generate random background noise from sweeping oscillators
  1237. *
  1238. * @param float $duration How long in seconds the generated sound will be
  1239. * @param int $numChannels Number of channels in output wav
  1240. * @param int $sampleRate Sample rate of output wav
  1241. * @param int $bitRate Bits per sample (8, 16, 24)
  1242. * @return string Audio data in wav format
  1243. */
  1244. protected function getSoxNoiseData($duration, $numChannels, $sampleRate, $bitRate)
  1245. {
  1246. $shapes = array('sine', 'square', 'triangle', 'sawtooth', 'trapezium');
  1247. $steps = array(':', '+', '/', '-');
  1248. $selShapes = array_rand($shapes, 2);
  1249. $selSteps = array_rand($steps, 2);
  1250. $sweep0 = array();
  1251. $sweep0[0] = mt_rand(100, 700);
  1252. $sweep0[1] = mt_rand(1500, 2500);
  1253. $sweep1 = array();
  1254. $sweep1[0] = mt_rand(500, 1000);
  1255. $sweep1[1] = mt_rand(1200, 2000);
  1256. if (mt_rand(0, 10) % 2 == 0)
  1257. $sweep0 = array_reverse($sweep0);
  1258. if (mt_rand(0, 10) % 2 == 0)
  1259. $sweep1 = array_reverse($sweep1);
  1260. $cmd = sprintf("%s -c %d -r %d -b %d -n -t wav - synth noise create vol 0.3 synth %.2f %s mix %d%s%d vol 0.3 synth %.2f %s fmod %d%s%d vol 0.3",
  1261. $numChannels,
  1262. $sampleRate,
  1263. $bitRate,
  1264. $duration,
  1265. $shapes[$selShapes[0]],
  1266. $sweep0[0],
  1267. $steps[$selSteps[0]],
  1268. $sweep0[1],
  1269. $duration,
  1270. $shapes[$selShapes[1]],
  1271. $sweep1[0],
  1272. $steps[$selSteps[1]],
  1273. $sweep1[1]
  1274. );
  1275. $data = `$cmd`;
  1276. return $data;
  1277. }
  1278. /**
  1279. * Checks to see if headers can be sent and if any error has been output
  1280. * to the browser
  1281. *
  1282. * @return bool true if it is safe to send headers, false if not
  1283. */
  1284. protected function canSendHeaders()
  1285. {
  1286. if (headers_sent()) {
  1287. // output has been flushed and headers have already been sent
  1288. return false;
  1289. } else if (strlen((string)ob_get_contents()) > 0) {
  1290. // headers haven't been sent, but there is data in the buffer that will break image and audio data
  1291. return false;
  1292. }
  1293. return true;
  1294. }
  1295. /**
  1296. * Return a random float between 0 and 0.9999
  1297. *
  1298. * @return float Random float between 0 and 0.9999
  1299. */
  1300. function frand()
  1301. {
  1302. return 0.0001 * mt_rand(0,9999);
  1303. }
  1304. /**
  1305. * Convert an html color code to a Securimage_Color
  1306. * @param string $color
  1307. * @param Securimage_Color $default The defalt color to use if $color is invalid
  1308. */
  1309. protected function initColor($color, $default)
  1310. {
  1311. if ($color == null) {
  1312. return new Securimage_Color($default);
  1313. } else if (is_string($color)) {
  1314. try {

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