Subs-Graphics.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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 2012 Simple Machines
  15. * @license http://www.simplemachines.org/about/smf/license.php BSD
  16. *
  17. * @version 2.1 Alpha 1
  18. */
  19. if (!defined('SMF'))
  20. die('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. * 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
  282. if (!checkGD() && !checkImagick())
  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://')
  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. if (checkGD() && !imageMemoryCheck($sizes))
  320. return false;
  321. // A known and supported format?
  322. // @todo test PSD and gif.
  323. if (checkImagick() && 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())
  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. $imagick = New Imagick($destName);
  368. $src_width = empty($src_width) ? $imagick->getImageWidth() : $src_width;
  369. $src_height = empty($src_height) ? $imagick->getImageHeight() : $src_height;
  370. $dest_width = empty($max_width) ? $src_width : $max_width;
  371. $dest_height = empty($max_height) ? $src_height : $max_height;
  372. $imagick->setImageFormat($default_formats[$preferred_format]);
  373. $imagick->resizeImage($dest_width, $dest_height, Imagick::FILTER_LANCZOS, 1, true);
  374. $success = $imagick->writeImage($destName);
  375. return !empty($success);
  376. }
  377. elseif (checkGD())
  378. {
  379. $success = false;
  380. // Determine whether to resize to max width or to max height (depending on the limits.)
  381. if (!empty($max_width) || !empty($max_height))
  382. {
  383. if (!empty($max_width) && (empty($max_height) || $src_height * $max_width / $src_width <= $max_height))
  384. {
  385. $dst_width = $max_width;
  386. $dst_height = floor($src_height * $max_width / $src_width);
  387. }
  388. elseif (!empty($max_height))
  389. {
  390. $dst_width = floor($src_width * $max_height / $src_height);
  391. $dst_height = $max_height;
  392. }
  393. // Don't bother resizing if it's already smaller...
  394. if (!empty($dst_width) && !empty($dst_height) && ($dst_width < $src_width || $dst_height < $src_height || $force_resize))
  395. {
  396. // (make a true color image, because it just looks better for resizing.)
  397. if ($gd2)
  398. {
  399. $dst_img = imagecreatetruecolor($dst_width, $dst_height);
  400. // Deal nicely with a PNG - because we can.
  401. if ((!empty($preferred_format)) && ($preferred_format == 3))
  402. {
  403. imagealphablending($dst_img, false);
  404. if (function_exists('imagesavealpha'))
  405. imagesavealpha($dst_img, true);
  406. }
  407. }
  408. else
  409. $dst_img = imagecreate($dst_width, $dst_height);
  410. // Resize it!
  411. if ($gd2)
  412. imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  413. else
  414. imagecopyresamplebicubic($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
  415. }
  416. else
  417. $dst_img = $src_img;
  418. }
  419. else
  420. $dst_img = $src_img;
  421. // Save the image as ...
  422. if (!empty($preferred_format) && ($preferred_format == 3) && function_exists('imagepng'))
  423. $success = imagepng($dst_img, $destName);
  424. elseif (!empty($preferred_format) && ($preferred_format == 1) && function_exists('imagegif'))
  425. $success = imagegif($dst_img, $destName);
  426. elseif (function_exists('imagejpeg'))
  427. $success = imagejpeg($dst_img, $destName);
  428. // Free the memory.
  429. imagedestroy($src_img);
  430. if ($dst_img != $src_img)
  431. imagedestroy($dst_img);
  432. return $success;
  433. }
  434. else
  435. // Without GD, no image resizing at all.
  436. return false;
  437. }
  438. /**
  439. * Copy image.
  440. * Used when imagecopyresample() is not available.
  441. * @param resource $dst_img
  442. * @param resource $src_img
  443. * @param int $dst_x
  444. * @param int $dst_y
  445. * @param int $src_x
  446. * @param int $src_y
  447. * @param int $dst_w
  448. * @param int $dst_h
  449. * @param int $src_w
  450. * @param int $src_h
  451. */
  452. function imagecopyresamplebicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
  453. {
  454. $palsize = imagecolorstotal($src_img);
  455. for ($i = 0; $i < $palsize; $i++)
  456. {
  457. $colors = imagecolorsforindex($src_img, $i);
  458. imagecolorallocate($dst_img, $colors['red'], $colors['green'], $colors['blue']);
  459. }
  460. $scaleX = ($src_w - 1) / $dst_w;
  461. $scaleY = ($src_h - 1) / $dst_h;
  462. $scaleX2 = (int) $scaleX / 2;
  463. $scaleY2 = (int) $scaleY / 2;
  464. for ($j = $src_y; $j < $dst_h; $j++)
  465. {
  466. $sY = (int) $j * $scaleY;
  467. $y13 = $sY + $scaleY2;
  468. for ($i = $src_x; $i < $dst_w; $i++)
  469. {
  470. $sX = (int) $i * $scaleX;
  471. $x34 = $sX + $scaleX2;
  472. $color1 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $y13));
  473. $color2 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $sY));
  474. $color3 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $y13));
  475. $color4 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $sY));
  476. $red = ($color1['red'] + $color2['red'] + $color3['red'] + $color4['red']) / 4;
  477. $green = ($color1['green'] + $color2['green'] + $color3['green'] + $color4['green']) / 4;
  478. $blue = ($color1['blue'] + $color2['blue'] + $color3['blue'] + $color4['blue']) / 4;
  479. $color = imagecolorresolve($dst_img, $red, $green, $blue);
  480. if ($color == -1)
  481. {
  482. if ($palsize++ < 256)
  483. imagecolorallocate($dst_img, $red, $green, $blue);
  484. $color = imagecolorclosest($dst_img, $red, $green, $blue);
  485. }
  486. imagesetpixel($dst_img, $i + $dst_x - $src_x, $j + $dst_y - $src_y, $color);
  487. }
  488. }
  489. }
  490. if (!function_exists('imagecreatefrombmp'))
  491. {
  492. /**
  493. * It is set only if it doesn't already exist (for forwards compatiblity.)
  494. * It only supports uncompressed bitmaps.
  495. *
  496. * @param string $filename
  497. * @return resource, an image identifier representing the bitmap image
  498. * obtained from the given filename.
  499. */
  500. function imagecreatefrombmp($filename)
  501. {
  502. global $gd2;
  503. $fp = fopen($filename, 'rb');
  504. $errors = error_reporting(0);
  505. $header = unpack('vtype/Vsize/Vreserved/Voffset', fread($fp, 14));
  506. $info = unpack('Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vcolorimportant', fread($fp, 40));
  507. if ($header['type'] != 0x4D42)
  508. false;
  509. if ($gd2)
  510. $dst_img = imagecreatetruecolor($info['width'], $info['height']);
  511. else
  512. $dst_img = imagecreate($info['width'], $info['height']);
  513. $palette_size = $header['offset'] - 54;
  514. $info['ncolor'] = $palette_size / 4;
  515. $palette = array();
  516. $palettedata = fread($fp, $palette_size);
  517. $n = 0;
  518. for ($j = 0; $j < $palette_size; $j++)
  519. {
  520. $b = ord($palettedata{$j++});
  521. $g = ord($palettedata{$j++});
  522. $r = ord($palettedata{$j++});
  523. $palette[$n++] = imagecolorallocate($dst_img, $r, $g, $b);
  524. }
  525. $scan_line_size = ($info['bits'] * $info['width'] + 7) >> 3;
  526. $scan_line_align = $scan_line_size & 3 ? 4 - ($scan_line_size & 3) : 0;
  527. for ($y = 0, $l = $info['height'] - 1; $y < $info['height']; $y++, $l--)
  528. {
  529. fseek($fp, $header['offset'] + ($scan_line_size + $scan_line_align) * $l);
  530. $scan_line = fread($fp, $scan_line_size);
  531. if (strlen($scan_line) < $scan_line_size)
  532. continue;
  533. if ($info['bits'] == 32)
  534. {
  535. $x = 0;
  536. for ($j = 0; $j < $scan_line_size; $x++)
  537. {
  538. $b = ord($scan_line{$j++});
  539. $g = ord($scan_line{$j++});
  540. $r = ord($scan_line{$j++});
  541. $j++;
  542. $color = imagecolorexact($dst_img, $r, $g, $b);
  543. if ($color == -1)
  544. {
  545. $color = imagecolorallocate($dst_img, $r, $g, $b);
  546. // Gah! Out of colors? Stupid GD 1... try anyhow.
  547. if ($color == -1)
  548. $color = imagecolorclosest($dst_img, $r, $g, $b);
  549. }
  550. imagesetpixel($dst_img, $x, $y, $color);
  551. }
  552. }
  553. elseif ($info['bits'] == 24)
  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. $color = imagecolorexact($dst_img, $r, $g, $b);
  562. if ($color == -1)
  563. {
  564. $color = imagecolorallocate($dst_img, $r, $g, $b);
  565. // Gah! Out of colors? Stupid GD 1... try anyhow.
  566. if ($color == -1)
  567. $color = imagecolorclosest($dst_img, $r, $g, $b);
  568. }
  569. imagesetpixel($dst_img, $x, $y, $color);
  570. }
  571. }
  572. elseif ($info['bits'] == 16)
  573. {
  574. $x = 0;
  575. for ($j = 0; $j < $scan_line_size; $x++)
  576. {
  577. $b1 = ord($scan_line{$j++});
  578. $b2 = ord($scan_line{$j++});
  579. $word = $b2 * 256 + $b1;
  580. $b = (($word & 31) * 255) / 31;
  581. $g = ((($word >> 5) & 31) * 255) / 31;
  582. $r = ((($word >> 10) & 31) * 255) / 31;
  583. // Scale the image colors up properly.
  584. $color = imagecolorexact($dst_img, $r, $g, $b);
  585. if ($color == -1)
  586. {
  587. $color = imagecolorallocate($dst_img, $r, $g, $b);
  588. // Gah! Out of colors? Stupid GD 1... try anyhow.
  589. if ($color == -1)
  590. $color = imagecolorclosest($dst_img, $r, $g, $b);
  591. }
  592. imagesetpixel($dst_img, $x, $y, $color);
  593. }
  594. }
  595. elseif ($info['bits'] == 8)
  596. {
  597. $x = 0;
  598. for ($j = 0; $j < $scan_line_size; $x++)
  599. imagesetpixel($dst_img, $x, $y, $palette[ord($scan_line{$j++})]);
  600. }
  601. elseif ($info['bits'] == 4)
  602. {
  603. $x = 0;
  604. for ($j = 0; $j < $scan_line_size; $x++)
  605. {
  606. $byte = ord($scan_line{$j++});
  607. imagesetpixel($dst_img, $x, $y, $palette[(int) ($byte / 16)]);
  608. if (++$x < $info['width'])
  609. imagesetpixel($dst_img, $x, $y, $palette[$byte & 15]);
  610. }
  611. }
  612. elseif ($info['bits'] == 1)
  613. {
  614. $x = 0;
  615. for ($j = 0; $j < $scan_line_size; $x++)
  616. {
  617. $byte = ord($scan_line{$j++});
  618. imagesetpixel($dst_img, $x, $y, $palette[(($byte) & 128) != 0]);
  619. for ($shift = 1; $shift < 8; $shift++) {
  620. if (++$x < $info['width']) imagesetpixel($dst_img, $x, $y, $palette[(($byte << $shift) & 128) != 0]);
  621. }
  622. }
  623. }
  624. }
  625. fclose($fp);
  626. error_reporting($errors);
  627. return $dst_img;
  628. }
  629. }
  630. /**
  631. * Writes a gif file to disk as a png file.
  632. * @param resource $gif
  633. * @param string $lpszFileName
  634. * @param int $background_color = -1
  635. * @return boolean, whether it was successful or not.
  636. */
  637. function gif_outputAsPng($gif, $lpszFileName, $background_color = -1)
  638. {
  639. if (!isset($gif) || @get_class($gif) != 'cgif' || !$gif->loaded || $lpszFileName == '')
  640. return false;
  641. $fd = $gif->get_png_data($background_color);
  642. if (strlen($fd) <= 0)
  643. return false;
  644. if (!($fh = @fopen($lpszFileName, 'wb')))
  645. return false;
  646. @fwrite($fh, $fd, strlen($fd));
  647. @fflush($fh);
  648. @fclose($fh);
  649. return true;
  650. }
  651. /**
  652. * Show an image containing the visual verification code for registration.
  653. * Requires the GD extension.
  654. * Uses a random font for each letter from default_theme_dir/fonts.
  655. * Outputs a gif or a png (depending on whether gif ix supported).
  656. *
  657. * @param string $code
  658. * @return false if something goes wrong.
  659. */
  660. function showCodeImage($code)
  661. {
  662. global $gd2, $settings, $user_info, $modSettings;
  663. // Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
  664. // What type are we going to be doing?
  665. $imageType = $modSettings['visual_verification_type'];
  666. // Special case to allow the admin center to show samples.
  667. if ($user_info['is_admin'] && isset($_GET['type']))
  668. $imageType = (int) $_GET['type'];
  669. // Some quick references for what we do.
  670. // Do we show no, low or high noise?
  671. $noiseType = $imageType == 3 ? 'low' : ($imageType == 4 ? 'high' : ($imageType == 5 ? 'extreme' : 'none'));
  672. // Can we have more than one font in use?
  673. $varyFonts = $imageType > 3 ? true : false;
  674. // Just a plain white background?
  675. $simpleBGColor = $imageType < 3 ? true : false;
  676. // Plain black foreground?
  677. $simpleFGColor = $imageType == 0 ? true : false;
  678. // High much to rotate each character.
  679. $rotationType = $imageType == 1 ? 'none' : ($imageType > 3 ? 'low' : 'high');
  680. // Do we show some characters inversed?
  681. $showReverseChars = $imageType > 3 ? true : false;
  682. // Special case for not showing any characters.
  683. $disableChars = $imageType == 0 ? true : false;
  684. // What do we do with the font colors. Are they one color, close to one color or random?
  685. $fontColorType = $imageType == 1 ? 'plain' : ($imageType > 3 ? 'random' : 'cyclic');
  686. // Are the fonts random sizes?
  687. $fontSizeRandom = $imageType > 3 ? true : false;
  688. // How much space between characters?
  689. $fontHorSpace = $imageType > 3 ? 'high' : ($imageType == 1 ? 'medium' : 'minus');
  690. // Where do characters sit on the image? (Fixed position or random/very random)
  691. $fontVerPos = $imageType == 1 ? 'fixed' : ($imageType > 3 ? 'vrandom' : 'random');
  692. // Make font semi-transparent?
  693. $fontTrans = $imageType == 2 || $imageType == 3 ? true : false;
  694. // Give the image a border?
  695. $hasBorder = $simpleBGColor;
  696. // The amount of pixels inbetween characters.
  697. $character_spacing = 1;
  698. // What color is the background - generally white unless we're on "hard".
  699. if ($simpleBGColor)
  700. $background_color = array(255, 255, 255);
  701. else
  702. $background_color = isset($settings['verification_background']) ? $settings['verification_background'] : array(236, 237, 243);
  703. // The color of the characters shown (red, green, blue).
  704. if ($simpleFGColor)
  705. $foreground_color = array(0, 0, 0);
  706. else
  707. {
  708. $foreground_color = array(64, 101, 136);
  709. // Has the theme author requested a custom color?
  710. if (isset($settings['verification_foreground']))
  711. $foreground_color = $settings['verification_foreground'];
  712. }
  713. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  714. return false;
  715. // Get a list of the available fonts.
  716. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  717. $font_list = array();
  718. $ttfont_list = array();
  719. while ($entry = $font_dir->read())
  720. {
  721. if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
  722. $font_list[] = $entry;
  723. elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
  724. $ttfont_list[] = $entry;
  725. }
  726. if (empty($font_list))
  727. return false;
  728. // For non-hard things don't even change fonts.
  729. if (!$varyFonts)
  730. {
  731. $font_list = array($font_list[0]);
  732. // Try use Screenge if we can - it looks good!
  733. if (in_array('Screenge.ttf', $ttfont_list))
  734. $ttfont_list = array('Screenge.ttf');
  735. else
  736. $ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
  737. }
  738. // Create a list of characters to be shown.
  739. $characters = array();
  740. $loaded_fonts = array();
  741. for ($i = 0; $i < strlen($code); $i++)
  742. {
  743. $characters[$i] = array(
  744. 'id' => $code{$i},
  745. 'font' => array_rand($font_list),
  746. );
  747. $loaded_fonts[$characters[$i]['font']] = null;
  748. }
  749. // Load all fonts and determine the maximum font height.
  750. foreach ($loaded_fonts as $font_index => $dummy)
  751. $loaded_fonts[$font_index] = imageloadfont($settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
  752. // Determine the dimensions of each character.
  753. $total_width = $character_spacing * strlen($code) + 20;
  754. $max_height = 0;
  755. foreach ($characters as $char_index => $character)
  756. {
  757. $characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
  758. $characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
  759. $max_height = max($characters[$char_index]['height'] + 5, $max_height);
  760. $total_width += $characters[$char_index]['width'];
  761. }
  762. // Create an image.
  763. $code_image = $gd2 ? imagecreatetruecolor($total_width, $max_height) : imagecreate($total_width, $max_height);
  764. // Draw the background.
  765. $bg_color = imagecolorallocate($code_image, $background_color[0], $background_color[1], $background_color[2]);
  766. imagefilledrectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $bg_color);
  767. // Randomize the foreground color a little.
  768. for ($i = 0; $i < 3; $i++)
  769. $foreground_color[$i] = mt_rand(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
  770. $fg_color = imagecolorallocate($code_image, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
  771. // Color for the dots.
  772. for ($i = 0; $i < 3; $i++)
  773. $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);
  774. $randomness_color = imagecolorallocate($code_image, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
  775. // Some squares/rectanges for new extreme level
  776. if ($noiseType == 'extreme')
  777. {
  778. for ($i = 0; $i < rand(1, 5); $i++)
  779. {
  780. $x1 = rand(0, $total_width / 4);
  781. $x2 = $x1 + round(rand($total_width / 4, $total_width));
  782. $y1 = rand(0, $max_height);
  783. $y2 = $y1 + round(rand(0, $max_height / 3));
  784. imagefilledrectangle($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  785. }
  786. }
  787. // Fill in the characters.
  788. if (!$disableChars)
  789. {
  790. $cur_x = 0;
  791. foreach ($characters as $char_index => $character)
  792. {
  793. // Can we use true type fonts?
  794. $can_do_ttf = function_exists('imagettftext');
  795. // How much rotation will we give?
  796. if ($rotationType == 'none')
  797. $angle = 0;
  798. else
  799. $angle = mt_rand(-100, 100) / ($rotationType == 'high' ? 6 : 10);
  800. // What color shall we do it?
  801. if ($fontColorType == 'cyclic')
  802. {
  803. // Here we'll pick from a set of acceptance types.
  804. $colors = array(
  805. array(10, 120, 95),
  806. array(46, 81, 29),
  807. array(4, 22, 154),
  808. array(131, 9, 130),
  809. array(0, 0, 0),
  810. array(143, 39, 31),
  811. );
  812. if (!isset($last_index))
  813. $last_index = -1;
  814. $new_index = $last_index;
  815. while ($last_index == $new_index)
  816. $new_index = mt_rand(0, count($colors) - 1);
  817. $char_fg_color = $colors[$new_index];
  818. $last_index = $new_index;
  819. }
  820. elseif ($fontColorType == 'random')
  821. $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]));
  822. else
  823. $char_fg_color = array($foreground_color[0], $foreground_color[1], $foreground_color[2]);
  824. if (!empty($can_do_ttf))
  825. {
  826. // GD2 handles font size differently.
  827. if ($fontSizeRandom)
  828. $font_size = $gd2 ? mt_rand(17, 19) : mt_rand(18, 25);
  829. else
  830. $font_size = $gd2 ? 18 : 24;
  831. // Work out the sizes - also fix the character width cause TTF not quite so wide!
  832. $font_x = $fontHorSpace == 'minus' && $cur_x > 0 ? $cur_x - 3 : $cur_x + 5;
  833. $font_y = $max_height - ($fontVerPos == 'vrandom' ? mt_rand(2, 8) : ($fontVerPos == 'random' ? mt_rand(3, 5) : 5));
  834. // What font face?
  835. if (!empty($ttfont_list))
  836. $fontface = $settings['default_theme_dir'] . '/fonts/' . $ttfont_list[mt_rand(0, count($ttfont_list) - 1)];
  837. // What color are we to do it in?
  838. $is_reverse = $showReverseChars ? mt_rand(0, 1) : false;
  839. $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]);
  840. $fontcord = @imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $char_color, $fontface, $character['id']);
  841. if (empty($fontcord))
  842. $can_do_ttf = false;
  843. elseif ($is_reverse)
  844. {
  845. imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
  846. // Put the character back!
  847. imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $randomness_color, $fontface, $character['id']);
  848. }
  849. if ($can_do_ttf)
  850. $cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
  851. }
  852. if (!$can_do_ttf)
  853. {
  854. // Rotating the characters a little...
  855. if (function_exists('imagerotate'))
  856. {
  857. $char_image = $gd2 ? imagecreatetruecolor($character['width'], $character['height']) : imagecreate($character['width'], $character['height']);
  858. $char_bgcolor = imagecolorallocate($char_image, $background_color[0], $background_color[1], $background_color[2]);
  859. imagefilledrectangle($char_image, 0, 0, $character['width'] - 1, $character['height'] - 1, $char_bgcolor);
  860. 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]));
  861. $rotated_char = imagerotate($char_image, mt_rand(-100, 100) / 10, $char_bgcolor);
  862. imagecopy($code_image, $rotated_char, $cur_x, 0, 0, 0, $character['width'], $character['height']);
  863. imagedestroy($rotated_char);
  864. imagedestroy($char_image);
  865. }
  866. // Sorry, no rotation available.
  867. else
  868. 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]));
  869. $cur_x += $character['width'] + $character_spacing;
  870. }
  871. }
  872. }
  873. // If disabled just show a cross.
  874. else
  875. {
  876. imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
  877. imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
  878. }
  879. // Make the background color transparent on the hard image.
  880. if (!$simpleBGColor)
  881. imagecolortransparent($code_image, $bg_color);
  882. if ($hasBorder)
  883. imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
  884. // Add some noise to the background?
  885. if ($noiseType != 'none')
  886. {
  887. for ($i = mt_rand(0, 2); $i < $max_height; $i += mt_rand(1, 2))
  888. for ($j = mt_rand(0, 10); $j < $total_width; $j += mt_rand(1, 10))
  889. imagesetpixel($code_image, $j, $i, mt_rand(0, 1) ? $fg_color : $randomness_color);
  890. // Put in some lines too?
  891. if ($noiseType != 'extreme')
  892. {
  893. $num_lines = $noiseType == 'high' ? mt_rand(3, 7) : mt_rand(2, 5);
  894. for ($i = 0; $i < $num_lines; $i++)
  895. {
  896. if (mt_rand(0, 1))
  897. {
  898. $x1 = mt_rand(0, $total_width);
  899. $x2 = mt_rand(0, $total_width);
  900. $y1 = 0; $y2 = $max_height;
  901. }
  902. else
  903. {
  904. $y1 = mt_rand(0, $max_height);
  905. $y2 = mt_rand(0, $max_height);
  906. $x1 = 0; $x2 = $total_width;
  907. }
  908. imagesetthickness($code_image, mt_rand(1, 2));
  909. imageline($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  910. }
  911. }
  912. else
  913. {
  914. // Put in some ellipse
  915. $num_ellipse = $noiseType == 'extreme' ? mt_rand(6, 12) : mt_rand(2, 6);
  916. for ($i = 0; $i < $num_ellipse; $i++)
  917. {
  918. $x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
  919. $x2 = round(rand($total_width / 2, 2 * $total_width));
  920. $y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
  921. $y2 = round(rand($max_height / 2, 2 * $max_height));
  922. imageellipse($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
  923. }
  924. }
  925. }
  926. // Show the image.
  927. if (function_exists('imagegif'))
  928. {
  929. header('Content-type: image/gif');
  930. imagegif($code_image);
  931. }
  932. else
  933. {
  934. header('Content-type: image/png');
  935. imagepng($code_image);
  936. }
  937. // Bail out.
  938. imagedestroy($code_image);
  939. die();
  940. }
  941. /**
  942. * Show a letter for the visual verification code.
  943. * Alternative function for showCodeImage() in case GD is missing.
  944. * Includes an image from a random sub directory of default_theme_dir/fonts.
  945. *
  946. * @param string $letter
  947. */
  948. function showLetterImage($letter)
  949. {
  950. global $settings;
  951. if (!is_dir($settings['default_theme_dir'] . '/fonts'))
  952. return false;
  953. // Get a list of the available font directories.
  954. $font_dir = dir($settings['default_theme_dir'] . '/fonts');
  955. $font_list = array();
  956. while ($entry = $font_dir->read())
  957. if ($entry[0] !== '.' && is_dir($settings['default_theme_dir'] . '/fonts/' . $entry) && file_exists($settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf'))
  958. $font_list[] = $entry;
  959. if (empty($font_list))
  960. return false;
  961. // Pick a random font.
  962. $random_font = $font_list[array_rand($font_list)];
  963. // Check if the given letter exists.
  964. if (!file_exists($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif'))
  965. return false;
  966. // Include it!
  967. header('Content-type: image/gif');
  968. include($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . $letter . '.gif');
  969. // Nothing more to come.
  970. die();
  971. }
  972. ?>