Test Failed
Push — master ( 398493...d4ef72 )
by Michael
11:04
created

phpthumb_functions   F

Complexity

Total Complexity 218

Size/Duplication

Total Lines 906
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 218
dl 0
loc 906
rs 1.263
c 0
b 0
f 0

44 Methods

Rating   Name   Duplication   Size   Complexity  
A PixelColorDifferencePercent() 0 6 2
B version_compare_replacement() 0 25 4
B ImageTypeToMIMEtype() 0 32 5
A GrayscaleValue() 0 2 1
A ImageCopyRespectAlpha() 0 21 3
B ScaleToFitInBox() 0 19 9
C version_compare_replacement_sub() 0 57 20
B ImageCreateFunction() 0 12 5
A IsHexColor() 0 2 1
A phpinfo_array() 0 10 2
A escapeshellarg_replacement() 0 5 3
B ImageCopyResampleBicubic() 0 49 4
A GetPixelColor() 0 5 2
A GrayscalePixel() 0 3 1
A TranslateWHbyAngle() 0 7 2
A GrayscalePixelRGB() 0 5 1
A HexColorXOR() 0 2 1
A ImageColorAllocateAlphaSafe() 0 5 3
B FunctionIsDisabled() 0 17 5
D SafeURLread() 0 86 17
A ImageHexColorAllocate() 0 14 4
B filesize_remote() 0 18 6
C GetAllFilesInSubfolders() 0 30 8
C ProportionalResize() 0 22 8
C URLreadFsock() 0 50 14
A gd_is_bundled() 0 7 2
A gd_version() 0 13 3
B exif_info() 0 23 5
A LittleEndian2String() 0 7 2
A md5_file_safe() 0 15 4
A SanitizeFilename() 0 6 2
B ParseURLbetter() 0 16 5
D SafeExec() 0 38 9
A OneOfThese() 0 9 3
A CaseInsensitiveInArray() 0 10 4
A builtin_function_exists() 0 9 3
A ApacheLookupURIarray() 0 14 4
A HexCharDisplay() 0 7 2
A user_function_exists() 0 9 3
A PasswordStrength() 0 7 1
B filedate_remote() 0 18 6
A nonempty_min() 0 9 3
C EnsureDirectoryExists() 0 30 11
F CleanUpURLencoding() 0 36 15

How to fix   Complexity   

Complex Class

Complex classes like phpthumb_functions often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use phpthumb_functions, and based on these observations, apply Extract Interface, too.

1
<?php
2
//////////////////////////////////////////////////////////////
3
//   phpThumb() by James Heinrich <[email protected]>   //
4
//        available at http://phpthumb.sourceforge.net      //
5
//         and/or https://github.com/JamesHeinrich/phpThumb //
6
//////////////////////////////////////////////////////////////
7
///                                                         //
8
// phpthumb.functions.php - general support functions       //
9
//                                                         ///
10
//////////////////////////////////////////////////////////////
11
12
class phpthumb_functions {
13
14
	public static function user_function_exists($functionname) {
15
		if (function_exists('get_defined_functions')) {
16
			static $get_defined_functions = array();
17
			if (empty($get_defined_functions)) {
18
				$get_defined_functions = get_defined_functions();
19
			}
20
			return in_array(strtolower($functionname), $get_defined_functions['user']);
21
		}
22
		return function_exists($functionname);
23
	}
24
25
26
	public static function builtin_function_exists($functionname) {
27
		if (function_exists('get_defined_functions')) {
28
			static $get_defined_functions = array();
29
			if (empty($get_defined_functions)) {
30
				$get_defined_functions = get_defined_functions();
31
			}
32
			return in_array(strtolower($functionname), $get_defined_functions['internal']);
33
		}
34
		return function_exists($functionname);
35
	}
36
37
38
	public static function version_compare_replacement_sub($version1, $version2, $operator='') {
39
		// If you specify the third optional operator argument, you can test for a particular relationship.
40
		// The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
41
		// Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
42
43
		// If a part contains special version strings these are handled in the following order:
44
		// (any string not found in this list) < (dev) < (alpha = a) < (beta = b) < (RC = rc) < (#) < (pl = p)
45
		static $versiontype_lookup = array();
46
		if (empty($versiontype_lookup)) {
47
			$versiontype_lookup['dev']   = 10001;
48
			$versiontype_lookup['a']     = 10002;
49
			$versiontype_lookup['alpha'] = 10002;
50
			$versiontype_lookup['b']     = 10003;
51
			$versiontype_lookup['beta']  = 10003;
52
			$versiontype_lookup['RC']    = 10004;
53
			$versiontype_lookup['rc']    = 10004;
54
			$versiontype_lookup['#']     = 10005;
55
			$versiontype_lookup['pl']    = 10006;
56
			$versiontype_lookup['p']     = 10006;
57
		}
58
		$version1 = (isset($versiontype_lookup[$version1]) ? $versiontype_lookup[$version1] : $version1);
59
		$version2 = (isset($versiontype_lookup[$version2]) ? $versiontype_lookup[$version2] : $version2);
60
61
		switch ($operator) {
62
			case '<':
63
			case 'lt':
64
				return (int) ($version1 < $version2);
65
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
66
			case '<=':
67
			case 'le':
68
				return (int) ($version1 <= $version2);
69
				break;
70
			case '>':
71
			case 'gt':
72
				return (int) ($version1 > $version2);
73
				break;
74
			case '>=':
75
			case 'ge':
76
				return (int) ($version1 >= $version2);
77
				break;
78
			case '==':
79
			case '=':
80
			case 'eq':
81
				return (int) ($version1 == $version2);
82
				break;
83
			case '!=':
84
			case '<>':
85
			case 'ne':
86
				return (int) ($version1 != $version2);
87
				break;
88
		}
89
		if ($version1 == $version2) {
90
			return 0;
91
		} elseif ($version1 < $version2) {
92
			return -1;
93
		}
94
		return 1;
95
	}
96
97
98
	public static function version_compare_replacement($version1, $version2, $operator='') {
99
		if (function_exists('version_compare')) {
100
			// built into PHP v4.1.0+
101
			return version_compare($version1, $version2, $operator);
102
		}
103
104
		// The function first replaces _, - and + with a dot . in the version strings
105
		$version1 = strtr($version1, '_-+', '...');
106
		$version2 = strtr($version2, '_-+', '...');
107
108
		// and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
109
		// Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
110
		$version1 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version1);
111
		$version2 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version2);
