Issues (1027)

Sources/Errors.php (18 issues)

1
<?php
2
3
/**
4
 * The purpose of this file is... errors. (hard to guess, I guess?)  It takes
5
 * care of logging, error messages, error handling, database errors, and
6
 * error log administration.
7
 *
8
 * Simple Machines Forum (SMF)
9
 *
10
 * @package SMF
11
 * @author Simple Machines http://www.simplemachines.org
12
 * @copyright 2019 Simple Machines and individual contributors
13
 * @license http://www.simplemachines.org/about/smf/license.php BSD
14
 *
15
 * @version 2.1 RC2
16
 */
17
18
if (!defined('SMF'))
19
	die('No direct access...');
20
21
/**
22
 * Log an error, if the error logging is enabled.
23
 * filename and line should be __FILE__ and __LINE__, respectively.
24
 * Example use:
25
 *  die(log_error($msg));
26
 *
27
 * @param string $error_message The message to log
28
 * @param string|bool $error_type The type of error
29
 * @param string $file The name of the file where this error occurred
30
 * @param int $line The line where the error occurred
31
 * @return string The message that was logged
32
 */
33
function log_error($error_message, $error_type = 'general', $file = null, $line = null)
34
{
35
	global $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error, $context, $db_show_debug;
36
	static $tried_hook = false;
37
	static $error_call = 0;
38
39
	$error_call++;
40
41
	// Collect a backtrace
42
	if (!isset($db_show_debug) || $db_show_debug === false)
43
		$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
44
	else
45
		$backtrace = debug_backtrace();
46
47
	// are we in a loop?
48
	if ($error_call > 2)
49
	{
50
		var_dump($backtrace);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($backtrace) looks like debug code. Are you sure you do not want to remove it?
Loading history...
51
		die('Error loop.');
0 ignored issues
show
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...
52
	}
53
54
	// Check if error logging is actually on.
55
	if (empty($modSettings['enableErrorLogging']))
56
		return $error_message;
57
58
	// Basically, htmlspecialchars it minus &. (for entities!)
59
	$error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
60
	$error_message = strtr($error_message, array('&lt;br /&gt;' => '<br>', '&lt;br&gt;' => '<br>', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br>'));
61
62
	// Add a file and line to the error message?
63
	// Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
64
	if ($file == null)
0 ignored issues
show
It seems like you are loosely comparing $file of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
65
		$file = '';
66
	else
67
		// Windows style slashes don't play well, lets convert them to the unix style.
68
		$file = str_replace('\\', '/', $file);
69
70
	if ($line == null)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $line of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison === instead.
Loading history...
71
		$line = 0;
72
	else
73
		$line = (int) $line;
74
75
	// Just in case there's no id_member or IP set yet.
76
	if (empty($user_info['id']))
77
		$user_info['id'] = 0;
78
	if (empty($user_info['ip']))
79
		$user_info['ip'] = '';
80
81
	// Find the best query string we can...
82
	$query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
83
84
	// Don't log the session hash in the url twice, it's a waste.
85
	if (!empty($smcFunc['htmlspecialchars']))
86
		$query_string = $smcFunc['htmlspecialchars']((SMF == 'SSI' || SMF == 'BACKGROUND' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
0 ignored issues
show
The condition SMF == 'SSI' is always true.
Loading history...
87
88
	// Just so we know what board error messages are from.
89
	if (isset($_POST['board']) && !isset($_GET['board']))
90
		$query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
91
92
	// What types of categories do we have?
93
	$known_error_types = array(
94
		'general',
95
		'critical',
96
		'database',
97
		'undefined_vars',
98
		'user',
99
		'ban',
100
		'template',
101
		'debug',
102
		'cron',
103
		'paidsubs',
104
		'backup',
105
		'login',
106
	);
107
108
	// This prevents us from infinite looping if the hook or call produces an error.
109
	$other_error_types = array();
110
	if (empty($tried_hook))
111
	{
112
		$tried_hook = true;
113
		// Allow the hook to change the error_type and know about the error.
114
		call_integration_hook('integrate_error_types', array(&$other_error_types, &$error_type, $error_message, $file, $line));
115
		$known_error_types += $other_error_types;
116
	}
117
	// Make sure the category that was specified is a valid one
118
	$error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
119
120
	// leave out the call to log_error
121
	array_splice($backtrace, 0, 1);
122
	$backtrace = !empty($smcFunc['json_encode']) ? $smcFunc['json_encode']($backtrace) : json_encode($backtrace);
123
124
	// Don't log the same error countless times, as we can get in a cycle of depression...
125
	$error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line, $backtrace);
126
	if (empty($last_error) || $last_error != $error_info)
127
	{
128
		// Insert the error into the database.
129
		$smcFunc['db_error_insert']($error_info);
130
		$last_error = $error_info;
131
132
		// Get an error count, if necessary
133
		if (!isset($context['num_errors']))
134
		{
135
			$query = $smcFunc['db_query']('', '
136
				SELECT COUNT(id_error)
137
				FROM {db_prefix}log_errors',
138
				array()
139
			);
140
141
			list($context['num_errors']) = $smcFunc['db_fetch_row']($query);
142
			$smcFunc['db_free_result']($query);
143
		}
144
		else
145
			$context['num_errors']++;
146
	}
147
148
	// reset error call
149
	$error_call = 0;
150
151
	// Return the message to make things simpler.
152
	return $error_message;
153
}
154
155
/**
156
 * An irrecoverable error. This function stops execution and displays an error message.
157
 * It logs the error message if $log is specified.
158
 *
159
 * @param string $error The error message
160
 * @param string|bool $log = 'general' What type of error to log this as (false to not log it))
161
 * @param int $status The HTTP status code associated with this error
162
 */
163
function fatal_error($error, $log = 'general', $status = 500)
164
{
165
	global $txt;
166
167
	// Send the appropriate HTTP status header - set this to 0 or false if you don't want to send one at all
168
	if (!empty($status))
169
		send_http_status($status);
170
171
	// We don't have $txt yet, but that's okay...
172
	if (empty($txt))
173
		die($error);
0 ignored issues
show
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...
174
175
	log_error_online($error);
176
	setup_fatal_error_context($log ? log_error($error, $log) : $error);
177
}
178
179
/**
180
 * Shows a fatal error with a message stored in the language file.
181
 *
182
 * This function stops execution and displays an error message by key.
183
 *  - uses the string with the error_message_key key.
184
 *  - logs the error in the forum's default language while displaying the error
185
 *    message in the user's language.
186
 *  - uses Errors language file and applies the $sprintf information if specified.
187
 *  - the information is logged if log is specified.
188
 *
189
 * @param string $error The error message
190
 * @param string|false $log The type of error, or false to not log it
191
 * @param array $sprintf An array of data to be sprintf()'d into the specified message
192
 * @param int $status = false The HTTP status code associated with this error
193
 */
194
function fatal_lang_error($error, $log = 'general', $sprintf = array(), $status = 403)
195
{
196
	global $txt, $language, $user_info, $context;
197
	static $fatal_error_called = false;
198
199
	// Send the status header - set this to 0 or false if you don't want to send one at all
200
	if (!empty($status))
201
		send_http_status($status);
202
203
	// Try to load a theme if we don't have one.
204
	if (empty($context['theme_loaded']) && empty($fatal_error_called))
205
	{
206
		$fatal_error_called = true;
207
		loadTheme();
208
	}
209
210
	// If we have no theme stuff we can't have the language file...
211
	if (empty($context['theme_loaded']))
212
		die($error);
0 ignored issues
show
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...
213
214
	$reload_lang_file = true;
215
	// Log the error in the forum's language, but don't waste the time if we aren't logging
216
	if ($log)
217
	{
218
		loadLanguage('Errors', $language);
219
		$reload_lang_file = $language != $user_info['language'];
220
		$error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
221
		log_error($error_message, $log);
222
	}
223
224
	// Load the language file, only if it needs to be reloaded
225
	if ($reload_lang_file)
0 ignored issues
show
The condition $reload_lang_file is always true.
Loading history...
226
	{
227
		loadLanguage('Errors');
228
		$error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
229
	}
230
231
	log_error_online($error, $sprintf);
232
	setup_fatal_error_context($error_message, $error);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error_message does not seem to be defined for all execution paths leading up to this point.
Loading history...
233
}
234
235
/**
236
 * Handler for standard error messages, standard PHP error handler replacement.
237
 * It dies with fatal_error() if the error_level matches with error_reporting.
238
 *
239
 * @param int $error_level A pre-defined error-handling constant (see {@link https://php.net/errorfunc.constants})
240
 * @param string $error_string The error message
241
 * @param string $file The file where the error occurred
242
 * @param int $line The line where the error occurred
243
 */
244
function smf_error_handler($error_level, $error_string, $file, $line)
245
{
246
	global $settings, $modSettings, $db_show_debug;
247
248
	// Ignore errors if we're ignoring them or they are strict notices from PHP 5
249
	if (error_reporting() == 0)
250
		return;
251
252
	if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
253
	{
254
		$array = debug_backtrace();
255
		$count = count($array);
256
		for ($i = 0; $i < $count; $i++)
257
		{
258
			if ($array[$i]['function'] != 'loadSubTemplate')
259
				continue;
260
261
			// This is a bug in PHP, with eval, it seems!
262
			if (empty($array[$i]['args']))
263
				$i++;
264
			break;
265
		}
266
267
		if (isset($array[$i]) && !empty($array[$i]['args']))
268
			$file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
269
		else
270
			$file = realpath($settings['current_include_filename']) . ' (eval?)';
271
	}
272
273
	if (isset($db_show_debug) && $db_show_debug === true)
274
	{
275
		// Commonly, undefined indexes will occur inside attributes; try to show them anyway!
276
		if ($error_level % 255 != E_ERROR)
277
		{
278
			$temporary = ob_get_contents();
279
			if (substr($temporary, -2) == '="')
280
				echo '"';
281
		}
282
283
		// Debugging!  This should look like a PHP error message.
284
		echo '<br>
285
<strong>', $error_level % 255 == E_ERROR ? 'Error' : ($error_level % 255 == E_WARNING ? 'Warning' : 'Notice'), '</strong>: ', $error_string, ' in <strong>', $file, '</strong> on line <strong>', $line, '</strong><br>';
286
	}
287
288
	$error_type = stripos($error_string, 'undefined') !== false ? 'undefined_vars' : 'general';
289
290
	$message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
291
292
	// Let's give integrations a chance to ouput a bit differently
293
	call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
294
295
	// Dying on these errors only causes MORE problems (blank pages!)
296
	if ($file == 'Unknown')
297
		return;
298
299
	// If this is an E_ERROR or E_USER_ERROR.... die.  Violently so.
300
	if ($error_level % 255 == E_ERROR)
301
		obExit(false);
302
	else
303
		return;
304
305
	// If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die.  Violently so.
306
	if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
307
		fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
308
309
	// We should NEVER get to this point.  Any fatal error MUST quit, or very bad things can happen.
310
	if ($error_level % 255 == E_ERROR)
311
		die('No direct access...');
0 ignored issues
show
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...
312
}
313
314
/**
315
 * It is called by {@link fatal_error()} and {@link fatal_lang_error()}.
316
 *
317
 * @uses Errors template, fatal_error sub template.
318
 *
319
 * @param string $error_message The error message
320
 * @param string $error_code An error code
321
 */
322
function setup_fatal_error_context($error_message, $error_code = null)
323
{
324
	global $context, $txt, $ssi_on_error_method;
325
	static $level = 0;
326
327
	// Attempt to prevent a recursive loop.
328
	++$level;
329
	if ($level > 1)
330
		return false;
331
332
	// Maybe they came from dlattach or similar?
333
	if (SMF != 'SSI' && SMF != 'BACKGROUND' && empty($context['theme_loaded']))
0 ignored issues
show
The condition SMF != 'SSI' is always false.
Loading history...
334
		loadTheme();
335
336
	// Don't bother indexing errors mate...
337
	$context['robot_no_index'] = true;
338
339
	if (!isset($context['error_title']))
340
		$context['error_title'] = $txt['error_occured'];
341
	$context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
342
343
	$context['error_code'] = isset($error_code) ? 'id="' . $error_code . '" ' : '';
344
345
	if (empty($context['page_title']))
346
		$context['page_title'] = $context['error_title'];
347
348
	loadTemplate('Errors');
349
	$context['sub_template'] = 'fatal_error';
350
351
	// If this is SSI, what do they want us to do?
352
	if (SMF == 'SSI')
353
	{
354
		if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
355
			$ssi_on_error_method();
356
		elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
357
			loadSubTemplate('fatal_error');
358
359
		// No layers?
360
		if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
361
			exit;
0 ignored issues
show
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...
362
	}
363
	// Alternatively from the cron call?
364
	elseif (SMF == 'BACKGROUND')
365
	{
366
		// We can't rely on even having language files available.
367
		if (defined('FROM_CLI') && FROM_CLI)
368
			echo 'cron error: ', $context['error_message'];
369
		else
370
			echo 'An error occurred. More information may be available in your logs.';
371
		exit;
0 ignored issues
show
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...
372
	}
373
374
	// We want whatever for the header, and a footer. (footer includes sub template!)
375
	obExit(null, true, false, true);
376
377
	/* DO NOT IGNORE:
378
		If you are creating a bridge to SMF or modifying this function, you MUST
379
		make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
380
		PROGRAM FLOW.  Otherwise, security error messages will not be shown, and
381
		your forum will be in a very easily hackable state.
382
	*/
383
	trigger_error('Hacking attempt...', E_USER_ERROR);
384
}
385
386
/**
387
 * Show a message for the (full block) maintenance mode.
388
 * It shows a complete page independent of language files or themes.
389
 * It is used only if $maintenance = 2 in Settings.php.
390
 * It stops further execution of the script.
391
 */
392
function display_maintenance_message()
393
{
394
	global $maintenance, $mtitle, $mmessage;
395
396
	set_fatal_error_headers();
397
398
	if (!empty($maintenance))
399
		echo '<!DOCTYPE html>
400
<html>
401
	<head>
402
		<meta name="robots" content="noindex">
403
		<title>', $mtitle, '</title>
404
	</head>
405
	<body>
406
		<h3>', $mtitle, '</h3>
407
		', $mmessage, '
408
	</body>
409
</html>';
410
411
	die();
0 ignored issues
show
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...
412
}
413
414
/**
415
 * Show an error message for the connection problems.
416
 * It shows a complete page independent of language files or themes.
417
 * It is used only if there's no way to connect to the database.
418
 * It stops further execution of the script.
419
 */
420
function display_db_error()
421
{
422
	global $mbname, $modSettings, $maintenance;
423
	global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc, $sourcedir, $cache_enable;
424
425
	require_once($sourcedir . '/Logging.php');
426
	set_fatal_error_headers();
427
428
	// For our purposes, we're gonna want this on if at all possible.
429
	$cache_enable = '1';
430
431
	if (($temp = cache_get_data('db_last_error', 600)) !== null)
432
		$db_last_error = max($db_last_error, $temp);
433
434
	if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
435
	{
436
		// Avoid writing to the Settings.php file if at all possible; use shared memory instead.
437
		cache_put_data('db_last_error', time(), 600);
438
		if (($temp = cache_get_data('db_last_error', 600)) === null)
0 ignored issues
show
The assignment to $temp is dead and can be removed.
Loading history...
439
			logLastDatabaseError();
440
441
		// Language files aren't loaded yet :(.
442
		$db_error = @$smcFunc['db_error']($db_connection);
443
		@mail($webmaster_email, $mbname . ': SMF Database Error!', 'There has been a problem with the database!' . ($db_error == '' ? '' : "\n" . $smcFunc['db_title'] . ' reported:' . "\n" . $db_error) . "\n\n" . 'This is a notice email to let you know that SMF could not connect to the database, contact your host if this continues.');
444
	}
445
446
	// What to do?  Language files haven't and can't be loaded yet...
447
	echo '<!DOCTYPE html>
448
<html>
449
	<head>
450
		<meta name="robots" content="noindex">
451
		<title>Connection Problems</title>
452
	</head>
453
	<body>
454
		<h3>Connection Problems</h3>
455
		Sorry, SMF was unable to connect to the database.  This may be caused by the server being busy.  Please try again later.
456
	</body>
457
</html>';
458
459
	die();
0 ignored issues
show
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...
460
}
461
462
/**
463
 * Show an error message for load average blocking problems.
464
 * It shows a complete page independent of language files or themes.
465
 * It is used only if the load averages are too high to continue execution.
466
 * It stops further execution of the script.
467
 */
468
function display_loadavg_error()
469
{
470
	// If this is a load average problem, display an appropriate message (but we still don't have language files!)
471
472
	set_fatal_error_headers();
473
474
	echo '<!DOCTYPE html>
475
<html>
476
	<head>
477
		<meta name="robots" content="noindex">
478
		<title>Temporarily Unavailable</title>
479
	</head>
480
	<body>
481
		<h3>Temporarily Unavailable</h3>
482
		Due to high stress on the server the forum is temporarily unavailable.  Please try again later.
483
	</body>
484
</html>';
485
486
	die();
0 ignored issues
show
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...
487
}
488
489
/**
490
 * Small utility function for fatal error pages.
491
 * Used by {@link display_db_error()}, {@link display_loadavg_error()},
492
 * {@link display_maintenance_message()}
493
 */
494
function set_fatal_error_headers()
495
{
496
	if (headers_sent())
497
		return;
498
499
	// Don't cache this page!
500
	header('expires: Mon, 26 Jul 1997 05:00:00 GMT');
501
	header('last-modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
502
	header('cache-control: no-cache');
503
504
	// Send the right error codes.
505
	send_http_status(503, 'Service Temporarily Unavailable');
506
	header('status: 503 Service Temporarily Unavailable');
507
	header('retry-after: 3600');
508
}
509
510
/**
511
 * Small utility function for fatal error pages.
512
 * Used by fatal_error(), fatal_lang_error()
513
 *
514
 * @param string $error The error
515
 * @param array $sprintf An array of data to be sprintf()'d into the specified message
516
 */
517
function log_error_online($error, $sprintf = array())
518
{
519
	global $smcFunc, $user_info, $modSettings;
520
521
	// Don't bother if Who's Online is disabled.
522
	if (empty($modSettings['who_enabled']))
523
		return;
524
525
	// Maybe they came from SSI or similar where sessions are not recorded?
526
	if (SMF == 'SSI' || SMF == 'BACKGROUND')
0 ignored issues
show
The condition SMF == 'SSI' is always true.
Loading history...
527
		return;
528
529
	$session_id = !empty($user_info['is_guest']) ? 'ip' . $user_info['ip'] : session_id();
530
531
	// First, we have to get the online log, because we need to break apart the serialized string.
532
	$request = $smcFunc['db_query']('', '
533
		SELECT url
534
		FROM {db_prefix}log_online
535
		WHERE session = {string:session}',
536
		array(
537
			'session' => $session_id,
538
		)
539
	);
540
	if ($smcFunc['db_num_rows']($request) != 0)
541
	{
542
		// If this happened very early on in SMF startup, $smcFunc may not fully be defined.
543
		if (!isset($smcFunc['json_decode']))
544
		{
545
			$smcFunc['json_decode'] = 'smf_json_decode';
546
			$smcFunc['json_encode'] = 'json_encode';
547
		}
548
549
		list ($url) = $smcFunc['db_fetch_row']($request);
550
		$url = $smcFunc['json_decode']($url, true);
551
		$url['error'] = $error;
552
		// Url field got a max length of 1024 in db
553
		if (strlen($url['error']) > 500)
554
			$url['error'] = substr($url['error'], 0, 500);
555
556
		if (!empty($sprintf))
557
			$url['error_params'] = $sprintf;
558
559
		$smcFunc['db_query']('', '
560
			UPDATE {db_prefix}log_online
561
			SET url = {string:url}
562
			WHERE session = {string:session}',
563
			array(
564
				'url' => $smcFunc['json_encode']($url),
565
				'session' => $session_id,
566
			)
567
		);
568
	}
569
	$smcFunc['db_free_result']($request);
570
}
571
572
?>