PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/forum/Sources/Subs-Graphics.php

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