112
113
		$parts1 = explode('.', $version1);
114
		$parts2 = explode('.', $version1);
115
		$parts_count = max(count($parts1), count($parts2));
116
		for ($i = 0; $i < $parts_count; $i++) {
117
			$comparison = self::version_compare_replacement_sub($version1, $version2, $operator);
118
			if ($comparison != 0) {
119
				return $comparison;
120
			}
121
		}
122
		return 0;
123
	}
124
125
	public static function escapeshellarg_replacement($arg) {
126
		if (function_exists('escapeshellarg') && !self::FunctionIsDisabled('escapeshellarg')) {
127
			return escapeshellarg($arg);
128
		}
129
		return '\''.str_replace('\'', '\\\'', $arg).'\'';
130
	}
131
132
	public static function phpinfo_array() {
133
		static $phpinfo_array = array();
134
		if (empty($phpinfo_array)) {
135
			ob_start();
136
			phpinfo();
137
			$phpinfo = ob_get_contents();
138
			ob_end_clean();
139
			$phpinfo_array = explode("\n", $phpinfo);
140
		}
141
		return $phpinfo_array;
142
	}
143
144
145
	public static function exif_info() {
146
		static $exif_info = array();
147
		if (empty($exif_info)) {
148
			// based on code by johnschaefer at gmx dot de
149
			// from PHP help on gd_info()
150
			$exif_info = array(
151
				'EXIF Support'           => '',
152
				'EXIF Version'           => '',
153
				'Supported EXIF Version' => '',
154
				'Supported filetypes'    => ''
155
			);
156
			$phpinfo_array = self::phpinfo_array();
157
			foreach ($phpinfo_array as $line) {
158
				$line = trim(strip_tags($line));
159
				foreach ($exif_info as $key => $value) {
160
					if (strpos($line, $key) === 0) {
161
						$newvalue = trim(str_replace($key, '', $line));
162
						$exif_info[$key] = $newvalue;
163
					}
164
				}
165
			}
166
		}
167
		return $exif_info;
168
	}
169
170
171
	public static function ImageTypeToMIMEtype($imagetype) {
172
		if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
173
			// PHP v4.3.0+
174
			return image_type_to_mime_type($imagetype);
175
		}
176
		static $image_type_to_mime_type = array(
177
			1  => 'image/gif',                     // IMAGETYPE_GIF
178
			2  => 'image/jpeg',                    // IMAGETYPE_JPEG
179
			3  => 'image/png',                     // IMAGETYPE_PNG
180
			4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
181
			5  => 'image/psd',                     // IMAGETYPE_PSD
182
			6  => 'image/bmp',                     // IMAGETYPE_BMP
183
			7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
184
			8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
185
			9  => 'application/octet-stream',      // IMAGETYPE_JPC
186
			10 => 'image/jp2',                     // IMAGETYPE_JP2
187
			11 => 'application/octet-stream',      // IMAGETYPE_JPX
188
			12 => 'application/octet-stream',      // IMAGETYPE_JB2
189
			13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
190
			14 => 'image/iff',                     // IMAGETYPE_IFF
191
			15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
192
			16 => 'image/xbm',                     // IMAGETYPE_XBM
193
194
			'gif'  => 'image/gif',                 // IMAGETYPE_GIF
195
			'jpg'  => 'image/jpeg',                // IMAGETYPE_JPEG
196
			'jpeg' => 'image/jpeg',                // IMAGETYPE_JPEG
197
			'png'  => 'image/png',                 // IMAGETYPE_PNG
198
			'bmp'  => 'image/bmp',                 // IMAGETYPE_BMP
199
			'ico'  => 'image/x-icon',
200
		);
201
202
		return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
203
	}
204
205
206
	public static function TranslateWHbyAngle($width, $height, $angle) {
207
		if (($angle % 180) == 0) {
208
			return array($width, $height);
209
		}
210
		$newwidth  = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
211
		$newheight = (abs(sin(deg2rad($angle))) * $width)  + (abs(cos(deg2rad($angle))) * $height);
212
		return array($newwidth, $newheight);
213
	}
214
215
	public static function HexCharDisplay($string) {
216
		$len = strlen($string);
217
		$output = '';
218
		for ($i = 0; $i < $len; $i++) {
219
			$output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
220
		}
221
		return $output;
222
	}
