Issues (1061)

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 https://www.simplemachines.org
12
 * @copyright 2020 Simple Machines and individual contributors
13
 * @license https://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
	// Error was suppressed with the @-operator.
249
	if (error_reporting() == 0)
250
		return true;
251
252
	// Ignore errors that should should not be logged.
253
	$error_match = error_reporting() & $error_level;
254
	if (empty($error_match) || empty($modSettings['enableErrorLogging']))
255
		return false;
256
257
	if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
258
	{
259
		$array = debug_backtrace();
260
		$count = count($array);
261
		for ($i = 0; $i < $count; $i++)
262
		{
263
			if ($array[$i]['function'] != 'loadSubTemplate')
264
				continue;
265
266
			// This is a bug in PHP, with eval, it seems!
267
			if (empty($array[$i]['args']))
268
				$i++;
269
			break;
270
		}
271
272
		if (isset($array[$i]) && !empty($array[$i]['args']))
273
			$file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
274
		else
275
			$file = realpath($settings['current_include_filename']) . ' (eval?)';
276
	}
277
278
	if (isset($db_show_debug) && $db_show_debug === true)
279
	{
280
		// Commonly, undefined indexes will occur inside attributes; try to show them anyway!
281
		if ($error_level % 255 != E_ERROR)
282
		{
283
			$temporary = ob_get_contents();
284
			if (substr($temporary, -2) == '="')
285
				echo '"';
286
		}
287
288
		// Debugging!  This should look like a PHP error message.
289
		echo '<br>
290
<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>';
291
	}
292
293
	$error_type = stripos($error_string, 'undefined') !== false ? 'undefined_vars' : 'general';
294
295
	$message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
296
297
	// Let's give integrations a chance to ouput a bit differently
298
	call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
299
300
	// Dying on these errors only causes MORE problems (blank pages!)
301
	if ($file == 'Unknown')
302
		return;
303
304
	// If this is an E_ERROR or E_USER_ERROR.... die.  Violently so.
305
	if ($error_level % 255 == E_ERROR)
306
		obExit(false);
307
	else
308
		return;
309
310
	// If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die.  Violently so.
311
	if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
312
		fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
313
314
	// We should NEVER get to this point.  Any fatal error MUST quit, or very bad things can happen.
315
	if ($error_level % 255 == E_ERROR)
316
		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...
317
}
318
319
/**
320
 * It is called by {@link fatal_error()} and {@link fatal_lang_error()}.
321
 *
322
 * @uses template_fatal_error()
323
 *
324
 * @param string $error_message The error message
325
 * @param string $error_code An error code
326
 * @return void|false Normally doesn't return anything, but returns false if a recursive loop is detected
327
 */
328
function setup_fatal_error_context($error_message, $error_code = null)
329
{
330
	global $context, $txt, $ssi_on_error_method;
331
	static $level = 0;
332
333
	// Attempt to prevent a recursive loop.
334
	++$level;
335
	if ($level > 1)
336
		return false;
337
338
	// Maybe they came from dlattach or similar?
339
	if (SMF != 'SSI' && SMF != 'BACKGROUND' && empty($context['theme_loaded']))
0 ignored issues
show
The condition SMF != 'SSI' is always false.
Loading history...
340
		loadTheme();
341
342
	// Don't bother indexing errors mate...
343
	$context['robot_no_index'] = true;
344
345
	if (!isset($context['error_title']))
346
		$context['error_title'] = $txt['error_occured'];
347
	$context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
348
349
	$context['error_code'] = isset($error_code) ? 'id="' . $error_code . '" ' : '';
350
351
	if (empty($context['page_title']))
352
		$context['page_title'] = $context['error_title'];
353
354
	loadTemplate('Errors');
355
	$context['sub_template'] = 'fatal_error';
356
357
	// If this is SSI, what do they want us to do?
358
	if (SMF == 'SSI')
359
	{
360
		if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
361
			$ssi_on_error_method();
362
		elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
363
			loadSubTemplate('fatal_error');
364
365
		// No layers?
366
		if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
367
			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...
368
	}
369
	// Alternatively from the cron call?
370
	elseif (SMF == 'BACKGROUND')
371
	{
372
		// We can't rely on even having language files available.
373
		if (defined('FROM_CLI') && FROM_CLI)
374
			echo 'cron error: ', $context['error_message'];
375
		else
376
			echo 'An error occurred. More information may be available in your logs.';
377
		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...
378
	}
379
380
	// We want whatever for the header, and a footer. (footer includes sub template!)
381
	obExit(null, true, false, true);
382
383
	/* DO NOT IGNORE:
384
		If you are creating a bridge to SMF or modifying this function, you MUST
385
		make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
386
		PROGRAM FLOW.  Otherwise, security error messages will not be shown, and
387
		your forum will be in a very easily hackable state.
388
	*/
389
	trigger_error('Hacking attempt...', E_USER_ERROR);
390
}
391
392
/**
393
 * Show a message for the (full block) maintenance mode.
394
 * It shows a complete page independent of language files or themes.
395
 * It is used only if $maintenance = 2 in Settings.php.
396
 * It stops further execution of the script.
397
 */
398
function display_maintenance_message()
399
{
400
	global $maintenance, $mtitle, $mmessage;
401
402
	set_fatal_error_headers();
403
404
	if (!empty($maintenance))
405
		echo '<!DOCTYPE html>
406
<html>
407
	<head>
408
		<meta name="robots" content="noindex">
409
		<title>', $mtitle, '</title>
410
	</head>
411
	<body>
412
		<h3>', $mtitle, '</h3>
413
		', $mmessage, '
414
	</body>
415
</html>';
416
417
	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...
418
}
419
420
/**
421
 * Show an error message for the connection problems.
422
 * It shows a complete page independent of language files or themes.
423
 * It is used only if there's no way to connect to the database.
424
 * It stops further execution of the script.
425
 */
