Subs-Graphics.php 33 KB

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