Passed
Pull Request — release-2.1 (#6775)
by
unknown
06:05
created

resizeImageFile()   D

Complexity

Conditions 28
Paths 83

Size

Total Lines 82
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 28
eloc 45
c 2
b 0
f 0
nc 83
nop 5
dl 0
loc 82
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file deals with low-level graphics operations performed on images,
5
 * specially as needed for avatars (uploaded avatars), attachments, or
6
 * visual verification images.
7
 * It uses, for gifs at least, Gif Util. For more information on that,
8
 * please see its website.
9
 * TrueType fonts supplied by www.LarabieFonts.com
10
 *
11
 * Simple Machines Forum (SMF)
12
 *
13
 * @package SMF
14
 * @author Simple Machines https://www.simplemachines.org
15
 * @copyright 2021 Simple Machines and individual contributors
16
 * @license https://www.simplemachines.org/about/smf/license.php BSD
17
 *
18
 * @version 2.1 RC3
19
 */
20
21
if (!defined('SMF'))
22
	die('No direct access...');
23
24
/**
25
 * downloads a file from a url and stores it locally for avatar use by id_member.
26
 * - supports GIF, JPG, PNG, BMP and WBMP formats.
27
 * - detects if GD2 is available.
28
 * - uses resizeImageFile() to resize to max_width by max_height, and saves the result to a file.
29
 * - updates the database info for the member's avatar.
30
 * - returns whether the download and resize was successful.
31
 *
32
 * @param string $url The full path to the temporary file
33
 * @param int $memID The member ID
34
 * @param int $max_width The maximum allowed width for the avatar
35
 * @param int $max_height The maximum allowed height for the avatar
36
 * @return boolean Whether the download and resize was successful.
37
 *
38
 */
39
function downloadAvatar($url, $memID, $max_width, $max_height)
40
{
41
	global $modSettings, $sourcedir, $smcFunc;
42
43
	$ext = !empty($modSettings['avatar_download_png']) ? 'png' : 'jpeg';
44
	$destName = 'avatar_' . $memID . '_' . time() . '.' . $ext;
45
46
	// Just making sure there is a non-zero member.
47
	if (empty($memID))
48
		return false;
49
50
	require_once($sourcedir . '/ManageAttachments.php');
51
	removeAttachments(array('id_member' => $memID));
52
53
	$id_folder = 1;
54
	$avatar_hash = '';
55
	$attachID = $smcFunc['db_insert']('',
56
		'{db_prefix}attachments',
57
		array(
58
			'id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-255', 'fileext' => 'string-8', 'size' => 'int',
59
			'id_folder' => 'int',
60
		),
61
		array(
62
			$memID, 1, $destName, $avatar_hash, $ext, 1,
63
			$id_folder,
64
		),
65
		array('id_attach'),
66
		1
67
	);
68
69
	// Retain this globally in case the script wants it.
70
	$modSettings['new_avatar_data'] = array(
71
		'id' => $attachID,
72
		'filename' => $destName,
73
		'type' => 1,
74
	);
75
76
	$destName = $modSettings['custom_avatar_dir'] . '/' . $destName . '.tmp';
77
78
	// Resize it.
79
	if (!empty($modSettings['avatar_download_png']))
80
		$success = resizeImageFile($url, $destName, $max_width, $max_height, 3);
81
	else
82
		$success = resizeImageFile($url, $destName, $max_width, $max_height);
83
84
	// Remove the .tmp extension.
85
	$destName = substr($destName, 0, -4);
86
87
	if ($success)
88
	{
89
		// Remove the .tmp extension from the attachment.
90
		if (rename($destName . '.tmp', $destName))
91
		{
92
			list ($width, $height) = getimagesize($destName);
93
			$mime_type = 'image/' . $ext;
94
95
			// Write filesize in the database.
96
			$smcFunc['db_query']('', '
97
				UPDATE {db_prefix}attachments
98
				SET size = {int:filesize}, width = {int:width}, height = {int:height},
99
					mime_type = {string:mime_type}
100
				WHERE id_attach = {int:current_attachment}',
101
				array(
102
					'filesize' => filesize($destName),
103
					'width' => (int) $width,
104
					'height' => (int) $height,
105
					'current_attachment' => $attachID,
106
					'mime_type' => $mime_type,
107
				)
108
			);
109
			return true;
110
		}
111
		else
112
			return false;
113
	}
114
	else
115
	{
116
		$smcFunc['db_query']('', '
117
			DELETE FROM {db_prefix}attachments
118
			WHERE id_attach = {int:current_attachment}',
119
			array(
120
				'current_attachment' => $attachID,
121
			)
122
		);
123
124
		@unlink($destName . '.tmp');
125
		return false;
126
	}
127
}
128
129
/**
130
 * Create a thumbnail of the given source.
131
 *
132
 * @uses resizeImageFile() function to achieve the resize.
133
 *
134
 * @param string $source The name of the source image
135
 * @param int $max_width The maximum allowed width
136
 * @param int $max_height The maximum allowed height
137
 * @return boolean Whether the thumbnail creation was successful.
138
 */
139
function createThumbnail($source, $max_width, $max_height)
140
{
141
	global $modSettings;
142
143
	$destName = $source . '_thumb.tmp';
144
145
	// Do the actual resize.
146
	if (!empty($modSettings['attachment_thumb_png']))
147
		$success = resizeImageFile($source, $destName, $max_width, $max_height, 3);
148
	else
149
		$success = resizeImageFile($source, $destName, $max_width, $max_height);
150
151
	// Okay, we're done with the temporary stuff.
152
	$destName = substr($destName, 0, -4);
153
154
	if ($success && @rename($destName . '.tmp', $destName))
155
		return true;
156
	else
157
	{
158
		@unlink($destName . '.tmp');
159
		@touch($destName);
160
		return false;
161
	}
162
}
163
164
/**
165
 * Used to re-econodes an image to a specified image format
166
 * - creates a copy of the file at the same location as fileName.
167
 * - the file would have the format preferred_format if possible, otherwise the default format is jpeg.
168
 * - the function makes sure that all non-essential image contents are disposed.
169
 *
170
 * @param string $fileName The path to the file
171
 * @param int $preferred_format The preferred format - 0 to automatically determine, 1 for gif, 2 for jpg, 3 for png, 6 for bmp and 15 for wbmp
172
 * @return boolean Whether the reencoding was successful
173
 */
174
function reencodeImage($fileName, $preferred_format = 0)
175
{
176
	if (!resizeImageFile($fileName, $fileName . '.tmp', null, null, $preferred_format))
177
	{
178
		if (file_exists($fileName . '.tmp'))
179
			unlink($fileName . '.tmp');
180
181
		return false;
182
	}
183
184
	if (!unlink($fileName))
185
		return false;
186
187
	if (!rename($fileName . '.tmp', $fileName))
188
		return false;
189
}
190
191
/**
192
 * Searches through the file to see if there's potentially harmful non-binary content.
193
 * - if extensiveCheck is true, searches for asp/php short tags as well.
194
 *
195
 * @param string $fileName The path to the file
196
 * @param bool $extensiveCheck Whether to perform extensive checks
197
 * @return bool Whether the image appears to be safe
198
 */
199
function checkImageContents($fileName, $extensiveCheck = false)
200
{
201
	$fp = fopen($fileName, 'rb');
202
	if (!$fp)
0 ignored issues
show
introduced by
$fp is of type resource, thus it always evaluated to false.
Loading history...
203
		fatal_lang_error('attach_timeout');
204
205
	$prev_chunk = '';
206
	while (!feof($fp))
207
	{
208
		$cur_chunk = fread($fp, 8192);
209
210
		// Though not exhaustive lists, better safe than sorry.
211
		if (!empty($extensiveCheck))
212
		{
213
			// Paranoid check.  Use this if you have reason to distrust your host's security config.
214
			// Will result in MANY false positives, and is not suitable for photography sites.
215
			if (preg_match('~(iframe|\\<\\?|\\<%|html|eval|body|script\W|(?-i)[CFZ]WS[\x01-\x0E])~i', $prev_chunk . $cur_chunk) === 1)
216
			{
217
				fclose($fp);
218
				return false;
219
			}
220
		}
221
		else
222
		{
223
			// Check for potential infection - focus on clues for inline php & flash.
224
			// Will result in significantly fewer false positives than the paranoid check.
225
			if (preg_match('~(\\<\\?php\s|(?-i)[CFZ]WS[\x01-\x0E])~i', $prev_chunk . $cur_chunk) === 1)
226
			{
227
				fclose($fp);
228
				return false;
229
			}
230
		}
231
		$prev_chunk = $cur_chunk;
232
	}
233
	fclose($fp);
234
235
	return true;
236
}
237
238
/**
239
 * Sets a global $gd2 variable needed by some functions to determine
240
 * whether the GD2 library is present.
241
 *
242
 * @return bool Whether or not GD1 is available.
243
 */
244
function checkGD()
245
{
246
	global $gd2;
247
248
	// Check to see if GD is installed and what version.
249
	if (($extensionFunctions = get_extension_funcs('gd')) === false)
250
		return false;
251
252
	// Also determine if GD2 is installed and store it in a global.
253
	$gd2 = in_array('imagecreatetruecolor', $extensionFunctions) && function_exists('imagecreatetruecolor');
254
255
	return true;
256
}
257
258
/**
259
 * Checks whether the Imagick class is present.
260
 *
261
 * @return bool Whether or not the Imagick extension is available.
262
 */
263
function checkImagick()
264
{
265
	return class_exists('Imagick', false);
266
}
267
268
/**
269
 * Checks whether the MagickWand extension is present.
270
 *
271
 * @return bool Whether or not the MagickWand extension is available.
272
 */
273
function checkMagickWand()
274
{
275
	return function_exists('newMagickWand');
276
}
277
278
/**
279
 * See if we have enough memory to thumbnail an image
280
 *
281
 * @param array $sizes image size
282
 * @return bool Whether we do
283
 */
284
function imageMemoryCheck($sizes)
285
{
286
	global $modSettings;
287
288
	// doing the old 'set it and hope' way?
289
	if (empty($modSettings['attachment_thumb_memory']))
290
	{
291
		setMemoryLimit('128M');
292
		return true;
293
	}
294
295
	// 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
296
	// 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
297
	// simply a shortcut of 8bpp, 3 channels, 1.66 overhead
298
	$needed_memory = ($sizes[0] * $sizes[1] * 5);
299
300
	// if we need more, lets try to get it
301
	return setMemoryLimit($needed_memory, true);
302
}
303
304
/**
305
 * Resizes an image from a remote location or a local file.
306
 * Puts the resized image at the destination location.
307
 * The file would have the format preferred_format if possible,
308
 * otherwise the default format is jpeg.
309
 *
310
 * @param string $source The path to the source image
311
 * @param string $destination The path to the destination image
312
 * @param int $max_width The maximum allowed width
313
 * @param int $max_height The maximum allowed height
314
 * @param int $preferred_format - The preferred format (0 to use jpeg, 1 for gif, 2 to force jpeg, 3 for png, 6 for bmp and 15 for wbmp)
315
 * @return bool Whether it succeeded.
316
 */
317
function resizeImageFile($source, $destination, $max_width, $max_height, $preferred_format = 0)
318
{
319
	global $sourcedir;
320
321
	// Nothing to do without GD or IM/MW
322
	if (!checkGD() && !checkImagick() && !checkMagickWand())
323
		return false;
324
325
	static $default_formats = array(
326
		'1' => 'gif',
327
		'2' => 'jpeg',
328
		'3' => 'png',
329
		'6' => 'bmp',
330
		'15' => 'wbmp'
331
	);
332
333
	// Get the image file, we have to work with something after all
334
	$fp_destination = fopen($destination, 'wb');
335
	if ($fp_destination && (substr($source, 0, 7) == 'http://' || substr($source, 0, 8) == 'https://'))
0 ignored issues
show
introduced by
$fp_destination is of type resource, thus it always evaluated to false.
Loading history...
336
	{
337
		$fileContents = fetch_web_data($source);
338
339
		$mime_valid = check_mime_type($fileContents, implode('|', array_map('image_type_to_mime_type', array_keys($default_formats))));
340
		if (empty($mime_valid))
341
			return false;
342
343
		fwrite($fp_destination, $fileContents);
344
		fclose($fp_destination);
345
346
		$sizes = @getimagesize($destination);
347
	}
348
	elseif ($fp_destination)
0 ignored issues
show
introduced by
$fp_destination is of type resource, thus it always evaluated to false.
Loading history...
349
	{
350
		$mime_valid = check_mime_type($source, implode('|', array_map('image_type_to_mime_type', array_keys($default_formats))), true);
351
		if (empty($mime_valid))
352
			return false;
353
354
		$sizes = @getimagesize($source);
355
356
		$fp_source = fopen($source, 'rb');
357
		if ($fp_source !== false)
358
		{
359
			while (!feof($fp_source))
360
				fwrite($fp_destination, fread($fp_source, 8192));
361
			fclose($fp_source);
362
		}
363
		else
364
			$sizes = array(-1, -1, -1);
365
		fclose($fp_destination);
366
	}
367
368
	$orientation = 0;
369
	if (($exif_data = @exif_read_data($destination)) !== false && !empty($exif_data['Orientation']))
370
	{
371
		$orientation = $exif_data['Orientation'];
372
	}
373
374
	// We can't get to the file. or a previous getimagesize failed.
375
	if (empty($sizes))
376
		$sizes = array(-1, -1, -1);
377
378
	// See if we have -or- can get the needed memory for this operation
379
	// ImageMagick isn't subject to PHP's memory limits :)
380
	if (!(checkIMagick() || checkMagickWand()) && checkGD() && !imageMemoryCheck($sizes))
381
		return false;
382
383
	// A known and supported format?
384
	// @todo test PSD and gif.
385
	if ((checkImagick() || checkMagickWand()) && isset($default_formats[$sizes[2]]))
386
	{
387
		return resizeImage(null, $destination, null, null, $max_width, $max_height, true, $preferred_format, $orientation);
388
	}
389
	elseif (checkGD() && isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]]))
