Failed Conditions
Branch release-2.1 (4e22cf)
by Rick
06:39
created

Errors.php ➔ display_db_error()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 41
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 6
nop 0
dl 0
loc 41
rs 6.7272
c 0
b 0
f 0
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 2017 Simple Machines and individual contributors
13
 * @license http://www.simplemachines.org/about/smf/license.php BSD
14
 *
15
 * @version 2.1 Beta 4
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 $error_type The type of error
29
 * @param string $file The name of the file where this error occurred
0 ignored issues
show
Documentation introduced by
Should the type for parameter $file not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
30
 * @param int $line The line where the error occurred
0 ignored issues
show
Documentation introduced by
Should the type for parameter $line not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
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;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $sc. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
36
	static $tried_hook = false;
37
38
	// Check if error logging is actually on.
39
	if (empty($modSettings['enableErrorLogging']))
40
		return $error_message;
41
42
	// Basically, htmlspecialchars it minus &. (for entities!)
43
	$error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
44
	$error_message = strtr($error_message, array('&lt;br /&gt;' => '<br>', '&lt;br&gt;' => '<br>', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br>'));
45
46
	// Add a file and line to the error message?
47
	// Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
48
	if ($file == null)
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $file of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
49
		$file = '';
50
	else
51
		// Window style slashes don't play well, lets convert them to the unix style.
52
		$file = str_replace('\\', '/', $file);
53
54
	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...
55
		$line = 0;
56
	else
57
		$line = (int) $line;
58
59
	// Just in case there's no id_member or IP set yet.
60
	if (empty($user_info['id']))
61
		$user_info['id'] = 0;
62
	if (empty($user_info['ip']))
63
		$user_info['ip'] = '';
64
65
	// Find the best query string we can...
66
	$query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
67
68
	// Don't log the session hash in the url twice, it's a waste.
69
	$query_string = $smcFunc['htmlspecialchars']((SMF == 'SSI' || SMF == 'BACKGROUND' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
70
71
	// Just so we know what board error messages are from.
72
	if (isset($_POST['board']) && !isset($_GET['board']))
73
		$query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
74
75
	// What types of categories do we have?
76
	$known_error_types = array(
77
		'general',
78
		'critical',
79
		'database',
80
		'undefined_vars',
81
		'user',
82
		'ban',
83
		'template',
84
		'debug',
85
		'cron',
86
		'paidsubs',
87
		'backup',
88
	);
89
90
	// This prevents us from infinite looping if the hook or call produces an error.
91
	$other_error_types = array();
92
	if (empty($tried_hook))
93
	{
94
		$tried_hook = true;
95
		// Allow the hook to change the error_type and know about the error.
96
		call_integration_hook('integrate_error_types', array(&$other_error_types, &$error_type, $error_message, $file, $line));
97
		$known_error_types += $other_error_types;
98
	}
99
	// Make sure the category that was specified is a valid one
100
	$error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
101
102
	// Don't log the same error countless times, as we can get in a cycle of depression...
103
	$error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
104
	if (empty($last_error) || $last_error != $error_info)
105
	{
106
		// Insert the error into the database.
107
		$smcFunc['db_insert']('',
108
			'{db_prefix}log_errors',
109
			array('id_member' => 'int', 'log_time' => 'int', 'ip' => 'inet', 'url' => 'string-65534', 'message' => 'string-65534', 'session' => 'string', 'error_type' => 'string', 'file' => 'string-255', 'line' => 'int'),
110
			$error_info,
111
			array('id_error')
112
		);
113
		$last_error = $error_info;
114
115
		// Increment our error count for the menu
116
		$context['num_errors']++;
117
	}
118
119
	// Return the message to make things simpler.
120
	return $error_message;
121
}
122
123
/**
124
 * An irrecoverable error. This function stops execution and displays an error message.
125
 * It logs the error message if $log is specified.
126
 * @param string $error The error message
127
 * @param string $log = 'general' What type of error to log this as (false to not log it))
128
 * @param int $status The HTTP status code associated with this error
129
 */
130
function fatal_error($error, $log = 'general', $status = 500)
131
{
132
	global $txt;
133
134
	// Send the appropriate HTTP status header - set this to 0 or false if you don't want to send one at all
135
	if (!empty($status))
136
		send_http_status($status);
137
138
	// We don't have $txt yet, but that's okay...
139
	if (empty($txt))
140
		die($error);
141
142
	log_error_online($error, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
143
	setup_fatal_error_context($log ? log_error($error, $log) : $error);
144
}
145
146
/**
147
 * Shows a fatal error with a message stored in the language file.
148
 *
149
 * This function stops execution and displays an error message by key.
150
 *  - uses the string with the error_message_key key.
151
 *  - logs the error in the forum's default language while displaying the error
152
 *    message in the user's language.
153
 *  - uses Errors language file and applies the $sprintf information if specified.
154
 *  - the information is logged if log is specified.
155
 *
156
 * @param string $error The error message
157
 * @param string|false $log The type of error, or false to not log it
158
 * @param array $sprintf An array of data to be sprintf()'d into the specified message
159
 * @param int $status = false The HTTP status code associated with this error
160
 */
161
function fatal_lang_error($error, $log = 'general', $sprintf = array(), $status = 403)
162
{
163
	global $txt, $language, $user_info, $context;
164
	static $fatal_error_called = false;
165
166
	// Send the status header - set this to 0 or false if you don't want to send one at all
167
	if (!empty($status))
168
		send_http_status($status);
169
170
	// Try to load a theme if we don't have one.
171
	if (empty($context['theme_loaded']) && empty($fatal_error_called))
172
	{
173
		$fatal_error_called = true;
174
		loadTheme();
175
	}
176
177
	// If we have no theme stuff we can't have the language file...
178
	if (empty($context['theme_loaded']))
179
		die($error);
180
181
	$reload_lang_file = true;
182
	// Log the error in the forum's language, but don't waste the time if we aren't logging
183
	if ($log)
0 ignored issues
show
Bug Best Practice introduced by
The expression $log of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

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

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
184
	{
185
		loadLanguage('Errors', $language);
186
		$reload_lang_file = $language != $user_info['language'];
187
		$error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
188
		log_error($error_message, $log);
189
	}
190
191
	// Load the language file, only if it needs to be reloaded
192
	if ($reload_lang_file)
193
	{
194
		loadLanguage('Errors');
195
		$error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
196
	}
197
198
	log_error_online($error, true, $sprintf);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Unused Code introduced by
The call to log_error_online() has too many arguments starting with $sprintf.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
199
	setup_fatal_error_context($error_message, $error);
0 ignored issues
show
Bug introduced by
The variable $error_message does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
200
}
201
202
/**
203
 * Handler for standard error messages, standard PHP error handler replacement.
204
 * It dies with fatal_error() if the error_level matches with error_reporting.
205
 * @param int $error_level A pre-defined error-handling constant (see {@link https://php.net/errorfunc.constants})
206
 * @param string $error_string The error message
207
 * @param string $file The file where the error occurred
208
 * @param int $line The line where the error occurred
209
 */
210
function smf_error_handler($error_level, $error_string, $file, $line)
211
{
212
	global $settings, $modSettings, $db_show_debug;
213
214
	// Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
215 View Code Duplication
	if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && !empty($modSettings['enableErrorLogging'])))
216
		return;
217
218
	if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
219
	{
220
		$array = debug_backtrace();
221
		$count = count($array);
222
		for ($i = 0; $i < $count; $i++)
223
		{
224
			if ($array[$i]['function'] != 'loadSubTemplate')
225
				continue;
226
227
			// This is a bug in PHP, with eval, it seems!
228
			if (empty($array[$i]['args']))
229
				$i++;
230
			break;
231
		}
232
233
		if (isset($array[$i]) && !empty($array[$i]['args']))
234
			$file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
235
		else
236
			$file = realpath($settings['current_include_filename']) . ' (eval?)';
237
	}
238
239
	if (isset($db_show_debug) && $db_show_debug === true)
240
	{
241
		// Commonly, undefined indexes will occur inside attributes; try to show them anyway!
242
		if ($error_level % 255 != E_ERROR)
243
		{
244
			$temporary = ob_get_contents();
245
			if (substr($temporary, -2) == '="')
246
				echo '"';
247
		}
248
249
		// Debugging!  This should look like a PHP error message.
250
		echo '<br>
251
<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>';
252
	}
253
254
	$error_type = stripos($error_string, 'undefined') !== false ? 'undefined_vars' : 'general';
255
256
	$message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
257
258
	// Let's give integrations a chance to ouput a bit differently
259
	call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
260
261
	// Dying on these errors only causes MORE problems (blank pages!)
262
	if ($file == 'Unknown')
263
		return;
264
265
	// If this is an E_ERROR or E_USER_ERROR.... die.  Violently so.
266
	if ($error_level % 255 == E_ERROR)
267
		obExit(false);
268
	else
269
		return;
270
271
	// If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die.  Violently so.
272
	if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
273
		fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
274
275
	// We should NEVER get to this point.  Any fatal error MUST quit, or very bad things can happen.
276
	if ($error_level % 255 == E_ERROR)
277
		die('No direct access...');
278
}
279
280
/**
281
 * It is called by {@link fatal_error()} and {@link fatal_lang_error()}.
282
 * @uses Errors template, fatal_error sub template.
283
 *
284
 * @param string $error_message The error message
285
 * @param string $error_code An error code
0 ignored issues
show
Documentation introduced by
Should the type for parameter $error_code not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
286
 */
287
function setup_fatal_error_context($error_message, $error_code = null)
288
{
289
	global $context, $txt, $ssi_on_error_method;
290
	static $level = 0;
291
292
	// Attempt to prevent a recursive loop.
293
	++$level;
294
	if ($level > 1)
295
		return false;
296
297
	// Maybe they came from dlattach or similar?
298
	if (SMF != 'SSI' && SMF != 'BACKGROUND' && empty($context['theme_loaded']))
299
		loadTheme();
300
301
	// Don't bother indexing errors mate...
302
	$context['robot_no_index'] = true;
303
304
	if (!isset($context['error_title']))
305
		$context['error_title'] = $txt['error_occured'];
306
	$context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
307
308
	$context['error_code'] = isset($error_code) ? 'id="' . $error_code . '" ' : '';
309
310
	if (empty($context['page_title']))
311
		$context['page_title'] = $context['error_title'];
312
313
	loadTemplate('Errors');
314
	$context['sub_template'] = 'fatal_error';
315
316
	// If this is SSI, what do they want us to do?
317
	if (SMF == 'SSI')
318
	{
319
		if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
320
			$ssi_on_error_method();
321
		elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
322
			loadSubTemplate('fatal_error');
323
324
		// No layers?
325
		if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
326
			exit;
327
	}
328
	// Alternatively from the cron call?
329
	elseif (SMF == 'BACKGROUND')
330
	{
331
		// We can't rely on even having language files available.
332
		if (defined('FROM_CLI') && FROM_CLI)
333
			echo 'cron error: ', $context['error_message'];
334
		else
335
			echo 'An error occurred. More information may be available in your logs.';
336
		exit;
337
	}
338
339
	// We want whatever for the header, and a footer. (footer includes sub template!)
340
	obExit(null, true, false, true);
341
342
	/* DO NOT IGNORE:
343
		If you are creating a bridge to SMF or modifying this function, you MUST
344
		make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
345
		PROGRAM FLOW.  Otherwise, security error messages will not be shown, and
346
		your forum will be in a very easily hackable state.
347
	*/
348
	trigger_error('Hacking attempt...', E_USER_ERROR);
349
}
350
351
/**
352
 * Show a message for the (full block) maintenance mode.
353
 * It shows a complete page independent of language files or themes.
354
 * It is used only if $maintenance = 2 in Settings.php.
355
 * It stops further execution of the script.
356
 */
357
function display_maintenance_message()
358
{
359
	global $maintenance, $mtitle, $mmessage;
360
361
	set_fatal_error_headers();
362
363
	if (!empty($maintenance))
364
		echo '<!DOCTYPE html>
365
<html>
366
	<head>
367
		<meta name="robots" content="noindex">
368
		<title>', $mtitle, '</title>
369
	</head>
370
	<body>
371
		<h3>', $mtitle, '</h3>
372
		', $mmessage, '
373
	</body>
374
</html>';
375
376
	die();
377
}
378
379
/**
380
 * Show an error message for the connection problems.
381
 * It shows a complete page independent of language files or themes.
382
 * It is used only if there's no way to connect to the database.
383
 * It stops further execution of the script.
384
 */
385
function display_db_error()
386
{
387
	global $mbname, $modSettings, $maintenance;
388
	global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc, $sourcedir;
389
390
	require_once($sourcedir . '/Logging.php');
391
	set_fatal_error_headers();
392
393
	// For our purposes, we're gonna want this on if at all possible.
394
	$modSettings['cache_enable'] = '1';
395
396
	if (($temp = cache_get_data('db_last_error', 600)) !== null)
397
		$db_last_error = max($db_last_error, $temp);
398
399
	if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
400
	{
401
		// Avoid writing to the Settings.php file if at all possible; use shared memory instead.
402
		cache_put_data('db_last_error', time(), 600);
403
		if (($temp = cache_get_data('db_last_error', 600)) === null)
404
			logLastDatabaseError();
405
406
		// Language files aren't loaded yet :(.
407
		$db_error = @$smcFunc['db_error']($db_connection);
408
		@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.');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
409
	}
410
411
	// What to do?  Language files haven't and can't be loaded yet...
412
	echo '<!DOCTYPE html>
413
<html>
414
	<head>
415
		<meta name="robots" content="noindex">
416
		<title>Connection Problems</title>
417
	</head>
418
	<body>
419
		<h3>Connection Problems</h3>
420
		Sorry, SMF was unable to connect to the database.  This may be caused by the server being busy.  Please try again later.
421
	</body>
422
</html>';
423
424
	die();
425
}
426
427
/**
428
 * Show an error message for load average blocking problems.
429
 * It shows a complete page independent of language files or themes.
430
 * It is used only if the load averages are too high to continue execution.
431
 * It stops further execution of the script.
432
 */
433
function display_loadavg_error()
434
{
435
	// If this is a load average problem, display an appropriate message (but we still don't have language files!)
436
437
	set_fatal_error_headers();
438
439
	echo '<!DOCTYPE html>
440
<html>
441
	<head>
442
		<meta name="robots" content="noindex">
443
		<title>Temporarily Unavailable</title>
444
	</head>
445
	<body>
446
		<h3>Temporarily Unavailable</h3>
447
		Due to high stress on the server the forum is temporarily unavailable.  Please try again later.
448
	</body>
449
</html>';
450
451
	die();
452
}
453
454
/**
455
 * Small utility function for fatal error pages.
456
 * Used by {@link display_db_error()}, {@link display_loadavg_error()},
457
 * {@link display_maintenance_message()}
458
 */
459
function set_fatal_error_headers()
460
{
461
	// Don't cache this page!
462
	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
463
	header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
464
	header('Cache-Control: no-cache');
465
466
	// Send the right error codes.
467
	header('HTTP/1.1 503 Service Temporarily Unavailable');
468
	header('Status: 503 Service Temporarily Unavailable');
469
	header('Retry-After: 3600');
470
}
471
472
473
/**
474
 * Small utility function for fatal error pages.
475
 * Used by fatal_error(), fatal_lang_error()
476
 *
477
 * @param string $error The error
478
 * @param array $sprintf An array of data to be sprintf()'d into the specified message
479
 */
480
function log_error_online($error, $sprintf = array())
481
{
482
	global $smcFunc, $user_info, $modSettings;
483
484
	// Don't bother if Who's Online is disabled.
485
	if (empty($modSettings['who_enabled']))
486
		return;
487
488
	// Maybe they came from SSI or similar where sessions are not recorded?
489
	if (SMF == 'SSI' || SMF == 'BACKGROUND')
490
		return;
491
492
	$session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
493
494
	// First, we have to get the online log, because we need to break apart the serialized string.
495
	$request = $smcFunc['db_query']('', '
496
		SELECT url
497
		FROM {db_prefix}log_online
498
		WHERE session = {string:session}',
499
		array(
500
			'session' => $session_id,
501
		)
502
	);
503
	if ($smcFunc['db_num_rows']($request) != 0)
504
	{
505
		// If this happened very early on in SMF startup, $smcFunc may not fully be defined.
506 View Code Duplication
		if (!isset($smcFunc['json_decode']))
507
		{
508
			$smcFunc['json_decode'] = 'smf_json_decode';
509
			$smcFunc['json_encode'] = 'json_encode';
510
		}
511
512
		list ($url) = $smcFunc['db_fetch_row']($request);
513
		$url = $smcFunc['json_decode']($url, true);
514
		$url['error'] = $error;
515
516
		if (!empty($sprintf))
517
			$url['error_params'] = $sprintf;
518
519
		$smcFunc['db_query']('', '
520
			UPDATE {db_prefix}log_online
521
			SET url = {string:url}
522
			WHERE session = {string:session}',
523
			array(
524
				'url' => $smcFunc['json_encode']($url),
525
				'session' => $session_id,
526
			)
527
		);
528
	}
529
	$smcFunc['db_free_result']($request);
530
}
531
532
/**
533
 * Sends an appropriate HTTP status header based on a given status code
534
 * @param int $code The status code
535
 */
536
function send_http_status($code)
537
{
538
	$statuses = array(
539
		403 => 'Forbidden',
540
		404 => 'Not Found',
541
		410 => 'Gone',
542
		500 => 'Internal Server Error',
543
		503 => 'Service Unavailable'
544
	);
545
546
	$protocol = preg_match('~HTTP/1\.[01]~i', $_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
547
548
	if (!isset($statuses[$code]))
549
		header($protocol . ' 500 Internal Server Error');
550
	else
551
		header($protocol . ' ' . $code . ' ' . $statuses[$code]);
552
}
553
554
?>