223
224
225
	public static function IsHexColor($HexColorString) {
226
		return preg_match('#^[0-9A-F]{6}$#i', $HexColorString);
227
	}
228
229
230
	public static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
231
		if (self::version_compare_replacement(PHP_VERSION, '4.3.2', '>=') && ($alpha !== false)) {
232
			return imagecolorallocatealpha($gdimg_hexcolorallocate, $R, $G, $B, (int) $alpha);
233
		} else {
234
			return imagecolorallocate($gdimg_hexcolorallocate, $R, $G, $B);
235
		}
236
	}
237
238
	public static function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
239
		if (!is_resource($gdimg_hexcolorallocate)) {
240
			die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
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...
241
		}
242
		if (self::IsHexColor($HexColorString)) {
243
			$R = hexdec(substr($HexColorString, 0, 2));
244
			$G = hexdec(substr($HexColorString, 2, 2));
245
			$B = hexdec(substr($HexColorString, 4, 2));
246
			return self::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
247
		}
248
		if ($dieOnInvalid) {
249
			die('Invalid hex color string: "'.$HexColorString.'"');
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...
250
		}
251
		return imagecolorallocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
252
	}
253
254
255
	public static function HexColorXOR($hexcolor) {
256
		return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
257
	}
258
259
260
	public static function GetPixelColor(&$img, $x, $y) {
261
		if (!is_resource($img)) {
262
			return false;
263
		}
264
		return @imagecolorsforindex($img, @imagecolorat($img, $x, $y));
265
	}
266
267
268
	public static function PixelColorDifferencePercent($currentPixel, $targetPixel) {
269
		$diff = 0;
270
		foreach ($targetPixel as $channel => $currentvalue) {
271
			$diff = max($diff, (max($currentPixel[$channel], $targetPixel[$channel]) - min($currentPixel[$channel], $targetPixel[$channel])) / 255);
272
		}
273
		return $diff * 100;
274
	}
275
276
	public static function GrayscaleValue($r, $g, $b) {
277
		return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
278
	}
279
280
281
	public static function GrayscalePixel($OriginalPixel) {
282
		$gray = self::GrayscaleValue($OriginalPixel[ 'red'], $OriginalPixel[ 'green'], $OriginalPixel[ 'blue']);
283
		return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
284
	}
285
286
287
	public static function GrayscalePixelRGB($rgb) {
288
		$r = ($rgb >> 16) & 0xFF;
289
		$g = ($rgb >>  8) & 0xFF;
290
		$b =  $rgb        & 0xFF;
291
		return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
292
	}
293
294
295
	public static function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
296
		$maxwidth  = (null === $maxwidth  ? $width  : $maxwidth);
297
		$maxheight = (null === $maxheight ? $height : $maxheight);
298
		$scale_x = 1;
299
		$scale_y = 1;
300
		if (($width > $maxwidth) || ($width < $maxwidth)) {
301
			$scale_x = ($maxwidth / $width);
302
		}
303
		if (($height > $maxheight) || ($height < $maxheight)) {
304
			$scale_y = ($maxheight / $height);
305
		}
306
		$scale = min($scale_x, $scale_y);
307
		if (!$allow_enlarge) {
308
			$scale = min($scale, 1);
309
		}
310
		if (!$allow_reduce) {
311
			$scale = max($scale, 1);
312
		}
313
		return $scale;
314
	}
315
316
	public static function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
317
		// ron at korving dot demon dot nl
318
		// http://www.php.net/imagecopyresampled
319
320
		$scaleX = ($src_w - 1) / $dst_w;
321
		$scaleY = ($src_h - 1) / $dst_h;
322
323
		$scaleX2 = $scaleX / 2.0;
324
		$scaleY2 = $scaleY / 2.0;
325
326
		$isTrueColor = imageistruecolor($src_img);
327
328
		for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
329
			$sY   = $y * $scaleY;
330
			$siY  = (int) $sY;
331
			$siY2 = (int) $sY + $scaleY2;
332
333
			for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
334
				$sX   = $x * $scaleX;
335
				$siX  = (int) $sX;
336
				$siX2 = (int) $sX + $scaleX2;
337
338
				if ($isTrueColor) {
339
340
					$c1 = imagecolorat($src_img, $siX, $siY2);
341
					$c2 = imagecolorat($src_img, $siX, $siY);
342
					$c3 = imagecolorat($src_img, $siX2, $siY2);
343
					$c4 = imagecolorat($src_img, $siX2, $siY);
344
345
					$r = (( $c1             +  $c2             +  $c3             +  $c4            ) >> 2) & 0xFF0000;
346
					$g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
347
					$b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
348
349
				} else {
350
351
					$c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
352
					$c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
353
					$c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
354
					$c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));
355
356
					$r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red'] )  << 14;
357
					$g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) <<  6;
358
					$b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >>  2;
359
360
				}
361
				imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
362
			}
363
		}
364
		return true;
365
	}