390
	{
391
		$imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
392
		if ($src_img = @$imagecreatefrom($destination))
393
		{
394
			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, $orientation);
0 ignored issues
show
introduced by
The condition $max_height === null is always false.
Loading history...
introduced by
The condition $max_width === null is always false.
Loading history...
395
		}
396
	}
397
398
	return false;
399
}
400
401
/**
402
 * Resizes src_img proportionally to fit within max_width and max_height limits
403
 * if it is too large.
404
 * If GD2 is present, it'll use it to achieve better quality.
405
 * It saves the new image to destination_filename, as preferred_format
406
 * if possible, default is jpeg.
407
 *
408
 * Uses Imagemagick (IMagick or MagickWand extension) or GD
409
 *
410
 * @param resource $src_img The source image
411
 * @param string $destName The path to the destination image
412
 * @param int $src_width The width of the source image
413
 * @param int $src_height The height of the source image
414
 * @param int $max_width The maximum allowed width
415
 * @param int $max_height The maximum allowed height
416
 * @param bool $force_resize = false Whether to forcibly resize it
417
 * @param int $preferred_format - 1 for gif, 2 for jpeg, 3 for png, 6 for bmp or 15 for wbmp
418
 * @param int orientation if the image should be rotated
0 ignored issues
show
Bug introduced by
The type orientation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
419
 * @return bool Whether the resize was successful
420
 */
