Subs-Graphics.php 35 KB

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