426
function display_db_error()
427
{
428
	global $mbname, $modSettings, $maintenance;
429
	global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc, $sourcedir, $cache_enable;
430
431
	require_once($sourcedir . '/Logging.php');
432
	set_fatal_error_headers();
433
434
	// For our purposes, we're gonna want this on if at all possible.
435
	$cache_enable = '1';
436
437
	if (($temp = cache_get_data('db_last_error', 600)) !== null)
438
		$db_last_error = max($db_last_error, $temp);
439
440
	if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
441
	{
442
		// Avoid writing to the Settings.php file if at all possible; use shared memory instead.
443
		cache_put_data('db_last_error', time(), 600);
444
		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...
445
			logLastDatabaseError();
446
447
		// Language files aren't loaded yet :(.
448
		$db_error = @$smcFunc['db_error']($db_connection);
449
		@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.');
450
	}
451
452
	// What to do?  Language files haven't and can't be loaded yet...
453
	echo '<!DOCTYPE html>
454
<html>
455
	<head>
456
		<meta name="robots" content="noindex">
457
		<title>Connection Problems</title>
458
	</head>
459
	<body>
460
		<h3>Connection Problems</h3>
461
		Sorry, SMF was unable to connect to the database.  This may be caused by the server being busy.  Please try again later.
462
	</body>
463
</html>';
464
465
	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...
466
}
467
468
/**
469
 * Show an error message for load average blocking problems.
470
 * It shows a complete page independent of language files or themes.
471
 * It is used only if the load averages are too high to continue execution.
472
 * It stops further execution of the script.
473
 */
474
function display_loadavg_error()
475
{
476
	// If this is a load average problem, display an appropriate message (but we still don't have language files!)
477
478
	set_fatal_error_headers();
479
480
	echo '<!DOCTYPE html>
481
<html>
482
	<head>
483
		<meta name="robots" content="noindex">
484
		<title>Temporarily Unavailable</title>
485
	</head>
486
	<body>
487
		<h3>Temporarily Unavailable</h3>
488
		Due to high stress on the server the forum is temporarily unavailable.  Please try again later.
489
	</body>
490
</html>';
491
492
	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...
493
}
494
495
/**
496
 * Small utility function for fatal error pages.
497
 * Used by {@link display_db_error()}, {@link display_loadavg_error()},
498
 * {@link display_maintenance_message()}
499
 */
500
function set_fatal_error_headers()
501
{
502
	if (headers_sent())
503
		return;
504
505
	// Don't cache this page!
506
	header('expires: Mon, 26 Jul 1997 05:00:00 GMT');
507
	header('last-modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
508
	header('cache-control: no-cache');
509
510
	// Send the right error codes.
511
	send_http_status(503, 'Service Temporarily Unavailable');
512
	header('status: 503 Service Temporarily Unavailable');
513
	header('retry-after: 3600');
514
}
515
516
/**
517
 * Small utility function for fatal error pages.
518
 * Used by fatal_error(), fatal_lang_error()
519
 *
520
 * @param string $error The error
521
 * @param array $sprintf An array of data to be sprintf()'d into the specified message
522
 */
523
function log_error_online($error, $sprintf = array())
524
{
525
	global $smcFunc, $user_info, $modSettings;
526
527
	// Don't bother if Who's Online is disabled.
528
	if (empty($modSettings['who_enabled']))
529
		return;
530
531
	// Maybe they came from SSI or similar where sessions are not recorded?
532
	if (SMF == 'SSI' || SMF == 'BACKGROUND')
0 ignored issues
show
The condition SMF == 'SSI' is always true.
Loading history...
533
		return;
534
535
	$session_id = !empty($user_info['is_guest']) ? 'ip' . $user_info['ip'] : session_id();
536
537
	// First, we have to get the online log, because we need to break apart the serialized string.
538
	$request = $smcFunc['db_query']('', '
539
		SELECT url
540
		FROM {db_prefix}log_online
541
		WHERE session = {string:session}',
542
		array(
543
			'session' => $session_id,
544
		)
545
	);
546
	if ($smcFunc['db_num_rows']($request) != 0)
547
	{
548
		// If this happened very early on in SMF startup, $smcFunc may not fully be defined.
549
		if (!isset($smcFunc['json_decode']))
550
		{
551
			$smcFunc['json_decode'] = 'smf_json_decode';
552
			$smcFunc['json_encode'] = 'json_encode';
553
		}
554
555
		list ($url) = $smcFunc['db_fetch_row']($request);
556
		$url = $smcFunc['json_decode']($url, true);
557
		$url['error'] = $error;
558
		// Url field got a max length of 1024 in db
559
		if (strlen($url['error']) > 500)
560
			$url['error'] = substr($url['error'], 0, 500);
561
562
		if (!empty($sprintf))
563
			$url['error_params'] = $sprintf;
564
565
		$smcFunc['db_query']('', '
566
			UPDATE {db_prefix}log_online
567
			SET url = {string:url}
568
			WHERE session = {string:session}',
569
			array(
570
				'url' => $smcFunc['json_encode']($url),
571
				'session' => $session_id,
572
			)
573
		);
574
	}
575
	$smcFunc['db_free_result']($request);
576
}
577
578
?>