421
function resizeImage($src_img, $destName, $src_width, $src_height, $max_width, $max_height, $force_resize = false, $preferred_format = 0, $orientation = 0)
422
{
423
	global $gd2, $modSettings;
424
425
	if (checkImagick() || checkMagickWand())
426
	{
427
		static $default_formats = array(
428
			'1' => 'gif',
429
			'2' => 'jpeg',
430
			'3' => 'png',
431
			'6' => 'bmp',
432
			'15' => 'wbmp'
433
		);
434
		$preferred_format = empty($preferred_format) || !isset($default_formats[$preferred_format]) ? 2 : $preferred_format;
435
436
		if (checkImagick())
437
		{
438
			$imagick = New Imagick($destName);
439
			$src_width = empty($src_width) ? $imagick->getImageWidth() : $src_width;
440
			$src_height = empty($src_height) ? $imagick->getImageHeight() : $src_height;
441
			$dest_width = empty($max_width) ? $src_width : $max_width;
442
			$dest_height = empty($max_height) ? $src_height : $max_height;
443
444
			if ($default_formats[$preferred_format] == 'jpeg')
445
				$imagick->setCompressionQuality(!empty($modSettings['avatar_jpeg_quality']) ? $modSettings['avatar_jpeg_quality'] : 82);
446
447
			$imagick->setImageFormat($default_formats[$preferred_format]);
448
			$imagick->resizeImage($dest_width, $dest_height, Imagick::FILTER_LANCZOS, 1, true);
449
			if ($orientation != 0 && $preferred_format == 3)
450
			{
451
				$rotate = 0;
452
				switch ($orientation)
453
				{
454
					case 3:
455
					case 4:
456
						$rotate = 180;
457
						break;
458
					case 5:
459
					case 6:
460
						$rotate = 90;
461
						break;
462
					case 7:
463
					case 8:
464
						$rotate = 270;
465
						break;
466
				}
467
				if ($rotate > 0)
468
					$imagick->rotateImage('#00000000', $rotate);
469
				if (in_array($orientation, [2, 4, 5, 7]))
470
					$imagick->flopImage();
471
			}
472
			$success = $imagick->writeImage($destName);
473
		}
474
		else
475
		{
476
			$magick_wand = newMagickWand();
0 ignored issues
show
Bug introduced by
The function newMagickWand was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

476
			$magick_wand = /** @scrutinizer ignore-call */ newMagickWand();
Loading history...
477
			MagickReadImage($magick_wand, $destName);
0 ignored issues
show
Bug introduced by
The function MagickReadImage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

477
			/** @scrutinizer ignore-call */ 
478
   MagickReadImage($magick_wand, $destName);
Loading history...
478
			$src_width = empty($src_width) ? MagickGetImageWidth($magick_wand) : $src_width;
0 ignored issues
show
Bug introduced by
The function MagickGetImageWidth was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

478
			$src_width = empty($src_width) ? /** @scrutinizer ignore-call */ MagickGetImageWidth($magick_wand) : $src_width;
Loading history...
479
			$src_height = empty($src_height) ? MagickGetImageSize($magick_wand) : $src_height;
0 ignored issues
show
Bug introduced by
The function MagickGetImageSize was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

479
			$src_height = empty($src_height) ? /** @scrutinizer ignore-call */ MagickGetImageSize($magick_wand) : $src_height;
Loading history...
480
			$dest_width = empty($max_width) ? $src_width : $max_width;
481
			$dest_height = empty($max_height) ? $src_height : $max_height;
482
483
			if ($default_formats[$preferred_format] == 'jpeg')
484
				MagickSetCompressionQuality($magick_wand, !empty($modSettings['avatar_jpeg_quality']) ? $modSettings['avatar_jpeg_quality'] : 82);
0 ignored issues
show
Bug introduced by
The function MagickSetCompressionQuality was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

484
				/** @scrutinizer ignore-call */ 
485
    MagickSetCompressionQuality($magick_wand, !empty($modSettings['avatar_jpeg_quality']) ? $modSettings['avatar_jpeg_quality'] : 82);
Loading history...
485
486
			MagickSetImageFormat($magick_wand, $default_formats[$preferred_format]);
0 ignored issues
show
Bug introduced by
The function MagickSetImageFormat was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

486
			/** @scrutinizer ignore-call */ 
487
   MagickSetImageFormat($magick_wand, $default_formats[$preferred_format]);
Loading history...
487
			MagickResizeImage($magick_wand, $dest_width, $dest_height, MW_LanczosFilter, 1, true);
0 ignored issues
show
Bug introduced by
The function MagickResizeImage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

487
			/** @scrutinizer ignore-call */ 
488
   MagickResizeImage($magick_wand, $dest_width, $dest_height, MW_LanczosFilter, 1, true);
Loading history...
Bug introduced by
The constant MW_LanczosFilter was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
488
			if ($orientation != 0)
489
			{
490
				$rotate = 0;
491
				switch ($orientation)
492
				{
493
					case 3:
494
						$rotate = 180;
495
						break;
496
					case 6:
497
						$rotate = 90;
498
						break;
499
					case 8:
500
						$rotate = 270;
501
						break;
502
				}
503
				MagickResizeImage($magick_wand, NewPixelWand('white'), $rotate);
0 ignored issues
show
Bug introduced by
The function NewPixelWand was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

503
				MagickResizeImage($magick_wand, /** @scrutinizer ignore-call */ NewPixelWand('white'), $rotate);
Loading history...
504
				if (in_array($orientation, [2, 4, 5, 7]))
505
					MagickFlopImage($magick_wand);
0 ignored issues
show
Bug introduced by
The function MagickFlopImage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

505
					/** @scrutinizer ignore-call */ 
506
     MagickFlopImage($magick_wand);
Loading history...
506
			}
507
			$success = MagickWriteImage($magick_wand, $destName);
0 ignored issues
show
Bug introduced by
The function MagickWriteImage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

507
			$success = /** @scrutinizer ignore-call */ MagickWriteImage($magick_wand, $destName);
Loading history...
508
		}
509
510
		return !empty($success);
511
	}
512
	elseif (checkGD())
513
	{
514
		$success = false;
515
516
		// Determine whether to resize to max width or to max height (depending on the limits.)
517
		if (!empty($max_width) || !empty($max_height))
518
		{
519
			if (!empty($max_width) && (empty($max_height) || round($src_height * $max_width / $src_width) <= $max_height))
520
			{
521
				$dst_width = $max_width;
522
				$dst_height = round($src_height * $max_width / $src_width);
523
			}
524
			elseif (!empty($max_height))
525
			{
526
				$dst_width = round($src_width * $max_height / $src_height);
527
				$dst_height = $max_height;
528
			}
529
530
			// Don't bother resizing if it's already smaller...
531
			if (!empty($dst_width) && !empty($dst_height) && ($dst_width < $src_width || $dst_height < $src_height || $force_resize))
532
			{
533
				// (make a true color image, because it just looks better for resizing.)
534
				if ($gd2)
535
				{
536
					$dst_img = imagecreatetruecolor($dst_width, $dst_height);
537
538
					// Deal nicely with a PNG - because we can.
539
					if ((!empty($preferred_format)) && ($preferred_format == 3))
540
					{
541
						imagealphablending($dst_img, false);
542
						if (function_exists('imagesavealpha'))
543
							imagesavealpha($dst_img, true);
544
					}
545
				}
546
				else
547
					$dst_img = imagecreate($dst_width, $dst_height);
548
549
				// Resize it!
550
				if ($gd2)
551
					imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
552
				else
553
					imagecopyresamplebicubic($dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
0 ignored issues
show
Bug introduced by
It seems like $dst_img can also be of type GdImage; however, parameter $dst_img of imagecopyresamplebicubic() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

553
					imagecopyresamplebicubic(/** @scrutinizer ignore-type */ $dst_img, $src_img, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
Loading history...
554
			}
555
			else
556
				$dst_img = $src_img;
557
		}
558
		else
559
			$dst_img = $src_img;
560
561
		if ($orientation != 0)
562
		{
563
			$rotate = 0;
564
			switch ($orientation)
565
			{
566
				case 3:
567
				case 4:
568
					$rotate = 180;
569
					break;
570
				case 5:
571
				case 6:
572
					$rotate = 270;
573
					break;
574
				case 7:
575
				case 8:
576
					$rotate = 90;
577
					break;
578
			}
579
			if ($rotate > 0)
580
				$dst_img = imagerotate($dst_img, $rotate, 0);
581
			if (in_array($orientation, [2, 4, 5, 7]))
582
				imageflip($dst_img, IMG_FLIP_HORIZONTAL);
583
		}
584
585
		// Save the image as ...
586
		if (!empty($preferred_format) && ($preferred_format == 3) && function_exists('imagepng'))
587
			$success = imagepng($dst_img, $destName);
588
		elseif (!empty($preferred_format) && ($preferred_format == 1) && function_exists('imagegif'))
589
			$success = imagegif($dst_img, $destName);
590
		elseif (function_exists('imagejpeg'))
591
			$success = imagejpeg($dst_img, $destName, !empty($modSettings['avatar_jpeg_quality']) ? $modSettings['avatar_jpeg_quality'] : 82);
592
593
		// Free the memory.
594
		imagedestroy($src_img);
595
		if ($dst_img != $src_img)
596
			imagedestroy($dst_img);
597
598
		return $success;
599
	}
600
	else
601
		// Without GD, no image resizing at all.
602
		return false;
603
}
604
605
/**
606
 * Copy image.
607
 * Used when imagecopyresample() is not available.
608
 *
609
 * @param resource $dst_img The destination image - a GD image resource
610
 * @param resource $src_img The source image - a GD image resource
611
 * @param int $dst_x The "x" coordinate of the destination image
612
 * @param int $dst_y The "y" coordinate of the destination image
613
 * @param int $src_x The "x" coordinate of the source image
614
 * @param int $src_y The "y" coordinate of the source image
615
 * @param int $dst_w The width of the destination image
616
 * @param int $dst_h The height of the destination image
617
 * @param int $src_w The width of the destination image
618
 * @param int $src_h The height of the destination image
619
 */
620
function imagecopyresamplebicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
621
{
622
	$palsize = imagecolorstotal($src_img);
623
	for ($i = 0; $i < $palsize; $i++)
624
	{
625
		$colors = imagecolorsforindex($src_img, $i);
626
		imagecolorallocate($dst_img, $colors['red'], $colors['green'], $colors['blue']);
627
	}
628
629
	$scaleX = ($src_w - 1) / $dst_w;
630
	$scaleY = ($src_h - 1) / $dst_h;
631
632
	$scaleX2 = (int) $scaleX / 2;
633
	$scaleY2 = (int) $scaleY / 2;
634
635
	for ($j = $src_y; $j < $dst_h; $j++)
636
	{
637
		$sY = (int) $j * $scaleY;
638
		$y13 = $sY + $scaleY2;
639
640
		for ($i = $src_x; $i < $dst_w; $i++)
641
		{
642
			$sX = (int) $i * $scaleX;
643
			$x34 = $sX + $scaleX2;
644
645
			$color1 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $y13));
646
			$color2 = imagecolorsforindex($src_img, imagecolorat($src_img, $sX, $sY));
647
			$color3 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $y13));
648
			$color4 = imagecolorsforindex($src_img, imagecolorat($src_img, $x34, $sY));
649
650
			$red = ($color1['red'] + $color2['red'] + $color3['red'] + $color4['red']) / 4;
651
			$green = ($color1['green'] + $color2['green'] + $color3['green'] + $color4['green']) / 4;
652
			$blue = ($color1['blue'] + $color2['blue'] + $color3['blue'] + $color4['blue']) / 4;
653
654
			$color = imagecolorresolve($dst_img, $red, $green, $blue);
655
			if ($color == -1)
656
			{
657
				if ($palsize++ < 256)
658
					imagecolorallocate($dst_img, $red, $green, $blue);
659
				$color = imagecolorclosest($dst_img, $red, $green, $blue);
660
			}
661
662
			imagesetpixel($dst_img, $i + $dst_x - $src_x, $j + $dst_y - $src_y, $color);
663
		}
