Subs-Graphics.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. <?php
  2. /**
  3. * This file deals with low-level graphics operations performed on images,
  4. * specially as needed for avatars (uploaded avatars), attachments, or
  5. * visual verification images.
  6. * It uses, for gifs at least, Gif Util. For more information on that,
  7. * please see its website.
  8. * TrueType fonts supplied by www.LarabieFonts.com
  9. *
  10. * Simple Machines Forum (SMF)
  11. *
  12. * @package SMF
  13. * @author Simple Machines http://www.simplemachines.org
  14. * @copyright 2011 Simple Machines
  15. * @license http://www.simplemachines.org/about/smf/license.php BSD
  16. *
  17. * @version 2.1 Alpha 1
  18. */
  19. if (!defined('SMF'))
  20. die('Hacking attempt...');
  21. /**
  22. * Create a thumbnail of the given source.
  23. *
  24. * @uses resizeImageFile() function to achieve the resize.
  25. *
  26. * @param string $source
  27. * @param int $max_width
  28. * @param int $max_height
  29. * @return bool, whether the thumbnail creation was successful.
  30. */
  31. function createThumbnail($source, $max_width, $max_height)
  32. {
  33. global $modSettings;
  34. $destName = $source . '_thumb.tmp';
  35. // Do the actual resize.
  36. if (!empty($modSettings['attachment_thumb_png']))
  37. $success = resizeImageFile($source, $destName, $max_width, $max_height, 3);
  38. else
  39. $success = resizeImageFile($source, $destName, $max_width, $max_height);
  40. // Okay, we're done with the temporary stuff.
  41. $destName = substr($destName, 0, -4);
  42. if ($success && @rename($destName . '.tmp', $destName))
  43. return true;
  44. else
  45. {
  46. @unlink($destName . '.tmp');
  47. @touch($destName);
  48. return false;
  49. }
  50. }
  51. /**
  52. * Creates a copy of the file at the same location as fileName.
  53. * The file would have the format preferred_format if possible,
  54. * otherwise the default format is jpeg.
  55. * The function makes sure that all non-essential image contents are disposed.
  56. *
  57. * @param string $fileName
  58. * @param int $preferred_format = 0
  59. * @return bool, true on success, false on failure.
  60. */
  61. function reencodeImage($fileName, $preferred_format = 0)
  62. {
  63. // There is nothing we can do without GD, sorry!
  64. if (!checkGD())
  65. return false;
  66. if (!resizeImageFile($fileName, $fileName . '.tmp', null, null, $preferred_format))
  67. {
  68. if (file_exists($fileName . '.tmp'))
  69. unlink($fileName . '.tmp');
  70. return false;
  71. }
  72. if (!unlink($fileName))
  73. return false;
  74. if (!rename($fileName . '.tmp', $fileName))
  75. return false;
  76. return true;
  77. }
  78. /**
  79. * Searches through the file to see if there's non-binary content.
  80. * If extensiveCheck is true, searches for asp/php short tags as well.
  81. *
  82. * @param string $fileName
  83. * @param bool $extensiveCheck = false
  84. * @return true on success, false on failure.
  85. */
  86. function checkImageContents($fileName, $extensiveCheck = false)
  87. {
  88. $fp = fopen($fileName, 'rb');
  89. if (!$fp)
  90. fatal_lang_error('attach_timeout');
  91. $prev_chunk = '';
  92. while (!feof($fp))
  93. {
  94. $cur_chunk = fread($fp, 8192);
  95. // Though not exhaustive lists, better safe than sorry.
  96. if (!empty($extensiveCheck))
  97. {
  98. // Paranoid check. Some like it that way.
  99. if (preg_match('~(iframe|\\<\\?|\\<%|html|eval|body|script\W|[CF]WS[\x01-\x0C])~i', $prev_chunk . $cur_chunk) === 1)
  100. {
  101. fclose($fp);
  102. return false;
  103. }
  104. }
  105. else
  106. {
  107. // Check for potential infection
  108. if (preg_match('~(iframe|html|eval|body|script\W|[CF]WS[\x01-\x0C])~i', $prev_chunk . $cur_chunk) === 1)
  109. {
  110. fclose($fp);
  111. return false;
  112. }
  113. }
  114. $prev_chunk = $cur_chunk;
  115. }
  116. fclose($fp);
  117. return true;
  118. }
  119. /**
  120. * Sets a global $gd2 variable needed by some functions to determine
  121. * whether the GD2 library is present.
  122. *
  123. * @return whether or not GD1 is available.
  124. */
  125. function checkGD()
  126. {
  127. global $gd2;
  128. // Check to see if GD is installed and what version.
  129. if (($extensionFunctions = get_extension_funcs('gd')) === false)
  130. return false;
  131. // Also determine if GD2 is installed and store it in a global.
  132. $gd2 = in_array('imagecreatetruecolor', $extensionFunctions) && function_exists('imagecreatetruecolor');
  133. return true;
  134. }
  135. /**
  136. * Resizes an image from a remote location or a local file.
  137. * Puts the resized image at the destination location.
  138. * The file would have the format preferred_format if possible,
  139. * otherwise the default format is jpeg.
  140. *
  141. * @param string $source
  142. * @param string $destination
  143. * @param int $max_width
  144. * @param int $max_height
  145. * @param int $preferred_format = 0
  146. * @return whether it succeeded.
  147. */
  148. function resizeImageFile($source, $destination, $max_width, $max_height, $preferred_format = 0)
  149. {
  150. global $sourcedir;
  151. // Nothing to do without GD
  152. if (!checkGD())
  153. return false;
  154. static $default_formats = array(
  155. '1' => 'gif',
  156. '2' => 'jpeg',
  157. '3' => 'png',
  158. '6' => 'bmp',
  159. '15' => 'wbmp'
  160. );
  161. require_once($sourcedir . '/Subs-Package.php');
  162. @ini_set('memory_limit', '90M');
  163. $success = false;
  164. // Get the image file, we have to work with something after all
  165. $fp_destination = fopen($destination, 'wb');
  166. if ($fp_destination && strpos($source, 'http://') === 0)
  167. {
  168. $fileContents = fetch_web_data($source);
  169. fwrite($fp_destination, $fileContents);
  170. fclose($fp_destination);
  171. $sizes = @getimagesize($destination);
  172. }
  173. elseif ($fp_destination)
  174. {
  175. $sizes = @getimagesize($source);
  176. $fp_source = fopen($source, 'rb');
  177. if ($fp_source !== false)
  178. {
  179. while (!feof($fp_source))
  180. fwrite($fp_destination, fread($fp_source, 8192));
  181. fclose($fp_source);
  182. }
  183. else
  184. $sizes = array(-1, -1, -1);
  185. fclose($fp_destination);
  186. }
  187. // We can't get to the file.
  188. else
  189. $sizes = array(-1, -1, -1);
  190. // A known and supported format?
  191. // @todo test PSD and gif.
  192. if (isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]]))
  193. {
  194. $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
  195. if ($src_img = @$imagecreatefrom($destination))
  196. {
  197. resizeImage($src_img, $destination, imagesx($src_img), imagesy($src_img), $max_width === null ? imagesx($src_img) : $max_width, $max_height === null ? imagesy($src_img) : $max_height, true, $preferred_format);
  198. $success = true;
  199. }
  200. }
  201. return $success;
  202. }
  203. /**
  204. * Resizes src_img proportionally to fit within max_width and max_height limits
  205. * if it is too large.
  206. * If GD2 is present, it'll use it to achieve better quality.
  207. * It saves the new image to destination_filename, as preferred_format
  208. * if possible, default is jpeg.
  209. * @uses GD
  210. *
  211. * @param resource $src_img
  212. * @param string $destName
  213. * @param int $src_width
  214. * @param int $src_height
  215. * @param int $max_width
  216. * @param int $max_height
  217. * @param bool $force_resize = false
  218. * @param int $preferred_format = 0
  219. */
  220. function resizeImage($src_img, $destName, $src_width, $src_height, $max_width, $max_height, $force_resize = false, $preferred_format = 0)
  221. {
  222. global $gd2, $modSettings;
  223. // Without GD, no image resizing at all.
  224. if (!checkGD())
  225. return false;
  226. $success = false;
  227. // Determine whether to resize to max width or to max height (depending on the limits.)
  228. if (!empty($max_width) || !empty($max_height))
  229. {
  230. if (!empty($max_width) && (empty($max_height) || $src_height * $max_width / $src_width <= $max_height))
  231. {
  232. $dst_width = $max_width;
  233. $dst_height = floor($src_height * $max_width / $src_width);
  234. }
  235. elseif (!empty($max_height))
  236. {
  237. $dst_width = floor($src_width * $max_height / $src_height);
  238. $dst_height = $max_height;
  239. }
  240. // Don't bother resizing if it's already smaller...
  241. if (!empty($dst_width) && !empty($dst_height) && ($dst_width < $src_width || $dst_height < $src_height || $force_resize))
  242. {
  243. // (make a true color image, because it just looks better for resizing.)
  244. if ($gd2)
  245. {
  246. $dst_img = imagecreatetruecolor($dst_width, $dst_height);
  247. // Deal nicely with a PNG - because we can.
  248. if ((!empty($preferred_format)) && ($preferred_format == 3))
  249. {
  250. imagealphablending($dst_img, false);
  251. if (function_exists('imagesavealpha'))
  252. imagesavealpha($dst_img, true);
  253. }
  254. }
  255. else
  256. $dst_img = imagecreate($dst_width, $dst_height);
  257. // Resize it!
  258. if ($gd2)
  259. imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  260. else
  261. imagecopyresamplebicubic($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  262. }
  263. else
  264. $dst_img = $src_img;
  265. }
  266. else
  267. $dst_img = $src_img;
  268. // Save the image as ...
  269. if (!empty($preferred_format) && ($preferred_format == 3) && function_exists('imagepng'))
  270. $success = imagepng($dst_img, $destName);
  271. elseif (!empty($preferred_format) && ($preferred_format == 1) && function_exists('imagegif'))
  272. $success = imagegif($dst_img, $destName);
  273. elseif (function_exists('imagejpeg'))
  274. $success = imagejpeg($dst_img, $destName);
  275. // Free the memory.
  276. imagedestroy($src_img);
  277. if ($dst_img != $src_img)
  278. imagedestroy($dst_img);
  279. return $success;
  280. }
  281. /**
  282. * Copy image.
  283. * Used when imagecopyresample() is not available.
  284. * @param resource $dst_img
  285. * @param resource $src_img
  286. * @param int $dst_x
  287. * @param int $dst_y
  288. * @param int $src_x
  289. * @param int $src_y
  290. * @param int $dst_w
  291. * @param int $dst_h
  292. * @param int $src_w
  293. * @param int $src_h
  294. */
  295. function imagecopyresamplebicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
  296. {
  297. $palsize = imagecolorstotal($src_img);
  298. for ($i = 0; $i < $palsize; $i++)
  299. {
  300. $colors = imagecolorsforindex($src_img, $i);
  301. imagecolorallocate($dst_img, $colors['red'], $colors['green'], $colors['blue']);
  302. }
  303. $scaleX = ($src_w - 1) / $dst_w;
  304. $scaleY = ($src_h - 1) / $dst_h;
  305. $scaleX2 = (int) $scaleX / 2;
  306. $scaleY2 = (int) $scaleY / 2;
  307. for ($j = $src_y; $j < $dst_h; $j++)
  308. {
  309. $sY = (int) $j * $scaleY;
  310. $y13 = $sY + $scaleY2;
  311. for ($i = $src_x; $i < $dst_w; $i++)
  312. {
  313. $sX = (int) $i * $scaleX;
  314. $x34 = $sX + $scaleX2;
  315. $color1 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $y13));
  316. $color2 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $sY));
  317. $color3 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $y13));
  318. $color4 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $sY));
  319. $red = ($color1['red'] + $color2['red'] + $color3['red'] + $color4['red']) / 4;
  320. $green = ($color1['green'] + $color2['green'] + $color3['green'] + $color4['green']) / 4;
  321. $blue = ($color1['blue'] + $color2['blue'] + $color3['blue'] + $color4['blue']) / 4;
  322. $color = imagecolorresolve($dst_img, $red, $green, $blue);
  323. if ($color == -1)
  324. {
  325. if ($palsize++ < 256)
  326. imagecolorallocate($dst_img, $red, $green, $blue);
  327. $color = imagecolorclosest($dst_img, $red, $green, $blue);
  328. }
  329. imagesetpixel($dst_img, $i + $dst_x - $src_x, $j + $dst_y - $src_y, $color);
  330. }
  331. }
  332. }
  333. if (!function_exists('imagecreatefrombmp'))
  334. {
  335. /**
  336. * It is set only if it doesn't already exist (for forwards compatiblity.)
  337. * It only supports uncompressed bitmaps.
  338. *
  339. * @param string $filename
  340. * @return resource, an image identifier representing the bitmap image
  341. * obtained from the given filename.
  342. */
  343. function imagecreatefrombmp($filename)
  344. {
  345. global $gd2;
  346. $fp = fopen($filename, 'rb');
  347. $errors = error_reporting(0);
  348. $header = unpack('vtype/Vsize/Vreserved/Voffset', fread($fp, 14));
  349. $info = unpack('Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vcolorimportant', fread($fp, 40));
  350. if ($header['type'] != 0x4D42)
  351. false;
  352. if ($gd2)
  353. $dst_img = imagecreatetruecolor($info['width'], $info['height']);
  354. else
  355. $dst_img = imagecreate($info['width'], $info['height']);
  356. $palette_size = $header['offset'] - 54;
  357. $info['ncolor'] = $palette_size / 4;
  358. $palette = array();
  359. $palettedata = fread($fp, $palette_size);
  360. $n = 0;
  361. for ($j = 0; $j < $palette_size; $j++)
  362. {
  363. $b = ord($palettedata{$j++});
  364. $g = ord($palettedata{$j++});
  365. $r = ord($palettedata{$j++});
  366. $palette[$n++] = imagecolorallocate($dst_img, $r, $g, $b);
  367. }
  368. $scan_line_size = ($info['bits'] * $info['width'] + 7) >> 3;
  369. $scan_line_align = $scan_line_size & 3 ? 4 - ($scan_line_size & 3) : 0;
  370. for ($y = 0, $l = $info['height'] - 1; $y < $info['height']; $y++, $l--)
  371. {
  372. fseek($fp, $header['offset'] + ($scan_line_size + $scan_line_align) * $l);
  373. $scan_line = fread($fp, $scan_line_size);
  374. if (strlen($scan_line) < $scan_line_size)
  375. continue;
  376. if ($info['bits'] == 32)
  377. {
  378. $x = 0;
  379. for ($j = 0; $j < $scan_line_size; $x++)
  380. {
  381. $b = ord($scan_line{$j++});
  382. $g = ord($scan_line{$j++});
  383. $r = ord($scan_line{$j++});
  384. $j++;
  385. $color = imagecolorexact($dst_img, $r, $g, $b);
  386. if ($color == -1)
  387. {
  388. $color = imagecolorallocate($dst_img, $r, $g, $b);
  389. // Gah! Out of colors? Stupid GD 1... try anyhow.
  390. if ($color == -1)
  391. $color = imagecolorclosest($dst_img, $r, $g, $b);
  392. }
  393. imagesetpixel($dst_img, $x, $y, $color);
  394. }
  395. }
  396. elseif ($info['bits'] == 24)
  397. {
  398. $x = 0;
  399. for ($j = 0; $j < $scan_line_size; $x++)
  400. {
  401. $b = ord($scan_line{$j++});
  402. $g = ord($scan_line{$j++});
  403. $r = ord($scan_line{$j++});
  404. $color = imagecolorexact($dst_img, $r, $g, $b);
  405. if ($color == -1)
  406. {
  407. $color = imagecolorallocate($dst_img, $r, $g, $b);
  408. // Gah! Out of colors? Stupid GD 1... try anyhow.
  409. if ($color == -1)
  410. $color = imagecolorclosest($dst_img, $r, $g, $b);
  411. }
  412. imagesetpixel($dst_img, $x, $y, $color);
  413. }
  414. }
  415. elseif ($info['bits'] == 16)
  416. {
  417. $x = 0;
  418. for ($j = 0; $j < $scan_line_size; $x++)
  419. {
  420. $b1 = ord($scan_line{$j++});
  421. $b2 = ord($scan_line{$j++});
  422. $word = $b2 * 256 + $b1;
  423. $b = (($word & 31) * 255) / 31;
  424. $g = ((($word >> 5) & 31) * 255) / 31;
  425. $r = ((($word >> 10) & 31) * 255) / 31;
  426. // Scale the image colors up properly.
  427. $color = imagecolorexact($dst_img, $r, $g, $b);
  428. if ($color == -1)
  429. {
  430. $color = imagecolorallocate($dst_img, $r, $g, $b);
  431. // Gah! Out of colors? Stupid GD 1... try anyhow.
  432. if ($color == -1)
  433. $color = imagecolorclosest($dst_img, $r, $g, $b);
  434. }
  435. imagesetpixel($dst_img, $x, $y, $color);
  436. }
  437. }
  438. elseif ($info['bits'] == 8)
  439. {
  440. $x = 0;
  441. for ($j = 0; $j < $scan_line_size; $x++)
  442. imagesetpixel($dst_img, $x, $y, $palette[ord($scan_line{$j++})]);
  443. }
  444. elseif ($info['bits'] == 4)
  445. {
  446. $x = 0;
  447. for ($j = 0; $j < $scan_line_size; $x++)
  448. {
  449. $byte = ord($scan_line{$j++});
  450. imagesetpixel($dst_img, $x, $y, $palette[(int) ($byte / 16)]);
  451. if (++$x < $info['width'])
  452. imagesetpixel($dst_img, $x, $y, $palette[$byte & 15]);
  453. }
  454. }
  455. else
  456. {
  457. // Sorry, I'm just not going to do monochrome :P.
  458. }
  459. }
  460. fclose($fp);
  461. error_reporting($errors);
  462. return $dst_img;
  463. }
  464. }
  465. /**
  466. * Writes a gif file to disk as a png file.
  467. * @param resource $gif
  468. * @param string $lpszFileName
  469. * @param int $background_color = -1
  470. * @return bool, whether it was successful or not.
  471. */
  472. function gif_outputAsPng($gif, $lpszFileName, $background_color = -1)
  473. {
  474. if (!isset($gif) || @get_class($gif) != 'cgif' || !$gif->loaded || $lpszFileName == '')
  475. return false;
  476. $fd = $gif->get_png_data($background_color);
  477. if (strlen($fd) <= 0)
  478. return false;
  479. if (!($fh = @fopen($lpszFileName, 'wb')))
  480. return false;
  481. @fwrite($fh, $fd, strlen($fd));
  482. @fflush($fh);
  483. @fclose($fh);
  484. return true;
  485. }
  486. /**
  487. * Show an image containing the visual verification code for registration.
  488. * Requires the GD extension.
  489. * Uses a random font for each letter from default_theme_dir/fonts.
  490. * Outputs a gif or a png (depending on whether gif ix supported).
  491. *
  492. * @param string $code
  493. * @return false if something goes wrong.
  494. */
  495. function showCodeImage($code)
  496. {
  497. global $settings, $user_info, $modSettings;
  498. // Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
  499. // What type are we going to be doing?
  500. $imageType = $modSettings['visual_verification_type'];
  501. // Special case to allow the admin center to show samples.
  502. if ($user_info['is_admin'] && isset($_GET['type']))
  503. $imageType = (int) $_GET['type'];
  504. // Some quick references for what we do.
  505. // Do we show no, low or high noise?
  506. $noiseType = $imageType == 3 ? 'low' : ($imageType == 4 ? 'high' : ($imageType == 5 ? 'extreme' : 'none'));
  507. // Can we have more than one font in use?
  508. $varyFonts = $imageType > 3 ? true : false;
  509. // Just a plain white background?
  510. $simpleBGColor = $imageType < 3 ? true : false;
  511. // Plain black foreground?
  512. $simpleFGColor = $imageType == 0 ? true : false;
  513. // High much to rotate each character.
  514. $rotationType = $imageType == 1 ? 'none' : ($imageType > 3 ? 'low' : 'high');
  515. // Do we show some characters inversed?
  516. $showReverseChars = $imageType > 3 ? true : false;
  517. // Special case for not showing any characters.
  518. $disableChars = $imageType == 0 ? true : false;
  519. // What do we do with the font colors. Are they one color, close to one color or random?
  520. $fontColorType = $imageType == 1 ? 'plain' : ($imageType > 3 ? 'random' : 'cyclic');
  521. // Are the fonts random sizes?
  522. $fontSizeRandom = $imageType > 3 ? true : false;
  523. // How much space between characters?
  524. $fontHorSpace = $imageType > 3 ? 'high' : ($imageType == 1 ? 'medium' : 'minus');
  525. // Where do characters sit on the image? (Fixed position or random/very random)
  526. $fontVerPos = $imageType == 1 ? 'fixed' : ($imageType > 3 ? 'vrandom' : 'random');
  527. // Make font semi-transparent?
  528. $fontTrans = $imageType == 2 || $imageType == 3 ? true : false;
  529. // Give the image a border?
  530. $hasBorder = $simpleBGColor;
  531. // Is this GD2? Needed for pixel size.
  532. $testGD = get_extension_funcs('gd');
  533. $gd2 = in_array('imagecreatetruecolor', $testGD) && function_exists('imagecreatetruecolor');
  534. unset($testGD);
  535. // The amount of pixels inbetween characters.
  536. $character_spacing = 1;
  537. // What color is the background - generally white unless we're on "hard".
  538. if ($simpleBGColor)
  539. $background_color = array(255, 255, 255);
  540. else
  541. $background_color = isset($settings['verification_background']) ? $settings['verification_background'] : array(236, 237, 243);
  542. // The color of the characters shown (red, green, blue).
  543. if ($simpleFGColor)
  544. $foreground_color = array(0, 0, 0);
  545. else
  546. {
  547. $foreground_color = array(64, 101, 136);
  548. // Has the theme author requested a custom color?
  549. if (isset($settings['verification_foreground']))
  550. $foreground_color = $settings['verification_foreground'];
  551. }
  552. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  553. return false;
  554. // Get a list of the available fonts.
  555. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  556. $font_list = array();
  557. $ttfont_list = array();
  558. while ($entry = $font_dir->read())
  559. {
  560. if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
  561. $font_list[] = $entry;
  562. elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
  563. $ttfont_list[] = $entry;
  564. }
  565. if (empty($font_list))
  566. return false;
  567. // For non-hard things don't even change fonts.
  568. if (!$varyFonts)
  569. {
  570. $font_list = array($font_list[0]);
  571. // Try use Screenge if we can - it looks good!
  572. if (in_array('Screenge.ttf', $ttfont_list))
  573. $ttfont_list = array('Screenge.ttf');
  574. else
  575. $ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
  576. }
  577. // Create a list of characters to be shown.
  578. $characters = array();
  579. $loaded_fonts = array();
  580. for ($i = 0; $i < strlen($code); $i++)
  581. {
  582. $characters[$i] = array(
  583. 'id' => $code{$i},
  584. 'font' => array_rand($font_list),
  585. );
  586. $loaded_fonts[$characters[$i]['font']] = null;
  587. }
  588. // Load all fonts and determine the maximum font height.
  589. foreach ($loaded_fonts as $font_index => $dummy)
  590. $loaded_fonts[$font_index] = imageloadfont($settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
  591. // Determine the dimensions of each character.
  592. $total_width = $character_spacing * strlen($code) + 20;
  593. $max_height = 0;
  594. foreach ($characters as $char_index => $character)
  595. {
  596. $characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
  597. $characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
  598. $max_height = max($characters[$char_index]['height'] + 5, $max_height);
  599. $total_width += $characters[$char_index]['width'];
  600. }
  601. // Create an image.
  602. $code_image = $gd2 ? imagecreatetruecolor($total_width, $max_height) : imagecreate($total_width, $max_height);
  603. // Draw the background.
  604. $bg_color = imagecolorallocate($code_image, $background_color[0], $background_color[1], $background_color[2]);
  605. imagefilledrectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $bg_color);
  606. // Randomize the foreground color a little.
  607. for ($i = 0; $i < 3; $i++)
  608. $foreground_color[$i] = mt_rand(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
  609. $fg_color = imagecolorallocate($code_image, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
  610. // Color for the dots.
  611. for ($i = 0; $i < 3; $i++)
  612. $dotbgcolor[$i] = $background_color[$i] < $foreground_color[$i] ? mt_rand(0, max($foreground_color[$i] - 20, 0)) : mt_rand(min($foreground_color[$i] + 20, 255), 255);
  613. $randomness_color = imagecolorallocate($code_image, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
  614. // Some squares/rectanges for new extreme level
  615. if ($noiseType == 'extreme')
  616. {
  617. for ($i = 0; $i < rand(1, 5); $i++)
  618. {
  619. $x1 = rand(0, $total_width / 4);
  620. $x2 = $x1 + round(rand($total_width / 4, $total_width));
  621. $y1 = rand(0, $max_height);
  622. $y2 = $y1 + round(rand(0, $max_height / 3));
  623. imagefilledrectangle($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  624. }
  625. }
  626. // Fill in the characters.
  627. if (!$disableChars)
  628. {
  629. $cur_x = 0;
  630. foreach ($characters as $char_index => $character)
  631. {
  632. // Can we use true type fonts?
  633. $can_do_ttf = function_exists('imagettftext');
  634. // How much rotation will we give?
  635. if ($rotationType == 'none')
  636. $angle = 0;
  637. else
  638. $angle = mt_rand(-100, 100) / ($rotationType == 'high' ? 6 : 10);
  639. // What color shall we do it?
  640. if ($fontColorType == 'cyclic')
  641. {
  642. // Here we'll pick from a set of acceptance types.
  643. $colors = array(
  644. array(10, 120, 95),
  645. array(46, 81, 29),
  646. array(4, 22, 154),
  647. array(131, 9, 130),
  648. array(0, 0, 0),
  649. array(143, 39, 31),
  650. );
  651. if (!isset($last_index))
  652. $last_index = -1;
  653. $new_index = $last_index;
  654. while ($last_index == $new_index)
  655. $new_index = mt_rand(0, count($colors) - 1);
  656. $char_fg_color = $colors[$new_index];
  657. $last_index = $new_index;
  658. }
  659. elseif ($fontColorType == 'random')
  660. $char_fg_color = array(mt_rand(max($foreground_color[0] - 2, 0), $foreground_color[0]), mt_rand(max($foreground_color[1] - 2, 0), $foreground_color[1]), mt_rand(max($foreground_color[2] - 2, 0), $foreground_color[2]));
  661. else
  662. $char_fg_color = array($foreground_color[0], $foreground_color[1], $foreground_color[2]);
  663. if (!empty($can_do_ttf))
  664. {
  665. // GD2 handles font size differently.
  666. if ($fontSizeRandom)
  667. $font_size = $gd2 ? mt_rand(17, 19) : mt_rand(18, 25);
  668. else
  669. $font_size = $gd2 ? 18 : 24;
  670. // Work out the sizes - also fix the character width cause TTF not quite so wide!
  671. $font_x = $fontHorSpace == 'minus' && $cur_x > 0 ? $cur_x - 3 : $cur_x + 5;
  672. $font_y = $max_height - ($fontVerPos == 'vrandom' ? mt_rand(2, 8) : ($fontVerPos == 'random' ? mt_rand(3, 5) : 5));
  673. // What font face?
  674. if (!empty($ttfont_list))
  675. $fontface = $settings['default_theme_dir'] . '/fonts/' . $ttfont_list[mt_rand(0, count($ttfont_list) - 1)];
  676. // What color are we to do it in?
  677. $is_reverse = $showReverseChars ? mt_rand(0, 1) : false;
  678. $char_color = function_exists('imagecolorallocatealpha') && $fontTrans ? imagecolorallocatealpha($code_image, $char_fg_color[0], $char_fg_color[1], $char_fg_color[2], 50) : imagecolorallocate($code_image, $char_fg_color[0], $char_fg_color[1], $char_fg_color[2]);
  679. $fontcord = @imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $char_color, $fontface, $character['id']);
  680. if (empty($fontcord))
  681. $can_do_ttf = false;
  682. elseif ($is_reverse)
  683. {
  684. imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
  685. // Put the character back!
  686. imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $randomness_color, $fontface, $character['id']);
  687. }
  688. if ($can_do_ttf)
  689. $cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
  690. }
  691. if (!$can_do_ttf)
  692. {
  693. // Rotating the characters a little...
  694. if (function_exists('imagerotate'))
  695. {
  696. $char_image = $gd2 ? imagecreatetruecolor($character['width'], $character['height']) : imagecreate($character['width'], $character['height']);
  697. $char_bgcolor = imagecolorallocate($char_image, $background_color[0], $background_color[1], $background_color[2]);
  698. imagefilledrectangle($char_image, 0, 0, $character['width'] - 1, $character['height'] - 1, $char_bgcolor);
  699. imagechar($char_image, $loaded_fonts[$character['font']], 0, 0, $character['id'], imagecolorallocate($char_image, $char_fg_color[0], $char_fg_color[1], $char_fg_color[2]));
  700. $rotated_char = imagerotate($char_image, mt_rand(-100, 100) / 10, $char_bgcolor);
  701. imagecopy($code_image, $rotated_char, $cur_x, 0, 0, 0, $character['width'], $character['height']);
  702. imagedestroy($rotated_char);
  703. imagedestroy($char_image);
  704. }
  705. // Sorry, no rotation available.
  706. else
  707. imagechar($code_image, $loaded_fonts[$character['font']], $cur_x, floor(($max_height - $character['height']) / 2), $character['id'], imagecolorallocate($code_image, $char_fg_color[0], $char_fg_color[1], $char_fg_color[2]));
  708. $cur_x += $character['width'] + $character_spacing;
  709. }
  710. }
  711. }
  712. // If disabled just show a cross.
  713. else
  714. {
  715. imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
  716. imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
  717. }
  718. // Make the background color transparent on the hard image.
  719. if (!$simpleBGColor)
  720. imagecolortransparent($code_image, $bg_color);
  721. if ($hasBorder)
  722. imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
  723. // Add some noise to the background?
  724. if ($noiseType != 'none')
  725. {
  726. for ($i = mt_rand(0, 2); $i < $max_height; $i += mt_rand(1, 2))
  727. for ($j = mt_rand(0, 10); $j < $total_width; $j += mt_rand(1, 10))
  728. imagesetpixel($code_image, $j, $i, mt_rand(0, 1) ? $fg_color : $randomness_color);
  729. // Put in some lines too?
  730. if ($noiseType != 'extreme')
  731. {
  732. $num_lines = $noiseType == 'high' ? mt_rand(3, 7) : mt_rand(2, 5);
  733. for ($i = 0; $i < $num_lines; $i++)
  734. {
  735. if (mt_rand(0, 1))
  736. {
  737. $x1 = mt_rand(0, $total_width);
  738. $x2 = mt_rand(0, $total_width);
  739. $y1 = 0; $y2 = $max_height;
  740. }
  741. else
  742. {
  743. $y1 = mt_rand(0, $max_height);
  744. $y2 = mt_rand(0, $max_height);
  745. $x1 = 0; $x2 = $total_width;
  746. }
  747. imagesetthickness($code_image, mt_rand(1, 2));
  748. imageline($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  749. }
  750. }
  751. else
  752. {
  753. // Put in some ellipse
  754. $num_ellipse = $noiseType == 'extreme' ? mt_rand(6, 12) : mt_rand(2, 6);
  755. for ($i = 0; $i < $num_ellipse; $i++)
  756. {
  757. $x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
  758. $x2 = round(rand($total_width / 2, 2 * $total_width));
  759. $y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
  760. $y2 = round(rand($max_height / 2, 2 * $max_height));
  761. imageellipse($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  762. }
  763. }
  764. }
  765. // Show the image.
  766. if (function_exists('imagegif'))
  767. {
  768. header('Content-type: image/gif');
  769. imagegif($code_image);
  770. }
  771. else
  772. {
  773. header('Content-type: image/png');
  774. imagepng($code_image);
  775. }
  776. // Bail out.
  777. imagedestroy($code_image);
  778. die();
  779. }
  780. /**
  781. * Show a letter for the visual verification code.
  782. * Alternative function for showCodeImage() in case GD is missing.
  783. * Includes an image from a random sub directory of default_theme_dir/fonts.
  784. *
  785. * @param string $letter
  786. */
  787. function showLetterImage($letter)
  788. {
  789. global $settings;
  790. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  791. return false;
  792. // Get a list of the available font directories.
  793. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  794. $font_list = array();
  795. while ($entry = $font_dir->read())
  796. if ($entry[0] !== '.' && is_dir($settings['default_theme_dir'] . '/fonts/' . $entry) && file_exists($settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf'))
  797. $font_list[] = $entry;
  798. if (empty($font_list))
  799. return false;
  800. // Pick a random font.
  801. $random_font = $font_list[array_rand($font_list)];
  802. // Check if the given letter exists.
  803. if (!file_exists($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif'))
  804. return false;
  805. // Include it!
  806. header('Content-type: image/gif');
  807. include($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif');
  808. // Nothing more to come.
  809. die();
  810. }
  811. ?>