Subs-Graphics.php 36 KB

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