664
	}
665
}
666
667
if (!function_exists('imagecreatefrombmp'))
668
{
669
	/**
670
	 * It is set only if it doesn't already exist (for forwards compatiblity.)
671
	 * It only supports uncompressed bitmaps.
672
	 *
673
	 * @param string $filename The name of the file
674
	 * @return resource An image identifier representing the bitmap image
675
	 * obtained from the given filename.
676
	 */
677
	function imagecreatefrombmp($filename)
678
	{
679
		global $gd2;
680
681
		$fp = fopen($filename, 'rb');
682
683
		$errors = error_reporting(0);
684
685
		$header = unpack('vtype/Vsize/Vreserved/Voffset', fread($fp, 14));
686
		$info = unpack('Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vcolorimportant', fread($fp, 40));
687
688
		if ($header['type'] != 0x4D42)
689
			return false;
690
691
		if ($gd2)
692
			$dst_img = imagecreatetruecolor($info['width'], $info['height']);
693
		else
694
			$dst_img = imagecreate($info['width'], $info['height']);
695
696
		$palette_size = $header['offset'] - 54;
697
		$info['ncolor'] = $palette_size / 4;
698
699
		$palette = array();
700
701
		$palettedata = fread($fp, $palette_size);
702
		$n = 0;
703
		for ($j = 0; $j < $palette_size; $j++)
704
		{
705
			$b = ord($palettedata[$j++]);
706
			$g = ord($palettedata[$j++]);
707
			$r = ord($palettedata[$j++]);
708
709
			$palette[$n++] = imagecolorallocate($dst_img, $r, $g, $b);
710
		}
711
712
		$scan_line_size = ($info['bits'] * $info['width'] + 7) >> 3;
713
		$scan_line_align = $scan_line_size & 3 ? 4 - ($scan_line_size & 3) : 0;
714
715
		for ($y = 0, $l = $info['height'] - 1; $y < $info['height']; $y++, $l--)
716
		{
717
			fseek($fp, $header['offset'] + ($scan_line_size + $scan_line_align) * $l);
718
			$scan_line = fread($fp, $scan_line_size);
719
720
			if (strlen($scan_line) < $scan_line_size)
721
				continue;
722
723
			if ($info['bits'] == 32)
724
			{
725
				$x = 0;
726
				for ($j = 0; $j < $scan_line_size; $x++)
727
				{
728
					$b = ord($scan_line[$j++]);
729
					$g = ord($scan_line[$j++]);
730
					$r = ord($scan_line[$j++]);
731
					$j++;
732
733
					$color = imagecolorexact($dst_img, $r, $g, $b);
734
					if ($color == -1)
735
					{
736
						$color = imagecolorallocate($dst_img, $r, $g, $b);
737
738
						// Gah!  Out of colors?  Stupid GD 1... try anyhow.
739
						if ($color == -1)
740
							$color = imagecolorclosest($dst_img, $r, $g, $b);
741
					}
742
743
					imagesetpixel($dst_img, $x, $y, $color);
744
				}
745
			}
746
			elseif ($info['bits'] == 24)
747
			{
748
				$x = 0;
749
				for ($j = 0; $j < $scan_line_size; $x++)
750
				{
751
					$b = ord($scan_line[$j++]);
752
					$g = ord($scan_line[$j++]);
753
					$r = ord($scan_line[$j++]);
754
755
					$color = imagecolorexact($dst_img, $r, $g, $b);
756
					if ($color == -1)
757
					{
758
						$color = imagecolorallocate($dst_img, $r, $g, $b);
759
760
						// Gah!  Out of colors?  Stupid GD 1... try anyhow.
761
						if ($color == -1)
762
							$color = imagecolorclosest($dst_img, $r, $g, $b);
763
					}
764
765
					imagesetpixel($dst_img, $x, $y, $color);
766
				}
767
			}
768
			elseif ($info['bits'] == 16)
769
			{
770
				$x = 0;
771
				for ($j = 0; $j < $scan_line_size; $x++)
772
				{
773
					$b1 = ord($scan_line[$j++]);
774
					$b2 = ord($scan_line[$j++]);
775
776
					$word = $b2 * 256 + $b1;
777
778
					$b = (($word & 31) * 255) / 31;
779
					$g = ((($word >> 5) & 31) * 255) / 31;
780
					$r = ((($word >> 10) & 31) * 255) / 31;
781
782
					// Scale the image colors up properly.
783
					$color = imagecolorexact($dst_img, $r, $g, $b);
784
					if ($color == -1)
785
					{
786
						$color = imagecolorallocate($dst_img, $r, $g, $b);
787
788
						// Gah!  Out of colors?  Stupid GD 1... try anyhow.
789
						if ($color == -1)
790
							$color = imagecolorclosest($dst_img, $r, $g, $b);
791
					}
792
793
					imagesetpixel($dst_img, $x, $y, $color);
794
				}
795
			}
796
			elseif ($info['bits'] == 8)
797
			{
798
				$x = 0;
799
				for ($j = 0; $j < $scan_line_size; $x++)
800
					imagesetpixel($dst_img, $x, $y, $palette[ord($scan_line[$j++])]);
801
			}
802
			elseif ($info['bits'] == 4)
803
			{
804
				$x = 0;
805
				for ($j = 0; $j < $scan_line_size; $x++)
806
				{
807
					$byte = ord($scan_line[$j++]);
808
809
					imagesetpixel($dst_img, $x, $y, $palette[(int) ($byte / 16)]);
810
811
					if (++$x < $info['width'])
812
						imagesetpixel($dst_img, $x, $y, $palette[$byte & 15]);
813
				}
814
			}
815
			elseif ($info['bits'] == 1)
816
			{
817
				$x = 0;
818
				for ($j = 0; $j < $scan_line_size; $x++)
819
				{
820
					$byte = ord($scan_line[$j++]);
821
822
					imagesetpixel($dst_img, $x, $y, $palette[(($byte) & 128) != 0]);
823
824
					for ($shift = 1; $shift < 8; $shift++)
825
					{
826
						if (++$x < $info['width'])
827
							imagesetpixel($dst_img, $x, $y, $palette[(($byte << $shift) & 128) != 0]);
828
					}
829
				}
830
			}
831
		}
832
833
		fclose($fp);
834
835
		error_reporting($errors);
836
837
		return $dst_img;
838
	}
839
}
840
841
/**
842
 * Writes a gif file to disk as a png file.
843
 *
844
 * @param gif_file $gif A gif image resource
845
 * @param string $lpszFileName The name of the file
846
 * @param int $background_color The background color
847
 * @return bool Whether the operation was successful
848
 */
