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

/ow_libraries/securimage/securimage.php

https://bitbucket.org/Noelfhim/no_ftp
PHP | 1313 lines | 577 code | 184 blank | 552 comment | 147 complexity | 29d4013bed104617f5e197e10e86992f MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
  4. * File: securimage.php<br />
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or any later version.<br /><br />
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.<br /><br />
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA<br /><br />
  19. *
  20. * Any modifications to the library should be indicated clearly in the source code
  21. * to inform users that the changes are not a part of the original software.<br /><br />
  22. *
  23. * If you found this script useful, please take a quick moment to rate it.<br />
  24. * http://www.hotscripts.com/rate/49400.html Thanks.
  25. *
  26. * @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
  27. * @link http://www.phpcaptcha.org/latest.zip Download Latest Version
  28. * @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
  29. * @copyright 2009 Drew Phillips
  30. * @author Drew Phillips <drew@drew-phillips.com>
  31. * @version 2.0 BETA (November 15, 2009)
  32. * @package Securimage
  33. *
  34. */
  35. /**
  36. ChangeLog
  37. 2.0.0
  38. - Add mathematical distortion to characters (using code from HKCaptcha)
  39. - Improved session support
  40. - Added Securimage_Color class for easier color definitions
  41. - Add distortion to audio output to prevent binary comparison attack (proposed by Sven "SavageTiger" Hagemann [insecurity.nl])
  42. - Flash button to stream mp3 audio (Douglas Walsh www.douglaswalsh.net)
  43. - Audio output is mp3 format by default
  44. - Change font to AlteHaasGrotesk by yann le coroller
  45. - Some code cleanup
  46. 1.0.4 (unreleased)
  47. - Ability to output audible codes in mp3 format to stream from flash
  48. 1.0.3.1
  49. - Error reading from wordlist in some cases caused words to be cut off 1 letter short
  50. 1.0.3
  51. - Removed shadow_text from code which could cause an undefined property error due to removal from previous version
  52. 1.0.2
  53. - Audible CAPTCHA Code wav files
  54. - Create codes from a word list instead of random strings
  55. 1.0
  56. - Added the ability to use a selected character set, rather than a-z0-9 only.
  57. - Added the multi-color text option to use different colors for each letter.
  58. - Switched to automatic session handling instead of using files for code storage
  59. - Added GD Font support if ttf support is not available. Can use internal GD fonts or load new ones.
  60. - Added the ability to set line thickness
  61. - Added option for drawing arced lines over letters
  62. - Added ability to choose image type for output
  63. */
  64. /**
  65. * Output images in JPEG format
  66. */
  67. define('SI_IMAGE_JPEG', 1);
  68. /**
  69. * Output images in PNG format
  70. */
  71. define('SI_IMAGE_PNG', 2);
  72. /**
  73. * Output images in GIF format
  74. * Must have GD >= 2.0.28!
  75. */
  76. define('SI_IMAGE_GIF', 3);
  77. /**
  78. * Securimage CAPTCHA Class.
  79. *
  80. * @package Securimage
  81. * @subpackage classes
  82. *
  83. */
  84. class Securimage {
  85. /**
  86. * The desired width of the CAPTCHA image.
  87. *
  88. * @var int
  89. */
  90. var $image_width;
  91. /**
  92. * The desired width of the CAPTCHA image.
  93. *
  94. * @var int
  95. */
  96. var $image_height;
  97. /**
  98. * The image format for output.<br />
  99. * Valid options: SI_IMAGE_PNG, SI_IMAGE_JPG, SI_IMAGE_GIF
  100. *
  101. * @var int
  102. */
  103. var $image_type;
  104. /**
  105. * The length of the code to generate.
  106. *
  107. * @var int
  108. */
  109. var $code_length;
  110. /**
  111. * The character set for individual characters in the image.<br />
  112. * Letters are converted to uppercase.<br />
  113. * The font must support the letters or there may be problematic substitutions.
  114. *
  115. * @var string
  116. */
  117. var $charset;
  118. /**
  119. * Create codes using this word list
  120. *
  121. * @var string The path to the word list to use for creating CAPTCHA codes
  122. */
  123. var $wordlist_file;
  124. /**
  125. * Use wordlist of not
  126. *
  127. * @var bool true to use wordlist file, false to use random code
  128. */
  129. var $use_wordlist = false;
  130. /**
  131. * Note: Use of GD fonts is not recommended as many distortion features are not available<br />
  132. * The GD font to use.<br />
  133. * Internal gd fonts can be loaded by their number.<br />
  134. * Alternatively, a file path can be given and the font will be loaded from file.
  135. *
  136. * @var mixed
  137. */
  138. var $gd_font_file;
  139. /**
  140. * The approximate size of the font in pixels.<br />
  141. * This does not control the size of the font because that is determined by the GD font itself.<br />
  142. * This is used to aid the calculations of positioning used by this class.<br />
  143. *
  144. * @var int
  145. */
  146. var $gd_font_size;
  147. /**
  148. * Use a gd font instead of TTF
  149. *
  150. * @var bool true for gd font, false for TTF
  151. */
  152. var $use_gd_font;
  153. // Note: These font options below do not apply if you set $use_gd_font to true with the exception of $text_color
  154. /**
  155. * The path to the TTF font file to load.
  156. *
  157. * @var string
  158. */
  159. var $ttf_file;
  160. /**
  161. * How much to distort image, higher = more distortion.<br />
  162. * Distortion is only available when using TTF fonts.<br />
  163. *
  164. * @var float
  165. */
  166. var $perturbation;
  167. /**
  168. * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
  169. * Higher values represent a counter-clockwise rotation.<br />
  170. * For example, a value of 90 would result in bottom-to-top reading text.<br />
  171. * This value along with maximum angle distance do not need to be very high with perturbation
  172. *
  173. * @var int
  174. */
  175. var $text_angle_minimum;
  176. /**
  177. * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
  178. * Higher values represent a counter-clockwise rotation.<br />
  179. * For example, a value of 90 would result in bottom-to-top reading text.
  180. *
  181. * @var int
  182. */
  183. var $text_angle_maximum;
  184. /**
  185. * The X-Position on the image where letter drawing will begin.<br />
  186. * This value is in pixels from the left side of the image.
  187. *
  188. * @var int
  189. * @deprecated 2.0
  190. */
  191. var $text_x_start;
  192. /**
  193. * The background color for the image as a Securimage_Color.<br />
  194. *
  195. * @var Securimage_Color
  196. */
  197. var $image_bg_color;
  198. /**
  199. * Scan this directory for gif, jpg, and png files to use as background images.<br />
  200. * A random image file will be picked each time.<br />
  201. * Change from null to the full path to your directory.<br />
  202. * i.e. var $background_directory = $_SERVER['DOCUMENT_ROOT'] . '/securimage/backgrounds';
  203. * Make sure not to pass a background image to the show function, otherwise this directive is ignored.
  204. *
  205. * @var string
  206. */
  207. var $background_directory = null; //'./backgrounds';
  208. /**
  209. * The text color to use for drawing characters as a Securimage_Color.<br />
  210. * This value is ignored if $use_multi_text is set to true.<br />
  211. * Make sure this contrasts well with the background color or image.<br />
  212. *
  213. * @see Securimage::$use_multi_text
  214. * @var Securimage_Color
  215. */
  216. var $text_color;
  217. /**
  218. * Set to true to use multiple colors for each character.
  219. *
  220. * @see Securimage::$multi_text_color
  221. * @var boolean
  222. */
  223. var $use_multi_text;
  224. /**
  225. * Array of Securimage_Colors which will be randomly selected for each letter.<br />
  226. *
  227. * @var array
  228. */
  229. var $multi_text_color;
  230. /**
  231. * Set to true to make the characters appear transparent.
  232. *
  233. * @see Securimage::$text_transparency_percentage
  234. * @var boolean
  235. */
  236. var $use_transparent_text;
  237. /**
  238. * The percentage of transparency, 0 to 100.<br />
  239. * A value of 0 is completely opaque, 100 is completely transparent (invisble)
  240. *
  241. * @see Securimage::$use_transparent_text
  242. * @var int
  243. */
  244. var $text_transparency_percentage;
  245. // Line options
  246. /**
  247. * Draw vertical and horizontal lines on the image.
  248. *
  249. * @see Securimage::$line_color
  250. * @see Securimage::$draw_lines_over_text
  251. * @var boolean
  252. */
  253. var $num_lines;
  254. /**
  255. * Color of lines drawn over text
  256. *
  257. * @var string
  258. */
  259. var $line_color;
  260. /**
  261. * Draw the lines over the text.<br />
  262. * If fales lines will be drawn before putting the text on the image.
  263. *
  264. * @var boolean
  265. */
  266. var $draw_lines_over_text;
  267. /**
  268. * Text to write at the bottom corner of captcha image
  269. *
  270. * @since 2.0
  271. * @var string Signature text
  272. */
  273. var $image_signature;
  274. /**
  275. * Color to use for writing signature text
  276. *
  277. * @since 2.0
  278. * @var Securimage_Color
  279. */
  280. var $signature_color;
  281. /**
  282. * Full path to the WAV files to use to make the audio files, include trailing /.<br />
  283. * Name Files [A-Z0-9].wav
  284. *
  285. * @since 1.0.1
  286. * @var string
  287. */
  288. var $audio_path;
  289. /**
  290. * Type of audio file to generate (mp3 or wav)
  291. *
  292. * @var string
  293. */
  294. var $audio_format;
  295. /**
  296. * The session name to use if not the default. Blank for none
  297. *
  298. * @see http://php.net/session_name
  299. * @since 2.0
  300. * @var string
  301. */
  302. var $session_name = '';
  303. //END USER CONFIGURATION
  304. //There should be no need to edit below unless you really know what you are doing.
  305. /**
  306. * The gd image resource.
  307. *
  308. * @access private
  309. * @var resource
  310. */
  311. var $im;
  312. /**
  313. * Temporary image for rendering
  314. *
  315. * @access private
  316. * @var resource
  317. */
  318. var $tmpimg;
  319. /**
  320. * Internal scale factor for anti-alias @hkcaptcha
  321. *
  322. * @access private
  323. * @since 2.0
  324. * @var int
  325. */
  326. var $iscale; // internal scale factor for anti-alias @hkcaptcha
  327. /**
  328. * The background image resource
  329. *
  330. * @access private
  331. * @var resource
  332. */
  333. var $bgimg;
  334. /**
  335. * The code generated by the script
  336. *
  337. * @access private
  338. * @var string
  339. */
  340. var $code;
  341. /**
  342. * The code that was entered by the user
  343. *
  344. * @access private
  345. * @var string
  346. */
  347. var $code_entered;
  348. /**
  349. * Whether or not the correct code was entered
  350. *
  351. * @access private
  352. * @var boolean
  353. */
  354. var $correct_code;
  355. /**
  356. * Class constructor.<br />
  357. * Because the class uses sessions, this will attempt to start a session if there is no previous one.<br />
  358. * If you do not start a session before calling the class, the constructor must be called before any
  359. * output is sent to the browser.
  360. *
  361. * <code>
  362. * $securimage = new Securimage();
  363. * </code>
  364. *
  365. */
  366. function Securimage()
  367. {
  368. // Initialize session or attach to existing
  369. if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
  370. if (trim($this->session_name) != '') {
  371. session_name($this->session_name);
  372. }
  373. session_start();
  374. }
  375. // Set Default Values
  376. $this->image_width = 230;
  377. $this->image_height = 80;
  378. $this->image_type = SI_IMAGE_PNG;
  379. $this->code_length = 6;
  380. $this->charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
  381. $this->wordlist_file = './words/words.txt';
  382. $this->use_wordlist = false;
  383. $this->gd_font_file = '';
  384. $this->use_gd_font = false;
  385. $this->gd_font_size = 24;
  386. $this->text_x_start = 15;
  387. $this->ttf_file = OW_DIR_LIB . 'securimage/AHGBold.ttf';
  388. $this->perturbation = 0.75;
  389. $this->iscale = 5;
  390. $this->text_angle_minimum = 0;
  391. $this->text_angle_maximum = 0;
  392. $this->image_bg_color = new Securimage_Color(0xff, 0xff, 0xff);
  393. $this->text_color = new Securimage_Color(0x3d, 0x3d, 0x3d);
  394. $this->multi_text_color = array(new Securimage_Color(0x0, 0x20, 0xCC),
  395. new Securimage_Color(0x0, 0x30, 0xEE),
  396. new Securimage_color(0x0, 0x40, 0xCC),
  397. new Securimage_Color(0x0, 0x50, 0xEE),
  398. new Securimage_Color(0x0, 0x60, 0xCC));
  399. $this->use_multi_text = false;
  400. $this->use_transparent_text = false;
  401. $this->text_transparency_percentage = 30;
  402. $this->num_lines = 10;
  403. $this->line_color = new Securimage_Color(0x3d, 0x3d, 0x3d);
  404. $this->draw_lines_over_text = true;
  405. $this->image_signature = '';
  406. $this->signature_color = new Securimage_Color(0x20, 0x50, 0xCC);
  407. $this->signature_font = OW_DIR_LIB . 'securimage/AHGBold.ttf';
  408. $this->audio_path = './audio/';
  409. $this->audio_format = 'mp3';
  410. $this->session_name = '';
  411. }
  412. /**
  413. * Generate a code and output the image to the browser.
  414. *
  415. * <code>
  416. * <?php
  417. * include 'securimage.php';
  418. * $securimage = new Securimage();
  419. * $securimage->show('bg.jpg');
  420. * ?>
  421. * </code>
  422. *
  423. * @param string $background_image The path to an image to use as the background for the CAPTCHA
  424. */
  425. function show($background_image = "")
  426. {
  427. if($background_image != "" && is_readable($background_image)) {
  428. $this->bgimg = $background_image;
  429. }
  430. $this->doImage();
  431. }
  432. /**
  433. * Validate the code entered by the user.
  434. *
  435. * <code>
  436. * $code = $_POST['code'];
  437. * if ($securimage->check($code) == false) {
  438. * die("Sorry, the code entered did not match.");
  439. * } else {
  440. * $valid = true;
  441. * }
  442. * </code>
  443. * @param string $code The code the user entered
  444. * @return boolean true if the code was correct, false if not
  445. */
  446. function check($code)
  447. {
  448. $this->code_entered = $code;
  449. $this->validate();
  450. return $this->correct_code;
  451. }
  452. /**
  453. * Output audio file with HTTP headers to browser
  454. *
  455. * <code>
  456. * $sound = new Securimage();
  457. * $sound->audio_format = 'mp3';
  458. * $sound->outputAudioFile();
  459. * </code>
  460. *
  461. * @since 2.0
  462. */
  463. function outputAudioFile()
  464. {
  465. if (strtolower($this->audio_format) == 'wav') {
  466. header('Content-type: audio/x-wav');
  467. $ext = 'wav';
  468. } else {
  469. header('Content-type: audio/mpeg'); // default to mp3
  470. $ext = 'mp3';
  471. }
  472. header("Content-Disposition: attachment; name=\"securimage_audio.{$ext}\"");
  473. header('Cache-Control: no-store, no-cache, must-revalidate');
  474. header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
  475. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
  476. $audio = $this->getAudibleCode($ext);
  477. header('Content-Length: ' . strlen($audio));
  478. echo $audio;
  479. exit;
  480. }
  481. /**
  482. * Generate and output the image
  483. *
  484. * @access private
  485. *
  486. */
  487. function doImage()
  488. {
  489. if ($this->use_gd_font == true) {
  490. $this->iscale = 1;
  491. }
  492. if($this->use_transparent_text == true || $this->bgimg != "") {
  493. $this->im = imagecreatetruecolor($this->image_width, $this->image_height);
  494. $bgcolor = imagecolorallocate($this->im, $this->image_bg_color->r, $this->image_bg_color->g, $this->image_bg_color->b);
  495. imagefilledrectangle($this->im, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $bgcolor);
  496. $this->tmpimg = imagecreatetruecolor($this->image_width * $this->iscale, $this->image_height * $this->iscale);
  497. imagepalettecopy($this->tmpimg, $this->im);
  498. imagefilledrectangle($this->tmpimg, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $bgcolor);
  499. } else { //no transparency
  500. $this->im = imagecreate($this->image_width, $this->image_height);
  501. $bgcolor = imagecolorallocate($this->im, $this->image_bg_color->r, $this->image_bg_color->g, $this->image_bg_color->b);
  502. $this->tmpimg = imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
  503. imagepalettecopy($this->tmpimg, $this->im);
  504. }
  505. $this->setBackground();
  506. $this->createCode();
  507. if (!$this->draw_lines_over_text && $this->num_lines > 0) $this->drawLines();
  508. $this->drawWord();
  509. if ($this->use_gd_font == false) $this->distortedCopy();
  510. if ($this->draw_lines_over_text && $this->num_lines > 0) $this->drawLines();
  511. if (trim($this->image_signature) != '') $this->addSignature();
  512. $this->output();
  513. }
  514. /**
  515. * Set the background of the CAPTCHA image
  516. *
  517. * @access private
  518. *
  519. */
  520. function setBackground()
  521. {
  522. if ($this->bgimg == '') {
  523. if ($this->background_directory != null && is_dir($this->background_directory) && is_readable($this->background_directory)) {
  524. $img = $this->getBackgroundFromDirectory();
  525. if ($img != false) {
  526. $this->bgimg = $img;
  527. }
  528. }
  529. }
  530. $dat = false;
  531. if ( !empty($this->bgimg) )
  532. {
  533. $dat = @getimagesize($this->bgimg);
  534. }
  535. if($dat == false) { return; }
  536. switch($dat[2]) {
  537. case 1: $newim = @imagecreatefromgif($this->bgimg); break;
  538. case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
  539. case 3: $newim = @imagecreatefrompng($this->bgimg); break;
  540. case 15: $newim = @imagecreatefromwbmp($this->bgimg); break;
  541. case 16: $newim = @imagecreatefromxbm($this->bgimg); break;
  542. default: return;
  543. }
  544. if(!$newim) return;
  545. imagecopyresized($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height, imagesx($newim), imagesy($newim));
  546. }
  547. /**
  548. * Return the full path to a random gif, jpg, or png from the background directory.
  549. *
  550. * @see Securimage::$background_directory
  551. * @return mixed false if none found, string $path if found
  552. */
  553. function getBackgroundFromDirectory()
  554. {
  555. $images = array();
  556. if ($dh = opendir($this->background_directory)) {
  557. while (($file = readdir($dh)) !== false) {
  558. if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
  559. }
  560. closedir($dh);
  561. if (sizeof($images) > 0) {
  562. return rtrim($this->background_directory, '/') . '/' . $images[rand(0, sizeof($images)-1)];
  563. }
  564. }
  565. return false;
  566. }
  567. /**
  568. * Draw random curvy lines over the image<br />
  569. * Modified code from HKCaptcha
  570. *
  571. * @since 2.0
  572. * @access private
  573. *
  574. */
  575. function drawLines()
  576. {
  577. $linecolor = imagecolorallocate($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b);
  578. for ($line = 0; $line < $this->num_lines; ++$line) {
  579. $x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
  580. $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
  581. $y = rand($this->image_height * 0.1, $this->image_height * 0.9);
  582. $theta = ($this->frand()-0.5) * M_PI * 0.7;
  583. $w = $this->image_width;
  584. $len = rand($w * 0.4, $w * 0.7);
  585. $lwid = rand(0, 2);
  586. $k = $this->frand() * 0.6 + 0.2;
  587. $k = $k * $k * 0.5;
  588. $phi = $this->frand() * 6.28;
  589. $step = 0.5;
  590. $dx = $step * cos($theta);
  591. $dy = $step * sin($theta);
  592. $n = $len / $step;
  593. $amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
  594. $x0 = $x - 0.5 * $len * cos($theta);
  595. $y0 = $y - 0.5 * $len * sin($theta);
  596. $ldx = round(-$dy * $lwid);
  597. $ldy = round($dx * $lwid);
  598. for ($i = 0; $i < $n; ++$i) {
  599. $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
  600. $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
  601. imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $linecolor);
  602. }
  603. }
  604. }
  605. /**
  606. * Draw the CAPTCHA code over the image
  607. *
  608. * @access private
  609. *
  610. */
  611. function drawWord()
  612. {
  613. $width2 = $this->image_width * $this->iscale;
  614. $height2 = $this->image_height * $this->iscale;
  615. if ($this->use_gd_font == true) {
  616. if (!is_int($this->gd_font_file)) { //is a file name
  617. $font = @imageloadfont($this->gd_font_file);
  618. if ($font == false) {
  619. trigger_error("Failed to load GD Font file {$this->gd_font_file} ", E_USER_WARNING);
  620. return;
  621. }
  622. } else { //gd font identifier
  623. $font = $this->gd_font_file;
  624. }
  625. $color = imagecolorallocate($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)));
  626. imagestring($this->im, $font, $this->text_x_start, ($this->image_height / 2) - ($this->gd_font_size / 2), $this->code, $color);
  627. } else { //ttf font
  628. $font_size = $height2 * .35;
  629. $bb = imagettfbbox($font_size, 0, $this->ttf_file, $this->code);
  630. $tx = $bb[4] - $bb[0];
  631. $ty = $bb[5] - $bb[1];
  632. $x = floor($width2 / 2 - $tx / 2 - $bb[0]);
  633. $y = round($height2 / 2 - $ty / 2 - $bb[1]);
  634. if($this->use_transparent_text == true) {
  635. $alpha = intval($this->text_transparency_percentage / 100 * 127);
  636. $font_color = imagecolorallocatealpha($this->tmpimg, $this->text_color->r, $this->text_color->g, $this->text_color->b, $alpha);
  637. } else { //no transparency
  638. $font_color = imagecolorallocate($this->tmpimg, $this->text_color->r, $this->text_color->g, $this->text_color->b);
  639. }
  640. $strlen = strlen($this->code);
  641. if (!is_array($this->multi_text_color)) $this->use_multi_text = false;
  642. if ($this->use_multi_text == false && $this->text_angle_minimum == 0 && $this->text_angle_maximum == 0) { // no angled or multi-color characters
  643. imagettftext($this->tmpimg, $font_size, 0, $x, $y, $font_color, $this->ttf_file, $this->code);
  644. } else {
  645. for($i = 0; $i < $strlen; ++$i) {
  646. $angle = rand($this->text_angle_minimum, $this->text_angle_maximum);
  647. $y = rand($y - 5, $y + 5);
  648. if ($this->use_multi_text == true) {
  649. $idx = rand(0, sizeof($this->multi_text_color) - 1);
  650. if (!is_object($this->multi_text_color[$idx])) $this->multi_text_color[$idx] = $this->text_color;
  651. if($this->use_transparent_text == true) {
  652. $font_color = imagecolorallocatealpha($this->tmpimg, $this->multi_text_color[$idx]->r, $this->multi_text_color[$idx]->g, $this->multi_text_color[$idx]->b, $alpha);
  653. } else {
  654. $font_color = imagecolorallocate($this->tmpimg, $this->multi_text_color[$idx]->r, $this->multi_text_color[$idx]->g, $this->multi_text_color[$idx]->b);
  655. }
  656. }
  657. $ch = $this->code{$i};
  658. imagettftext($this->tmpimg, $font_size, $angle, $x, $y, $font_color, $this->ttf_file, $ch);
  659. // estimate character widths to increment $x without creating spaces that are too large or too small
  660. // these are best estimates to align text but may vary between fonts
  661. // for optimal character widths, do not use multiple text colors or character angles and the complete string will be written by imagettftext
  662. if (strpos('abcdeghknopqsuvxyz', $ch) !== false) {
  663. $min_x = $font_size - ($this->iscale * 6);
  664. $max_x = $font_size - ($this->iscale * 6);
  665. } else if (strpos('ilI1', $ch) !== false) {
  666. $min_x = $font_size / 5;
  667. $max_x = $font_size / 3;
  668. } else if (strpos('fjrt', $ch) !== false) {
  669. $min_x = $font_size - ($this->iscale * 12);
  670. $max_x = $font_size - ($this->iscale * 12);
  671. } else if ($ch == 'wm') {
  672. $min_x = $font_size;
  673. $max_x = $font_size + ($this->iscale * 3);
  674. } else { // numbers, capitals or unicode
  675. $min_x = $font_size + ($this->iscale * 2);
  676. $max_x = $font_size + ($this->iscale * 5);
  677. }
  678. $x += rand($min_x, $max_x);
  679. } //for loop
  680. } // angled or multi-color
  681. } //else ttf font
  682. //$this->im = $this->tmpimg;
  683. //$this->output();
  684. } //function
  685. /**
  686. * Warp text from temporary image onto final image.<br />
  687. * Modified for securimage
  688. *
  689. * @access private
  690. * @since 2.0
  691. * @author Han-Kwang Nienhuys modified
  692. * @copyright Han-Kwang Neinhuys
  693. *
  694. */
  695. function distortedCopy()
  696. {
  697. $numpoles = 3; // distortion factor
  698. // make array of poles AKA attractor points
  699. for ($i = 0; $i < $numpoles; ++$i) {
  700. $px[$i] = rand($this->image_width * 0.3, $this->image_width * 0.7);
  701. $py[$i] = rand($this->image_height * 0.3, $this->image_height * 0.7);
  702. $rad[$i] = rand($this->image_width * 0.4, $this->image_width * 0.7);
  703. $tmp = -$this->frand() * 0.15 - 0.15;
  704. $amp[$i] = $this->perturbation * $tmp;
  705. }
  706. $bgCol = imagecolorat($this->tmpimg, 0, 0);
  707. $width2 = $this->iscale * $this->image_width;
  708. $height2 = $this->iscale * $this->image_height;
  709. imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
  710. // loop over $img pixels, take pixels from $tmpimg with distortion field
  711. for ($ix = 0; $ix < $this->image_width; ++$ix) {
  712. for ($iy = 0; $iy < $this->image_height; ++$iy) {
  713. $x = $ix;
  714. $y = $iy;
  715. for ($i = 0; $i < $numpoles; ++$i) {
  716. $dx = $ix - $px[$i];
  717. $dy = $iy - $py[$i];
  718. if ($dx == 0 && $dy == 0) continue;
  719. $r = sqrt($dx * $dx + $dy * $dy);
  720. if ($r > $rad[$i]) continue;
  721. $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
  722. $x += $dx * $rscale;
  723. $y += $dy * $rscale;
  724. }
  725. $c = $bgCol;
  726. $x *= $this->iscale;
  727. $y *= $this->iscale;
  728. if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
  729. $c = imagecolorat($this->tmpimg, $x, $y);
  730. }
  731. if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
  732. imagesetpixel($this->im, $ix, $iy, $c);
  733. }
  734. }
  735. }
  736. }
  737. /**
  738. * Create a code and save to the session
  739. *
  740. * @since 1.0.1
  741. *
  742. */
  743. function createCode()
  744. {
  745. $this->code = false;
  746. if ($this->use_wordlist && is_readable($this->wordlist_file)) {
  747. $this->code = $this->readCodeFromFile();
  748. }
  749. if ($this->code == false) {
  750. $this->code = $this->generateCode($this->code_length);
  751. }
  752. $this->saveData();
  753. }
  754. /**
  755. * Generate a code
  756. *
  757. * @access private
  758. * @param int $len The code length
  759. * @return string
  760. */
  761. function generateCode($len)
  762. {
  763. $code = '';
  764. for($i = 1, $cslen = strlen($this->charset); $i <= $len; ++$i) {
  765. $code .= $this->charset{rand(0, $cslen - 1)};
  766. }
  767. return $code;
  768. }
  769. /**
  770. * Reads a word list file to get a code
  771. *
  772. * @access private
  773. * @since 1.0.2
  774. * @return mixed false on failure, a word on success
  775. */
  776. function readCodeFromFile()
  777. {
  778. $fp = @fopen($this->wordlist_file, 'rb');
  779. if (!$fp) return false;
  780. $fsize = filesize($this->wordlist_file);
  781. if ($fsize < 32) return false; // too small of a list to be effective
  782. if ($fsize < 128) {
  783. $max = $fsize; // still pretty small but changes the range of seeking
  784. } else {
  785. $max = 128;
  786. }
  787. fseek($fp, rand(0, $fsize - $max), SEEK_SET);
  788. $data = fread($fp, 128); // read a random 128 bytes from file
  789. fclose($fp);
  790. $data = preg_replace("/\r?\n/", "\n", $data);
  791. $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
  792. $end = strpos($data, "\n", $start); // find end of word
  793. return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
  794. }
  795. /**
  796. * Output image to the browser
  797. *
  798. * @access private
  799. *
  800. */
  801. function output()
  802. {
  803. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  804. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  805. header("Cache-Control: no-store, no-cache, must-revalidate");
  806. header("Cache-Control: post-check=0, pre-check=0", false);
  807. header("Pragma: no-cache");
  808. switch($this->image_type)
  809. {
  810. case SI_IMAGE_JPEG:
  811. header("Content-Type: image/jpeg");
  812. imagejpeg($this->im, null, 90);
  813. break;
  814. case SI_IMAGE_GIF:
  815. header("Content-Type: image/gif");
  816. imagegif($this->im);
  817. break;
  818. default:
  819. header("Content-Type: image/png");
  820. imagepng($this->im);
  821. break;
  822. }
  823. imagedestroy($this->im);
  824. exit;
  825. }
  826. /**
  827. * Get WAV or MP3 file data of the spoken code.<br />
  828. * This is appropriate for output to the browser as audio/x-wav or audio/mpeg
  829. *
  830. * @since 1.0.1
  831. * @return string WAV or MP3 data
  832. *
  833. */
  834. function getAudibleCode($format = 'wav')
  835. {
  836. $letters = array();
  837. $code = $this->getCode();
  838. if ($code == '') {
  839. $this->createCode();
  840. $code = $this->getCode();
  841. }
  842. for($i = 0; $i < strlen($code); ++$i) {
  843. $letters[] = $code{$i};
  844. }
  845. if ($format == 'mp3') {
  846. return $this->generateMP3($letters);
  847. } else {
  848. return $this->generateWAV($letters);
  849. }
  850. }
  851. /**
  852. * Set the path to the audio directory.<br />
  853. *
  854. * @since 1.0.4
  855. * @return bool true if the directory exists and is readble, false if not
  856. */
  857. function setAudioPath($audio_directory)
  858. {
  859. if (is_dir($audio_directory) && is_readable($audio_directory)) {
  860. $this->audio_path = $audio_directory;
  861. return true;
  862. } else {
  863. return false;
  864. }
  865. }
  866. /**
  867. * Save the code in the session
  868. *
  869. * @access private
  870. *
  871. */
  872. function saveData()
  873. {
  874. $_SESSION['securimage_code_value'] = strtolower($this->code);
  875. }
  876. /**
  877. * Validate the code to the user code
  878. *
  879. * @access private
  880. *
  881. */
  882. function validate()
  883. {
  884. if ( isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value']) ) {
  885. if ( strtolower($_SESSION['securimage_code_value']) == strtolower(trim($this->code_entered)) ) {
  886. $this->correct_code = true;
  887. $_SESSION['securimage_code_value'] = ''; // clear code to prevent session re-use
  888. } else {
  889. $this->correct_code = false;
  890. }
  891. } else {
  892. $this->correct_code = false; // value was never set or is blank
  893. }
  894. }
  895. /**
  896. * Get the captcha code
  897. *
  898. * @since 1.0.1
  899. * @return string
  900. */
  901. function getCode()
  902. {
  903. if (isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value'])) {
  904. return strtolower($_SESSION['securimage_code_value']);
  905. } else {
  906. return '';
  907. }
  908. }
  909. /**
  910. * Check if the user entered code was correct
  911. *
  912. * @access private
  913. * @return boolean
  914. */
  915. function checkCode()
  916. {
  917. return $this->correct_code;
  918. }
  919. /**
  920. * Generate a wav file by concatenating individual files
  921. *
  922. * @since 1.0.1
  923. * @access private
  924. * @param array $letters Array of letters to build a file from
  925. * @return string WAV file data
  926. */
  927. function generateWAV($letters)
  928. {
  929. $data_len = 0;
  930. $files = array();
  931. $out_data = '';
  932. foreach ($letters as $letter) {
  933. $filename = $this->audio_path . strtoupper($letter) . '.wav';
  934. $fp = fopen($filename, 'rb');
  935. $file = array();
  936. $data = fread($fp, filesize($filename)); // read file in
  937. $header = substr($data, 0, 36);
  938. $body = substr($data, 44);
  939. $data = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/VSubChunk1Size/vAudioFormat/vNumChannels/VSampleRate/VByteRate/vBlockAlign/vBitsPerSample', $header);
  940. $file['sub_chunk1_id'] = $data['SubChunk1ID'];
  941. $file['bits_per_sample'] = $data['BitsPerSample'];
  942. $file['channels'] = $data['NumChannels'];
  943. $file['format'] = $data['AudioFormat'];
  944. $file['sample_rate'] = $data['SampleRate'];
  945. $file['size'] = $data['ChunkSize'] + 8;
  946. $file['data'] = $body;
  947. if ( ($p = strpos($file['data'], 'LIST')) !== false) {
  948. // If the LIST data is not at the end of the file, this will probably break your sound file
  949. $info = substr($file['data'], $p + 4, 8);
  950. $data = unpack('Vlength/Vjunk', $info);
  951. $file['data'] = substr($file['data'], 0, $p);
  952. $file['size'] = $file['size'] - (strlen($file['data']) - $p);
  953. }
  954. $files[] = $file;
  955. $data = null;
  956. $header = null;
  957. $body = null;
  958. $data_len += strlen($file['data']);
  959. fclose($fp);
  960. }
  961. $out_data = '';
  962. for($i = 0; $i < sizeof($files); ++$i) {
  963. if ($i == 0) { // output header
  964. $out_data .= pack('C4VC8', ord('R'), ord('I'), ord('F'), ord('F'), $data_len + 36, ord('W'), ord('A'), ord('V'), ord('E'), ord('f'), ord('m'), ord('t'), ord(' '));
  965. $out_data .= pack('VvvVVvv',
  966. 16,
  967. $files[$i]['format'],
  968. $files[$i]['channels'],
  969. $files[$i]['sample_rate'],
  970. $files[$i]['sample_rate'] * (($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8),
  971. ($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8,
  972. $files[$i]['bits_per_sample'] );
  973. $out_data .= pack('C4', ord('d'), ord('a'), ord('t'), ord('a'));
  974. $out_data .= pack('V', $data_len);
  975. }
  976. $out_data .= $files[$i]['data'];
  977. }
  978. $this->scrambleAudioData($out_data, 'wav');
  979. return $out_data;
  980. }
  981. /**
  982. * Randomly modify the audio data to scramble sound and prevent binary recognition.<br />
  983. * Take care not to "break" the audio file by leaving the header data intact.
  984. *
  985. * @since 2.0
  986. * @param $data Sound data in mp3 of wav format
  987. */
  988. function scrambleAudioData(&$data, $format)
  989. {
  990. if ($format == 'wav') {
  991. $start = strpos($data, 'data') + 4; // look for "data" indicator
  992. if ($start === false) $start = 44; // if not found assume 44 byte header
  993. } else { // mp3
  994. $start = 4; // 4 byte (32 bit) frame header
  995. }
  996. $start += rand(1, 64); // randomize starting offset
  997. $datalen = strlen($data) - $start - 256; // leave last 256 bytes unchanged
  998. for ($i = $start; $i < $datalen; $i += 64) {
  999. $ch = ord($data{$i});
  1000. if ($ch < 9 || $ch > 119) continue;
  1001. $data{$i} = chr($ch + rand(-8, 8));
  1002. }
  1003. }
  1004. /**
  1005. * Generate an mp3 file by concatenating individual files
  1006. * @since 1.0.4
  1007. * @access private
  1008. * @param array $letters Array of letters to build a file from
  1009. * @return string MP3 file data
  1010. */
  1011. function generateMP3($letters)
  1012. {
  1013. $data_len = 0;
  1014. $files = array();
  1015. $out_data = '';
  1016. foreach ($letters as $letter) {
  1017. $filename = $this->audio_path . strtoupper($letter) . '.mp3';
  1018. $fp = fopen($filename, 'rb');
  1019. $data = fread($fp, filesize($filename)); // read file in
  1020. $this->scrambleAudioData($data, 'mp3');
  1021. $out_data .= $data;
  1022. fclose($fp);
  1023. }
  1024. return $out_data;
  1025. }
  1026. /**
  1027. * Generate random number less than 1
  1028. * @since 2.0
  1029. * @access private
  1030. * @return float
  1031. */
  1032. function frand()
  1033. {
  1034. return 0.0001*rand(0,9999);
  1035. }
  1036. /**
  1037. * Print signature text on image
  1038. *
  1039. * @since 2.0
  1040. * @access private
  1041. *
  1042. */
  1043. function addSignature()
  1044. {
  1045. $cmtcol = imagecolorallocate($this->im, $this->signature_color->r, $this->signature_color->g, $this->signature_color->b);
  1046. if ($this->use_gd_font) {
  1047. imagestring($this->im, 5, $this->image_width - (strlen($this->image_signature) * 10), $this->image_height - 20, $this->image_signature, $cmtcol);
  1048. } else {
  1049. $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
  1050. $textlen = $bbox[2] - $bbox[0];
  1051. $x = $this->image_width - $textlen - 5;
  1052. $y = $this->image_height - 3;
  1053. imagettftext($this->im, 10, 0, $x, $y, $cmtcol, $this->signature_font, $this->image_signature);
  1054. }
  1055. }
  1056. } /* class Securimage */
  1057. /**
  1058. * Color object for Securimage CAPTCHA
  1059. *
  1060. * @since 2.0
  1061. * @package Securimage
  1062. * @subpackage classes
  1063. *
  1064. */
  1065. class Securimage_Color {
  1066. /**
  1067. * Red component: 0-255
  1068. *
  1069. * @var int
  1070. */
  1071. var $r;
  1072. /**
  1073. * Green component: 0-255
  1074. *
  1075. * @var int
  1076. */
  1077. var $g;
  1078. /**
  1079. * Blue component: 0-255
  1080. *
  1081. * @var int
  1082. */
  1083. var $b;
  1084. /**
  1085. * Create a new Securimage_Color object.<br />
  1086. * Specify the red, green, and blue components using their HTML hex code equivalent.<br />
  1087. * Example: The code for the HTML color #4A203C is:<br />
  1088. * $color = new Securimage_Color(0x4A, 0x20, 0x3C);
  1089. *
  1090. * @param $red Red component 0-255
  1091. * @param $green Green component 0-255
  1092. * @param $blue Blue component 0-255
  1093. */
  1094. function Securimage_Color($red, $green = null, $blue = null)
  1095. {
  1096. if ($green == null && $blue == null && preg_match('/^#[a-f0-9]{3,6}$/i', $red)) {
  1097. $col = substr($red, 1);
  1098. if (strlen($col) == 3) {
  1099. $red = str_repeat(substr($col, 0, 1), 2);
  1100. $green = str_repeat(substr($col, 1, 1), 2);
  1101. $blue = str_repeat(substr($col, 2, 1), 2);
  1102. } else {
  1103. $red = substr($col, 0, 2);
  1104. $green = substr($col, 2, 2);
  1105. $blue = substr($col, 4, 2);
  1106. }
  1107. $red = hexdec($red);
  1108. $green = hexdec($green);
  1109. $blue = hexdec($blue);
  1110. } else {
  1111. if ($red < 0) $red = 0;
  1112. if ($red > 255) $red = 255;
  1113. if ($green < 0) $green = 0;
  1114. if ($green > 255) $green = 255;
  1115. if ($blue < 0) $blue = 0;
  1116. if ($blue > 255) $blue = 255;
  1117. }
  1118. $this->r = $red;
  1119. $this->g = $green;
  1120. $this->b = $blue;
  1121. }
  1122. }