Subs-Graphics.php 32 KB

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