366
367
368
	public static function ImageCreateFunction($x_size, $y_size) {
369
		$ImageCreateFunction = 'imagecreate';
370
		if (self::gd_version() >= 2.0) {
371
			$ImageCreateFunction = 'imagecreatetruecolor';
372
		}
373
		if (!function_exists($ImageCreateFunction)) {
374
			return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
0 ignored issues
show
Bug Best Practice introduced by
The method phpthumb::ErrorImage() is not static, but was called statically. ( Ignorable by Annotation )

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

374
			return phpthumb::/** @scrutinizer ignore-call */ ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
Loading history...
375
		}
376
		if (($x_size <= 0) || ($y_size <= 0)) {
377
			return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
378
		}
379
		return $ImageCreateFunction(round($x_size), round($y_size));
380
	}
381
382
383
	public static function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
384
		$opacipct = $opacity_pct / 100;
385
		for ($x = $src_x; $x < $src_w; $x++) {
386
			for ($y = $src_y; $y < $src_h; $y++) {
387
				$RealPixel    = self::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
388
				$OverlayPixel = self::GetPixelColor($src_im, $x, $y);
389
				$alphapct = $OverlayPixel['alpha'] / 127;
390
				$overlaypct = (1 - $alphapct) * $opacipct;
391
392
				$newcolor = self::ImageColorAllocateAlphaSafe(
393
					$dst_im,
394
					round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
395
					round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
396
					round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
397
					//$RealPixel['alpha']);
398
					0);
399
400
				imagesetpixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
401
			}
402
		}
403
		return true;
404
	}
405
406
407
	public static function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
408
		$old_aspect_ratio = $old_width / $old_height;
409
		if (($new_width === false) && ($new_height === false)) {
410
			return false;
411
		} elseif ($new_width === false) {
412
			$new_width = $new_height * $old_aspect_ratio;
413
		} elseif ($new_height === false) {
414
			$new_height = $new_width / $old_aspect_ratio;
415
		}
416
		$new_aspect_ratio = $new_width / $new_height;
417
		if ($new_aspect_ratio == $old_aspect_ratio) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
418
			// great, done
419
		} elseif ($new_aspect_ratio < $old_aspect_ratio) {
420
			// limited by width
421
			$new_height = $new_width / $old_aspect_ratio;
422
		} elseif ($new_aspect_ratio > $old_aspect_ratio) {
423
			// limited by height
424
			$new_width = $new_height * $old_aspect_ratio;
425
		}
426
		return array(
427
			(int) round($new_width),
428
			(int) round($new_height)
429
		);
430
	}
431
432
433
	public static function FunctionIsDisabled($function) {
434
		static $DisabledFunctions = null;
435
		if (null === $DisabledFunctions) {
436
			$disable_functions_local  = explode(',',     strtolower(@ini_get('disable_functions')));
437
			$disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
438
			foreach ($disable_functions_local as $key => $value) {
439
				$DisabledFunctions[trim($value)] = 'local';
440
			}
441
			foreach ($disable_functions_global as $key => $value) {
442
				$DisabledFunctions[trim($value)] = 'global';
443
			}
444
			if (@ini_get('safe_mode')) {
445
				$DisabledFunctions['shell_exec']     = 'local';
446
				$DisabledFunctions['set_time_limit'] = 'local';
447
			}
448
		}
449
		return isset($DisabledFunctions[strtolower($function)]);
450
	}
451
452
453
	public static function SafeExec($command) {
454
		static $AllowedExecFunctions = array();
455
		if (empty($AllowedExecFunctions)) {
456
			$AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
457
			foreach ($AllowedExecFunctions as $key => $value) {
458
				$AllowedExecFunctions[$key] = !self::FunctionIsDisabled($key);
459
			}
460
		}
461
		$command .= ' 2>&1'; // force redirect stderr to stdout
462
		foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
463
			if (!$is_allowed) {
464
				continue;
465
			}
466
			$returnvalue = false;
467
			switch ($execfunction) {
468
				case 'passthru':
469
				case 'system':
470
					ob_start();
471
					$execfunction($command);
472
					$returnvalue = ob_get_contents();
473
					ob_end_clean();
474
					break;
475
476
				case 'exec':
477
					$output = array();
478
					$lastline = $execfunction($command, $output);
0 ignored issues
show
Unused Code introduced by
The assignment to $lastline is dead and can be removed.
Loading history...
479
					$returnvalue = implode("\n", $output);
480
					break;
481
482
				case 'shell_exec':
483
					ob_start();
484
					$returnvalue = $execfunction($command);
485
					ob_end_clean();
486
					break;
487
			}
488
			return $returnvalue;
489
		}
490
		return false;
491
	}
492
493
494
	public static function ApacheLookupURIarray($filename) {
495
		// apache_lookup_uri() only works when PHP is installed as an Apache module.
496
		if (PHP_SAPI == 'apache') {
497
			//$property_exists_exists = function_exists('property_exists');
498
			$keys = array('status', 'the_request', 'status_line', 'method', 'content_type', 'handler', 'uri', 'filename', 'path_info', 'args', 'boundary', 'no_cache', 'no_local_copy', 'allowed', 'send_bodyct', 'bytes_sent', 'byterange', 'clength', 'unparsed_uri', 'mtime', 'request_time');
499
			if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
500
				$apacheLookupURIarray = array();
501
				foreach ($keys as $key) {
502
					$apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
503
				}
504
				return $apacheLookupURIarray;
505
			}
506
		}
507
		return false;
508
	}
509
510
511
	public static function gd_is_bundled() {
512
		static $isbundled = null;
513
		if (null === $isbundled) {
514
			$gd_info = gd_info();
515
			$isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
516
		}
517
		return $isbundled;
518
	}
