PageRenderTime 56ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/sources/subs/Graphics.subs.php

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