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