519
520
521
	public static function gd_version($fullstring=false) {
522
		static $cache_gd_version = array();
523
		if (empty($cache_gd_version)) {
524
			$gd_info = gd_info();
525
			if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
526
				$cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
527
				$cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
528
			} else {
529
				$cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
530
				$cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
531
			}
532
		}
533
		return $cache_gd_version[ (int) $fullstring ];
534
	}
535
536
537
	public static function filesize_remote($remotefile, $timeout=10) {
538
		$size = false;
539
		$url = self::ParseURLbetter($remotefile);
540
		if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
541
			fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
542
			if (self::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
543
				stream_set_timeout($fp, $timeout);
544
			}
545
			while (!feof($fp)) {
546
				$headerline = fgets($fp, 4096);
547
				if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
548
					$size = (int) $matches[ 1];
549
					break;
550
				}
551
			}
552
			fclose ($fp);
553
		}
554
		return $size;
555
	}
556
557
558
	public static function filedate_remote($remotefile, $timeout=10) {
559
		$date = false;
560
		$url = self::ParseURLbetter($remotefile);
561
		if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
562
			fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
563
			if (self::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
564
				stream_set_timeout($fp, $timeout);
565
			}
566
			while (!feof($fp)) {
567
				$headerline = fgets($fp, 4096);
568
				if (preg_match('#^Last-Modified: (.*)#i', $headerline, $matches)) {
569
					$date = strtotime($matches[1]) - date('Z');
570
					break;
571
				}
572
			}
573
			fclose ($fp);
574
		}
575
		return $date;
576
	}
577
578
579
	public static function md5_file_safe($filename) {
580
		// md5_file() doesn't exist in PHP < 4.2.0
581
		if (function_exists('md5_file')) {
582
			return md5_file($filename);
583
		}
584
		if ($fp = @fopen($filename, 'rb')) {
585
			$rawData = '';
586
			do {
587
				$buffer = fread($fp, 8192);
588
				$rawData .= $buffer;
589
			} while (strlen($buffer) > 0);
590
			fclose($fp);
591
			return md5($rawData);
592
		}
593
		return false;
594
	}
595
596
597
	public static function nonempty_min() {
598
		$arg_list = func_get_args();
599
		$acceptable = array();
600
		foreach ($arg_list as $arg) {
601
			if ($arg) {
602
				$acceptable[] = $arg;
603
			}
604
		}
605
		return min($acceptable);
606
	}
607
608
609
	public static function LittleEndian2String($number, $minbytes=1) {
610
		$intstring = '';
611
		while ($number > 0) {
612
			$intstring .= chr($number & 255);
613
			$number    >>= 8;
614
		}
615
		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
616
	}
617
618
	public static function OneOfThese() {
619
		// return the first useful (non-empty/non-zero/non-false) value from those passed
620
		$arg_list = func_get_args();
621
		foreach ($arg_list as $key => $value) {
622
			if ($value) {
623
				return $value;
624
			}
625
		}
626
		return false;
627
	}
628
629
	public static function CaseInsensitiveInArray($needle, $haystack) {
630
		$needle = strtolower($needle);
631
		foreach ($haystack as $key => $value) {
632
			if (is_array($value)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
633
				// skip?
634
			} elseif ($needle == strtolower($value)) {
635
				return true;
636
			}
637
		}
638
		return false;
639
	}
640
641
	public static function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
642
		if (!function_exists('fsockopen') || self::FunctionIsDisabled('fsockopen')) {
643
			$errstr = 'fsockopen() unavailable';
644
			return false;
645
		}
646
		//if ($fp = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
647
		if ($fp = @fsockopen((($port == 443) ? 'ssl://' : '').$host, $port, $errno, $errstr, $timeout)) { // https://github.com/JamesHeinrich/phpThumb/issues/39
648
			$out  = 'GET '.$file.' HTTP/1.0'."\r\n";
649
			$out .= 'Host: '.$host."\r\n";
650
			$out .= 'Connection: Close'."\r\n\r\n";
651
			fwrite($fp, $out);
652
653
			$isHeader = true;
654
			$Data_header = '';
655
			$Data_body   = '';
656
			$header_newlocation = '';
657
			while (!feof($fp)) {
658
				$line = fgets($fp, 1024);
659
				if ($isHeader) {
660
					$Data_header .= $line;
661
				} else {
662
					$Data_body .= $line;
663
				}
664
				if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
665
					list( , $errno, $errstr) = $matches;
666
					$errno = (int) $errno;
667
				} elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
668
					$header_newlocation = $matches[1];
669
				}
670
				if ($isHeader && ($line == "\r\n")) {
671
					$isHeader = false;
672
					if ($successonly) {
673
						switch ($errno) {
674
							case 200:
675
								// great, continue
676
								break;
677
678
							default:
679
								$errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
680
								fclose($fp);
681
								return false;
682
								break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
683
						}
684
					}
685
				}
686
			}
687
			fclose($fp);
688
			return $Data_body;
689
		}
690
		return null;
691
	}
