annotate forum/Sources/Errors.php @ 76:e3e11437ecea website

Add forum code
author Chris Cannam
date Sun, 07 Jul 2013 11:25:48 +0200
parents
children
rev   line source
Chris@76 1 <?php
Chris@76 2
Chris@76 3 /**
Chris@76 4 * Simple Machines Forum (SMF)
Chris@76 5 *
Chris@76 6 * @package SMF
Chris@76 7 * @author Simple Machines http://www.simplemachines.org
Chris@76 8 * @copyright 2011 Simple Machines
Chris@76 9 * @license http://www.simplemachines.org/about/smf/license.php BSD
Chris@76 10 *
Chris@76 11 * @version 2.0.4
Chris@76 12 */
Chris@76 13
Chris@76 14 if (!defined('SMF'))
Chris@76 15 die('Hacking attempt...');
Chris@76 16
Chris@76 17 /* The purpose of this file is... errors. (hard to guess, huh?) It takes
Chris@76 18 care of logging, error messages, error handling, database errors, and
Chris@76 19 error log administration. It does this with:
Chris@76 20
Chris@76 21 bool db_fatal_error(bool loadavg = false)
Chris@76 22 - calls show_db_error().
Chris@76 23 - this is used for database connection error handling.
Chris@76 24 - loadavg means this is a load average problem, not a database error.
Chris@76 25
Chris@76 26 string log_error(string error_message, string error_type = general,
Chris@76 27 string filename = none, int line = none)
Chris@76 28 - logs an error, if error logging is enabled.
Chris@76 29 - depends on the enableErrorLogging setting.
Chris@76 30 - filename and line should be __FILE__ and __LINE__, respectively.
Chris@76 31 - returns the error message. (ie. die(log_error($msg));)
Chris@76 32
Chris@76 33 void fatal_error(string error_message, mixed (bool or string) log = general)
Chris@76 34 - stops execution and displays an error message.
Chris@76 35 - logs the error message if log is missing or true.
Chris@76 36
Chris@76 37 void fatal_lang_error(string error_message_key, mixed (bool or string) log = general,
Chris@76 38 array sprintf = array())
Chris@76 39 - stops execution and displays an error message by key.
Chris@76 40 - uses the string with the error_message_key key.
Chris@76 41 - loads the Errors language file.
Chris@76 42 - applies the sprintf information if specified.
Chris@76 43 - the information is logged if log is true or missing.
Chris@76 44 - logs the error in the forum's default language while displaying the error
Chris@76 45 message in the user's language
Chris@76 46
Chris@76 47 void error_handler(int error_level, string error_string, string filename,
Chris@76 48 int line)
Chris@76 49 - this is a standard PHP error handler replacement.
Chris@76 50 - dies with fatal_error() if the error_level matches with
Chris@76 51 error_reporting.
Chris@76 52
Chris@76 53 void setup_fatal_error_context(string error_message)
Chris@76 54 - uses the fatal_error sub template of the Errors template - or the
Chris@76 55 error sub template in the Wireless template.
Chris@76 56 - used by fatal_error() and fatal_lang_error()
Chris@76 57
Chris@76 58 void show_db_error(bool loadavg = false)
Chris@76 59 - called by db_fatal_error() function
Chris@76 60 - shows a complete page independent of language files or themes.
Chris@76 61 - used only if there's no way to connect to the database or the
Chris@76 62 load averages are too high to do so.
Chris@76 63 - loadavg means this is a load average problem, not a database error.
Chris@76 64 - stops further execution of the script.
Chris@76 65 */
Chris@76 66
Chris@76 67 // Handle fatal errors - like connection errors or load average problems
Chris@76 68 function db_fatal_error($loadavg = false)
Chris@76 69 {
Chris@76 70 global $sourcedir;
Chris@76 71
Chris@76 72 show_db_error($loadavg);
Chris@76 73
Chris@76 74 // Since we use "or db_fatal_error();" this is needed...
Chris@76 75 return false;
Chris@76 76 }
Chris@76 77
Chris@76 78 // Log an error, if the option is on.
Chris@76 79 function log_error($error_message, $error_type = 'general', $file = null, $line = null)
Chris@76 80 {
Chris@76 81 global $txt, $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error;
Chris@76 82
Chris@76 83 // Check if error logging is actually on.
Chris@76 84 if (empty($modSettings['enableErrorLogging']))
Chris@76 85 return $error_message;
Chris@76 86
Chris@76 87 // Basically, htmlspecialchars it minus &. (for entities!)
Chris@76 88 $error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
Chris@76 89 $error_message = strtr($error_message, array('&lt;br /&gt;' => '<br />', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br />'));
Chris@76 90
Chris@76 91 // Add a file and line to the error message?
Chris@76 92 // Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
Chris@76 93 if ($file == null)
Chris@76 94 $file = '';
Chris@76 95 else
Chris@76 96 // Window style slashes don't play well, lets convert them to the unix style.
Chris@76 97 $file = str_replace('\\', '/', $file);
Chris@76 98
Chris@76 99 if ($line == null)
Chris@76 100 $line = 0;
Chris@76 101 else
Chris@76 102 $line = (int) $line;
Chris@76 103
Chris@76 104 // Just in case there's no id_member or IP set yet.
Chris@76 105 if (empty($user_info['id']))
Chris@76 106 $user_info['id'] = 0;
Chris@76 107 if (empty($user_info['ip']))
Chris@76 108 $user_info['ip'] = '';
Chris@76 109
Chris@76 110 // Find the best query string we can...
Chris@76 111 $query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
Chris@76 112
Chris@76 113 // Don't log the session hash in the url twice, it's a waste.
Chris@76 114 $query_string = htmlspecialchars((SMF == 'SSI' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
Chris@76 115
Chris@76 116 // Just so we know what board error messages are from.
Chris@76 117 if (isset($_POST['board']) && !isset($_GET['board']))
Chris@76 118 $query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
Chris@76 119
Chris@76 120 // What types of categories do we have?
Chris@76 121 $known_error_types = array(
Chris@76 122 'general',
Chris@76 123 'critical',
Chris@76 124 'database',
Chris@76 125 'undefined_vars',
Chris@76 126 'user',
Chris@76 127 'template',
Chris@76 128 'debug',
Chris@76 129 );
Chris@76 130
Chris@76 131 // Make sure the category that was specified is a valid one
Chris@76 132 $error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
Chris@76 133
Chris@76 134 // Don't log the same error countless times, as we can get in a cycle of depression...
Chris@76 135 $error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
Chris@76 136 if (empty($last_error) || $last_error != $error_info)
Chris@76 137 {
Chris@76 138 // Insert the error into the database.
Chris@76 139 $smcFunc['db_insert']('',
Chris@76 140 '{db_prefix}log_errors',
Chris@76 141 array('id_member' => 'int', 'log_time' => 'int', 'ip' => 'string-16', 'url' => 'string-65534', 'message' => 'string-65534', 'session' => 'string', 'error_type' => 'string', 'file' => 'string-255', 'line' => 'int'),
Chris@76 142 $error_info,
Chris@76 143 array('id_error')
Chris@76 144 );
Chris@76 145 $last_error = $error_info;
Chris@76 146 }
Chris@76 147
Chris@76 148 // Return the message to make things simpler.
Chris@76 149 return $error_message;
Chris@76 150 }
Chris@76 151
Chris@76 152 // An irrecoverable error.
Chris@76 153 function fatal_error($error, $log = 'general')
Chris@76 154 {
Chris@76 155 global $txt, $context, $modSettings;
Chris@76 156
Chris@76 157 // We don't have $txt yet, but that's okay...
Chris@76 158 if (empty($txt))
Chris@76 159 die($error);
Chris@76 160
Chris@76 161 setup_fatal_error_context($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2) ? log_error($error, $log) : $error);
Chris@76 162 }
Chris@76 163
Chris@76 164 // A fatal error with a message stored in the language file.
Chris@76 165 function fatal_lang_error($error, $log = 'general', $sprintf = array())
Chris@76 166 {
Chris@76 167 global $txt, $language, $modSettings, $user_info, $context;
Chris@76 168 static $fatal_error_called = false;
Chris@76 169
Chris@76 170 // Try to load a theme if we don't have one.
Chris@76 171 if (empty($context['theme_loaded']) && empty($fatal_error_called))
Chris@76 172 {
Chris@76 173 $fatal_error_called = true;
Chris@76 174 loadTheme();
Chris@76 175 }
Chris@76 176
Chris@76 177 // If we have no theme stuff we can't have the language file...
Chris@76 178 if (empty($context['theme_loaded']))
Chris@76 179 die($error);
Chris@76 180
Chris@76 181 $reload_lang_file = true;
Chris@76 182 // Log the error in the forum's language, but don't waste the time if we aren't logging
Chris@76 183 if ($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2))
Chris@76 184 {
Chris@76 185 loadLanguage('Errors', $language);
Chris@76 186 $reload_lang_file = $language != $user_info['language'];
Chris@76 187 $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
Chris@76 188 log_error($error_message, $log);
Chris@76 189 }
Chris@76 190
Chris@76 191 // Load the language file, only if it needs to be reloaded
Chris@76 192 if ($reload_lang_file)
Chris@76 193 {
Chris@76 194 loadLanguage('Errors');
Chris@76 195 $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
Chris@76 196 }
Chris@76 197
Chris@76 198 setup_fatal_error_context($error_message);
Chris@76 199 }
Chris@76 200
Chris@76 201 // Handler for standard error messages.
Chris@76 202 function error_handler($error_level, $error_string, $file, $line)
Chris@76 203 {
Chris@76 204 global $settings, $modSettings, $db_show_debug;
Chris@76 205
Chris@76 206 // Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
Chris@76 207 if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && (empty($modSettings['enableErrorLogging']) || $modSettings['enableErrorLogging'] != 2)))
Chris@76 208 return;
Chris@76 209
Chris@76 210 if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
Chris@76 211 {
Chris@76 212 if (function_exists('debug_backtrace'))
Chris@76 213 {
Chris@76 214 $array = debug_backtrace();
Chris@76 215 for ($i = 0; $i < count($array); $i++)
Chris@76 216 {
Chris@76 217 if ($array[$i]['function'] != 'loadSubTemplate')
Chris@76 218 continue;
Chris@76 219
Chris@76 220 // This is a bug in PHP, with eval, it seems!
Chris@76 221 if (empty($array[$i]['args']))
Chris@76 222 $i++;
Chris@76 223 break;
Chris@76 224 }
Chris@76 225
Chris@76 226 if (isset($array[$i]) && !empty($array[$i]['args']))
Chris@76 227 $file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
Chris@76 228 else
Chris@76 229 $file = realpath($settings['current_include_filename']) . ' (eval?)';
Chris@76 230 }
Chris@76 231 else
Chris@76 232 $file = realpath($settings['current_include_filename']) . ' (eval?)';
Chris@76 233 }
Chris@76 234
Chris@76 235 if (isset($db_show_debug) && $db_show_debug === true)
Chris@76 236 {
Chris@76 237 // Commonly, undefined indexes will occur inside attributes; try to show them anyway!
Chris@76 238 if ($error_level % 255 != E_ERROR)
Chris@76 239 {
Chris@76 240 $temporary = ob_get_contents();
Chris@76 241 if (substr($temporary, -2) == '="')
Chris@76 242 echo '"';
Chris@76 243 }
Chris@76 244
Chris@76 245 // Debugging! This should look like a PHP error message.
Chris@76 246 echo '<br />
Chris@76 247 <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 />';
Chris@76 248 }
Chris@76 249
Chris@76 250 $error_type = strpos(strtolower($error_string), 'undefined') !== false ? 'undefined_vars' : 'general';
Chris@76 251
Chris@76 252 $message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
Chris@76 253
Chris@76 254 // Let's give integrations a chance to ouput a bit differently
Chris@76 255 call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
Chris@76 256
Chris@76 257 // Dying on these errors only causes MORE problems (blank pages!)
Chris@76 258 if ($file == 'Unknown')
Chris@76 259 return;
Chris@76 260
Chris@76 261 // If this is an E_ERROR or E_USER_ERROR.... die. Violently so.
Chris@76 262 if ($error_level % 255 == E_ERROR)
Chris@76 263 obExit(false);
Chris@76 264 else
Chris@76 265 return;
Chris@76 266
Chris@76 267 // If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die. Violently so.
Chris@76 268 if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
Chris@76 269 fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
Chris@76 270
Chris@76 271 // We should NEVER get to this point. Any fatal error MUST quit, or very bad things can happen.
Chris@76 272 if ($error_level % 255 == E_ERROR)
Chris@76 273 die('Hacking attempt...');
Chris@76 274 }
Chris@76 275
Chris@76 276 function setup_fatal_error_context($error_message)
Chris@76 277 {
Chris@76 278 global $context, $txt, $ssi_on_error_method;
Chris@76 279 static $level = 0;
Chris@76 280
Chris@76 281 // Attempt to prevent a recursive loop.
Chris@76 282 ++$level;
Chris@76 283 if ($level > 1)
Chris@76 284 return false;
Chris@76 285
Chris@76 286 // Maybe they came from dlattach or similar?
Chris@76 287 if (SMF != 'SSI' && empty($context['theme_loaded']))
Chris@76 288 loadTheme();
Chris@76 289
Chris@76 290 // Don't bother indexing errors mate...
Chris@76 291 $context['robot_no_index'] = true;
Chris@76 292
Chris@76 293 if (!isset($context['error_title']))
Chris@76 294 $context['error_title'] = $txt['error_occured'];
Chris@76 295 $context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
Chris@76 296
Chris@76 297 if (empty($context['page_title']))
Chris@76 298 $context['page_title'] = $context['error_title'];
Chris@76 299
Chris@76 300 // Display the error message - wireless?
Chris@76 301 if (defined('WIRELESS') && WIRELESS)
Chris@76 302 $context['sub_template'] = WIRELESS_PROTOCOL . '_error';
Chris@76 303 // Load the template and set the sub template.
Chris@76 304 else
Chris@76 305 {
Chris@76 306 loadTemplate('Errors');
Chris@76 307 $context['sub_template'] = 'fatal_error';
Chris@76 308 }
Chris@76 309
Chris@76 310 // If this is SSI, what do they want us to do?
Chris@76 311 if (SMF == 'SSI')
Chris@76 312 {
Chris@76 313 if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
Chris@76 314 $ssi_on_error_method();
Chris@76 315 elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
Chris@76 316 loadSubTemplate('fatal_error');
Chris@76 317
Chris@76 318 // No layers?
Chris@76 319 if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
Chris@76 320 exit;
Chris@76 321 }
Chris@76 322
Chris@76 323 // We want whatever for the header, and a footer. (footer includes sub template!)
Chris@76 324 obExit(null, true, false, true);
Chris@76 325
Chris@76 326 /* DO NOT IGNORE:
Chris@76 327 If you are creating a bridge to SMF or modifying this function, you MUST
Chris@76 328 make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
Chris@76 329 PROGRAM FLOW. Otherwise, security error messages will not be shown, and
Chris@76 330 your forum will be in a very easily hackable state.
Chris@76 331 */
Chris@76 332 trigger_error('Hacking attempt...', E_USER_ERROR);
Chris@76 333 }
Chris@76 334
Chris@76 335 // Show an error message for the connection problems.
Chris@76 336 function show_db_error($loadavg = false)
Chris@76 337 {
Chris@76 338 global $sourcedir, $mbname, $maintenance, $mtitle, $mmessage, $modSettings;
Chris@76 339 global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc;
Chris@76 340
Chris@76 341 // Just check we're not in any buffers, just in case.
Chris@76 342 for ($i = ob_get_level(); $i > 0; $i--)
Chris@76 343 @ob_end_clean();
Chris@76 344
Chris@76 345 // Don't cache this page!
Chris@76 346 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
Chris@76 347 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
Chris@76 348 header('Cache-Control: no-cache');
Chris@76 349
Chris@76 350 // Send the right error codes.
Chris@76 351 header('HTTP/1.1 503 Service Temporarily Unavailable');
Chris@76 352 header('Status: 503 Service Temporarily Unavailable');
Chris@76 353 header('Retry-After: 3600');
Chris@76 354
Chris@76 355 if ($loadavg == false)
Chris@76 356 {
Chris@76 357 // For our purposes, we're gonna want this on if at all possible.
Chris@76 358 $modSettings['cache_enable'] = '1';
Chris@76 359
Chris@76 360 if (($temp = cache_get_data('db_last_error', 600)) !== null)
Chris@76 361 $db_last_error = max($db_last_error, $temp);
Chris@76 362
Chris@76 363 if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
Chris@76 364 {
Chris@76 365 require_once($sourcedir . '/Subs-Admin.php');
Chris@76 366
Chris@76 367 // Avoid writing to the Settings.php file if at all possible; use shared memory instead.
Chris@76 368 cache_put_data('db_last_error', time(), 600);
Chris@76 369 if (($temp = cache_get_data('db_last_error', 600)) == null)
Chris@76 370 updateLastDatabaseError();
Chris@76 371
Chris@76 372 // Language files aren't loaded yet :(.
Chris@76 373 $db_error = @$smcFunc['db_error']($db_connection);
Chris@76 374 @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.');
Chris@76 375 }
Chris@76 376 }
Chris@76 377
Chris@76 378 if (!empty($maintenance))
Chris@76 379 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Chris@76 380 <html xmlns="http://www.w3.org/1999/xhtml">
Chris@76 381 <head>
Chris@76 382 <meta name="robots" content="noindex" />
Chris@76 383 <title>', $mtitle, '</title>
Chris@76 384 </head>
Chris@76 385 <body>
Chris@76 386 <h3>', $mtitle, '</h3>
Chris@76 387 ', $mmessage, '
Chris@76 388 </body>
Chris@76 389 </html>';
Chris@76 390 // If this is a load average problem, display an appropriate message (but we still don't have language files!)
Chris@76 391 elseif ($loadavg)
Chris@76 392 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Chris@76 393 <html xmlns="http://www.w3.org/1999/xhtml">
Chris@76 394 <head>
Chris@76 395 <meta name="robots" content="noindex" />
Chris@76 396 <title>Temporarily Unavailable</title>
Chris@76 397 </head>
Chris@76 398 <body>
Chris@76 399 <h3>Temporarily Unavailable</h3>
Chris@76 400 Due to high stress on the server the forum is temporarily unavailable. Please try again later.
Chris@76 401 </body>
Chris@76 402 </html>';
Chris@76 403 // What to do? Language files haven't and can't be loaded yet...
Chris@76 404 else
Chris@76 405 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Chris@76 406 <html xmlns="http://www.w3.org/1999/xhtml">
Chris@76 407 <head>
Chris@76 408 <meta name="robots" content="noindex" />
Chris@76 409 <title>Connection Problems</title>
Chris@76 410 </head>
Chris@76 411 <body>
Chris@76 412 <h3>Connection Problems</h3>
Chris@76 413 Sorry, SMF was unable to connect to the database. This may be caused by the server being busy. Please try again later.
Chris@76 414 </body>
Chris@76 415 </html>';
Chris@76 416
Chris@76 417 die;
Chris@76 418 }
Chris@76 419
Chris@76 420 ?>