849
function gif_outputAsPng($gif, $lpszFileName, $background_color = -1)
850
{
851
	if (!is_a($gif, 'gif_file') || $lpszFileName == '')
852
		return false;
853
854
	if (($fd = $gif->get_png_data($background_color)) === false)
855
		return false;
856
857
	if (($fh = @fopen($lpszFileName, 'wb')) === false)
858
		return false;
859
860
	@fwrite($fh, $fd, strlen($fd));
861
	@fflush($fh);
862
	@fclose($fh);
863
864
	return true;
865
}
866
867
/**
868
 * Show an image containing the visual verification code for registration.
869
 * Requires the GD extension.
870
 * Uses a random font for each letter from default_theme_dir/fonts.
871
 * Outputs a gif or a png (depending on whether gif ix supported).
872
 *
873
 * @param string $code The code to display
874
 * @return void|false False if something goes wrong.
875
 */
876
function showCodeImage($code)
877
{
878
	global $gd2, $settings, $user_info, $modSettings;
879
880
	// Note: The higher the value of visual_verification_type the harder the verification is - from 0 as disabled through to 4 as "Very hard".
881
882
	// What type are we going to be doing?
883
	$imageType = $modSettings['visual_verification_type'];
884
	// Special case to allow the admin center to show samples.
885
	if ($user_info['is_admin'] && isset($_GET['type']))
886
		$imageType = (int) $_GET['type'];
887
888
	// Some quick references for what we do.
889
	// Do we show no, low or high noise?
890
	$noiseType = $imageType == 3 ? 'low' : ($imageType == 4 ? 'high' : ($imageType == 5 ? 'extreme' : 'none'));
891
	// Can we have more than one font in use?
892
	$varyFonts = $imageType > 3 ? true : false;
893
	// Just a plain white background?
894
	$simpleBGColor = $imageType < 3 ? true : false;
895
	// Plain black foreground?
896
	$simpleFGColor = $imageType == 0 ? true : false;
897
	// High much to rotate each character.
898
	$rotationType = $imageType == 1 ? 'none' : ($imageType > 3 ? 'low' : 'high');
899
	// Do we show some characters inversed?
900
	$showReverseChars = $imageType > 3 ? true : false;
901
	// Special case for not showing any characters.
902
	$disableChars = $imageType == 0 ? true : false;
903
	// What do we do with the font colors. Are they one color, close to one color or random?
904
	$fontColorType = $imageType == 1 ? 'plain' : ($imageType > 3 ? 'random' : 'cyclic');
905
	// Are the fonts random sizes?
906
	$fontSizeRandom = $imageType > 3 ? true : false;
907
	// How much space between characters?
908
	$fontHorSpace = $imageType > 3 ? 'high' : ($imageType == 1 ? 'medium' : 'minus');
909
	// Where do characters sit on the image? (Fixed position or random/very random)
910
	$fontVerPos = $imageType == 1 ? 'fixed' : ($imageType > 3 ? 'vrandom' : 'random');
911
	// Make font semi-transparent?
912
	$fontTrans = $imageType == 2 || $imageType == 3 ? true : false;
913
	// Give the image a border?
914
	$hasBorder = $simpleBGColor;
915
916
	// The amount of pixels inbetween characters.
917
	$character_spacing = 1;
918
919
	// What color is the background - generally white unless we're on "hard".
920
	if ($simpleBGColor)
921
		$background_color = array(255, 255, 255);
922
	else
923
		$background_color = isset($settings['verification_background']) ? $settings['verification_background'] : array(236, 237, 243);
924
925
	// The color of the characters shown (red, green, blue).
926
	if ($simpleFGColor)
927
		$foreground_color = array(0, 0, 0);
928
	else
929
	{
930
		$foreground_color = array(64, 101, 136);
931
932
		// Has the theme author requested a custom color?
933
		if (isset($settings['verification_foreground']))
934
			$foreground_color = $settings['verification_foreground'];
935
	}
936
937
	if (!is_dir($settings['default_theme_dir'] . '/fonts'))
938
		return false;
939
940
	// Get a list of the available fonts.
941
	$font_dir = dir($settings['default_theme_dir'] . '/fonts');
942
	$font_list = array();
943
	$ttfont_list = array();
944
	$endian = unpack('v', pack('S', 0x00FF)) === 0x00FF;
945
	while ($entry = $font_dir->read())
946
	{
947
		if (preg_match('~^(.+)\.gdf$~', $entry, $matches) === 1)
948
		{
949
			if ($endian ^ (strpos($entry, '_end.gdf') === false))
950
				$font_list[] = $entry;
951
		}
952
		elseif (preg_match('~^(.+)\.ttf$~', $entry, $matches) === 1)
953
			$ttfont_list[] = $entry;
954
	}
955
956
	if (empty($font_list))
957
		return false;
958
959
	// For non-hard things don't even change fonts.
960
	if (!$varyFonts)
961
	{
962
		$font_list = array($font_list[0]);
963
		// Try use Screenge if we can - it looks good!
964
		if (in_array('AnonymousPro.ttf', $ttfont_list))
965
			$ttfont_list = array('AnonymousPro.ttf');
966
		else
967
			$ttfont_list = empty($ttfont_list) ? array() : array($ttfont_list[0]);
968
	}
969
970
	// Create a list of characters to be shown.
971
	$characters = array();
972
	$loaded_fonts = array();
973
	for ($i = 0; $i < strlen($code); $i++)
974
	{
975
		$characters[$i] = array(
976
			'id' => $code[$i],
977
			'font' => array_rand($font_list),
978
		);
979
980
		$loaded_fonts[$characters[$i]['font']] = null;
981
	}
982
983
	// Load all fonts and determine the maximum font height.
984
	foreach ($loaded_fonts as $font_index => $dummy)
985
		$loaded_fonts[$font_index] = imageloadfont($settings['default_theme_dir'] . '/fonts/' . $font_list[$font_index]);
986
987
	// Determine the dimensions of each character.
988
	if ($imageType == 4 || $imageType == 5)
989
		$extra = 80;
990
	else
991
		$extra = 45;
992
993
	$total_width = $character_spacing * strlen($code) + $extra;
994
	$max_height = 0;
995
	foreach ($characters as $char_index => $character)
996
	{
997
		$characters[$char_index]['width'] = imagefontwidth($loaded_fonts[$character['font']]);
998
		$characters[$char_index]['height'] = imagefontheight($loaded_fonts[$character['font']]);
999
1000
		$max_height = max($characters[$char_index]['height'] + 5, $max_height);
1001
		$total_width += $characters[$char_index]['width'];
1002
	}
1003
1004
	// Create an image.
1005
	$code_image = $gd2 ? imagecreatetruecolor($total_width, $max_height) : imagecreate($total_width, $max_height);
1006
1007
	// Draw the background.
1008
	$bg_color = imagecolorallocate($code_image, $background_color[0], $background_color[1], $background_color[2]);
1009
	imagefilledrectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $bg_color);