692
693
	public static function CleanUpURLencoding($url, $queryseperator='&') {
694
		if (!preg_match('#^http#i', $url)) {
695
			return $url;
696
		}
697
		$parse_url = self::ParseURLbetter($url);
698
		$pathelements = explode('/', $parse_url['path']);
699
		$CleanPathElements = array();
700
		$TranslationMatrix = array(' '=>'%20');
701
		foreach ($pathelements as $key => $pathelement) {
702
			$CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
703
		}
704
		foreach ($CleanPathElements as $key => $value) {
705
			if ($value === '') {
706
				unset($CleanPathElements[$key]);
707
			}
708
		}
709
710
		$queries = explode($queryseperator, (isset($parse_url['query']) ? $parse_url['query'] : ''));
711
		$CleanQueries = array();
712
		foreach ($queries as $key => $query) {
713
			@list($param, $value) = explode('=', $query);
714
			$CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
715
		}
716
		foreach ($CleanQueries as $key => $value) {
717
			if ($value === '') {
718
				unset($CleanQueries[$key]);
719
			}
720
		}
721
722
		$cleaned_url  = $parse_url['scheme'].'://';
723
		$cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
724
		$cleaned_url .= $parse_url['host'];
725
		$cleaned_url .= ((!empty($parse_url['port']) && ($parse_url['port'] != 80)) ? ':'.$parse_url['port'] : '');
726
		$cleaned_url .= '/'.implode('/', $CleanPathElements);
727
		$cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
728
		return $cleaned_url;
729
	}
730
731
	public static function ParseURLbetter($url) {
732
		$parsedURL = @parse_url($url);
733
		if (!@$parsedURL['port']) {
734
			switch (strtolower(@$parsedURL['scheme'])) {
735
				case 'ftp':
736
					$parsedURL['port'] = 21;
737
					break;
738
				case 'https':
739
					$parsedURL['port'] = 443;
740
					break;
741
				case 'http':
742
					$parsedURL['port'] = 80;
743
					break;
744
			}
745
		}
746
		return $parsedURL;
747
	}
748
749
	public static function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
750
		$error   = '';
751
		$errstr  = '';
752
		$rawData = '';
753
754
		$parsed_url = self::ParseURLbetter($url);
755
		$alreadyLookedAtURLs[trim($url)] = true;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$alreadyLookedAtURLs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $alreadyLookedAtURLs = array(); before regardless.
Loading history...
756
757
		while (true) {
758
			$tryagain = false;
759
			$rawData = self::URLreadFsock(@$parsed_url[ 'host'], @$parsed_url[ 'path'].'?'.@$parsed_url[ 'query'], $errstr, true, (@$parsed_url[ 'port'] ? @$parsed_url[ 'port'] : 80), $timeout);
760
			if ($followredirects && preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
761
				$matches[1] = trim(@$matches[1]);
762
				if (!@$alreadyLookedAtURLs[$matches[1]]) {
763
					// loop through and examine new URL
764
					$error .= 'URL "'.$url.'" redirected to "'.$matches[1].'"';
765
766
					$tryagain = true;
767
					$alreadyLookedAtURLs[$matches[1]] = true;
768
					$parsed_url = self::ParseURLbetter($matches[ 1]);
769
				}
770
			}
771
			if (!$tryagain) {
772
				break;
773
			}
774
		}
775
776
		if ($rawData === false) {
777
			$error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
778
			return false;
779
		} elseif ($rawData === null) {
0 ignored issues
show
introduced by
The condition $rawData === null is always false.
Loading history...
780
			// fall through
781
			$error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
782
		} else {
783
			return $rawData;
784
		}
785
786
		if (function_exists('curl_version') && !self::FunctionIsDisabled('curl_exec')) {
787
			$ch = curl_init();
788
			curl_setopt($ch, CURLOPT_URL, $url);
789
			curl_setopt($ch, CURLOPT_HEADER, false);
790
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
791
			curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
792
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
793
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
794
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, (bool) $followredirects);
795
			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
796
			$rawData = curl_exec($ch);
797
			curl_close($ch);
798
			if (strlen($rawData) > 0) {
799
				$error .= 'CURL succeeded ('.strlen($rawData).' bytes); ';
800
				return $rawData;
801
			}
802
			$error .= 'CURL available but returned no data; ';
803
		} else {
804
			$error .= 'CURL unavailable; ';
805
		}
806
807
		$BrokenURLfopenPHPversions = array('4.4.2');
808
		if (in_array(PHP_VERSION, $BrokenURLfopenPHPversions)) {
809
			$error .= 'fopen(URL) broken in PHP v'. PHP_VERSION .'; ';
810
		} elseif (@ini_get('allow_url_fopen')) {
811
			$rawData = '';
812
			$error_fopen = '';
813
			ob_start();
814
			if ($fp = fopen($url, 'rb')) {
815
				do {
816
					$buffer = fread($fp, 8192);
817
					$rawData .= $buffer;
818
				} while (strlen($buffer) > 0);
819
				fclose($fp);
820
			} else {
821
				$error_fopen .= trim(strip_tags(ob_get_contents()));
822
			}
823
			ob_end_clean();
824
			$error .= $error_fopen;
825
			if (!$error_fopen) {
826
				$error .= '; "allow_url_fopen" succeeded ('.strlen($rawData).' bytes); ';
827
				return $rawData;
828
			}
829
			$error .= '; "allow_url_fopen" enabled but returned no data ('.$error_fopen.'); ';
830
		} else {
831
			$error .= '"allow_url_fopen" disabled; ';
832
		}
833
834
		return false;
835
	}
