Subs-Graphics.php 34 KB

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