Passed
Push — master ( 998341...98a658 )
by Richard
18:44 queued 11:05
created

SendSaveAsFileHeaderIfNeeded()   C

Complexity

Conditions 14
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 16
rs 6.2666
cc 14
nc 5
nop 1

How to fix   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
//   phpThumb() by James Heinrich <[email protected]>   //
4
//        available at http://phpthumb.sourceforge.net      //
5
//         and/or https://github.com/JamesHeinrich/phpThumb //
6
//////////////////////////////////////////////////////////////
7
///                                                         //
8
// See: phpthumb.changelog.txt for recent changes           //
9
// See: phpthumb.readme.txt for usage instructions          //
10
//                                                         ///
11
//////////////////////////////////////////////////////////////
12
13
error_reporting(E_ALL);
14
ini_set('display_errors', '1');
15
ini_set('magic_quotes_runtime', '0');
16
if (ini_get('magic_quotes_runtime')) {
17
	die('"magic_quotes_runtime" is set in php.ini, cannot run phpThumb with this enabled');
18
}
19
// Set a default timezone if web server has not done already in php.ini
20
if (!ini_get('date.timezone') && function_exists('date_default_timezone_set')) { // PHP >= 5.1.0
21
    date_default_timezone_set('UTC');
22
}
23
$starttime = array_sum(explode(' ', microtime())); // could be called as microtime(true) for PHP 5.0.0+
24
25
// this script relies on the superglobal arrays, fake it here for old PHP versions
26
if (PHP_VERSION < '4.1.0') {
27
	$_SERVER = $HTTP_SERVER_VARS;
28
	$_GET    = $HTTP_GET_VARS;
29
}
30
31
function SendSaveAsFileHeaderIfNeeded($getimagesize=false) {
32
	if (headers_sent()) {
33
		return false;
34
	}
35
	global $phpThumb;
36
	$downloadfilename = phpthumb_functions::SanitizeFilename(!empty($_GET['sia']) ? $_GET['sia'] : (!empty($_GET['down']) ? $_GET['down'] : 'phpThumb_generated_thumbnail.'.(!empty($_GET['f']) ? $_GET['f'] : 'jpg')));
37
	//if (empty($_GET['sia']) && empty($_GET['down']) && !empty($phpThumb->thumbnail_image_width) && !empty($phpThumb->thumbnail_image_height)) {
38
	if (empty($_GET['sia']) && empty($_GET['down']) && !empty($getimagesize[0]) && !empty($getimagesize[1])) {
39
		// if we know the output image dimensions we can generate a better default filename
40
		$downloadfilename = phpthumb_functions::SanitizeFilename((!empty($phpThumb->src) ? basename($phpThumb->src) : md5($this->rawImageData)).'-'.intval($getimagesize[0]).'x'.intval($getimagesize[1]).'.'.(!empty($_GET['f']) ? $_GET['f'] : 'jpg'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $this seems to be never defined.
Loading history...
41
	}
42
	if (!empty($downloadfilename)) {
43
		$phpThumb->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: '.(!empty($_GET['down']) ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"', __FILE__, __LINE__);
44
		header('Content-Disposition: '.(!empty($_GET['down']) ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"');
45
	}
46
	return true;
47
}
48
49
function RedirectToCachedFile() {
50
	global $phpThumb;
51
52
	$nice_cachefile = str_replace(DIRECTORY_SEPARATOR, '/', $phpThumb->cache_filename);
53
	$nice_docroot   = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($phpThumb->config_document_root, '/\\'));
54
55
	$parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
56
57
	$nModified  = filemtime($phpThumb->cache_filename);
58
59
	if ($phpThumb->config_nooffsitelink_enabled && !empty($_SERVER['HTTP_REFERER']) && !in_array(@$parsed_url['host'], $phpThumb->config_nooffsitelink_valid_domains)) {
60
61
		$phpThumb->DebugMessage('Would have used cached (image/'.$phpThumb->thumbnailFormat.') file "'.$phpThumb->cache_filename.'" (Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT), but skipping because $_SERVER[HTTP_REFERER] ('.@$_SERVER['HTTP_REFERER'].') is not in $phpThumb->config_nooffsitelink_valid_domains ('.implode(';', $phpThumb->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
62
63
	} elseif ($phpThumb->phpThumbDebug) {
64
65
		$phpThumb->DebugTimingMessage('skipped using cached image', __FILE__, __LINE__);
66
		$phpThumb->DebugMessage('Would have used cached file, but skipping due to phpThumbDebug', __FILE__, __LINE__);
67
		$phpThumb->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT', __FILE__, __LINE__);
68
		if ($getimagesize = @getimagesize($phpThumb->cache_filename)) {
69
			$phpThumb->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);
0 ignored issues
show
Bug introduced by
Are you sure phpthumb_functions::Imag...Etype($getimagesize[2]) of type false|mixed|string can be used in concatenation? ( Ignorable by Annotation )

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

69
			$phpThumb->DebugMessage('* Would have sent headers (2): Content-Type: './** @scrutinizer ignore-type */ phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);
Loading history...
70
		}
71
		if (preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
72
			$phpThumb->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);
73
		} else {
74
			$phpThumb->DebugMessage('* Would have sent data: readfile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
75
		}
76
77
	} else {
78
79
		if (headers_sent()) {
80
			$phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
81
			exit;
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...
82
		}
83
		$getimagesize = @getimagesize($phpThumb->cache_filename);
84
		SendSaveAsFileHeaderIfNeeded($getimagesize);
85
86
		header('Pragma: private');
87
		header('Cache-Control: max-age='.$phpThumb->getParameter('config_cache_maxage'));
88
		header('Expires: '.date(DATE_RFC1123,  time() + $phpThumb->getParameter('config_cache_maxage')));
89
		if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && !empty($_SERVER['SERVER_PROTOCOL'])) {
90
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
91
			header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
92
			exit;
93
		}
94
		header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
95
		header('ETag: "'.md5_file($phpThumb->cache_filename).'"');
96
		if (!empty($getimagesize[2])) {
97
			header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
98
		} elseif (preg_match('#\\.ico$#i', $phpThumb->cache_filename)) {
99
			header('Content-Type: image/x-icon');
100
		}
101
		header('Content-Length: '.filesize($phpThumb->cache_filename));
102
		if (empty($phpThumb->config_cache_force_passthru) && preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
103
			header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));
104
		} else {
105
			@readfile($phpThumb->cache_filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for readfile(). 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

105
			/** @scrutinizer ignore-unhandled */ @readfile($phpThumb->cache_filename);

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...
106
		}
107
		exit;
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...
108
109
	}
110
	return true;
111
}
112
113
114
115
// instantiate a new phpThumb() object
116
ob_start();
117
if (!include_once __DIR__ .'/phpthumb.class.php' ) {
118
	ob_end_flush();
119
	die('failed to include_once("'.realpath( __DIR__ .'/phpthumb.class.php').'")');
120
}
121
ob_end_clean();
122
$phpThumb = new phpThumb();
123
$phpThumb->DebugTimingMessage('phpThumb.php start', __FILE__, __LINE__, $starttime);
124
$phpThumb->setParameter('config_error_die_on_error', true);
125
126
if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
127
	set_time_limit(60);  // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
128
}
129
130
// phpThumbDebug[0] used to be here, but may reveal too much
131
// info when high_security_mode should be enabled (not set yet)
132
133
if (file_exists( __DIR__ .'/phpThumb.config.php')) {
134
	ob_start();
135
	if (include_once __DIR__ .'/phpThumb.config.php' ) {
136
		// great
137
	} else {
138
		ob_end_flush();
139
		$phpThumb->config_disable_debug = false; // otherwise error message won't print
140
		$phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
141
	}
142
	ob_end_clean();
143
} elseif (file_exists( __DIR__ .'/phpThumb.config.php.default')) {
144
	$phpThumb->config_disable_debug = false; // otherwise error message won't print
145
	$phpThumb->ErrorImage('Please rename "phpThumb.config.php.default" to "phpThumb.config.php"');
146
} else {
147
	$phpThumb->config_disable_debug = false; // otherwise error message won't print
148
	$phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
149
}
150
151
if (!empty($PHPTHUMB_CONFIG)) {
152
	foreach ($PHPTHUMB_CONFIG as $key => $value) {
153
		$keyname = 'config_'.$key;
154
		$phpThumb->setParameter($keyname, $value);
155
		if (!preg_match('#(password|mysql)#i', $key)) {
156
			$phpThumb->DebugMessage('setParameter('.$keyname.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
157
		}
158
	}
159
	if (!$phpThumb->config_disable_debug) {
160
		// if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated
161
		$_GET['phpThumbDebug'] = (!empty($_GET['phpThumbDebug']) ? max(1, (int) $_GET[ 'phpThumbDebug']) : 9);
162
		$phpThumb->setParameter('phpThumbDebug', $_GET['phpThumbDebug']);
163
	}
164
} else {
165
	$phpThumb->DebugMessage('$PHPTHUMB_CONFIG is empty', __FILE__, __LINE__);
166
}
167
168
if (empty($phpThumb->config_disable_pathinfo_parsing) && (empty($_GET) || isset($_GET['phpThumbDebug'])) && !empty($_SERVER['PATH_INFO'])) {
169
	$_SERVER['PHP_SELF'] = str_replace($_SERVER['PATH_INFO'], '', @$_SERVER['PHP_SELF']);
170
171
	$args = explode(';', substr($_SERVER['PATH_INFO'], 1));
172
	$phpThumb->DebugMessage('PATH_INFO.$args set to ('.implode(')(', $args).')', __FILE__, __LINE__);
173
	if (!empty($args)) {
174
		$_GET['src'] = @$args[count($args) - 1];
175
		$phpThumb->DebugMessage('PATH_INFO."src" = "'.$_GET['src'].'"', __FILE__, __LINE__);
176
		if (preg_match('#^new\=([a-z0-9]+)#i', $_GET['src'], $matches)) {
177
			unset($_GET['src']);
178
			$_GET['new'] = $matches[1];
179
		}
180
	}
181
	if (preg_match('#^([\d]*)x?([\d]*)$#i', @$args[count($args) - 2], $matches)) {
182
		$_GET['w'] = $matches[1];
183
		$_GET['h'] = $matches[2];
184
		$phpThumb->DebugMessage('PATH_INFO."w"x"h" set to "'.$_GET['w'].'"x"'.$_GET['h'].'"', __FILE__, __LINE__);
185
	}
186
	for ($i = 0; $i < count($args) - 2; $i++) {
187
		@list($key, $value) = explode('=', @$args[$i]);
188
		if (substr($key, -2) == '[]') {
189
			$array_key_name = substr($key, 0, -2);
190
			$_GET[$array_key_name][] = $value;
191
			$phpThumb->DebugMessage('PATH_INFO."'.$array_key_name.'[]" = "'.$value.'"', __FILE__, __LINE__);
192
		} else {
193
			$_GET[$key] = $value;
194
			$phpThumb->DebugMessage('PATH_INFO."'.$key.'" = "'.$value.'"', __FILE__, __LINE__);
195
		}
196
	}
197
}
198
199
if (!empty($phpThumb->config_high_security_enabled)) {
200
	if (empty($_GET['hash'])) {
201
		$phpThumb->config_disable_debug = false; // otherwise error message won't print
202
		$phpThumb->ErrorImage('ERROR: missing hash');
203
	} elseif (phpthumb_functions::PasswordStrength($phpThumb->config_high_security_password) < 20) {
204
		$phpThumb->config_disable_debug = false; // otherwise error message won't print
205
		$phpThumb->ErrorImage('ERROR: $PHPTHUMB_CONFIG[high_security_password] is not complex enough');
206
	} elseif ($_GET['hash'] != md5(str_replace($phpThumb->config_high_security_url_separator.'hash='.$_GET['hash'], '', $_SERVER['QUERY_STRING']).$phpThumb->config_high_security_password)) {
207
		header('HTTP/1.0 403 Forbidden');
208
		sleep(10); // deliberate delay to discourage password-guessing
209
		$phpThumb->ErrorImage('ERROR: invalid hash');
210
	}
211
}
212
213
////////////////////////////////////////////////////////////////
214
// Debug output, to try and help me diagnose problems
215
$phpThumb->DebugTimingMessage('phpThumbDebug[0]', __FILE__, __LINE__);
216
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '0')) {
217
	$phpThumb->phpThumbDebug();
218
}
219
////////////////////////////////////////////////////////////////
220
221
// returned the fixed string if the evil "magic_quotes_gpc" setting is on
222
if (get_magic_quotes_gpc()) {
223
	// deprecated: 'err', 'file', 'goto',
224
	$RequestVarsToStripSlashes = array('src', 'wmf', 'down');
225
	foreach ($RequestVarsToStripSlashes as $key) {
226
		if (isset($_GET[$key])) {
227
			if (is_string($_GET[$key])) {
228
				$_GET[$key] = stripslashes($_GET[$key]);
229
			} else {
230
				unset($_GET[$key]);
231
			}
232
		}
233
	}
234
}
235
236
if (empty($_SERVER['PATH_INFO']) && empty($_SERVER['QUERY_STRING'])) {
237
	$phpThumb->config_disable_debug = false; // otherwise error message won't print
238
	$phpThumb->ErrorImage('ERROR: no parameters specified');
239
}
240
241
if (!empty($_GET['src']) && isset($_GET['md5s']) && empty($_GET['md5s'])) {
242
	$md5s = '';
243
	if (preg_match('#^([a-z0-9]+)://#i', $_GET['src'], $protocol_matches)) {
244
		if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
245
			if ($rawImageData = phpthumb_functions::SafeURLread($_GET['src'], $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
246
				$md5s = md5($rawImageData);
247
			}
248
		} else {
249
			$phpThumb->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
250
		}
251
	} else {
252
		$SourceFilename = $phpThumb->ResolveFilenameToAbsolute($_GET['src']);
253
		if (is_readable($SourceFilename)) {
0 ignored issues
show
Bug introduced by
It seems like $SourceFilename can also be of type false; however, parameter $filename of is_readable() does only seem to accept string, 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

253
		if (is_readable(/** @scrutinizer ignore-type */ $SourceFilename)) {
Loading history...
254
			$md5s = phpthumb_functions::md5_file_safe($SourceFilename);
255
		} else {
256
			$phpThumb->ErrorImage('ERROR: "'.$SourceFilename.'" cannot be read');
257
		}
258
	}
259
	if (!empty($_SERVER['HTTP_REFERER'])) {
260
		$phpThumb->ErrorImage('&md5s='.$md5s);
0 ignored issues
show
Bug introduced by
Are you sure $md5s of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

260
		$phpThumb->ErrorImage('&md5s='./** @scrutinizer ignore-type */ $md5s);
Loading history...
261
	} else {
262
		die('&md5s='.$md5s);
263
	}
264
}
265
266
if (!empty($_GET['src']) && empty($phpThumb->config_allow_local_http_src) && preg_match('#^http://'.@$_SERVER['HTTP_HOST'].'(.+)#i', $_GET['src'], $matches)) {
267
	$phpThumb->ErrorImage('It is MUCH better to specify the "src" parameter as "'.$matches[1].'" instead of "'.$matches[0].'".'."\n\n".'If you really must do it this way, enable "allow_local_http_src" in phpThumb.config.php');
268
}
269
270
////////////////////////////////////////////////////////////////
271
// Debug output, to try and help me diagnose problems
272
$phpThumb->DebugTimingMessage('phpThumbDebug[1]', __FILE__, __LINE__);
273
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '1')) {
274
	$phpThumb->phpThumbDebug();
275
}
276
////////////////////////////////////////////////////////////////
277
278
$parsed_url_referer = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
279
if ($phpThumb->config_nooffsitelink_require_refer && !in_array(@$parsed_url_referer['host'], $phpThumb->config_nohotlink_valid_domains)) {
280
	$phpThumb->ErrorImage('config_nooffsitelink_require_refer enabled and '.(@$parsed_url_referer['host'] ? '"'.$parsed_url_referer['host'].'" is not an allowed referer' : 'no HTTP_REFERER exists'));
281
}
282
$parsed_url_src = phpthumb_functions::ParseURLbetter(@$_GET['src']);
283
if ($phpThumb->config_nohotlink_enabled && $phpThumb->config_nohotlink_erase_image && preg_match('#^(f|ht)tps?://#i', @$_GET['src']) && !in_array(@$parsed_url_src['host'], $phpThumb->config_nohotlink_valid_domains)) {
284
	$phpThumb->ErrorImage($phpThumb->config_nohotlink_text_message);
285
}
286
287
if ($phpThumb->config_mysql_query) {
288
	if ($phpThumb->config_mysql_extension == 'mysqli') {
289
290
		$found_missing_function = false;
291
		foreach (array('mysqli_connect') as $required_mysqli_function) {
292
			if (!function_exists($required_mysqli_function)) {
293
				$found_missing_function = $required_mysqli_function;
294
				break;
295
			}
296
		}
297
		if ($found_missing_function) {
298
			$phpThumb->ErrorImage('SQL function unavailable: '.$found_missing_function);
299
		} else {
300
			$mysqli = new mysqli($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password, $phpThumb->config_mysql_database);
301
			if ($mysqli->connect_error) {
302
				$phpThumb->ErrorImage('MySQLi connect error ('.$mysqli->connect_errno.') '.$mysqli->connect_error);
303
			} else {
304
				if ($result = $mysqli->query($phpThumb->config_mysql_query)) {
305
					if ($row = $result->fetch_array()) {
306
307
						$result->free();
308
						$mysqli->close();
309
						$phpThumb->setSourceData($row[0]);
310
						unset($row);
311
312
					} else {
313
						$result->free();
314
						$mysqli->close();
315
						$phpThumb->ErrorImage('no matching data in database.');
316
					}
317
				} else {
318
					$mysqli->close();
319
					$phpThumb->ErrorImage('Error in MySQL query: "'.$mysqli->error.'"');
320
				}
321
			}
322
			unset($_GET['id']);
323
		}
324
325
	} elseif ($phpThumb->config_mysql_extension == 'mysql') {
326
327
		$found_missing_function = false;
328
		//foreach (array('mysql_connect', 'mysql_select_db', 'mysql_query', 'mysql_fetch_array', 'mysql_free_result', 'mysql_close', 'mysql_error') as $required_mysql_function) {
329
		foreach (array('mysql_connect') as $required_mysql_function) {
330
			if (!function_exists($required_mysql_function)) {
331
				$found_missing_function = $required_mysql_function;
332
				break;
333
			}
334
		}
335
		if ($found_missing_function) {
336
			$phpThumb->ErrorImage('SQL function unavailable: '.$found_missing_function);
337
		} else {
338
			if ($cid = @mysql_connect($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password)) {
0 ignored issues
show
Deprecated Code introduced by
The function mysql_connect() has been deprecated: 5.5 Open a connection to a MySQL Server ( Ignorable by Annotation )

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

338
			if ($cid = @/** @scrutinizer ignore-deprecated */ mysql_connect($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password)) {

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
339
				if (@mysql_select_db($phpThumb->config_mysql_database, $cid)) {
0 ignored issues
show
Deprecated Code introduced by
The function mysql_select_db() has been deprecated: 5.5 Select a MySQL database ( Ignorable by Annotation )

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

339
				if (@/** @scrutinizer ignore-deprecated */ mysql_select_db($phpThumb->config_mysql_database, $cid)) {

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
340
					if ($result = @mysql_query($phpThumb->config_mysql_query, $cid)) {
0 ignored issues
show
Deprecated Code introduced by
The function mysql_query() has been deprecated: 5.5 Send a MySQL query ( Ignorable by Annotation )

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

340
					if ($result = @/** @scrutinizer ignore-deprecated */ mysql_query($phpThumb->config_mysql_query, $cid)) {

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
341
						if ($row = @mysql_fetch_array($result)) {
0 ignored issues
show
Deprecated Code introduced by
The function mysql_fetch_array() has been deprecated: 5.5 Fetch a result row as an associative array, a numeric array, or both ( Ignorable by Annotation )

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

341
						if ($row = @/** @scrutinizer ignore-deprecated */ mysql_fetch_array($result)) {

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
342
343
							mysql_free_result($result);
0 ignored issues
show
Deprecated Code introduced by
The function mysql_free_result() has been deprecated: 5.5 Free result memory ( Ignorable by Annotation )

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

343
							/** @scrutinizer ignore-deprecated */ mysql_free_result($result);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
344
							mysql_close($cid);
0 ignored issues
show
Deprecated Code introduced by
The function mysql_close() has been deprecated: 5.5 Close MySQL connection ( Ignorable by Annotation )

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

344
							/** @scrutinizer ignore-deprecated */ mysql_close($cid);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
345
							$phpThumb->setSourceData($row[0]);
346
							unset($row);
347
348
						} else {
349
							mysql_free_result($result);
0 ignored issues
show
Deprecated Code introduced by
The function mysql_free_result() has been deprecated: 5.5 Free result memory ( Ignorable by Annotation )

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

349
							/** @scrutinizer ignore-deprecated */ mysql_free_result($result);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
350
							mysql_close($cid);
0 ignored issues
show
Deprecated Code introduced by
The function mysql_close() has been deprecated: 5.5 Close MySQL connection ( Ignorable by Annotation )

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

350
							/** @scrutinizer ignore-deprecated */ mysql_close($cid);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
351
							$phpThumb->ErrorImage('no matching data in database.');
352
						}
353
					} else {
354
						mysql_close($cid);
0 ignored issues
show
Deprecated Code introduced by
The function mysql_close() has been deprecated: 5.5 Close MySQL connection ( Ignorable by Annotation )

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

354
						/** @scrutinizer ignore-deprecated */ mysql_close($cid);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
355
						$phpThumb->ErrorImage('Error in MySQL query: "'.mysql_error($cid).'"');
0 ignored issues
show
Deprecated Code introduced by
The function mysql_error() has been deprecated: 5.5 Returns the text of the error message from previous MySQL operation ( Ignorable by Annotation )

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

355
						$phpThumb->ErrorImage('Error in MySQL query: "'./** @scrutinizer ignore-deprecated */ mysql_error($cid).'"');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
356
					}
357
				} else {
358
					mysql_close($cid);
0 ignored issues
show
Deprecated Code introduced by
The function mysql_close() has been deprecated: 5.5 Close MySQL connection ( Ignorable by Annotation )

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

358
					/** @scrutinizer ignore-deprecated */ mysql_close($cid);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
359
					$phpThumb->ErrorImage('cannot select MySQL database: "'.mysql_error($cid).'"');
0 ignored issues
show
Deprecated Code introduced by
The function mysql_error() has been deprecated: 5.5 Returns the text of the error message from previous MySQL operation ( Ignorable by Annotation )

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

359
					$phpThumb->ErrorImage('cannot select MySQL database: "'./** @scrutinizer ignore-deprecated */ mysql_error($cid).'"');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
360
				}
361
			} else {
362
				$phpThumb->ErrorImage('cannot connect to MySQL server');
363
			}
364
			unset($_GET['id']);
365
		}
366
367
	} else {
368
		$phpThumb->ErrorImage('config_mysql_extension not supported');
369
	}
370
}
371
372
////////////////////////////////////////////////////////////////
373
// Debug output, to try and help me diagnose problems
374
$phpThumb->DebugTimingMessage('phpThumbDebug[2]', __FILE__, __LINE__);
375
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '2')) {
376
	$phpThumb->phpThumbDebug();
377
}
378
////////////////////////////////////////////////////////////////
379
380
$PHPTHUMB_DEFAULTS_DISABLEGETPARAMS = (bool) ($phpThumb->config_cache_default_only_suffix && (strpos($phpThumb->config_cache_default_only_suffix, '*') !== false));
0 ignored issues
show
Bug introduced by
$phpThumb->config_cache_default_only_suffix of type true is incompatible with the type string expected by parameter $haystack of strpos(). ( Ignorable by Annotation )

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

380
$PHPTHUMB_DEFAULTS_DISABLEGETPARAMS = (bool) ($phpThumb->config_cache_default_only_suffix && (strpos(/** @scrutinizer ignore-type */ $phpThumb->config_cache_default_only_suffix, '*') !== false));
Loading history...
381
382
// deprecated: 'err', 'file', 'goto',
383
$allowedGETparameters = array('src', 'new', 'w', 'h', 'wp', 'hp', 'wl', 'hl', 'ws', 'hs', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'zc', 'bc', 'bg', 'bgt', 'fltr', 'xto', 'ra', 'ar', 'aoe', 'far', 'iar', 'maxb', 'down', 'phpThumbDebug', 'hash', 'md5s', 'sfn', 'dpi', 'sia', 'nocache');
384
foreach ($_GET as $key => $value) {
385
	if (!empty($PHPTHUMB_DEFAULTS_DISABLEGETPARAMS) && ($key != 'src')) {
386
		// disabled, do not set parameter
387
		$phpThumb->DebugMessage('ignoring $_GET['.$key.'] because of $PHPTHUMB_DEFAULTS_DISABLEGETPARAMS', __FILE__, __LINE__);
388
	} elseif (in_array($key, $allowedGETparameters)) {
389
		$phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
390
		$phpThumb->setParameter($key, $value);
391
	} else {
392
		$phpThumb->ErrorImage('Forbidden parameter: '.$key);
393
	}
394
}
395
396
if (!empty($PHPTHUMB_DEFAULTS) && is_array($PHPTHUMB_DEFAULTS)) {
397
	$phpThumb->DebugMessage('setting $PHPTHUMB_DEFAULTS['.implode(';', array_keys($PHPTHUMB_DEFAULTS)).']', __FILE__, __LINE__);
398
	foreach ($PHPTHUMB_DEFAULTS as $key => $value) {
399
		if (!$PHPTHUMB_DEFAULTS_GETSTRINGOVERRIDE || !isset($_GET[$key])) { // set parameter to default value if config is set to allow _GET to override default, OR if no value is passed via _GET for this parameter
400
			//$_GET[$key] = $value;
401
			//$phpThumb->DebugMessage('PHPTHUMB_DEFAULTS assigning ('.(is_array($value) ? print_r($value, true) : $value).') to $_GET['.$key.']', __FILE__, __LINE__);
402
			$phpThumb->setParameter($key, $value);
403
			$phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).') from $PHPTHUMB_DEFAULTS', __FILE__, __LINE__);
404
		}
405
	}
406
}
407
408
////////////////////////////////////////////////////////////////
409
// Debug output, to try and help me diagnose problems
410
$phpThumb->DebugTimingMessage('phpThumbDebug[3]', __FILE__, __LINE__);
411
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '3')) {
412
	$phpThumb->phpThumbDebug();
413
}
414
////////////////////////////////////////////////////////////////
415
416
//if (!@$_GET['phpThumbDebug'] && !is_file($phpThumb->sourceFilename) && !phpthumb_functions::gd_version()) {
417
//	if (!headers_sent()) {
418
//		// base64-encoded error image in GIF format
419
//		$ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
420
//		header('Content-Type: image/gif');
421
//		echo base64_decode($ERROR_NOGD);
422
//	} else {
423
//		echo '*** ERROR: No PHP-GD support available ***';
424
//	}
425
//	exit;
426
//}
427
428
// check to see if file can be output from source with no processing or caching
429
$CanPassThroughDirectly = true;
430
if ($phpThumb->rawImageData) {
431
	// data from SQL, should be fine
432
} elseif (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
433
	// assume is ok to passthru if no other parameters specified
434
} elseif (preg_match('#^(f|ht)tp\://#i', $phpThumb->src)) {
435
	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because preg_match("#^(f|ht)tp\://#i", '.$phpThumb->src.')', __FILE__, __LINE__);
436
	$CanPassThroughDirectly = false;
437
} elseif (!@is_readable($phpThumb->sourceFilename)) {
438
	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_readable('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
439
	$CanPassThroughDirectly = false;
440
} elseif (!@is_file($phpThumb->sourceFilename)) {
441
	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_file('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
442
	$CanPassThroughDirectly = false;
443
}
444
foreach ($_GET as $key => $value) {
445
	switch ($key) {
446
		case 'src':
447
			// allowed
448
			break;
449
450
		case 'w':
451
		case 'h':
452
			// might be OK if exactly matches original
453
			if (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
454
				// assume it is not ok for direct-passthru of remote image
455
				$CanPassThroughDirectly = false;
456
			}
457
			break;
458
459
		case 'phpThumbDebug':
460
			// handled in direct-passthru code
461
			break;
462
463
		default:
464
			// all other parameters will cause some processing,
465
			// therefore cannot pass through original image unmodified
466
			$CanPassThroughDirectly = false;
467
			$UnAllowedGET[] = $key;
468
			break;
469
	}
470
}
471
if (!empty($UnAllowedGET)) {
472
	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because $_GET['.implode(';', array_unique($UnAllowedGET)).'] are set', __FILE__, __LINE__);
473
}
474
475
////////////////////////////////////////////////////////////////
476
// Debug output, to try and help me diagnose problems
477
$phpThumb->DebugTimingMessage('phpThumbDebug[4]', __FILE__, __LINE__);
478
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '4')) {
479
	$phpThumb->phpThumbDebug();
480
}
481
////////////////////////////////////////////////////////////////
482
483
$phpThumb->DebugMessage('$CanPassThroughDirectly="'. (int) $CanPassThroughDirectly .'" && $phpThumb->src="'.$phpThumb->src.'"', __FILE__, __LINE__);
484
while ($CanPassThroughDirectly && $phpThumb->src) {
485
	// no parameters set, passthru
486
487
	if (preg_match('#^http\://[^\\?&]+\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
488
		$phpThumb->DebugMessage('Passing HTTP source through directly as Location: redirect ('.$phpThumb->src.')', __FILE__, __LINE__);
489
		header('Location: '.$phpThumb->src);
490
		exit;
491
	}
492
493
	$SourceFilename = $phpThumb->ResolveFilenameToAbsolute($phpThumb->src);
494
495
	// security and size checks
496
	if ($phpThumb->getimagesizeinfo = @getimagesize($SourceFilename)) {
0 ignored issues
show
Bug introduced by
It seems like $SourceFilename can also be of type false; however, parameter $filename of getimagesize() does only seem to accept string, 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

496
	if ($phpThumb->getimagesizeinfo = @getimagesize(/** @scrutinizer ignore-type */ $SourceFilename)) {
Loading history...
497
		$phpThumb->DebugMessage('Direct passthru getimagesize() returned [w='.$phpThumb->getimagesizeinfo[0].';h='.$phpThumb->getimagesizeinfo[1].';t='.$phpThumb->getimagesizeinfo[2].']', __FILE__, __LINE__);
498
499
		if (!@$_GET['w'] && !@$_GET['wp'] && !@$_GET['wl'] && !@$_GET['ws'] && !@$_GET['h'] && !@$_GET['hp'] && !@$_GET['hl'] && !@$_GET['hs']) {
500
			// no resizing needed
501
			$phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'")', __FILE__, __LINE__);
502
		} elseif (($phpThumb->getimagesizeinfo[0] <= @$_GET['w']) && ($phpThumb->getimagesizeinfo[1] <= @$_GET['h']) && ((@$_GET['w'] == $phpThumb->getimagesizeinfo[0]) || (@$_GET['h'] == $phpThumb->getimagesizeinfo[1]))) {
503
			// image fits into 'w'x'h' box, and at least one dimension matches exactly, therefore no resizing needed
504
			$phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" fits inside "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
505
		} else {
506
			$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because resizing required (from "'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" to "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
507
			break;
508
		}
509
		switch ($phpThumb->getimagesizeinfo[2]) {
510
			case 1: // GIF
511
			case 2: // JPG
512
			case 3: // PNG
513
				// great, let it through
514
				break;
515
			default:
516
				// browser probably can't handle format, remangle it to JPEG/PNG/GIF
517
				$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because $phpThumb->getimagesizeinfo[2] = "'.$phpThumb->getimagesizeinfo[2].'"', __FILE__, __LINE__);
518
				break 2;
519
		}
520
521
		$ImageCreateFunctions = array(1=>'imagecreatefromgif', 2=>'imagecreatefromjpeg', 3=>'imagecreatefrompng');
522
		$theImageCreateFunction = @$ImageCreateFunctions[$phpThumb->getimagesizeinfo[2]];
523
		$dummyImage = false;
524
		if ($phpThumb->config_disable_onlycreateable_passthru || (function_exists($theImageCreateFunction) && ($dummyImage = @$theImageCreateFunction($SourceFilename)))) {
525
526
			// great
527
			if (@is_resource($dummyImage)) {
528
				unset($dummyImage);
529
			}
530
531
			if (headers_sent()) {
532
				$phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
533
				exit;
534
			}
535
			if (!empty($_GET['phpThumbDebug'])) {
536
				$phpThumb->DebugTimingMessage('skipped direct $SourceFilename passthru', __FILE__, __LINE__);
537
				$phpThumb->DebugMessage('Would have passed "'.$SourceFilename.'" through directly, but skipping due to phpThumbDebug', __FILE__, __LINE__);
538
				break;
539
			}
540
541
			SendSaveAsFileHeaderIfNeeded($phpThumb->getimagesizeinfo);
542
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', @filemtime($SourceFilename)).' GMT');
0 ignored issues
show
Bug introduced by
It seems like $SourceFilename can also be of type false; however, parameter $filename of filemtime() does only seem to accept string, 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

542
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', @filemtime(/** @scrutinizer ignore-type */ $SourceFilename)).' GMT');
Loading history...
543
			if ($contentType = phpthumb_functions::ImageTypeToMIMEtype(@$phpThumb->getimagesizeinfo[2])) {
544
				header('Content-Type: '.$contentType);
545
			}
546
			@readfile($SourceFilename);
0 ignored issues
show
Bug introduced by
It seems like $SourceFilename can also be of type false; however, parameter $filename of readfile() does only seem to accept string, 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

546
			@readfile(/** @scrutinizer ignore-type */ $SourceFilename);
Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for readfile(). 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

546
			/** @scrutinizer ignore-unhandled */ @readfile($SourceFilename);

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...
547
			exit;
548
549
		} else {
550
			$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because ($phpThumb->config_disable_onlycreateable_passthru = "'.$phpThumb->config_disable_onlycreateable_passthru.'") and '.$theImageCreateFunction.'() failed', __FILE__, __LINE__);
0 ignored issues
show
Bug introduced by
Are you sure $phpThumb->config_disable_onlycreateable_passthru of type false can be used in concatenation? ( Ignorable by Annotation )

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

550
			$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because ($phpThumb->config_disable_onlycreateable_passthru = "'./** @scrutinizer ignore-type */ $phpThumb->config_disable_onlycreateable_passthru.'") and '.$theImageCreateFunction.'() failed', __FILE__, __LINE__);
Loading history...
551
			break;
552
		}
553
554
	} else {
555
		$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because getimagesize() failed', __FILE__, __LINE__);
556
		break;
557
	}
558
	break;
559
}
560
561
////////////////////////////////////////////////////////////////
562
// Debug output, to try and help me diagnose problems
563
$phpThumb->DebugTimingMessage('phpThumbDebug[5]', __FILE__, __LINE__);
564
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '5')) {
565
	$phpThumb->phpThumbDebug();
566
}
567
////////////////////////////////////////////////////////////////
568
569
// check to see if file already exists in cache, and output it with no processing if it does
570
$phpThumb->SetCacheFilename();
571
if (@is_readable($phpThumb->cache_filename)) {
572
	RedirectToCachedFile();
573
} else {
574
	$phpThumb->DebugMessage('Cached file "'.$phpThumb->cache_filename.'" does not exist, processing as normal', __FILE__, __LINE__);
575
}
576
577
////////////////////////////////////////////////////////////////
578
// Debug output, to try and help me diagnose problems
579
$phpThumb->DebugTimingMessage('phpThumbDebug[6]', __FILE__, __LINE__);
580
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '6')) {
581
	$phpThumb->phpThumbDebug();
582
}
583
////////////////////////////////////////////////////////////////
584
585
if ($phpThumb->rawImageData) {
586
587
	// great
588
589
} elseif (!empty($_GET['new'])) {
590
591
	// generate a blank image resource of the specified size/background color/opacity
592
	if (($phpThumb->w <= 0) || ($phpThumb->h <= 0)) {
593
		$phpThumb->ErrorImage('"w" and "h" parameters required for "new"');
594
	}
595
	@list($bghexcolor, $opacity) = explode('|', $_GET['new']);
596
	if (!phpthumb_functions::IsHexColor($bghexcolor)) {
597
		$phpThumb->ErrorImage('BGcolor parameter for "new" is not valid');
598
	}
599
	$opacity = ('' !== $opacity ? $opacity : 100);
600
	if ($phpThumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpThumb->w, $phpThumb->h)) {
601
		$alpha = (100 - min(100, max(0, $opacity))) * 1.27;
602
		if ($alpha) {
603
			$phpThumb->setParameter('is_alpha', true);
604
			imagealphablending($phpThumb->gdimg_source, false);
605
			imagesavealpha($phpThumb->gdimg_source, true);
606
		}
607
		$new_background_color = phpthumb_functions::ImageHexColorAllocate($phpThumb->gdimg_source, $bghexcolor, false, $alpha);
608
		imagefilledrectangle($phpThumb->gdimg_source, 0, 0, $phpThumb->w, $phpThumb->h, $new_background_color);
609
	} else {
610
		$phpThumb->ErrorImage('failed to create "new" image ('.$phpThumb->w.'x'.$phpThumb->h.')');
611
	}