836
837
	public static function EnsureDirectoryExists($dirname, $mask = 0755) {
838
		$directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
839
		$startoffset = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
840
		$open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
841
		foreach ($open_basedirs as $key => $open_basedir) {
842
			if (preg_match('#^'.preg_quote($open_basedir).'#', $dirname) && (strlen($dirname) > strlen($open_basedir))) {
843
				$startoffset = substr_count($open_basedir, DIRECTORY_SEPARATOR) + 1;
844
				break;
845
			}
846
		}
847
		$i = $startoffset;
0 ignored issues
show
Unused Code introduced by
The assignment to $i is dead and can be removed.
Loading history...
848
		$endoffset = count($directory_elements);
849
		for ($i = $startoffset; $i <= $endoffset; $i++) {
850
			$test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
851
			if (!$test_directory) {
852
				continue;
853
			}
854
			if (!@is_dir($test_directory)) {
855
				if (@file_exists($test_directory)) {
856
					// directory name already exists as a file
857
					return false;
858
				}
859
				@mkdir($test_directory, $mask);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

859
				/** @scrutinizer ignore-unhandled */ @mkdir($test_directory, $mask);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
860
				@chmod($test_directory, $mask);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

860
				/** @scrutinizer ignore-unhandled */ @chmod($test_directory, $mask);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
861
				if (!@is_dir($test_directory) || !@is_writable($test_directory)) {
862
					return false;
863
				}
864
			}
865
		}
866
		return true;
867
	}
868
869
870
	public static function GetAllFilesInSubfolders($dirname) {
871
		$AllFiles = array();
872
		$dirname = rtrim(realpath($dirname), '/\\');
873
		if ($dirhandle = @opendir($dirname)) {
874
			while (($file = readdir($dirhandle)) !== false) {
875
				$fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
876
				if (is_file($fullfilename)) {
877
					$AllFiles[] = $fullfilename;
878
				} elseif (is_dir($fullfilename)) {
879
					switch ($file) {
880
						case '.':
881
						case '..':
882
							break;
883
884
						default:
885
							$AllFiles[] = $fullfilename;
886
							$subfiles = self::GetAllFilesInSubfolders($fullfilename);
887
							foreach ($subfiles as $filename) {
888
								$AllFiles[] = $filename;
889
							}
890
							break;
891
					}
892
				} else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
893
					// ignore?
894
				}
895
			}
896
			closedir($dirhandle);
897
		}
898
		sort($AllFiles);
899
		return array_unique($AllFiles);
900
	}
901
902
903
	public static function SanitizeFilename($filename) {
904
		$filename = preg_replace('/[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]/', '_', $filename);
905
		if (self::version_compare_replacement(PHP_VERSION, '4.1.0', '>=')) {
906
			$filename = trim($filename, '.');
907
		}
908
		return $filename;
909
	}
910
911
	public static function PasswordStrength($password) {
912
		$strength = 0;
913
		$strength += strlen(preg_replace('#[^a-z]#',       '', $password)) * 0.5; // lowercase characters are weak
914
		$strength += strlen(preg_replace('#[^A-Z]#',       '', $password)) * 0.8; // uppercase characters are somewhat better
915
		$strength += strlen(preg_replace('#[^0-9]#',       '', $password)) * 1.0; // numbers are somewhat better
916
		$strength += strlen(preg_replace('#[a-zA-Z0-9]#',  '', $password)) * 2.0; // other non-alphanumeric characters are best
917
		return $strength;
918
	}