1010
1011
	// Randomize the foreground color a little.
1012
	for ($i = 0; $i < 3; $i++)
1013
		$foreground_color[$i] = mt_rand(max($foreground_color[$i] - 3, 0), min($foreground_color[$i] + 3, 255));
1014
	$fg_color = imagecolorallocate($code_image, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
1015
1016
	// Color for the dots.
1017
	for ($i = 0; $i < 3; $i++)
1018
		$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);
1019
	$randomness_color = imagecolorallocate($code_image, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dotbgcolor does not seem to be defined for all execution paths leading up to this point.
Loading history...
1020
1021
	// Some squares/rectanges for new extreme level
1022
	if ($noiseType == 'extreme')
1023
	{
1024
		for ($i = 0; $i < mt_rand(1, 5); $i++)
1025
		{
1026
			$x1 = mt_rand(0, $total_width / 4);
1027
			$x2 = $x1 + round(rand($total_width / 4, $total_width));
1028
			$y1 = mt_rand(0, $max_height);
1029
			$y2 = $y1 + round(rand(0, $max_height / 3));
1030
			imagefilledrectangle($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
0 ignored issues
show
Bug introduced by
$x2 of type double is incompatible with the type integer expected by parameter $x2 of imagefilledrectangle(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1030
			imagefilledrectangle($code_image, $x1, $y1, /** @scrutinizer ignore-type */ $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
Loading history...
Bug introduced by
$y2 of type double is incompatible with the type integer expected by parameter $y2 of imagefilledrectangle(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1030
			imagefilledrectangle($code_image, $x1, $y1, $x2, /** @scrutinizer ignore-type */ $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
Loading history...
1031
		}
1032
	}
1033
1034
	// Fill in the characters.
1035
	if (!$disableChars)
1036
	{
1037
		$cur_x = 0;
1038
		foreach ($characters as $char_index => $character)
1039
		{
1040
			// Can we use true type fonts?
1041
			$can_do_ttf = function_exists('imagettftext');
1042
1043
			// How much rotation will we give?
1044
			if ($rotationType == 'none')
1045
				$angle = 0;
1046
			else
1047
				$angle = mt_rand(-100, 100) / ($rotationType == 'high' ? 6 : 10);
1048
1049
			// What color shall we do it?
1050
			if ($fontColorType == 'cyclic')
1051
			{
1052
				// Here we'll pick from a set of acceptance types.
1053
				$colors = array(
1054
					array(10, 120, 95),
1055
					array(46, 81, 29),
1056
					array(4, 22, 154),
1057
					array(131, 9, 130),
1058
					array(0, 0, 0),
1059
					array(143, 39, 31),
1060
				);
1061
				if (!isset($last_index))
1062
					$last_index = -1;
1063
				$new_index = $last_index;
1064
				while ($last_index == $new_index)
1065
					$new_index = mt_rand(0, count($colors) - 1);
1066
				$char_fg_color = $colors[$new_index];
1067
				$last_index = $new_index;
1068
			}
1069
			elseif ($fontColorType == 'random')
1070
				$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]));
1071
			else
1072
				$char_fg_color = array($foreground_color[0], $foreground_color[1], $foreground_color[2]);
1073
1074
			if (!empty($can_do_ttf))
1075
			{
1076
				// GD2 handles font size differently.
1077
				if ($fontSizeRandom)
1078
					$font_size = $gd2 ? mt_rand(17, 19) : mt_rand(18, 25);
1079
				else
1080
					$font_size = $gd2 ? 18 : 24;
1081
1082
				// Work out the sizes - also fix the character width cause TTF not quite so wide!
1083
				$font_x = $fontHorSpace == 'minus' && $cur_x > 0 ? $cur_x - 3 : $cur_x + 5;
1084
				$font_y = $max_height - ($fontVerPos == 'vrandom' ? mt_rand(2, 8) : ($fontVerPos == 'random' ? mt_rand(3, 5) : 5));
1085
1086
				// What font face?
1087
				if (!empty($ttfont_list))
1088
					$fontface = $settings['default_theme_dir'] . '/fonts/' . $ttfont_list[mt_rand(0, count($ttfont_list) - 1)];
1089
1090
				// What color are we to do it in?
1091
				$is_reverse = $showReverseChars ? mt_rand(0, 1) : false;
1092
				$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]);
1093
1094
				$fontcord = @imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $char_color, $fontface, $character['id']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fontface does not seem to be defined for all execution paths leading up to this point.
Loading history...
1095
				if (empty($fontcord))
1096
					$can_do_ttf = false;
1097
				elseif ($is_reverse)
0 ignored issues
show
Bug Best Practice introduced by
The expression $is_reverse of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1098
				{
1099
					imagefilledpolygon($code_image, $fontcord, 4, $fg_color);
1100
					// Put the character back!
1101
					imagettftext($code_image, $font_size, $angle, $font_x, $font_y, $randomness_color, $fontface, $character['id']);
1102
				}
1103
1104
				if ($can_do_ttf)
1105
					$cur_x = max($fontcord[2], $fontcord[4]) + ($angle == 0 ? 0 : 3);
1106
			}
1107
1108
			if (!$can_do_ttf)
1109
			{
1110
				// Rotating the characters a little...
1111
				if (function_exists('imagerotate'))
1112
				{
1113
					$char_image = $gd2 ? imagecreatetruecolor($character['width'], $character['height']) : imagecreate($character['width'], $character['height']);
1114
					$char_bgcolor = imagecolorallocate($char_image, $background_color[0], $background_color[1], $background_color[2]);
1115
					imagefilledrectangle($char_image, 0, 0, $character['width'] - 1, $character['height'] - 1, $char_bgcolor);
1116
					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]));
1117
					$rotated_char = imagerotate($char_image, mt_rand(-100, 100) / 10, $char_bgcolor);
1118
					imagecopy($code_image, $rotated_char, $cur_x, 0, 0, 0, $character['width'], $character['height']);
1119
					imagedestroy($rotated_char);
1120
					imagedestroy($char_image);
1121
				}
1122
1123
				// Sorry, no rotation available.
1124
				else
1125
					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]));
