Completed
Push — release-2.1 ( 4c82a0...64d581 )
by Rick
09:29
created

Errors.php ➔ log_error()   F

Complexity

Conditions 18
Paths 3073

Size

Total Lines 89
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 51
nc 3073
nop 4
dl 0
loc 89
rs 2
c 0
b 0
f 0

How to fix   Long Method    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
/**
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 2016 Simple Machines and individual contributors
13
 * @license http://www.simplemachines.org/about/smf/license.php BSD
14
 *
15
 * @version 2.1 Beta 3
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
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;
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 $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)
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 http://www.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'])))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
216
		return;
217
218
	if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
219
	{
220
		$array = debug_backtrace();
221
		for ($i = 0; $i < count($array); $i++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

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

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...