Subs-Graphics.php 35 KB

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