Subs-Graphics.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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. /*
  499. Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
  500. */
  501. // What type are we going to be doing?
  502. $imageType = $modSettings['visual_verification_type'];
  503. // Special case to allow the admin center to show samples.
  504. if ($user_info['is_admin'] && isset($_GET['type']))
  505. $imageType = (int) $_GET['type'];
  506. // Some quick references for what we do.
  507. // Do we show no, low or high noise?
  508. $noiseType = $imageType == 3 ? 'low' : ($imageType == 4 ? 'high' : ($imageType == 5 ? 'extreme' : 'none'));
  509. // Can we have more than one font in use?
  510. $varyFonts = $imageType > 3 ? true : false;
  511. // Just a plain white background?
  512. $simpleBGColor = $imageType < 3 ? true : false;
  513. // Plain black foreground?
  514. $simpleFGColor = $imageType == 0 ? true : false;
  515. // High much to rotate each character.
  516. $rotationType = $imageType == 1 ? 'none' : ($imageType > 3 ? 'low' : 'high');
  517. // Do we show some characters inversed?
  518. $showReverseChars = $imageType > 3 ? true : false;
  519. // Special case for not showing any characters.
  520. $disableChars = $imageType == 0 ? true : false;
  521. // What do we do with the font colors. Are they one color, close to one color or random?
  522. $fontColorType = $imageType == 1 ? 'plain' : ($imageType > 3 ? 'random' : 'cyclic');
  523. // Are the fonts random sizes?
  524. $fontSizeRandom = $imageType > 3 ? true : false;
  525. // How much space between characters?
  526. $fontHorSpace = $imageType > 3 ? 'high' : ($imageType == 1 ? 'medium' : 'minus');
  527. // Where do characters sit on the image? (Fixed position or random/very random)
  528. $fontVerPos = $imageType == 1 ? 'fixed' : ($imageType > 3 ? 'vrandom' : 'random');
  529. // Make font semi-transparent?
  530. $fontTrans = $imageType == 2 || $imageType == 3 ? true : false;
  531. // Give the image a border?
  532. $hasBorder = $simpleBGColor;
  533. // Is this GD2? Needed for pixel size.
  534. $testGD = get_extension_funcs('gd');
  535. $gd2 = in_array('imagecreatetruecolor', $testGD) && function_exists('imagecreatetruecolor');
  536. unset($testGD);
  537. // The amount of pixels inbetween characters.
  538. $character_spacing = 1;
  539. // What color is the background - generally white unless we're on "hard".
  540. if ($simpleBGColor)
  541. $background_color = array(255, 255, 255);
  542. else
  543. $background_color = isset($settings['verification_background']) ? $settings['verification_background'] : array(236, 237, 243);
  544. // The color of the characters shown (red, green, blue).
  545. if ($simpleFGColor)
  546. $foreground_color = array(0, 0, 0);
  547. else
  548. {
  549. $foreground_color = array(64, 101, 136);
  550. // Has the theme author requested a custom color?
  551. if (isset($settings['verification_foreground']))
  552. $foreground_color = $settings['verification_foreground'];
  553. }
  554. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  555. return false;
  556. // Get a list of the available fonts.
  557. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  558. $font_list = array();
  559. $ttfont_list = array();
  560. while ($entry = $font_dir->read())
  561. {
  562. if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
  563. $font_list[] = $entry;
  564. elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
  565. $ttfont_list[] = $entry;
  566. }
  567. if (empty($font_list))
  568. return false;
  569. // For non-hard things don't even change fonts.
  570. if (!$varyFonts)
  571. {
  572. $font_list = array($font_list[0]);
  573. // Try use Screenge if we can - it looks good!
  574. if (in_array('Screenge.ttf', $ttfont_list))
  575. $ttfont_list = array('Screenge.ttf');
  576. else
  577. $ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
  578. }
  579. // Create a list of characters to be shown.
  580. $characters = array();
  581. $loaded_fonts = array();
  582. for ($i = 0; $i < strlen($code); $i++)
  583. {
  584. $characters[$i] = array(
  585. 'id' => $code{$i},
  586. 'font' => array_rand($font_list),
  587. );
  588. $loaded_fonts[$characters[$i]['font']] = null;
  589. }
  590. // Load all fonts and determine the maximum font height.
  591. foreach ($loaded_fonts as $font_index => $dummy)
  592. $loaded_fonts[$font_index] = imageloadfont($settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
  593. // Determine the dimensions of each character.
  594. $total_width = $character_spacing * strlen($code) + 20;
  595. $max_height = 0;
  596. foreach ($characters as $char_index => $character)
  597. {
  598. $characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
  599. $characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
  600. $max_height = max($characters[$char_index]['height'] + 5, $max_height);
  601. $total_width += $characters[$char_index]['width'];
  602. }
  603. // Create an image.
  604. $code_image = $gd2 ? imagecreatetruecolor($total_width, $max_height) : imagecreate($total_width, $max_height);
  605. // Draw the background.
  606. $bg_color = imagecolorallocate($code_image, $background_color[0], $background_color[1], $background_color[2]);
  607. imagefilledrectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $bg_color);
  608. // Randomize the foreground color a little.
  609. for ($i = 0; $i < 3; $i++)
  610. $foreground_color[$i] = mt_rand(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
  611. $fg_color = imagecolorallocate($code_image, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
  612. // Color for the dots.
  613. for ($i = 0; $i < 3; $i++)
  614. $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);
  615. $randomness_color = imagecolorallocate($code_image, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
  616. // Some squares/rectanges for new extreme level
  617. if ($noiseType == 'extreme')
  618. {
  619. for ($i = 0; $i < rand(1, 5); $i++)
  620. {
  621. $x1 = rand(0, $total_width / 4);
  622. $x2 = $x1 + round(rand($total_width / 4, $total_width));
  623. $y1 = rand(0, $max_height);
  624. $y2 = $y1 + round(rand(0, $max_height / 3));
  625. imagefilledrectangle($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  626. }
  627. }
  628. // Fill in the characters.
  629. if (!$disableChars)
  630. {
  631. $cur_x = 0;
  632. foreach ($characters as $char_index => $character)
  633. {
  634. // Can we use true type fonts?
  635. $can_do_ttf = function_exists('imagettftext');
  636. // How much rotation will we give?
  637. if ($rotationType == 'none')
  638. $angle = 0;
  639. else
  640. $angle = mt_rand(-100, 100) / ($rotationType == 'high' ? 6 : 10);
  641. // What color shall we do it?
  642. if ($fontColorType == 'cyclic')
  643. {
  644. // Here we'll pick from a set of acceptance types.
  645. $colors = array(
  646. array(10, 120, 95),
  647. array(46, 81, 29),
  648. array(4, 22, 154),
  649. array(131, 9, 130),
  650. array(0, 0, 0),
  651. array(143, 39, 31),
  652. );
  653. if (!isset($last_index))
  654. $last_index = -1;
  655. $new_index = $last_index;
  656. while ($last_index == $new_index)
  657. $new_index = mt_rand(0, count($colors) - 1);
  658. $char_fg_color = $colors[$new_index];
  659. $last_index = $new_index;
  660. }
  661. elseif ($fontColorType == 'random')
  662. $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]));
  663. else
  664. $char_fg_color = array($foreground_color[0], $foreground_color[1], $foreground_color[2]);
  665. if (!empty($can_do_ttf))
  666. {
  667. // GD2 handles font size differently.
  668. if ($fontSizeRandom)
  669. $font_size = $gd2 ? mt_rand(17, 19) : mt_rand(18, 25);
  670. else
  671. $font_size = $gd2 ? 18 : 24;
  672. // Work out the sizes - also fix the character width cause TTF not quite so wide!
  673. $font_x = $fontHorSpace == 'minus' && $cur_x > 0 ? $cur_x - 3 : $cur_x + 5;
  674. $font_y = $max_height - ($fontVerPos == 'vrandom' ? mt_rand(2, 8) : ($fontVerPos == 'random' ? mt_rand(3, 5) : 5));
  675. // What font face?
  676. if (!empty($ttfont_list))
  677. $fontface = $settings['default_theme_dir'] . '/fonts/' . $ttfont_list[mt_rand(0, count($ttfont_list) - 1)];
  678. // What color are we to do it in?
  679. $is_reverse = $showReverseChars ? mt_rand(0, 1) : false;
  680. $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]);
  681. $fontcord = @imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $char_color, $fontface, $character['id']);
  682. if (empty($fontcord))
  683. $can_do_ttf = false;
  684. elseif ($is_reverse)
  685. {
  686. imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
  687. // Put the character back!
  688. imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $randomness_color, $fontface, $character['id']);
  689. }
  690. if ($can_do_ttf)
  691. $cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
  692. }
  693. if (!$can_do_ttf)
  694. {
  695. // Rotating the characters a little...
  696. if (function_exists('imagerotate'))
  697. {
  698. $char_image = $gd2 ? imagecreatetruecolor($character['width'], $character['height']) : imagecreate($character['width'], $character['height']);
  699. $char_bgcolor = imagecolorallocate($char_image, $background_color[0], $background_color[1], $background_color[2]);
  700. imagefilledrectangle($char_image, 0, 0, $character['width'] - 1, $character['height'] - 1, $char_bgcolor);
  701. 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]));
  702. $rotated_char = imagerotate($char_image, mt_rand(-100, 100) / 10, $char_bgcolor);
  703. imagecopy($code_image, $rotated_char, $cur_x, 0, 0, 0, $character['width'], $character['height']);
  704. imagedestroy($rotated_char);
  705. imagedestroy($char_image);
  706. }
  707. // Sorry, no rotation available.
  708. else
  709. 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]));
  710. $cur_x += $character['width'] + $character_spacing;
  711. }
  712. }
  713. }
  714. // If disabled just show a cross.
  715. else
  716. {
  717. imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
  718. imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
  719. }
  720. // Make the background color transparent on the hard image.
  721. if (!$simpleBGColor)
  722. imagecolortransparent($code_image, $bg_color);
  723. if ($hasBorder)
  724. imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
  725. // Add some noise to the background?
  726. if ($noiseType != 'none')
  727. {
  728. for ($i = mt_rand(0, 2); $i < $max_height; $i += mt_rand(1, 2))
  729. for ($j = mt_rand(0, 10); $j < $total_width; $j += mt_rand(1, 10))
  730. imagesetpixel($code_image, $j, $i, mt_rand(0, 1) ? $fg_color : $randomness_color);
  731. // Put in some lines too?
  732. if ($noiseType != 'extreme')
  733. {
  734. $num_lines = $noiseType == 'high' ? mt_rand(3, 7) : mt_rand(2, 5);
  735. for ($i = 0; $i < $num_lines; $i++)
  736. {
  737. if (mt_rand(0, 1))
  738. {
  739. $x1 = mt_rand(0, $total_width);
  740. $x2 = mt_rand(0, $total_width);
  741. $y1 = 0; $y2 = $max_height;
  742. }
  743. else
  744. {
  745. $y1 = mt_rand(0, $max_height);
  746. $y2 = mt_rand(0, $max_height);
  747. $x1 = 0; $x2 = $total_width;
  748. }
  749. imagesetthickness($code_image, mt_rand(1, 2));
  750. imageline($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  751. }
  752. }
  753. else
  754. {
  755. // Put in some ellipse
  756. $num_ellipse = $noiseType == 'extreme' ? mt_rand(6, 12) : mt_rand(2, 6);
  757. for ($i = 0; $i < $num_ellipse; $i++)
  758. {
  759. $x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
  760. $x2 = round(rand($total_width / 2, 2 * $total_width));
  761. $y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
  762. $y2 = round(rand($max_height / 2, 2 * $max_height));
  763. imageellipse($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  764. }
  765. }
  766. }
  767. // Show the image.
  768. if (function_exists('imagegif'))
  769. {
  770. header('Content-type: image/gif');
  771. imagegif($code_image);
  772. }
  773. else
  774. {
  775. header('Content-type: image/png');
  776. imagepng($code_image);
  777. }
  778. // Bail out.
  779. imagedestroy($code_image);
  780. die();
  781. }
  782. /**
  783. * Show a letter for the visual verification code.
  784. * Alternative function for showCodeImage() in case GD is missing.
  785. * Includes an image from a random sub directory of default_theme_dir/fonts.
  786. *
  787. * @param string $letter
  788. */
  789. function showLetterImage($letter)
  790. {
  791. global $settings;
  792. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  793. return false;
  794. // Get a list of the available font directories.
  795. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  796. $font_list = array();
  797. while ($entry = $font_dir->read())
  798. if ($entry[0] !== '.' && is_dir($settings['default_theme_dir'] . '/fonts/' . $entry) && file_exists($settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf'))
  799. $font_list[] = $entry;
  800. if (empty($font_list))
  801. return false;
  802. // Pick a random font.
  803. $random_font = $font_list[array_rand($font_list)];
  804. // Check if the given letter exists.
  805. if (!file_exists($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif'))
  806. return false;
  807. // Include it!
  808. header('Content-type: image/gif');
  809. include($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif');
  810. // Nothing more to come.
  811. die();
  812. }
  813. ?>