Subs-Graphics.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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 2013 Simple Machines and individual contributors
  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('No direct access...');
  21. /**
  22. * downloads a file from a 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 $url 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 boolean 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 boolean, 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. * Used to re-econodes an image to a specifed image format
  156. * - creates a copy of the file at the same location as fileName.
  157. * - the file would have the format preferred_format if possible, 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 boolean, true on success, false on failure.
  163. */
  164. function reencodeImage($fileName, $preferred_format = 0)
  165. {
  166. if (!resizeImageFile($fileName, $fileName . '.tmp', null, null, $preferred_format))
  167. {
  168. if (file_exists($fileName . '.tmp'))
  169. unlink($fileName . '.tmp');
  170. return false;
  171. }
  172. if (!unlink($fileName))
  173. return false;
  174. if (!rename($fileName . '.tmp', $fileName))
  175. return false;
  176. }
  177. /**
  178. * Searches through the file to see if there's potentialy harmful non-binary content.
  179. * - if extensiveCheck is true, searches for asp/php short tags as well.
  180. *
  181. * @param string $fileName
  182. * @param bool $extensiveCheck = false
  183. * @return true on success, false on failure.
  184. */
  185. function checkImageContents($fileName, $extensiveCheck = false)
  186. {
  187. $fp = fopen($fileName, 'rb');
  188. if (!$fp)
  189. fatal_lang_error('attach_timeout');
  190. $prev_chunk = '';
  191. while (!feof($fp))
  192. {
  193. $cur_chunk = fread($fp, 8192);
  194. // Though not exhaustive lists, better safe than sorry.
  195. if (!empty($extensiveCheck))
  196. {
  197. // Paranoid check. Some like it that way.
  198. if (preg_match('~(iframe|\\<\\?|\\<%|html|eval|body|script\W|[CF]WS[\x01-\x0C])~i', $prev_chunk . $cur_chunk) === 1)
  199. {
  200. fclose($fp);
  201. return false;
  202. }
  203. }
  204. else
  205. {
  206. // Check for potential infection
  207. if (preg_match('~(iframe|(?<!cellTextIs)html|eval|body|script\W|[CF]WS[\x01-\x0C])~i', $prev_chunk . $cur_chunk) === 1)
  208. {
  209. fclose($fp);
  210. return false;
  211. }
  212. }
  213. $prev_chunk = $cur_chunk;
  214. }
  215. fclose($fp);
  216. return true;
  217. }
  218. /**
  219. * Sets a global $gd2 variable needed by some functions to determine
  220. * whether the GD2 library is present.
  221. *
  222. * @return whether or not GD1 is available.
  223. */
  224. function checkGD()
  225. {
  226. global $gd2;
  227. // Check to see if GD is installed and what version.
  228. if (($extensionFunctions = get_extension_funcs('gd')) === false)
  229. return false;
  230. // Also determine if GD2 is installed and store it in a global.
  231. $gd2 = in_array('imagecreatetruecolor', $extensionFunctions) && function_exists('imagecreatetruecolor');
  232. return true;
  233. }
  234. /**
  235. * Checks whether the Imagick class is present.
  236. *
  237. * @return whether or not Imagick is available.
  238. */
  239. function checkImagick()
  240. {
  241. return class_exists('Imagick', false);
  242. }
  243. /**
  244. * Checks whether the MagickWand extension is present.
  245. *
  246. * @return whether or not MagickWand is available.
  247. */
  248. function checkMagickWand()
  249. {
  250. return function_exists('newMagickWand');
  251. }
  252. /**
  253. * See if we have enough memory to thumbnail an image
  254. *
  255. * @param array $sizes image size
  256. * @return whether we do
  257. */
  258. function imageMemoryCheck($sizes)
  259. {
  260. global $modSettings;
  261. // doing the old 'set it and hope' way?
  262. if (empty($modSettings['attachment_thumb_memory']))
  263. {
  264. setMemoryLimit('128M');
  265. return true;
  266. }
  267. // Determine the memory requirements for this image, note: if you want to use an image formula W x H x bits/8 x channels x Overhead factor
  268. // you will need to account for single bit images as GD expands them to an 8 bit and will greatly overun the calculated value. The 5 is
  269. // simply a shortcut of 8bpp, 3 channels, 1.66 overhead
  270. $needed_memory = ($sizes[0] * $sizes[1] * 5);
  271. // if we need more, lets try to get it
  272. return setMemoryLimit($needed_memory, true);
  273. }
  274. /**
  275. * Resizes an image from a remote location or a local file.
  276. * Puts the resized image at the destination location.
  277. * The file would have the format preferred_format if possible,
  278. * otherwise the default format is jpeg.
  279. *
  280. * @param string $source
  281. * @param string $destination
  282. * @param int $max_width
  283. * @param int $max_height
  284. * @param int $preferred_format = 0
  285. * @return whether it succeeded.
  286. */
  287. function resizeImageFile($source, $destination, $max_width, $max_height, $preferred_format = 0)
  288. {
  289. global $sourcedir;
  290. // Nothing to do without GD or IM/MW
  291. if (!checkGD() && !checkImagick() && !checkMagickWand())
  292. return false;
  293. static $default_formats = array(
  294. '1' => 'gif',
  295. '2' => 'jpeg',
  296. '3' => 'png',
  297. '6' => 'bmp',
  298. '15' => 'wbmp'
  299. );
  300. require_once($sourcedir . '/Subs-Package.php');
  301. // Get the image file, we have to work with something after all
  302. $fp_destination = fopen($destination, 'wb');
  303. if ($fp_destination && substr($source, 0, 7) == 'http://')
  304. {
  305. $fileContents = fetch_web_data($source);
  306. fwrite($fp_destination, $fileContents);
  307. fclose($fp_destination);
  308. $sizes = @getimagesize($destination);
  309. }
  310. elseif ($fp_destination)
  311. {
  312. $sizes = @getimagesize($source);
  313. $fp_source = fopen($source, 'rb');
  314. if ($fp_source !== false)
  315. {
  316. while (!feof($fp_source))
  317. fwrite($fp_destination, fread($fp_source, 8192));
  318. fclose($fp_source);
  319. }
  320. else
  321. $sizes = array(-1, -1, -1);
  322. fclose($fp_destination);
  323. }
  324. // We can't get to the file.
  325. else
  326. $sizes = array(-1, -1, -1);
  327. // See if we have -or- can get the needed memory for this operation
  328. // ImageMagick isn't subject to PHP's memory limits :)
  329. if (!(checkIMagick() || checkMagickWand()) && checkGD() && !imageMemoryCheck($sizes))
  330. return false;
  331. // A known and supported format?
  332. // @todo test PSD and gif.
  333. if ((checkImagick() || checkMagickWand()) && isset($default_formats[$sizes[2]]))
  334. {
  335. return resizeImage(null, $destination, null, null, $max_width, $max_height, true, $preferred_format);
  336. }
  337. elseif (checkGD() && isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]]))
  338. {
  339. $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
  340. if ($src_img = @$imagecreatefrom($destination))
  341. {
  342. return 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);
  343. }
  344. }
  345. return false;
  346. }
  347. /**
  348. * Resizes src_img proportionally to fit within max_width and max_height limits
  349. * if it is too large.
  350. * If GD2 is present, it'll use it to achieve better quality.
  351. * It saves the new image to destination_filename, as preferred_format
  352. * if possible, default is jpeg.
  353. * @uses GD
  354. *
  355. * @param resource $src_img
  356. * @param string $destName
  357. * @param int $src_width
  358. * @param int $src_height
  359. * @param int $max_width
  360. * @param int $max_height
  361. * @param bool $force_resize = false
  362. * @param int $preferred_format = 0
  363. */
  364. function resizeImage($src_img, $destName, $src_width, $src_height, $max_width, $max_height, $force_resize = false, $preferred_format = 0)
  365. {
  366. global $gd2, $modSettings;
  367. if (checkImagick() || checkMagickWand())
  368. {
  369. static $default_formats = array(
  370. '1' => 'gif',
  371. '2' => 'jpeg',
  372. '3' => 'png',
  373. '6' => 'bmp',
  374. '15' => 'wbmp'
  375. );
  376. $preferred_format = empty($preferred_format) || !isset($default_formats[$preferred_format]) ? 2 : $preferred_format;
  377. if (checkImagick())
  378. {
  379. $imagick = New Imagick($destName);
  380. $src_width = empty($src_width) ? $imagick->getImageWidth() : $src_width;
  381. $src_height = empty($src_height) ? $imagick->getImageHeight() : $src_height;
  382. $dest_width = empty($max_width) ? $src_width : $max_width;
  383. $dest_height = empty($max_height) ? $src_height : $max_height;
  384. $imagick->setImageFormat($default_formats[$preferred_format]);
  385. $imagick->resizeImage($dest_width, $dest_height, Imagick::FILTER_LANCZOS, 1, true);
  386. $success = $imagick->writeImage($destName);
  387. }
  388. else
  389. {
  390. $magick_wand = newMagickWand();
  391. MagickReadImage($magick_wand, $destName);
  392. $src_width = empty($src_width) ? MagickGetImageWidth($magick_wand) : $src_width;
  393. $src_height = empty($src_height) ? MagickGetImageSize($magick_wand) : $src_height;
  394. $dest_width = empty($max_width) ? $src_width : $max_width;
  395. $dest_height = empty($max_height) ? $src_height : $max_height;
  396. MagickSetImageFormat($magick_wand, $default_formats[$preferred_format]);
  397. MagickResizeImage($magic_wand, $dest_width, $dest_height, MW_LanczosFilter, 1, true);
  398. $success = MagickWriteImage($magick_wand, $destName);
  399. }
  400. return !empty($success);
  401. }
  402. elseif (checkGD())
  403. {
  404. $success = false;
  405. // Determine whether to resize to max width or to max height (depending on the limits.)
  406. if (!empty($max_width) || !empty($max_height))
  407. {
  408. if (!empty($max_width) && (empty($max_height) || $src_height * $max_width / $src_width <= $max_height))
  409. {
  410. $dst_width = $max_width;
  411. $dst_height = floor($src_height * $max_width / $src_width);
  412. }
  413. elseif (!empty($max_height))
  414. {
  415. $dst_width = floor($src_width * $max_height / $src_height);
  416. $dst_height = $max_height;
  417. }
  418. // Don't bother resizing if it's already smaller...
  419. if (!empty($dst_width) && !empty($dst_height) && ($dst_width < $src_width || $dst_height < $src_height || $force_resize))
  420. {
  421. // (make a true color image, because it just looks better for resizing.)
  422. if ($gd2)
  423. {
  424. $dst_img = imagecreatetruecolor($dst_width, $dst_height);
  425. // Deal nicely with a PNG - because we can.
  426. if ((!empty($preferred_format)) && ($preferred_format == 3))
  427. {
  428. imagealphablending($dst_img, false);
  429. if (function_exists('imagesavealpha'))
  430. imagesavealpha($dst_img, true);
  431. }
  432. }
  433. else
  434. $dst_img = imagecreate($dst_width, $dst_height);
  435. // Resize it!
  436. if ($gd2)
  437. imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  438. else
  439. imagecopyresamplebicubic($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  440. }
  441. else
  442. $dst_img = $src_img;
  443. }
  444. else
  445. $dst_img = $src_img;
  446. // Save the image as ...
  447. if (!empty($preferred_format) && ($preferred_format == 3) && function_exists('imagepng'))
  448. $success = imagepng($dst_img, $destName);
  449. elseif (!empty($preferred_format) && ($preferred_format == 1) && function_exists('imagegif'))
  450. $success = imagegif($dst_img, $destName);
  451. elseif (function_exists('imagejpeg'))
  452. $success = imagejpeg($dst_img, $destName);
  453. // Free the memory.
  454. imagedestroy($src_img);
  455. if ($dst_img != $src_img)
  456. imagedestroy($dst_img);
  457. return $success;
  458. }
  459. else
  460. // Without GD, no image resizing at all.
  461. return false;
  462. }
  463. /**
  464. * Copy image.
  465. * Used when imagecopyresample() is not available.
  466. * @param resource $dst_img
  467. * @param resource $src_img
  468. * @param int $dst_x
  469. * @param int $dst_y
  470. * @param int $src_x
  471. * @param int $src_y
  472. * @param int $dst_w
  473. * @param int $dst_h
  474. * @param int $src_w
  475. * @param int $src_h
  476. */
  477. function imagecopyresamplebicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
  478. {
  479. $palsize = imagecolorstotal($src_img);
  480. for ($i = 0; $i < $palsize; $i++)
  481. {
  482. $colors = imagecolorsforindex($src_img, $i);
  483. imagecolorallocate($dst_img, $colors['red'], $colors['green'], $colors['blue']);
  484. }
  485. $scaleX = ($src_w - 1) / $dst_w;
  486. $scaleY = ($src_h - 1) / $dst_h;
  487. $scaleX2 = (int) $scaleX / 2;
  488. $scaleY2 = (int) $scaleY / 2;
  489. for ($j = $src_y; $j < $dst_h; $j++)
  490. {
  491. $sY = (int) $j * $scaleY;
  492. $y13 = $sY + $scaleY2;
  493. for ($i = $src_x; $i < $dst_w; $i++)
  494. {
  495. $sX = (int) $i * $scaleX;
  496. $x34 = $sX + $scaleX2;
  497. $color1 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $y13));
  498. $color2 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $sY));
  499. $color3 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $y13));
  500. $color4 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $sY));
  501. $red = ($color1['red'] + $color2['red'] + $color3['red'] + $color4['red']) / 4;
  502. $green = ($color1['green'] + $color2['green'] + $color3['green'] + $color4['green']) / 4;
  503. $blue = ($color1['blue'] + $color2['blue'] + $color3['blue'] + $color4['blue']) / 4;
  504. $color = imagecolorresolve($dst_img, $red, $green, $blue);
  505. if ($color == -1)
  506. {
  507. if ($palsize++ < 256)
  508. imagecolorallocate($dst_img, $red, $green, $blue);
  509. $color = imagecolorclosest($dst_img, $red, $green, $blue);
  510. }
  511. imagesetpixel($dst_img, $i + $dst_x - $src_x, $j + $dst_y - $src_y, $color);
  512. }
  513. }
  514. }
  515. if (!function_exists('imagecreatefrombmp'))
  516. {
  517. /**
  518. * It is set only if it doesn't already exist (for forwards compatiblity.)
  519. * It only supports uncompressed bitmaps.
  520. *
  521. * @param string $filename
  522. * @return resource, an image identifier representing the bitmap image
  523. * obtained from the given filename.
  524. */
  525. function imagecreatefrombmp($filename)
  526. {
  527. global $gd2;
  528. $fp = fopen($filename, 'rb');
  529. $errors = error_reporting(0);
  530. $header = unpack('vtype/Vsize/Vreserved/Voffset', fread($fp, 14));
  531. $info = unpack('Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vcolorimportant', fread($fp, 40));
  532. if ($header['type'] != 0x4D42)
  533. false;
  534. if ($gd2)
  535. $dst_img = imagecreatetruecolor($info['width'], $info['height']);
  536. else
  537. $dst_img = imagecreate($info['width'], $info['height']);
  538. $palette_size = $header['offset'] - 54;
  539. $info['ncolor'] = $palette_size / 4;
  540. $palette = array();
  541. $palettedata = fread($fp, $palette_size);
  542. $n = 0;
  543. for ($j = 0; $j < $palette_size; $j++)
  544. {
  545. $b = ord($palettedata{$j++});
  546. $g = ord($palettedata{$j++});
  547. $r = ord($palettedata{$j++});
  548. $palette[$n++] = imagecolorallocate($dst_img, $r, $g, $b);
  549. }
  550. $scan_line_size = ($info['bits'] * $info['width'] + 7) >> 3;
  551. $scan_line_align = $scan_line_size & 3 ? 4 - ($scan_line_size & 3) : 0;
  552. for ($y = 0, $l = $info['height'] - 1; $y < $info['height']; $y++, $l--)
  553. {
  554. fseek($fp, $header['offset'] + ($scan_line_size + $scan_line_align) * $l);
  555. $scan_line = fread($fp, $scan_line_size);
  556. if (strlen($scan_line) < $scan_line_size)
  557. continue;
  558. if ($info['bits'] == 32)
  559. {
  560. $x = 0;
  561. for ($j = 0; $j < $scan_line_size; $x++)
  562. {
  563. $b = ord($scan_line{$j++});
  564. $g = ord($scan_line{$j++});
  565. $r = ord($scan_line{$j++});
  566. $j++;
  567. $color = imagecolorexact($dst_img, $r, $g, $b);
  568. if ($color == -1)
  569. {
  570. $color = imagecolorallocate($dst_img, $r, $g, $b);
  571. // Gah! Out of colors? Stupid GD 1... try anyhow.
  572. if ($color == -1)
  573. $color = imagecolorclosest($dst_img, $r, $g, $b);
  574. }
  575. imagesetpixel($dst_img, $x, $y, $color);
  576. }
  577. }
  578. elseif ($info['bits'] == 24)
  579. {
  580. $x = 0;
  581. for ($j = 0; $j < $scan_line_size; $x++)
  582. {
  583. $b = ord($scan_line{$j++});
  584. $g = ord($scan_line{$j++});
  585. $r = ord($scan_line{$j++});
  586. $color = imagecolorexact($dst_img, $r, $g, $b);
  587. if ($color == -1)
  588. {
  589. $color = imagecolorallocate($dst_img, $r, $g, $b);
  590. // Gah! Out of colors? Stupid GD 1... try anyhow.
  591. if ($color == -1)
  592. $color = imagecolorclosest($dst_img, $r, $g, $b);
  593. }
  594. imagesetpixel($dst_img, $x, $y, $color);
  595. }
  596. }
  597. elseif ($info['bits'] == 16)
  598. {
  599. $x = 0;
  600. for ($j = 0; $j < $scan_line_size; $x++)
  601. {
  602. $b1 = ord($scan_line{$j++});
  603. $b2 = ord($scan_line{$j++});
  604. $word = $b2 * 256 + $b1;
  605. $b = (($word & 31) * 255) / 31;
  606. $g = ((($word >> 5) & 31) * 255) / 31;
  607. $r = ((($word >> 10) & 31) * 255) / 31;
  608. // Scale the image colors up properly.
  609. $color = imagecolorexact($dst_img, $r, $g, $b);
  610. if ($color == -1)
  611. {
  612. $color = imagecolorallocate($dst_img, $r, $g, $b);
  613. // Gah! Out of colors? Stupid GD 1... try anyhow.
  614. if ($color == -1)
  615. $color = imagecolorclosest($dst_img, $r, $g, $b);
  616. }
  617. imagesetpixel($dst_img, $x, $y, $color);
  618. }
  619. }
  620. elseif ($info['bits'] == 8)
  621. {
  622. $x = 0;
  623. for ($j = 0; $j < $scan_line_size; $x++)
  624. imagesetpixel($dst_img, $x, $y, $palette[ord($scan_line{$j++})]);
  625. }
  626. elseif ($info['bits'] == 4)
  627. {
  628. $x = 0;
  629. for ($j = 0; $j < $scan_line_size; $x++)
  630. {
  631. $byte = ord($scan_line{$j++});
  632. imagesetpixel($dst_img, $x, $y, $palette[(int) ($byte / 16)]);
  633. if (++$x < $info['width'])
  634. imagesetpixel($dst_img, $x, $y, $palette[$byte & 15]);
  635. }
  636. }
  637. elseif ($info['bits'] == 1)
  638. {
  639. $x = 0;
  640. for ($j = 0; $j < $scan_line_size; $x++)
  641. {
  642. $byte = ord($scan_line{$j++});
  643. imagesetpixel($dst_img, $x, $y, $palette[(($byte) & 128) != 0]);
  644. for ($shift = 1; $shift < 8; $shift++) {
  645. if (++$x < $info['width']) imagesetpixel($dst_img, $x, $y, $palette[(($byte << $shift) & 128) != 0]);
  646. }
  647. }
  648. }
  649. }
  650. fclose($fp);
  651. error_reporting($errors);
  652. return $dst_img;
  653. }
  654. }
  655. /**
  656. * Writes a gif file to disk as a png file.
  657. * @param resource $gif
  658. * @param string $lpszFileName
  659. * @param int $background_color = -1
  660. * @return boolean, whether it was successful or not.
  661. */
  662. function gif_outputAsPng($gif, $lpszFileName, $background_color = -1)
  663. {
  664. if (!isset($gif) || @get_class($gif) != 'cgif' || !$gif->loaded || $lpszFileName == '')
  665. return false;
  666. $fd = $gif->get_png_data($background_color);
  667. if (strlen($fd) <= 0)
  668. return false;
  669. if (!($fh = @fopen($lpszFileName, 'wb')))
  670. return false;
  671. @fwrite($fh, $fd, strlen($fd));
  672. @fflush($fh);
  673. @fclose($fh);
  674. return true;
  675. }
  676. /**
  677. * Show an image containing the visual verification code for registration.
  678. * Requires the GD extension.
  679. * Uses a random font for each letter from default_theme_dir/fonts.
  680. * Outputs a gif or a png (depending on whether gif ix supported).
  681. *
  682. * @param string $code
  683. * @return false if something goes wrong.
  684. */
  685. function showCodeImage($code)
  686. {
  687. global $gd2, $settings, $user_info, $modSettings;
  688. // Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
  689. // What type are we going to be doing?
  690. $imageType = $modSettings['visual_verification_type'];
  691. // Special case to allow the admin center to show samples.
  692. if ($user_info['is_admin'] && isset($_GET['type']))
  693. $imageType = (int) $_GET['type'];
  694. // Some quick references for what we do.
  695. // Do we show no, low or high noise?
  696. $noiseType = $imageType == 3 ? 'low' : ($imageType == 4 ? 'high' : ($imageType == 5 ? 'extreme' : 'none'));
  697. // Can we have more than one font in use?
  698. $varyFonts = $imageType > 3 ? true : false;
  699. // Just a plain white background?
  700. $simpleBGColor = $imageType < 3 ? true : false;
  701. // Plain black foreground?
  702. $simpleFGColor = $imageType == 0 ? true : false;
  703. // High much to rotate each character.
  704. $rotationType = $imageType == 1 ? 'none' : ($imageType > 3 ? 'low' : 'high');
  705. // Do we show some characters inversed?
  706. $showReverseChars = $imageType > 3 ? true : false;
  707. // Special case for not showing any characters.
  708. $disableChars = $imageType == 0 ? true : false;
  709. // What do we do with the font colors. Are they one color, close to one color or random?
  710. $fontColorType = $imageType == 1 ? 'plain' : ($imageType > 3 ? 'random' : 'cyclic');
  711. // Are the fonts random sizes?
  712. $fontSizeRandom = $imageType > 3 ? true : false;
  713. // How much space between characters?
  714. $fontHorSpace = $imageType > 3 ? 'high' : ($imageType == 1 ? 'medium' : 'minus');
  715. // Where do characters sit on the image? (Fixed position or random/very random)
  716. $fontVerPos = $imageType == 1 ? 'fixed' : ($imageType > 3 ? 'vrandom' : 'random');
  717. // Make font semi-transparent?
  718. $fontTrans = $imageType == 2 || $imageType == 3 ? true : false;
  719. // Give the image a border?
  720. $hasBorder = $simpleBGColor;
  721. // The amount of pixels inbetween characters.
  722. $character_spacing = 1;
  723. // What color is the background - generally white unless we're on "hard".
  724. if ($simpleBGColor)
  725. $background_color = array(255, 255, 255);
  726. else
  727. $background_color = isset($settings['verification_background']) ? $settings['verification_background'] : array(236, 237, 243);
  728. // The color of the characters shown (red, green, blue).
  729. if ($simpleFGColor)
  730. $foreground_color = array(0, 0, 0);
  731. else
  732. {
  733. $foreground_color = array(64, 101, 136);
  734. // Has the theme author requested a custom color?
  735. if (isset($settings['verification_foreground']))
  736. $foreground_color = $settings['verification_foreground'];
  737. }
  738. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  739. return false;
  740. // Get a list of the available fonts.
  741. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  742. $font_list = array();
  743. $ttfont_list = array();
  744. while ($entry = $font_dir->read())
  745. {
  746. if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
  747. $font_list[] = $entry;
  748. elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
  749. $ttfont_list[] = $entry;
  750. }
  751. if (empty($font_list))
  752. return false;
  753. // For non-hard things don't even change fonts.
  754. if (!$varyFonts)
  755. {
  756. $font_list = array($font_list[0]);
  757. // Try use Screenge if we can - it looks good!
  758. if (in_array('AnonymousPro.ttf', $ttfont_list))
  759. $ttfont_list = array('AnonymousPro.ttf');
  760. else
  761. $ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
  762. }
  763. // Create a list of characters to be shown.
  764. $characters = array();
  765. $loaded_fonts = array();
  766. for ($i = 0; $i < strlen($code); $i++)
  767. {
  768. $characters[$i] = array(
  769. 'id' => $code{$i},
  770. 'font' => array_rand($font_list),
  771. );
  772. $loaded_fonts[$characters[$i]['font']] = null;
  773. }
  774. // Load all fonts and determine the maximum font height.
  775. foreach ($loaded_fonts as $font_index => $dummy)
  776. $loaded_fonts[$font_index] = imageloadfont($settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
  777. // Determine the dimensions of each character.
  778. $total_width = $character_spacing * strlen($code) + 40;
  779. $max_height = 0;
  780. foreach ($characters as $char_index => $character)
  781. {
  782. $characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
  783. $characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
  784. $max_height = max($characters[$char_index]['height'] + 5, $max_height);
  785. $total_width += $characters[$char_index]['width'];
  786. }
  787. // Create an image.
  788. $code_image = $gd2 ? imagecreatetruecolor($total_width, $max_height) : imagecreate($total_width, $max_height);
  789. // Draw the background.
  790. $bg_color = imagecolorallocate($code_image, $background_color[0], $background_color[1], $background_color[2]);
  791. imagefilledrectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $bg_color);
  792. // Randomize the foreground color a little.
  793. for ($i = 0; $i < 3; $i++)
  794. $foreground_color[$i] = mt_rand(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
  795. $fg_color = imagecolorallocate($code_image, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
  796. // Color for the dots.
  797. for ($i = 0; $i < 3; $i++)
  798. $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);
  799. $randomness_color = imagecolorallocate($code_image, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
  800. // Some squares/rectanges for new extreme level
  801. if ($noiseType == 'extreme')
  802. {
  803. for ($i = 0; $i < rand(1, 5); $i++)
  804. {
  805. $x1 = rand(0, $total_width / 4);
  806. $x2 = $x1 + round(rand($total_width / 4, $total_width));
  807. $y1 = rand(0, $max_height);
  808. $y2 = $y1 + round(rand(0, $max_height / 3));
  809. imagefilledrectangle($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  810. }
  811. }
  812. // Fill in the characters.
  813. if (!$disableChars)
  814. {
  815. $cur_x = 0;
  816. foreach ($characters as $char_index => $character)
  817. {
  818. // Can we use true type fonts?
  819. $can_do_ttf = function_exists('imagettftext');
  820. // How much rotation will we give?
  821. if ($rotationType == 'none')
  822. $angle = 0;
  823. else
  824. $angle = mt_rand(-100, 100) / ($rotationType == 'high' ? 6 : 10);
  825. // What color shall we do it?
  826. if ($fontColorType == 'cyclic')
  827. {
  828. // Here we'll pick from a set of acceptance types.
  829. $colors = array(
  830. array(10, 120, 95),
  831. array(46, 81, 29),
  832. array(4, 22, 154),
  833. array(131, 9, 130),
  834. array(0, 0, 0),
  835. array(143, 39, 31),
  836. );
  837. if (!isset($last_index))
  838. $last_index = -1;
  839. $new_index = $last_index;
  840. while ($last_index == $new_index)
  841. $new_index = mt_rand(0, count($colors) - 1);
  842. $char_fg_color = $colors[$new_index];
  843. $last_index = $new_index;
  844. }
  845. elseif ($fontColorType == 'random')
  846. $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]));
  847. else
  848. $char_fg_color = array($foreground_color[0], $foreground_color[1], $foreground_color[2]);
  849. if (!empty($can_do_ttf))
  850. {
  851. // GD2 handles font size differently.
  852. if ($fontSizeRandom)
  853. $font_size = $gd2 ? mt_rand(17, 19) : mt_rand(18, 25);
  854. else
  855. $font_size = $gd2 ? 18 : 24;
  856. // Work out the sizes - also fix the character width cause TTF not quite so wide!
  857. $font_x = $fontHorSpace == 'minus' && $cur_x > 0 ? $cur_x - 3 : $cur_x + 5;
  858. $font_y = $max_height - ($fontVerPos == 'vrandom' ? mt_rand(2, 8) : ($fontVerPos == 'random' ? mt_rand(3, 5) : 5));
  859. // What font face?
  860. if (!empty($ttfont_list))
  861. $fontface = $settings['default_theme_dir'] . '/fonts/' . $ttfont_list[mt_rand(0, count($ttfont_list) - 1)];
  862. // What color are we to do it in?
  863. $is_reverse = $showReverseChars ? mt_rand(0, 1) : false;
  864. $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]);
  865. $fontcord = @imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $char_color, $fontface, $character['id']);
  866. if (empty($fontcord))
  867. $can_do_ttf = false;
  868. elseif ($is_reverse)
  869. {
  870. imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
  871. // Put the character back!
  872. imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $randomness_color, $fontface, $character['id']);
  873. }
  874. if ($can_do_ttf)
  875. $cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
  876. }
  877. if (!$can_do_ttf)
  878. {
  879. // Rotating the characters a little...
  880. if (function_exists('imagerotate'))
  881. {
  882. $char_image = $gd2 ? imagecreatetruecolor($character['width'], $character['height']) : imagecreate($character['width'], $character['height']);
  883. $char_bgcolor = imagecolorallocate($char_image, $background_color[0], $background_color[1], $background_color[2]);
  884. imagefilledrectangle($char_image, 0, 0, $character['width'] - 1, $character['height'] - 1, $char_bgcolor);
  885. 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]));
  886. $rotated_char = imagerotate($char_image, mt_rand(-100, 100) / 10, $char_bgcolor);
  887. imagecopy($code_image, $rotated_char, $cur_x, 0, 0, 0, $character['width'], $character['height']);
  888. imagedestroy($rotated_char);
  889. imagedestroy($char_image);
  890. }
  891. // Sorry, no rotation available.
  892. else
  893. 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]));
  894. $cur_x += $character['width'] + $character_spacing;
  895. }
  896. }
  897. }
  898. // If disabled just show a cross.
  899. else
  900. {
  901. imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
  902. imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
  903. }
  904. // Make the background color transparent on the hard image.
  905. if (!$simpleBGColor)
  906. imagecolortransparent($code_image, $bg_color);
  907. if ($hasBorder)
  908. imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
  909. // Add some noise to the background?
  910. if ($noiseType != 'none')
  911. {
  912. for ($i = mt_rand(0, 2); $i < $max_height; $i += mt_rand(1, 2))
  913. for ($j = mt_rand(0, 10); $j < $total_width; $j += mt_rand(1, 10))
  914. imagesetpixel($code_image, $j, $i, mt_rand(0, 1) ? $fg_color : $randomness_color);
  915. // Put in some lines too?
  916. if ($noiseType != 'extreme')
  917. {
  918. $num_lines = $noiseType == 'high' ? mt_rand(3, 7) : mt_rand(2, 5);
  919. for ($i = 0; $i < $num_lines; $i++)
  920. {
  921. if (mt_rand(0, 1))
  922. {
  923. $x1 = mt_rand(0, $total_width);
  924. $x2 = mt_rand(0, $total_width);
  925. $y1 = 0; $y2 = $max_height;
  926. }
  927. else
  928. {
  929. $y1 = mt_rand(0, $max_height);
  930. $y2 = mt_rand(0, $max_height);
  931. $x1 = 0; $x2 = $total_width;
  932. }
  933. imagesetthickness($code_image, mt_rand(1, 2));
  934. imageline($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  935. }
  936. }
  937. else
  938. {
  939. // Put in some ellipse
  940. $num_ellipse = $noiseType == 'extreme' ? mt_rand(6, 12) : mt_rand(2, 6);
  941. for ($i = 0; $i < $num_ellipse; $i++)
  942. {
  943. $x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
  944. $x2 = round(rand($total_width / 2, 2 * $total_width));
  945. $y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
  946. $y2 = round(rand($max_height / 2, 2 * $max_height));
  947. imageellipse($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  948. }
  949. }
  950. }
  951. // Show the image.
  952. if (function_exists('imagegif'))
  953. {
  954. header('Content-type: image/gif');
  955. imagegif($code_image);
  956. }
  957. else
  958. {
  959. header('Content-type: image/png');
  960. imagepng($code_image);
  961. }
  962. // Bail out.
  963. imagedestroy($code_image);
  964. die();
  965. }
  966. /**
  967. * Show a letter for the visual verification code.
  968. * Alternative function for showCodeImage() in case GD is missing.
  969. * Includes an image from a random sub directory of default_theme_dir/fonts.
  970. *
  971. * @param string $letter
  972. */
  973. function showLetterImage($letter)
  974. {
  975. global $settings;
  976. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  977. return false;
  978. // Get a list of the available font directories.
  979. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  980. $font_list = array();
  981. while ($entry = $font_dir->read())
  982. if ($entry[0] !== '.' && is_dir($settings['default_theme_dir'] . '/fonts/' . $entry) && file_exists($settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf'))
  983. $font_list[] = $entry;
  984. if (empty($font_list))
  985. return false;
  986. // Pick a random font.
  987. $random_font = $font_list[array_rand($font_list)];
  988. // Check if the given letter exists.
  989. if (!file_exists($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.png'))
  990. return false;
  991. // Include it!
  992. header('Content-type: image/png');
  993. include($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.png');
  994. // Nothing more to come.
  995. die();
  996. }
  997. ?>