919
920
}
921
922
923
////////////// END: class phpthumb_functions //////////////
924
925
926
if (!function_exists('gd_info')) {
927
	// built into PHP v4.3.0+ (with bundled GD2 library)
928
	function gd_info() {
929
		static $gd_info = array();
930
		if (empty($gd_info)) {
931
			// based on code by johnschaefer at gmx dot de
932
			// from PHP help on gd_info()
933
			$gd_info = array(
934
				'GD Version'         => '',
935
				'FreeType Support'   => false,
936
				'FreeType Linkage'   => '',
937
				'T1Lib Support'      => false,
938
				'GIF Read Support'   => false,
939
				'GIF Create Support' => false,
940
				'JPG Support'        => false,
941
				'PNG Support'        => false,
942
				'WBMP Support'       => false,
943
				'XBM Support'        => false
944
			);
945
			$phpinfo_array = phpthumb_functions::phpinfo_array();
946
			foreach ($phpinfo_array as $line) {
947
				$line = trim(strip_tags($line));
948
				foreach ($gd_info as $key => $value) {
949
					//if (strpos($line, $key) !== false) {
950
					if (strpos($line, $key) === 0) {
951
						$newvalue = trim(str_replace($key, '', $line));
952
						$gd_info[$key] = $newvalue;
953
					}
954
				}
955
			}
956
			if (empty($gd_info['GD Version'])) {
957
				// probable cause: "phpinfo() disabled for security reasons"
958
				if (function_exists('imagetypes')) {
959
					$imagetypes = imagetypes();
960
					if ($imagetypes & IMG_PNG) {
961
						$gd_info['PNG Support'] = true;
962
					}
963
					if ($imagetypes & IMG_GIF) {
964
						$gd_info['GIF Create Support'] = true;
965
					}
966
					if ($imagetypes & IMG_JPG) {
967
						$gd_info['JPG Support'] = true;
968
					}
969
					if ($imagetypes & IMG_WBMP) {
970
						$gd_info['WBMP Support'] = true;
971
					}
972
				}
973
				// to determine capability of GIF creation, try to use imagecreatefromgif on a 1px GIF
974
				if (function_exists('imagecreatefromgif')) {
975
					if ($tempfilename = phpthumb::phpThumb_tempnam()) {
0 ignored issues
show
Bug Best Practice introduced by
The method phpthumb::phpThumb_tempnam() is not static, but was called statically. ( Ignorable by Annotation )

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

975
					if ($tempfilename = phpthumb::/** @scrutinizer ignore-call */ phpThumb_tempnam()) {
Loading history...
976
						if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
977
							fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
978
							fclose($fp_tempfile);
979
							@chmod($tempfilename, $this->getParameter('config_file_create_mask'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $this seems to be never defined.
Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

979
							/** @scrutinizer ignore-unhandled */ @chmod($tempfilename, $this->getParameter('config_file_create_mask'));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
980
981
							// if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
982
							$gd_info['GIF Read Support'] = (bool) @imagecreatefromgif($tempfilename);
983
						}
984
						unlink($tempfilename);
985
					}
986
				}
987
				if (function_exists('imagecreatetruecolor') && @imagecreatetruecolor(1, 1)) {
988
					$gd_info['GD Version'] = '2.0.1 or higher (assumed)';
989
				} elseif (function_exists('imagecreate') && @imagecreate(1, 1)) {
990
					$gd_info['GD Version'] = '1.6.0 or higher (assumed)';
991
				}
992
			}
993
		}
994
		return $gd_info;
995
	}
996
}
997
998
999
if (!function_exists('is_executable')) {
1000
	// in PHP v3+, but v5.0+ for Windows
1001
	function is_executable($filename) {
1002
		// poor substitute, but better than nothing
1003
		return file_exists($filename);
1004
	}
1005
}
1006
1007
1008
if (!function_exists('preg_quote')) {
1009
	// included in PHP v3.0.9+, but may be unavailable if not compiled in
1010
	function preg_quote($string, $delimiter='\\') {
1011
		static $preg_quote_array = array();
1012
		if (empty($preg_quote_array)) {
1013
			$escapeables = '.\\+*?[^]$(){}=!<>|:';
1014
			for ($i = 0, $iMax = strlen($escapeables); $i < $iMax; $i++) {
1015
				$strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
1016
			}
1017
		}
1018
		return strtr($string, $strtr_preg_quote);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $strtr_preg_quote does not seem to be defined for all execution paths leading up to this point.
Loading history...
1019
	}
1020
}
1021
1022
if (!function_exists('file_get_contents')) {
1023
	// included in PHP v4.3.0+
1024
	function file_get_contents($filename) {
1025
		if (preg_match('#^(f|ht)tp\://#i', $filename)) {
1026
			return SafeURLread($filename, $error);
0 ignored issues
show
Bug introduced by
The function SafeURLread 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

1026
			return /** @scrutinizer ignore-call */ SafeURLread($filename, $error);
Loading history...
Comprehensibility Best Practice introduced by
The variable $error seems to be never defined.
Loading history...
1027
		}
1028
		if ($fp = @fopen($filename, 'rb')) {
1029
			$rawData = '';
1030
			do {
1031
				$buffer = fread($fp, 8192);
1032
				$rawData .= $buffer;
1033
			} while (strlen($buffer) > 0);
1034
			fclose($fp);
1035
			return $rawData;
1036
		}
1037
		return false;
1038
	}
1039
}
1040
1041
1042
if (!function_exists('file_put_contents')) {
1043
	// included in PHP v5.0.0+
1044
	function file_put_contents($filename, $filedata) {
1045
		if ($fp = @fopen($filename, 'wb')) {
1046
			fwrite($fp, $filedata);
1047
			fclose($fp);
1048
			return true;
1049
		}
1050
		return false;
1051
	}
1052
}
1053
1054
if (!function_exists('imagealphablending')) {
1055
	// built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
1056
	function imagealphablending(&$img, $blendmode=true) {
0 ignored issues
show
Unused Code introduced by
The parameter $img is not used and could be removed. ( Ignorable by Annotation )

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

1056
	function imagealphablending(/** @scrutinizer ignore-unused */ &$img, $blendmode=true) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $blendmode is not used and could be removed. ( Ignorable by Annotation )

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

1056
	function imagealphablending(&$img, /** @scrutinizer ignore-unused */ $blendmode=true) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1057
		// do nothing, this function is declared here just to
1058
		// prevent runtime errors if GD2 is not available
1059
		return true;
1060
	}
1061
}
1062
1063
if (!function_exists('imagesavealpha')) {
1064
	// built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
1065
	function imagesavealpha(&$img, $blendmode=true) {
0 ignored issues
show
Unused Code introduced by
The parameter $img is not used and could be removed. ( Ignorable by Annotation )

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

1065
	function imagesavealpha(/** @scrutinizer ignore-unused */ &$img, $blendmode=true) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $blendmode is not used and could be removed. ( Ignorable by Annotation )

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

1065
	function imagesavealpha(&$img, /** @scrutinizer ignore-unused */ $blendmode=true) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1066
		// do nothing, this function is declared here just to
1067
		// prevent runtime errors if GD2 is not available
1068
		return true;
1069
	}
1070
}
1071