0 ignored issues
show
Bug introduced by
floor($max_height - $character['height'] / 2) of type double is incompatible with the type integer expected by parameter $y of imagechar(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1125
					imagechar($code_image, $loaded_fonts[$character['font']], $cur_x, /** @scrutinizer ignore-type */ floor(($max_height - $character['height']) / 2), $character['id'], imagecolorallocate($code_image, $char_fg_color[0], $char_fg_color[1], $char_fg_color[2]));
Loading history...
1126
				$cur_x += $character['width'] + $character_spacing;
1127
			}
1128
		}
1129
	}
1130
	// If disabled just show a cross.
1131
	else
1132
	{
1133
		imageline($code_image, 0, 0, $total_width, $max_height, $fg_color);
1134
		imageline($code_image, 0, $max_height, $total_width, 0, $fg_color);
1135
	}
1136
1137
	// Make the background color transparent on the hard image.
1138
	if (!$simpleBGColor)
1139
		imagecolortransparent($code_image, $bg_color);
1140
	if ($hasBorder)
1141
		imagerectangle($code_image, 0, 0, $total_width - 1, $max_height - 1, $fg_color);
1142
1143
	// Add some noise to the background?
1144
	if ($noiseType != 'none')
1145
	{
1146
		for ($i = mt_rand(0, 2); $i < $max_height; $i += mt_rand(1, 2))
1147
			for ($j = mt_rand(0, 10); $j < $total_width; $j += mt_rand(1, 10))
1148
				imagesetpixel($code_image, $j, $i, mt_rand(0, 1) ? $fg_color : $randomness_color);
1149
1150
		// Put in some lines too?
1151
		if ($noiseType != 'extreme')
1152
		{
1153
			$num_lines = $noiseType == 'high' ? mt_rand(3, 7) : mt_rand(2, 5);
1154
			for ($i = 0; $i < $num_lines; $i++)
1155
			{
1156
				if (mt_rand(0, 1))
1157
				{
1158
					$x1 = mt_rand(0, $total_width);
1159
					$x2 = mt_rand(0, $total_width);
1160
					$y1 = 0;
1161
					$y2 = $max_height;
1162
				}
1163
				else
1164
				{
1165
					$y1 = mt_rand(0, $max_height);
1166
					$y2 = mt_rand(0, $max_height);
1167
					$x1 = 0;
1168
					$x2 = $total_width;
1169
				}
1170
				imagesetthickness($code_image, mt_rand(1, 2));
1171
				imageline($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
1172
			}
1173
		}
1174
		else
1175
		{
1176
			// Put in some ellipse
1177
			$num_ellipse = $noiseType == 'extreme' ? mt_rand(6, 12) : mt_rand(2, 6);
1178
			for ($i = 0; $i < $num_ellipse; $i++)
1179
			{
1180
				$x1 = round(rand(($total_width / 4) * -1, $total_width + ($total_width / 4)));
1181
				$x2 = round(rand($total_width / 2, 2 * $total_width));
1182
				$y1 = round(rand(($max_height / 4) * -1, $max_height + ($max_height / 4)));
1183
				$y2 = round(rand($max_height / 2, 2 * $max_height));
1184
				imageellipse($code_image, $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
0 ignored issues
show
Bug introduced by
$x2 of type double is incompatible with the type integer expected by parameter $width of imageellipse(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1184
				imageellipse($code_image, $x1, $y1, /** @scrutinizer ignore-type */ $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
Loading history...
Bug introduced by
$x1 of type double is incompatible with the type integer expected by parameter $cx of imageellipse(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1184
				imageellipse($code_image, /** @scrutinizer ignore-type */ $x1, $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
Loading history...
Bug introduced by
$y1 of type double is incompatible with the type integer expected by parameter $cy of imageellipse(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1184
				imageellipse($code_image, $x1, /** @scrutinizer ignore-type */ $y1, $x2, $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
Loading history...
Bug introduced by
$y2 of type double is incompatible with the type integer expected by parameter $height of imageellipse(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1184
				imageellipse($code_image, $x1, $y1, $x2, /** @scrutinizer ignore-type */ $y2, mt_rand(0, 1) ? $fg_color : $randomness_color);
Loading history...
1185
			}
1186
		}
1187
	}
1188
1189
	// Show the image.
1190
	if (function_exists('imagegif'))
1191
	{
1192
		header('content-type: image/gif');
1193
		imagegif($code_image);
1194
	}
1195
	else
1196
	{
1197
		header('content-type: image/png');
1198
		imagepng($code_image);
1199
	}
1200
1201
	// Bail out.
1202
	imagedestroy($code_image);
1203
	die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1204
}
1205
1206
/**
1207
 * Show a letter for the visual verification code.
1208
 * Alternative function for showCodeImage() in case GD is missing.
1209
 * Includes an image from a random sub directory of default_theme_dir/fonts.
1210
 *
1211
 * @param string $letter A letter to show as an image
1212
 * @return void|false False if something went wrong
1213
 */
1214
function showLetterImage($letter)
1215
{
1216
	global $settings;
1217
1218
	if (!is_dir($settings['default_theme_dir'] . '/fonts'))
1219
		return false;
1220
1221
	// Get a list of the available font directories.
1222
	$font_dir = dir($settings['default_theme_dir'] . '/fonts');
1223
	$font_list = array();
1224
	while ($entry = $font_dir->read())
1225
		if ($entry[0] !== '.' && is_dir($settings['default_theme_dir'] . '/fonts/' . $entry) && file_exists($settings['default_theme_dir'] . '/fonts/' . $entry . '.gdf'))
1226
			$font_list[] = $entry;
1227
1228
	if (empty($font_list))
1229
		return false;
1230
1231
	// Pick a random font.
1232
	$random_font = $font_list[array_rand($font_list)];
1233
1234
	// Check if the given letter exists.
1235
	if (!file_exists($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . strtoupper($letter) . '.png'))
1236
		return false;
1237
1238
	// Include it!
1239
	header('content-type: image/png');
1240
	include($settings['default_theme_dir'] . '/fonts/' . $random_font . '/' . strtoupper($letter) . '.png');
1241
1242
	// Nothing more to come.
1243
	die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1244
}
1245
1246
?>