612
613
} elseif (!$phpThumb->src) {
614
615
	$phpThumb->ErrorImage('Usage: '.$_SERVER['PHP_SELF'].'?src=/path/and/filename.jpg'."\n".'read Usage comments for details');
616
617
} elseif (preg_match('#^([a-z0-9]+)://#i', $_GET['src'], $protocol_matches)) {
618
619
	if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
620
		$phpThumb->DebugMessage('$phpThumb->src ('.$phpThumb->src.') is remote image, attempting to download', __FILE__, __LINE__);
621
		if ($phpThumb->config_http_user_agent) {
622
			$phpThumb->DebugMessage('Setting "user_agent" to "'.$phpThumb->config_http_user_agent.'"', __FILE__, __LINE__);
623
			ini_set('user_agent', $phpThumb->config_http_user_agent);
624
		}
625
		$cleanedupurl = phpthumb_functions::CleanUpURLencoding($phpThumb->src);
626
		$phpThumb->DebugMessage('CleanUpURLencoding('.$phpThumb->src.') returned "'.$cleanedupurl.'"', __FILE__, __LINE__);
627
		$phpThumb->src = $cleanedupurl;
628
		unset($cleanedupurl);
629
		if ($rawImageData = phpthumb_functions::SafeURLread($phpThumb->src, $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
630
			$phpThumb->DebugMessage('SafeURLread('.$phpThumb->src.') succeeded'.($error ? ' with messages: "'.$error.'"' : ''), __FILE__, __LINE__);
631
			$phpThumb->DebugMessage('Setting source data from URL "'.$phpThumb->src.'"', __FILE__, __LINE__);
632
			$phpThumb->setSourceData($rawImageData, urlencode($phpThumb->src));
633
		} else {
634
			$phpThumb->ErrorImage($error);
635
		}
636
	} else {
637
		$phpThumb->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
638
	}
639
640
}
641
642
////////////////////////////////////////////////////////////////
643
// Debug output, to try and help me diagnose problems
644
$phpThumb->DebugTimingMessage('phpThumbDebug[7]', __FILE__, __LINE__);
645
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '7')) {
646
	$phpThumb->phpThumbDebug();
647
}
648
////////////////////////////////////////////////////////////////
649
650
$phpThumb->GenerateThumbnail();
651
652
////////////////////////////////////////////////////////////////
653
// Debug output, to try and help me diagnose problems
654
$phpThumb->DebugTimingMessage('phpThumbDebug[8]', __FILE__, __LINE__);
655
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '8')) {
656
	$phpThumb->phpThumbDebug();
657
}
658
////////////////////////////////////////////////////////////////
659
660
if (!empty($phpThumb->config_high_security_enabled) && !empty($_GET['nocache'])) {
661
662
	// cache disabled, don't write cachefile
663
664
} else {
665
666
	phpthumb_functions::EnsureDirectoryExists(dirname($phpThumb->cache_filename));
667
	if (is_writable(dirname($phpThumb->cache_filename)) || (file_exists($phpThumb->cache_filename) && is_writable($phpThumb->cache_filename))) {
668
669
		$phpThumb->CleanUpCacheDirectory();
670
		if ($phpThumb->RenderToFile($phpThumb->cache_filename) && is_readable($phpThumb->cache_filename)) {
671
			chmod($phpThumb->cache_filename, 0644);
672
			RedirectToCachedFile();
673
		} else {
674
			$phpThumb->DebugMessage('Failed: RenderToFile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
675
		}
676
677
	} else {
678
679
		$phpThumb->DebugMessage('Cannot write to $phpThumb->cache_filename ('.$phpThumb->cache_filename.') because that directory ('.dirname($phpThumb->cache_filename).') is not writable', __FILE__, __LINE__);
680
681
	}
682
683
}
684
685
////////////////////////////////////////////////////////////////
686
// Debug output, to try and help me diagnose problems
687
$phpThumb->DebugTimingMessage('phpThumbDebug[9]', __FILE__, __LINE__);
688
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '9')) {
689
	$phpThumb->phpThumbDebug();
690
}
691
////////////////////////////////////////////////////////////////
692
693
if (!$phpThumb->OutputThumbnail()) {
694
	$phpThumb->ErrorImage('Error in OutputThumbnail():'."\n". $phpThumb->debugmessages[ count($phpThumb->debugmessages) - 1 ]);
695
}
696
697
////////////////////////////////////////////////////////////////
698
// Debug output, to try and help me diagnose problems
699
$phpThumb->DebugTimingMessage('phpThumbDebug[10]', __FILE__, __LINE__);
700
if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '10')) {
701
	$phpThumb->phpThumbDebug();
702
}
703
////////////////////////////////////////////////////////////////
704