Subs-Graphics.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. // Gif? That might mean trouble if gif support is not available.
  191. if ($sizes[2] == 1 && !function_exists('imagecreatefromgif') && function_exists('imagecreatefrompng'))
  192. {
  193. // Download it to the temporary file... use the special gif library... and save as png.
  194. if ($img = @gif_loadFile($destination) && gif_outputAsPng($img, $destination))
  195. $sizes[2] = 3;
  196. }
  197. // A known and supported format?
  198. if (isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]]))
  199. {
  200. $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
  201. if ($src_img = @$imagecreatefrom($destination))
  202. {
  203. 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);
  204. $success = true;
  205. }
  206. }
  207. return $success;
  208. }
  209. /**
  210. * Resizes src_img proportionally to fit within max_width and max_height limits
  211. * if it is too large.
  212. * If GD2 is present, it'll use it to achieve better quality.
  213. * It saves the new image to destination_filename, as preferred_format
  214. * if possible, default is jpeg.
  215. * @uses GD
  216. *
  217. * @param resource $src_img
  218. * @param string $destName
  219. * @param int $src_width
  220. * @param int $src_height
  221. * @param int $max_width
  222. * @param int $max_height
  223. * @param bool $force_resize = false
  224. * @param int $preferred_format = 0
  225. */
  226. function resizeImage($src_img, $destName, $src_width, $src_height, $max_width, $max_height, $force_resize = false, $preferred_format = 0)
  227. {
  228. global $gd2, $modSettings;
  229. // Without GD, no image resizing at all.
  230. if (!checkGD())
  231. return false;
  232. $success = false;
  233. // Determine whether to resize to max width or to max height (depending on the limits.)
  234. if (!empty($max_width) || !empty($max_height))
  235. {
  236. if (!empty($max_width) && (empty($max_height) || $src_height * $max_width / $src_width <= $max_height))
  237. {
  238. $dst_width = $max_width;
  239. $dst_height = floor($src_height * $max_width / $src_width);
  240. }
  241. elseif (!empty($max_height))
  242. {
  243. $dst_width = floor($src_width * $max_height / $src_height);
  244. $dst_height = $max_height;
  245. }
  246. // Don't bother resizing if it's already smaller...
  247. if (!empty($dst_width) && !empty($dst_height) && ($dst_width < $src_width || $dst_height < $src_height || $force_resize))
  248. {
  249. // (make a true color image, because it just looks better for resizing.)
  250. if ($gd2)
  251. {
  252. $dst_img = imagecreatetruecolor($dst_width, $dst_height);
  253. // Deal nicely with a PNG - because we can.
  254. if ((!empty($preferred_format)) && ($preferred_format == 3))
  255. {
  256. imagealphablending($dst_img, false);
  257. if (function_exists('imagesavealpha'))
  258. imagesavealpha($dst_img, true);
  259. }
  260. }
  261. else
  262. $dst_img = imagecreate($dst_width, $dst_height);
  263. // Resize it!
  264. if ($gd2)
  265. imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  266. else
  267. imagecopyresamplebicubic($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  268. }
  269. else
  270. $dst_img = $src_img;
  271. }
  272. else
  273. $dst_img = $src_img;
  274. // Save the image as ...
  275. if (!empty($preferred_format) && ($preferred_format == 3) && function_exists('imagepng'))
  276. $success = imagepng($dst_img, $destName);
  277. elseif (!empty($preferred_format) && ($preferred_format == 1) && function_exists('imagegif'))
  278. $success = imagegif($dst_img, $destName);
  279. elseif (function_exists('imagejpeg'))
  280. $success = imagejpeg($dst_img, $destName);
  281. // Free the memory.
  282. imagedestroy($src_img);
  283. if ($dst_img != $src_img)
  284. imagedestroy($dst_img);
  285. return $success;
  286. }
  287. /**
  288. * Copy image.
  289. * Used when imagecopyresample() is not available.
  290. * @param resource $dst_img
  291. * @param resource $src_img
  292. * @param int $dst_x
  293. * @param int $dst_y
  294. * @param int $src_x
  295. * @param int $src_y
  296. * @param int $dst_w
  297. * @param int $dst_h
  298. * @param int $src_w
  299. * @param int $src_h
  300. */
  301. function imagecopyresamplebicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
  302. {
  303. $palsize = imagecolorstotal($src_img);
  304. for ($i = 0; $i < $palsize; $i++)
  305. {
  306. $colors = imagecolorsforindex($src_img, $i);
  307. imagecolorallocate($dst_img, $colors['red'], $colors['green'], $colors['blue']);
  308. }
  309. $scaleX = ($src_w - 1) / $dst_w;
  310. $scaleY = ($src_h - 1) / $dst_h;
  311. $scaleX2 = (int) $scaleX / 2;
  312. $scaleY2 = (int) $scaleY / 2;
  313. for ($j = $src_y; $j < $dst_h; $j++)
  314. {
  315. $sY = (int) $j * $scaleY;
  316. $y13 = $sY + $scaleY2;
  317. for ($i = $src_x; $i < $dst_w; $i++)
  318. {
  319. $sX = (int) $i * $scaleX;
  320. $x34 = $sX + $scaleX2;
  321. $color1 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $y13));
  322. $color2 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $sY));
  323. $color3 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $y13));
  324. $color4 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $sY));
  325. $red = ($color1['red'] + $color2['red'] + $color3['red'] + $color4['red']) / 4;
  326. $green = ($color1['green'] + $color2['green'] + $color3['green'] + $color4['green']) / 4;
  327. $blue = ($color1['blue'] + $color2['blue'] + $color3['blue'] + $color4['blue']) / 4;
  328. $color = imagecolorresolve($dst_img, $red, $green, $blue);
  329. if ($color == -1)
  330. {
  331. if ($palsize++ < 256)
  332. imagecolorallocate($dst_img, $red, $green, $blue);
  333. $color = imagecolorclosest($dst_img, $red, $green, $blue);
  334. }
  335. imagesetpixel($dst_img, $i + $dst_x - $src_x, $j + $dst_y - $src_y, $color);
  336. }
  337. }
  338. }
  339. if (!function_exists('imagecreatefrombmp'))
  340. {
  341. /**
  342. * It is set only if it doesn't already exist (for forwards compatiblity.)
  343. * It only supports uncompressed bitmaps.
  344. *
  345. * @param string $filename
  346. * @return resource, an image identifier representing the bitmap image
  347. * obtained from the given filename.
  348. */
  349. function imagecreatefrombmp($filename)
  350. {
  351. global $gd2;
  352. $fp = fopen($filename, 'rb');
  353. $errors = error_reporting(0);
  354. $header = unpack('vtype/Vsize/Vreserved/Voffset', fread($fp, 14));
  355. $info = unpack('Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vcolorimportant', fread($fp, 40));
  356. if ($header['type'] != 0x4D42)
  357. false;
  358. if ($gd2)
  359. $dst_img = imagecreatetruecolor($info['width'], $info['height']);
  360. else
  361. $dst_img = imagecreate($info['width'], $info['height']);
  362. $palette_size = $header['offset'] - 54;
  363. $info['ncolor'] = $palette_size / 4;
  364. $palette = array();
  365. $palettedata = fread($fp, $palette_size);
  366. $n = 0;
  367. for ($j = 0; $j < $palette_size; $j++)
  368. {
  369. $b = ord($palettedata{$j++});
  370. $g = ord($palettedata{$j++});
  371. $r = ord($palettedata{$j++});
  372. $palette[$n++] = imagecolorallocate($dst_img, $r, $g, $b);
  373. }
  374. $scan_line_size = ($info['bits'] * $info['width'] + 7) >> 3;
  375. $scan_line_align = $scan_line_size & 3 ? 4 - ($scan_line_size & 3) : 0;
  376. for ($y = 0, $l = $info['height'] - 1; $y < $info['height']; $y++, $l--)
  377. {
  378. fseek($fp, $header['offset'] + ($scan_line_size + $scan_line_align) * $l);
  379. $scan_line = fread($fp, $scan_line_size);
  380. if (strlen($scan_line) < $scan_line_size)
  381. continue;
  382. if ($info['bits'] == 32)
  383. {
  384. $x = 0;
  385. for ($j = 0; $j < $scan_line_size; $x++)
  386. {
  387. $b = ord($scan_line{$j++});
  388. $g = ord($scan_line{$j++});
  389. $r = ord($scan_line{$j++});
  390. $j++;
  391. $color = imagecolorexact($dst_img, $r, $g, $b);
  392. if ($color == -1)
  393. {
  394. $color = imagecolorallocate($dst_img, $r, $g, $b);
  395. // Gah! Out of colors? Stupid GD 1... try anyhow.
  396. if ($color == -1)
  397. $color = imagecolorclosest($dst_img, $r, $g, $b);
  398. }
  399. imagesetpixel($dst_img, $x, $y, $color);
  400. }
  401. }
  402. elseif ($info['bits'] == 24)
  403. {
  404. $x = 0;
  405. for ($j = 0; $j < $scan_line_size; $x++)
  406. {
  407. $b = ord($scan_line{$j++});
  408. $g = ord($scan_line{$j++});
  409. $r = ord($scan_line{$j++});
  410. $color = imagecolorexact($dst_img, $r, $g, $b);
  411. if ($color == -1)
  412. {
  413. $color = imagecolorallocate($dst_img, $r, $g, $b);
  414. // Gah! Out of colors? Stupid GD 1... try anyhow.
  415. if ($color == -1)
  416. $color = imagecolorclosest($dst_img, $r, $g, $b);
  417. }
  418. imagesetpixel($dst_img, $x, $y, $color);
  419. }
  420. }
  421. elseif ($info['bits'] == 16)
  422. {
  423. $x = 0;
  424. for ($j = 0; $j < $scan_line_size; $x++)
  425. {
  426. $b1 = ord($scan_line{$j++});
  427. $b2 = ord($scan_line{$j++});
  428. $word = $b2 * 256 + $b1;
  429. $b = (($word & 31) * 255) / 31;
  430. $g = ((($word >> 5) & 31) * 255) / 31;
  431. $r = ((($word >> 10) & 31) * 255) / 31;
  432. // Scale the image colors up properly.
  433. $color = imagecolorexact($dst_img, $r, $g, $b);
  434. if ($color == -1)
  435. {
  436. $color = imagecolorallocate($dst_img, $r, $g, $b);
  437. // Gah! Out of colors? Stupid GD 1... try anyhow.
  438. if ($color == -1)
  439. $color = imagecolorclosest($dst_img, $r, $g, $b);
  440. }
  441. imagesetpixel($dst_img, $x, $y, $color);
  442. }
  443. }
  444. elseif ($info['bits'] == 8)
  445. {
  446. $x = 0;
  447. for ($j = 0; $j < $scan_line_size; $x++)
  448. imagesetpixel($dst_img, $x, $y, $palette[ord($scan_line{$j++})]);
  449. }
  450. elseif ($info['bits'] == 4)
  451. {
  452. $x = 0;
  453. for ($j = 0; $j < $scan_line_size; $x++)
  454. {
  455. $byte = ord($scan_line{$j++});
  456. imagesetpixel($dst_img, $x, $y, $palette[(int) ($byte / 16)]);
  457. if (++$x < $info['width'])
  458. imagesetpixel($dst_img, $x, $y, $palette[$byte & 15]);
  459. }
  460. }
  461. else
  462. {
  463. // Sorry, I'm just not going to do monochrome :P.
  464. }
  465. }
  466. fclose($fp);
  467. error_reporting($errors);
  468. return $dst_img;
  469. }
  470. }
  471. /**
  472. * Loads a gif file with the Yamasoft GIF utility class.
  473. *
  474. * @param string $lpszFileName
  475. * @param int $iIndex
  476. * @return resource, a new GD image.
  477. */
  478. function gif_loadFile($lpszFileName, $iIndex = 0)
  479. {
  480. // The classes needed are in this file.
  481. loadClassFile('Class-Graphics.php');
  482. $gif = new gif_file();
  483. if (!$gif->loadFile($lpszFileName, $iIndex))
  484. return false;
  485. return $gif;
  486. }
  487. /**
  488. * Writes a gif file to disk as a png file.
  489. * @param resource $gif
  490. * @param string $lpszFileName
  491. * @param int $background_color = -1
  492. * @return bool, whether it was successful or not.
  493. */
  494. function gif_outputAsPng($gif, $lpszFileName, $background_color = -1)
  495. {
  496. if (!isset($gif) || @get_class($gif) != 'cgif' || !$gif->loaded || $lpszFileName == '')
  497. return false;
  498. $fd = $gif->get_png_data($background_color);
  499. if (strlen($fd) <= 0)
  500. return false;
  501. if (!($fh = @fopen($lpszFileName, 'wb')))
  502. return false;
  503. @fwrite($fh, $fd, strlen($fd));
  504. @fflush($fh);
  505. @fclose($fh);
  506. return true;
  507. }
  508. /**
  509. * Show an image containing the visual verification code for registration.
  510. * Requires the GD extension.
  511. * Uses a random font for each letter from default_theme_dir/fonts.
  512. * Outputs a gif or a png (depending on whether gif ix supported).
  513. *
  514. * @param string $code
  515. * @return false if something goes wrong.
  516. */
  517. function showCodeImage($code)
  518. {
  519. global $settings, $user_info, $modSettings;
  520. /*
  521. Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
  522. */
  523. // What type are we going to be doing?
  524. $imageType = $modSettings['visual_verification_type'];
  525. // Special case to allow the admin center to show samples.
  526. if ($user_info['is_admin'] && isset($_GET['type']))
  527. $imageType = (int) $_GET['type'];
  528. // Some quick references for what we do.
  529. // Do we show no, low or high noise?
  530. $noiseType = $imageType == 3 ? 'low' : ($imageType == 4 ? 'high' : ($imageType == 5 ? 'extreme' : 'none'));
  531. // Can we have more than one font in use?
  532. $varyFonts = $imageType > 3 ? true : false;
  533. // Just a plain white background?
  534. $simpleBGColor = $imageType < 3 ? true : false;
  535. // Plain black foreground?
  536. $simpleFGColor = $imageType == 0 ? true : false;
  537. // High much to rotate each character.
  538. $rotationType = $imageType == 1 ? 'none' : ($imageType > 3 ? 'low' : 'high');
  539. // Do we show some characters inversed?
  540. $showReverseChars = $imageType > 3 ? true : false;
  541. // Special case for not showing any characters.
  542. $disableChars = $imageType == 0 ? true : false;
  543. // What do we do with the font colors. Are they one color, close to one color or random?
  544. $fontColorType = $imageType == 1 ? 'plain' : ($imageType > 3 ? 'random' : 'cyclic');
  545. // Are the fonts random sizes?
  546. $fontSizeRandom = $imageType > 3 ? true : false;
  547. // How much space between characters?
  548. $fontHorSpace = $imageType > 3 ? 'high' : ($imageType == 1 ? 'medium' : 'minus');
  549. // Where do characters sit on the image? (Fixed position or random/very random)
  550. $fontVerPos = $imageType == 1 ? 'fixed' : ($imageType > 3 ? 'vrandom' : 'random');
  551. // Make font semi-transparent?
  552. $fontTrans = $imageType == 2 || $imageType == 3 ? true : false;
  553. // Give the image a border?
  554. $hasBorder = $simpleBGColor;
  555. // Is this GD2? Needed for pixel size.
  556. $testGD = get_extension_funcs('gd');
  557. $gd2 = in_array('imagecreatetruecolor', $testGD) && function_exists('imagecreatetruecolor');
  558. unset($testGD);
  559. // The amount of pixels inbetween characters.
  560. $character_spacing = 1;
  561. // What color is the background - generally white unless we're on "hard".
  562. if ($simpleBGColor)
  563. $background_color = array(255, 255, 255);
  564. else
  565. $background_color = isset($settings['verification_background']) ? $settings['verification_background'] : array(236, 237, 243);
  566. // The color of the characters shown (red, green, blue).
  567. if ($simpleFGColor)
  568. $foreground_color = array(0, 0, 0);
  569. else
  570. {
  571. $foreground_color = array(64, 101, 136);
  572. // Has the theme author requested a custom color?
  573. if (isset($settings['verification_foreground']))
  574. $foreground_color = $settings['verification_foreground'];
  575. }
  576. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  577. return false;
  578. // Get a list of the available fonts.
  579. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  580. $font_list = array();
  581. $ttfont_list = array();
  582. while ($entry = $font_dir->read())
  583. {
  584. if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
  585. $font_list[] = $entry;
  586. elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
  587. $ttfont_list[] = $entry;
  588. }
  589. if (empty($font_list))
  590. return false;
  591. // For non-hard things don't even change fonts.
  592. if (!$varyFonts)
  593. {
  594. $font_list = array($font_list[0]);
  595. // Try use Screenge if we can - it looks good!
  596. if (in_array('Screenge.ttf', $ttfont_list))
  597. $ttfont_list = array('Screenge.ttf');
  598. else
  599. $ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
  600. }
  601. // Create a list of characters to be shown.
  602. $characters = array();
  603. $loaded_fonts = array();
  604. for ($i = 0; $i < strlen($code); $i++)
  605. {
  606. $characters[$i] = array(
  607. 'id' => $code{$i},
  608. 'font' => array_rand($font_list),
  609. );
  610. $loaded_fonts[$characters[$i]['font']] = null;
  611. }
  612. // Load all fonts and determine the maximum font height.
  613. foreach ($loaded_fonts as $font_index => $dummy)
  614. $loaded_fonts[$font_index] = imageloadfont($settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
  615. // Determine the dimensions of each character.
  616. $total_width = $character_spacing * strlen($code) + 20;
  617. $max_height = 0;
  618. foreach ($characters as $char_index => $character)
  619. {
  620. $characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
  621. $characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
  622. $max_height = max($characters[$char_index]['height'] + 5, $max_height);
  623. $total_width += $characters[$char_index]['width'];
  624. }
  625. // Create an image.
  626. $code_image = $gd2 ? imagecreatetruecolor($total_width, $max_height) : imagecreate($total_width, $max_height);
  627. // Draw the background.
  628. $bg_color = imagecolorallocate($code_image, $background_color[0], $background_color[1], $background_color[2]);
  629. imagefilledrectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $bg_color);
  630. // Randomize the foreground color a little.
  631. for ($i = 0; $i < 3; $i++)
  632. $foreground_color[$i] = mt_rand(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
  633. $fg_color = imagecolorallocate($code_image, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
  634. // Color for the dots.
  635. for ($i = 0; $i < 3; $i++)
  636. $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);
  637. $randomness_color = imagecolorallocate($code_image, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
  638. // Some squares/rectanges for new extreme level
  639. if ($noiseType == 'extreme')
  640. {
  641. for ($i = 0; $i < rand(1, 5); $i++)
  642. {
  643. $x1 = rand(0, $total_width / 4);
  644. $x2 = $x1 + round(rand($total_width / 4, $total_width));
  645. $y1 = rand(0, $max_height);
  646. $y2 = $y1 + round(rand(0, $max_height / 3));
  647. imagefilledrectangle($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  648. }
  649. }
  650. // Fill in the characters.
  651. if (!$disableChars)
  652. {
  653. $cur_x = 0;
  654. foreach ($characters as $char_index => $character)
  655. {
  656. // Can we use true type fonts?
  657. $can_do_ttf = function_exists('imagettftext');
  658. // How much rotation will we give?
  659. if ($rotationType == 'none')
  660. $angle = 0;
  661. else
  662. $angle = mt_rand(-100, 100) / ($rotationType == 'high' ? 6 : 10);
  663. // What color shall we do it?
  664. if ($fontColorType == 'cyclic')
  665. {
  666. // Here we'll pick from a set of acceptance types.
  667. $colors = array(
  668. array(10, 120, 95),
  669. array(46, 81, 29),
  670. array(4, 22, 154),
  671. array(131, 9, 130),
  672. array(0, 0, 0),
  673. array(143, 39, 31),
  674. );
  675. if (!isset($last_index))
  676. $last_index = -1;
  677. $new_index = $last_index;
  678. while ($last_index == $new_index)
  679. $new_index = mt_rand(0, count($colors) - 1);
  680. $char_fg_color = $colors[$new_index];
  681. $last_index = $new_index;
  682. }
  683. elseif ($fontColorType == 'random')
  684. $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]));
  685. else
  686. $char_fg_color = array($foreground_color[0], $foreground_color[1], $foreground_color[2]);
  687. if (!empty($can_do_ttf))
  688. {
  689. // GD2 handles font size differently.
  690. if ($fontSizeRandom)
  691. $font_size = $gd2 ? mt_rand(17, 19) : mt_rand(18, 25);
  692. else
  693. $font_size = $gd2 ? 18 : 24;
  694. // Work out the sizes - also fix the character width cause TTF not quite so wide!
  695. $font_x = $fontHorSpace == 'minus' && $cur_x > 0 ? $cur_x - 3 : $cur_x + 5;
  696. $font_y = $max_height - ($fontVerPos == 'vrandom' ? mt_rand(2, 8) : ($fontVerPos == 'random' ? mt_rand(3, 5) : 5));
  697. // What font face?
  698. if (!empty($ttfont_list))
  699. $fontface = $settings['default_theme_dir'] . '/fonts/' . $ttfont_list[mt_rand(0, count($ttfont_list) - 1)];
  700. // What color are we to do it in?
  701. $is_reverse = $showReverseChars ? mt_rand(0, 1) : false;
  702. $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]);
  703. $fontcord = @imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $char_color, $fontface, $character['id']);
  704. if (empty($fontcord))
  705. $can_do_ttf = false;
  706. elseif ($is_reverse)
  707. {
  708. imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
  709. // Put the character back!
  710. imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $randomness_color, $fontface, $character['id']);
  711. }
  712. if ($can_do_ttf)
  713. $cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
  714. }
  715. if (!$can_do_ttf)
  716. {
  717. // Rotating the characters a little...
  718. if (function_exists('imagerotate'))
  719. {
  720. $char_image = $gd2 ? imagecreatetruecolor($character['width'], $character['height']) : imagecreate($character['width'], $character['height']);
  721. $char_bgcolor = imagecolorallocate($char_image, $background_color[0], $background_color[1], $background_color[2]);
  722. imagefilledrectangle($char_image, 0, 0, $character['width'] - 1, $character['height'] - 1, $char_bgcolor);
  723. 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]));
  724. $rotated_char = imagerotate($char_image, mt_rand(-100, 100) / 10, $char_bgcolor);
  725. imagecopy($code_image, $rotated_char, $cur_x, 0, 0, 0, $character['width'], $character['height']);
  726. imagedestroy($rotated_char);
  727. imagedestroy($char_image);
  728. }
  729. // Sorry, no rotation available.
  730. else
  731. 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]));
  732. $cur_x += $character['width'] + $character_spacing;
  733. }
  734. }
  735. }
  736. // If disabled just show a cross.
  737. else
  738. {
  739. imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
  740. imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
  741. }
  742. // Make the background color transparent on the hard image.
  743. if (!$simpleBGColor)
  744. imagecolortransparent($code_image, $bg_color);
  745. if ($hasBorder)
  746. imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
  747. // Add some noise to the background?
  748. if ($noiseType != 'none')
  749. {
  750. for ($i = mt_rand(0, 2); $i < $max_height; $i += mt_rand(1, 2))
  751. for ($j = mt_rand(0, 10); $j < $total_width; $j += mt_rand(1, 10))
  752. imagesetpixel($code_image, $j, $i, mt_rand(0, 1) ? $fg_color : $randomness_color);
  753. // Put in some lines too?
  754. if ($noiseType != 'extreme')
  755. {
  756. $num_lines = $noiseType == 'high' ? mt_rand(3, 7) : mt_rand(2, 5);
  757. for ($i = 0; $i < $num_lines; $i++)
  758. {
  759. if (mt_rand(0, 1))
  760. {
  761. $x1 = mt_rand(0, $total_width);
  762. $x2 = mt_rand(0, $total_width);
  763. $y1 = 0; $y2 = $max_height;
  764. }
  765. else
  766. {
  767. $y1 = mt_rand(0, $max_height);
  768. $y2 = mt_rand(0, $max_height);
  769. $x1 = 0; $x2 = $total_width;
  770. }
  771. imagesetthickness($code_image, mt_rand(1, 2));
  772. imageline($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  773. }
  774. }
  775. else
  776. {
  777. // Put in some ellipse
  778. $num_ellipse = $noiseType == 'extreme' ? mt_rand(6, 12) : mt_rand(2, 6);
  779. for ($i = 0; $i < $num_ellipse; $i++)
  780. {
  781. $x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
  782. $x2 = round(rand($total_width / 2, 2 * $total_width));
  783. $y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
  784. $y2 = round(rand($max_height / 2, 2 * $max_height));
  785. imageellipse($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  786. }
  787. }
  788. }
  789. // Show the image.
  790. if (function_exists('imagegif'))
  791. {
  792. header('Content-type: image/gif');
  793. imagegif($code_image);
  794. }
  795. else
  796. {
  797. header('Content-type: image/png');
  798. imagepng($code_image);
  799. }
  800. // Bail out.
  801. imagedestroy($code_image);
  802. die();
  803. }
  804. /**
  805. * Show a letter for the visual verification code.
  806. * Alternative function for showCodeImage() in case GD is missing.
  807. * Includes an image from a random sub directory of default_theme_dir/fonts.
  808. *
  809. * @param string $letter
  810. */
  811. function showLetterImage($letter)
  812. {
  813. global $settings;
  814. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  815. return false;
  816. // Get a list of the available font directories.
  817. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  818. $font_list = array();
  819. while ($entry = $font_dir->read())
  820. if ($entry[0] !== '.' && is_dir($settings['default_theme_dir'] . '/fonts/' . $entry) && file_exists($settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf'))
  821. $font_list[] = $entry;
  822. if (empty($font_list))
  823. return false;
  824. // Pick a random font.
  825. $random_font = $font_list[array_rand($font_list)];
  826. // Check if the given letter exists.
  827. if (!file_exists($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif'))
  828. return false;
  829. // Include it!
  830. header('Content-type: image/gif');
  831. include($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif');
  832. // Nothing more to come.
  833. die();
  834. }
  835. ?>