PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/php/Sources/Subs-Graphics.php

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