Errors.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. <?php
  2. /**
  3. * The purpose of this file is... errors. (hard to guess, I guess?) It takes
  4. * care of logging, error messages, error handling, database errors, and
  5. * error log administration.
  6. *
  7. * Simple Machines Forum (SMF)
  8. *
  9. * @package SMF
  10. * @author Simple Machines http://www.simplemachines.org
  11. * @copyright 2011 Simple Machines
  12. * @license http://www.simplemachines.org/about/smf/license.php BSD
  13. *
  14. * @version 2.0
  15. */
  16. if (!defined('SMF'))
  17. die('Hacking attempt...');
  18. /**
  19. * Handle fatal errors - like connection errors or load average problems.
  20. * This calls show_db_error(), which is used for database connection error handling.
  21. * @todo when awake: clean up this terrible terrible ugliness.
  22. *
  23. * @param bool $loadavg - whether it's a load average problem...
  24. */
  25. function db_fatal_error($loadavg = false)
  26. {
  27. global $sourcedir;
  28. show_db_error($loadavg);
  29. // Since we use "or db_fatal_error();" this is needed...
  30. return false;
  31. }
  32. /**
  33. * Log an error, if the error logging is enabled.
  34. * filename and line should be __FILE__ and __LINE__, respectively.
  35. * Example use:
  36. * die(log_error($msg));
  37. * @param string $error_message
  38. * @param string $error_type = 'general'
  39. * @param string $file = null
  40. * @param int $line = null
  41. * @return string, the error message
  42. */
  43. function log_error($error_message, $error_type = 'general', $file = null, $line = null)
  44. {
  45. global $txt, $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error;
  46. // Check if error logging is actually on.
  47. if (empty($modSettings['enableErrorLogging']))
  48. return $error_message;
  49. // Basically, htmlspecialchars it minus &. (for entities!)
  50. $error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  51. $error_message = strtr($error_message, array('&lt;br /&gt;' => '<br />', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br />'));
  52. // Add a file and line to the error message?
  53. // Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
  54. if ($file == null)
  55. $file = '';
  56. else
  57. // Window style slashes don't play well, lets convert them to the unix style.
  58. $file = str_replace('\\', '/', $file);
  59. if ($line == null)
  60. $line = 0;
  61. else
  62. $line = (int) $line;
  63. // Just in case there's no id_member or IP set yet.
  64. if (empty($user_info['id']))
  65. $user_info['id'] = 0;
  66. if (empty($user_info['ip']))
  67. $user_info['ip'] = '';
  68. // Find the best query string we can...
  69. $query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
  70. // Don't log the session hash in the url twice, it's a waste.
  71. $query_string = htmlspecialchars((SMF == 'SSI' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
  72. // Just so we know what board error messages are from.
  73. if (isset($_POST['board']) && !isset($_GET['board']))
  74. $query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
  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. 'template',
  83. 'debug',
  84. );
  85. // Make sure the category that was specified is a valid one
  86. $error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
  87. // Don't log the same error countless times, as we can get in a cycle of depression...
  88. $error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
  89. if (empty($last_error) || $last_error != $error_info)
  90. {
  91. // Insert the error into the database.
  92. $smcFunc['db_insert']('',
  93. '{db_prefix}log_errors',
  94. 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'),
  95. $error_info,
  96. array('id_error')
  97. );
  98. $last_error = $error_info;
  99. }
  100. // Return the message to make things simpler.
  101. return $error_message;
  102. }
  103. /**
  104. * This function logs an action in the respective log. (database log)
  105. * @example logAction('remove', array('starter' => $id_member_started));
  106. *
  107. * @param string $action
  108. * @param array $extra = array()
  109. * @param string $log_type, options 'moderate', 'admin', ...etc.
  110. */
  111. function logAction($action, $extra = array(), $log_type = 'moderate')
  112. {
  113. global $modSettings, $user_info, $smcFunc, $sourcedir;
  114. $log_types = array(
  115. 'moderate' => 1,
  116. 'user' => 2,
  117. 'admin' => 3,
  118. );
  119. if (!is_array($extra))
  120. trigger_error('logAction(): data is not an array with action \'' . $action . '\'', E_USER_NOTICE);
  121. // Pull out the parts we want to store separately, but also make sure that the data is proper
  122. if (isset($extra['topic']))
  123. {
  124. if (!is_numeric($extra['topic']))
  125. trigger_error('logAction(): data\'s topic is not a number', E_USER_NOTICE);
  126. $topic_id = empty($extra['topic']) ? '0' : (int)$extra['topic'];
  127. unset($extra['topic']);
  128. }
  129. else
  130. $topic_id = '0';
  131. if (isset($extra['message']))
  132. {
  133. if (!is_numeric($extra['message']))
  134. trigger_error('logAction(): data\'s message is not a number', E_USER_NOTICE);
  135. $msg_id = empty($extra['message']) ? '0' : (int)$extra['message'];
  136. unset($extra['message']);
  137. }
  138. else
  139. $msg_id = '0';
  140. // Is there an associated report on this?
  141. if (in_array($action, array('move', 'remove', 'split', 'merge')))
  142. {
  143. $request = $smcFunc['db_query']('', '
  144. SELECT id_report
  145. FROM {db_prefix}log_reported
  146. WHERE {raw:column_name} = {int:reported}
  147. LIMIT 1',
  148. array(
  149. 'column_name' => !empty($msg_id) ? 'id_msg' : 'id_topic',
  150. 'reported' => !empty($msg_id) ? $msg_id : $topic_id,
  151. ));
  152. // Alright, if we get any result back, update open reports.
  153. if ($smcFunc['db_num_rows']($request) > 0)
  154. {
  155. require_once($sourcedir . '/ModerationCenter.php');
  156. updateSettings(array('last_mod_report_action' => time()));
  157. recountOpenReports();
  158. }
  159. $smcFunc['db_free_result']($request);
  160. }
  161. // No point in doing anything else, if the log isn't even enabled.
  162. if (empty($modSettings['modlog_enabled']) || !isset($log_types[$log_type]))
  163. return false;
  164. if (isset($extra['member']) && !is_numeric($extra['member']))
  165. trigger_error('logAction(): data\'s member is not a number', E_USER_NOTICE);
  166. if (isset($extra['board']))
  167. {
  168. if (!is_numeric($extra['board']))
  169. trigger_error('logAction(): data\'s board is not a number', E_USER_NOTICE);
  170. $board_id = empty($extra['board']) ? '0' : (int)$extra['board'];
  171. unset($extra['board']);
  172. }
  173. else
  174. $board_id = '0';
  175. if (isset($extra['board_to']))
  176. {
  177. if (!is_numeric($extra['board_to']))
  178. trigger_error('logAction(): data\'s board_to is not a number', E_USER_NOTICE);
  179. if (empty($board_id))
  180. {
  181. $board_id = empty($extra['board_to']) ? '0' : (int)$extra['board_to'];
  182. unset($extra['board_to']);
  183. }
  184. }
  185. $smcFunc['db_insert']('',
  186. '{db_prefix}log_actions',
  187. array(
  188. 'log_time' => 'int', 'id_log' => 'int', 'id_member' => 'int', 'ip' => 'string-16', 'action' => 'string',
  189. 'id_board' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534',
  190. ),
  191. array(
  192. time(), $log_types[$log_type], $user_info['id'], $user_info['ip'], $action,
  193. $board_id, $topic_id, $msg_id, serialize($extra),
  194. ),
  195. array('id_action')
  196. );
  197. return $smcFunc['db_insert_id']('{db_prefix}log_actions', 'id_action');
  198. }
  199. /**
  200. * Debugging.
  201. */
  202. function db_debug_junk()
  203. {
  204. global $context, $scripturl, $boarddir, $modSettings, $boarddir;
  205. global $db_cache, $db_count, $db_show_debug, $cache_count, $cache_hits, $txt;
  206. // Add to Settings.php if you want to show the debugging information.
  207. if (!isset($db_show_debug) || $db_show_debug !== true || (isset($_GET['action']) && $_GET['action'] == 'viewquery') || WIRELESS)
  208. return;
  209. if (empty($_SESSION['view_queries']))
  210. $_SESSION['view_queries'] = 0;
  211. if (empty($context['debug']['language_files']))
  212. $context['debug']['language_files'] = array();
  213. if (empty($context['debug']['sheets']))
  214. $context['debug']['sheets'] = array();
  215. $files = get_included_files();
  216. $total_size = 0;
  217. for ($i = 0, $n = count($files); $i < $n; $i++)
  218. {
  219. if (file_exists($files[$i]))
  220. $total_size += filesize($files[$i]);
  221. $files[$i] = strtr($files[$i], array($boarddir => '.'));
  222. }
  223. $warnings = 0;
  224. if (!empty($db_cache))
  225. {
  226. foreach ($db_cache as $q => $qq)
  227. {
  228. if (!empty($qq['w']))
  229. $warnings += count($qq['w']);
  230. }
  231. $_SESSION['debug'] = &$db_cache;
  232. }
  233. // Gotta have valid HTML ;).
  234. $temp = ob_get_contents();
  235. if (function_exists('ob_clean'))
  236. ob_clean();
  237. else
  238. {
  239. ob_end_clean();
  240. ob_start('ob_sessrewrite');
  241. }
  242. echo preg_replace('~</body>\s*</html>~', '', $temp), '
  243. <div class="smalltext" style="text-align: left; margin: 1ex;">
  244. ', $txt['debug_templates'], count($context['debug']['templates']), ': <em>', implode('</em>, <em>', $context['debug']['templates']), '</em>.<br />
  245. ', $txt['debug_subtemplates'], count($context['debug']['sub_templates']), ': <em>', implode('</em>, <em>', $context['debug']['sub_templates']), '</em>.<br />
  246. ', $txt['debug_language_files'], count($context['debug']['language_files']), ': <em>', implode('</em>, <em>', $context['debug']['language_files']), '</em>.<br />
  247. ', $txt['debug_stylesheets'], count($context['debug']['sheets']), ': <em>', implode('</em>, <em>', $context['debug']['sheets']), '</em>.<br />
  248. ', $txt['debug_files_included'], count($files), ' - ', round($total_size / 1024), $txt['debug_kb'], ' (<a href="javascript:void(0);" onclick="document.getElementById(\'debug_include_info\').style.display = \'inline\'; this.style.display = \'none\'; return false;">', $txt['debug_show'], '</a><span id="debug_include_info" style="display: none;"><em>', implode('</em>, <em>', $files), '</em></span>)<br />';
  249. if (!empty($modSettings['cache_enable']) && !empty($cache_hits))
  250. {
  251. $entries = array();
  252. $total_t = 0;
  253. $total_s = 0;
  254. foreach ($cache_hits as $cache_hit)
  255. {
  256. $entries[] = $cache_hit['d'] . ' ' . $cache_hit['k'] . ': ' . sprintf($txt['debug_cache_seconds_bytes'], comma_format($cache_hit['t'], 5), $cache_hit['s']);
  257. $total_t += $cache_hit['t'];
  258. $total_s += $cache_hit['s'];
  259. }
  260. echo '
  261. ', $txt['debug_cache_hits'], $cache_count, ': ', sprintf($txt['debug_cache_seconds_bytes_total'], comma_format($total_t, 5), comma_format($total_s)), ' (<a href="javascript:void(0);" onclick="document.getElementById(\'debug_cache_info\').style.display = \'inline\'; this.style.display = \'none\'; return false;">', $txt['debug_show'], '</a><span id="debug_cache_info" style="display: none;"><em>', implode('</em>, <em>', $entries), '</em></span>)<br />';
  262. }
  263. echo '
  264. <a href="', $scripturl, '?action=viewquery" target="_blank" class="new_win">', $warnings == 0 ? sprintf($txt['debug_queries_used'], (int) $db_count) : sprintf($txt['debug_queries_used_and_warnings'], (int) $db_count, $warnings), '</a><br />
  265. <br />';
  266. if ($_SESSION['view_queries'] == 1 && !empty($db_cache))
  267. foreach ($db_cache as $q => $qq)
  268. {
  269. $is_select = substr(trim($qq['q']), 0, 6) == 'SELECT' || preg_match('~^INSERT(?: IGNORE)? INTO \w+(?:\s+\([^)]+\))?\s+SELECT .+$~s', trim($qq['q'])) != 0;
  270. // Temporary tables created in earlier queries are not explainable.
  271. if ($is_select)
  272. {
  273. foreach (array('log_topics_unread', 'topics_posted_in', 'tmp_log_search_topics', 'tmp_log_search_messages') as $tmp)
  274. if (strpos(trim($qq['q']), $tmp) !== false)
  275. {
  276. $is_select = false;
  277. break;
  278. }
  279. }
  280. // But actual creation of the temporary tables are.
  281. elseif (preg_match('~^CREATE TEMPORARY TABLE .+?SELECT .+$~s', trim($qq['q'])) != 0)
  282. $is_select = true;
  283. // Make the filenames look a bit better.
  284. if (isset($qq['f']))
  285. $qq['f'] = preg_replace('~^' . preg_quote($boarddir, '~') . '~', '...', $qq['f']);
  286. echo '
  287. <strong>', $is_select ? '<a href="' . $scripturl . '?action=viewquery;qq=' . ($q + 1) . '#qq' . $q . '" target="_blank" class="new_win" style="text-decoration: none;">' : '', nl2br(str_replace("\t", '&nbsp;&nbsp;&nbsp;', htmlspecialchars(ltrim($qq['q'], "\n\r")))) . ($is_select ? '</a></strong>' : '</strong>') . '<br />
  288. &nbsp;&nbsp;&nbsp;';
  289. if (!empty($qq['f']) && !empty($qq['l']))
  290. echo sprintf($txt['debug_query_in_line'], $qq['f'], $qq['l']);
  291. if (isset($qq['s'], $qq['t']) && isset($txt['debug_query_which_took_at']))
  292. echo sprintf($txt['debug_query_which_took_at'], round($qq['t'], 8), round($qq['s'], 8)) . '<br />';
  293. elseif (isset($qq['t']))
  294. echo sprintf($txt['debug_query_which_took'], round($qq['t'], 8)) . '<br />';
  295. echo '
  296. <br />';
  297. }
  298. echo '
  299. <a href="' . $scripturl . '?action=viewquery;sa=hide">', $txt['debug_' . (empty($_SESSION['view_queries']) ? 'show' : 'hide') . '_queries'], '</a>
  300. </div></body></html>';
  301. }
  302. /**
  303. * Logs the last database error into a file.
  304. * Attempts to use the backup file first, to store the last database error
  305. * and only update Settings.php if the first was successful.
  306. */
  307. function updateLastDatabaseError()
  308. {
  309. global $boarddir;
  310. // Find out this way if we can even write things on this filesystem.
  311. // In addition, store things first in the backup file
  312. $last_settings_change = @filemtime($boarddir . '/Settings.php');
  313. // Make sure the backup file is there...
  314. $file = $boarddir . '/Settings_bak.php';
  315. if ((!file_exists($file) || filesize($file) == 0) && !copy($boarddir . '/Settings.php', $file))
  316. return false;
  317. // ...and writable!
  318. if (!is_writable($file))
  319. {
  320. chmod($file, 0755);
  321. if (!is_writable($file))
  322. {
  323. chmod($file, 0775);
  324. if (!is_writable($file))
  325. {
  326. chmod($file, 0777);
  327. if (!is_writable($file))
  328. return false;
  329. }
  330. }
  331. }
  332. // Put the new timestamp.
  333. $data = file_get_contents($file);
  334. $data = preg_replace('~\$db_last_error = \d+;~', '$db_last_error = ' . time() . ';', $data);
  335. // Open the backup file for writing
  336. if ($fp = @fopen($file, 'w'))
  337. {
  338. // Reset the file buffer.
  339. set_file_buffer($fp, 0);
  340. // Update the file.
  341. $t = flock($fp, LOCK_EX);
  342. $bytes = fwrite($fp, $data);
  343. flock($fp, LOCK_UN);
  344. fclose($fp);
  345. // Was it a success?
  346. // ...only relevant if we're still dealing with the same good ole' settings file.
  347. clearstatcache();
  348. if (($bytes == strlen($data)) && (filemtime($boarddir . '/Settings.php') === $last_settings_change))
  349. {
  350. // This is our new Settings file...
  351. // At least this one is an atomic operation
  352. @copy($file, $boarddir . '/Settings.php');
  353. return true;
  354. }
  355. else
  356. {
  357. // Oops. Someone might have been faster
  358. // or we have no more disk space left, troubles, troubles...
  359. // Copy the file back and run for your life!
  360. @copy($boarddir . '/Settings.php', $file);
  361. }
  362. }
  363. return false;
  364. }
  365. /**
  366. * An irrecoverable error. This function stops execution and displays an error message.
  367. * It logs the error message if $log is specified.
  368. * @param string $error
  369. * @param string $log = 'general'
  370. */
  371. function fatal_error($error, $log = 'general')
  372. {
  373. global $txt, $context, $modSettings;
  374. // We don't have $txt yet, but that's okay...
  375. if (empty($txt))
  376. die($error);
  377. setup_fatal_error_context($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2) ? log_error($error, $log) : $error);
  378. }
  379. /**
  380. * A fatal error with a message stored in the language file.
  381. * This function stops executing and displays an error message by key.
  382. * It uses the string with the error_message_key key.
  383. * It logs the error in the forum's default language while displaying the error
  384. * message in the user's language.
  385. * @uses Errors language file and applies the $sprintf information if specified.
  386. * the information is logged if log is specified.
  387. * @param $error
  388. * @param $log
  389. * @param $sprintf
  390. */
  391. function fatal_lang_error($error, $log = 'general', $sprintf = array())
  392. {
  393. global $txt, $language, $modSettings, $user_info, $context;
  394. static $fatal_error_called = false;
  395. // Try to load a theme if we don't have one.
  396. if (empty($context['theme_loaded']) && empty($fatal_error_called))
  397. {
  398. $fatal_error_called = true;
  399. loadTheme();
  400. }
  401. // If we have no theme stuff we can't have the language file...
  402. if (empty($context['theme_loaded']))
  403. die($error);
  404. $reload_lang_file = true;
  405. // Log the error in the forum's language, but don't waste the time if we aren't logging
  406. if ($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2))
  407. {
  408. loadLanguage('Errors', $language);
  409. $reload_lang_file = $language != $user_info['language'];
  410. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  411. log_error($error_message, $log);
  412. }
  413. // Load the language file, only if it needs to be reloaded
  414. if ($reload_lang_file)
  415. {
  416. loadLanguage('Errors');
  417. $error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
  418. }
  419. setup_fatal_error_context($error_message);
  420. }
  421. /**
  422. * Handler for standard error messages, standard PHP error handler replacement.
  423. * It dies with fatal_error() if the error_level matches with error_reporting.
  424. * @param int $error_level
  425. * @param string $error_string
  426. * @param string $file
  427. * @param int $line
  428. */
  429. function error_handler($error_level, $error_string, $file, $line)
  430. {
  431. global $settings, $modSettings, $db_show_debug;
  432. // Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
  433. if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && (empty($modSettings['enableErrorLogging']) || $modSettings['enableErrorLogging'] != 2)))
  434. return;
  435. if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
  436. {
  437. if (function_exists('debug_backtrace'))
  438. {
  439. $array = debug_backtrace();
  440. for ($i = 0; $i < count($array); $i++)
  441. {
  442. if ($array[$i]['function'] != 'loadSubTemplate')
  443. continue;
  444. // This is a bug in PHP, with eval, it seems!
  445. if (empty($array[$i]['args']))
  446. $i++;
  447. break;
  448. }
  449. if (isset($array[$i]) && !empty($array[$i]['args']))
  450. $file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
  451. else
  452. $file = realpath($settings['current_include_filename']) . ' (eval?)';
  453. }
  454. else
  455. $file = realpath($settings['current_include_filename']) . ' (eval?)';
  456. }
  457. if (isset($db_show_debug) && $db_show_debug === true)
  458. {
  459. // Commonly, undefined indexes will occur inside attributes; try to show them anyway!
  460. if ($error_level % 255 != E_ERROR)
  461. {
  462. $temporary = ob_get_contents();
  463. if (substr($temporary, -2) == '="')
  464. echo '"';
  465. }
  466. // Debugging! This should look like a PHP error message.
  467. echo '<br />
  468. <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 />';
  469. }
  470. $error_type = strpos(strtolower($error_string), 'undefined') !== false ? 'undefined_vars' : 'general';
  471. $message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
  472. // Let's give integrations a chance to ouput a bit differently
  473. call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
  474. // Dying on these errors only causes MORE problems (blank pages!)
  475. if ($file == 'Unknown')
  476. return;
  477. // If this is an E_ERROR or E_USER_ERROR.... die. Violently so.
  478. if ($error_level % 255 == E_ERROR)
  479. obExit(false);
  480. else
  481. return;
  482. // If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die. Violently so.
  483. if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
  484. fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
  485. // We should NEVER get to this point. Any fatal error MUST quit, or very bad things can happen.
  486. if ($error_level % 255 == E_ERROR)
  487. die('Hacking attempt...');
  488. }
  489. /**
  490. * It is called by fatal_error() and fatal_lang_error().
  491. * @uses Errors template, fatal_error sub template, or Wireless template,
  492. * error sub template.
  493. * @param string $error_message
  494. */
  495. function setup_fatal_error_context($error_message)
  496. {
  497. global $context, $txt, $ssi_on_error_method;
  498. static $level = 0;
  499. // Attempt to prevent a recursive loop.
  500. ++$level;
  501. if ($level > 1)
  502. return false;
  503. // Maybe they came from dlattach or similar?
  504. if (SMF != 'SSI' && empty($context['theme_loaded']))
  505. loadTheme();
  506. // Don't bother indexing errors mate...
  507. $context['robot_no_index'] = true;
  508. if (!isset($context['error_title']))
  509. $context['error_title'] = $txt['error_occured'];
  510. $context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
  511. if (empty($context['page_title']))
  512. $context['page_title'] = $context['error_title'];
  513. // Display the error message - wireless?
  514. if (defined('WIRELESS') && WIRELESS)
  515. $context['sub_template'] = WIRELESS_PROTOCOL . '_error';
  516. // Load the template and set the sub template.
  517. else
  518. {
  519. loadTemplate('Errors');
  520. $context['sub_template'] = 'fatal_error';
  521. }
  522. // If this is SSI, what do they want us to do?
  523. if (SMF == 'SSI')
  524. {
  525. if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
  526. $ssi_on_error_method();
  527. elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
  528. loadSubTemplate('fatal_error');
  529. // No layers?
  530. if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
  531. exit;
  532. }
  533. // We want whatever for the header, and a footer. (footer includes sub template!)
  534. obExit(null, true, false, true);
  535. /* DO NOT IGNORE:
  536. If you are creating a bridge to SMF or modifying this function, you MUST
  537. make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
  538. PROGRAM FLOW. Otherwise, security error messages will not be shown, and
  539. your forum will be in a very easily hackable state.
  540. */
  541. trigger_error('Hacking attempt...', E_USER_ERROR);
  542. }
  543. /**
  544. * Show an error message for the connection problems... or load average.
  545. * It is called by db_fatal_error() function.
  546. * It shows a complete page independent of language files or themes.
  547. * It is used only if there's no way to connect to the database or the load averages
  548. * are too high to do so.
  549. * It stops further execution of the script.
  550. * @param bool $loadavg - whether it's a load average problem...
  551. */
  552. function show_db_error($loadavg = false)
  553. {
  554. global $sourcedir, $mbname, $maintenance, $mtitle, $mmessage, $modSettings;
  555. global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc;
  556. // Don't cache this page!
  557. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  558. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  559. header('Cache-Control: no-cache');
  560. // Send the right error codes.
  561. header('HTTP/1.1 503 Service Temporarily Unavailable');
  562. header('Status: 503 Service Temporarily Unavailable');
  563. header('Retry-After: 3600');
  564. if ($loadavg == false)
  565. {
  566. // For our purposes, we're gonna want this on if at all possible.
  567. $modSettings['cache_enable'] = '1';
  568. if (($temp = cache_get_data('db_last_error', 600)) !== null)
  569. $db_last_error = max($db_last_error, $temp);
  570. if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
  571. {
  572. // Avoid writing to the Settings.php file if at all possible; use shared memory instead.
  573. cache_put_data('db_last_error', time(), 600);
  574. if (($temp = cache_get_data('db_last_error', 600)) == null)
  575. updateLastDatabaseError();
  576. // Language files aren't loaded yet :(.
  577. $db_error = @$smcFunc['db_error']($db_connection);
  578. @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.');
  579. }
  580. }
  581. if (!empty($maintenance))
  582. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  583. <html xmlns="http://www.w3.org/1999/xhtml">
  584. <head>
  585. <meta name="robots" content="noindex" />
  586. <title>', $mtitle, '</title>
  587. </head>
  588. <body>
  589. <h3>', $mtitle, '</h3>
  590. ', $mmessage, '
  591. </body>
  592. </html>';
  593. // If this is a load average problem, display an appropriate message (but we still don't have language files!)
  594. elseif ($loadavg)
  595. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  596. <html xmlns="http://www.w3.org/1999/xhtml">
  597. <head>
  598. <meta name="robots" content="noindex" />
  599. <title>Temporarily Unavailable</title>
  600. </head>
  601. <body>
  602. <h3>Temporarily Unavailable</h3>
  603. Due to high stress on the server the forum is temporarily unavailable. Please try again later.
  604. </body>
  605. </html>';
  606. // What to do? Language files haven't and can't be loaded yet...
  607. else
  608. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  609. <html xmlns="http://www.w3.org/1999/xhtml">
  610. <head>
  611. <meta name="robots" content="noindex" />
  612. <title>Connection Problems</title>
  613. </head>
  614. <body>
  615. <h3>Connection Problems</h3>
  616. Sorry, SMF was unable to connect to the database. This may be caused by the server being busy. Please try again later.
  617. </body>
  618. </html>';
  619. die;
  620. }
  621. /**
  622. * Put this user in the online log.
  623. *
  624. * @param bool $force = false
  625. */
  626. function writeLog($force = false)
  627. {
  628. global $user_info, $user_settings, $context, $modSettings, $settings, $topic, $board, $smcFunc, $sourcedir;
  629. // If we are showing who is viewing a topic, let's see if we are, and force an update if so - to make it accurate.
  630. if (!empty($settings['display_who_viewing']) && ($topic || $board))
  631. {
  632. // Take the opposite approach!
  633. $force = true;
  634. // Don't update for every page - this isn't wholly accurate but who cares.
  635. if ($topic)
  636. {
  637. if (isset($_SESSION['last_topic_id']) && $_SESSION['last_topic_id'] == $topic)
  638. $force = false;
  639. $_SESSION['last_topic_id'] = $topic;
  640. }
  641. }
  642. // Are they a spider we should be tracking? Mode = 1 gets tracked on its spider check...
  643. if (!empty($user_info['possibly_robot']) && !empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1)
  644. {
  645. require_once($sourcedir . '/ManageSearchEngines.php');
  646. logSpider();
  647. }
  648. // Don't mark them as online more than every so often.
  649. if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= (time() - 8) && !$force)
  650. return;
  651. if (!empty($modSettings['who_enabled']))
  652. {
  653. $serialized = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
  654. // In the case of a dlattach action, session_var may not be set.
  655. if (!isset($context['session_var']))
  656. $context['session_var'] = $_SESSION['session_var'];
  657. unset($serialized['sesc'], $serialized[$context['session_var']]);
  658. $serialized = serialize($serialized);
  659. }
  660. else
  661. $serialized = '';
  662. // Guests use 0, members use their session ID.
  663. $session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
  664. // Grab the last all-of-SMF-specific log_online deletion time.
  665. $do_delete = cache_get_data('log_online-update', 30) < time() - 30;
  666. // If the last click wasn't a long time ago, and there was a last click...
  667. if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - $modSettings['lastActive'] * 20)
  668. {
  669. if ($do_delete)
  670. {
  671. $smcFunc['db_query']('delete_log_online_interval', '
  672. DELETE FROM {db_prefix}log_online
  673. WHERE log_time < {int:log_time}
  674. AND session != {string:session}',
  675. array(
  676. 'log_time' => time() - $modSettings['lastActive'] * 60,
  677. 'session' => $session_id,
  678. )
  679. );
  680. // Cache when we did it last.
  681. cache_put_data('log_online-update', time(), 30);
  682. }
  683. $smcFunc['db_query']('', '
  684. UPDATE {db_prefix}log_online
  685. SET log_time = {int:log_time}, ip = IFNULL(INET_ATON({string:ip}), 0), url = {string:url}
  686. WHERE session = {string:session}',
  687. array(
  688. 'log_time' => time(),
  689. 'ip' => $user_info['ip'],
  690. 'url' => $serialized,
  691. 'session' => $session_id,
  692. )
  693. );
  694. // Guess it got deleted.
  695. if ($smcFunc['db_affected_rows']() == 0)
  696. $_SESSION['log_time'] = 0;
  697. }
  698. else
  699. $_SESSION['log_time'] = 0;
  700. // Otherwise, we have to delete and insert.
  701. if (empty($_SESSION['log_time']))
  702. {
  703. if ($do_delete || !empty($user_info['id']))
  704. $smcFunc['db_query']('', '
  705. DELETE FROM {db_prefix}log_online
  706. WHERE ' . ($do_delete ? 'log_time < {int:log_time}' : '') . ($do_delete && !empty($user_info['id']) ? ' OR ' : '') . (empty($user_info['id']) ? '' : 'id_member = {int:current_member}'),
  707. array(
  708. 'current_member' => $user_info['id'],
  709. 'log_time' => time() - $modSettings['lastActive'] * 60,
  710. )
  711. );
  712. $smcFunc['db_insert']($do_delete ? 'ignore' : 'replace',
  713. '{db_prefix}log_online',
  714. array('session' => 'string', 'id_member' => 'int', 'id_spider' => 'int', 'log_time' => 'int', 'ip' => 'raw', 'url' => 'string'),
  715. array($session_id, $user_info['id'], empty($_SESSION['id_robot']) ? 0 : $_SESSION['id_robot'], time(), 'IFNULL(INET_ATON(\'' . $user_info['ip'] . '\'), 0)', $serialized),
  716. array('session')
  717. );
  718. }
  719. // Mark your session as being logged.
  720. $_SESSION['log_time'] = time();
  721. // Well, they are online now.
  722. if (empty($_SESSION['timeOnlineUpdated']))
  723. $_SESSION['timeOnlineUpdated'] = time();
  724. // Set their login time, if not already done within the last minute.
  725. if (SMF != 'SSI' && !empty($user_info['last_login']) && $user_info['last_login'] < time() - 60)
  726. {
  727. // Don't count longer than 15 minutes.
  728. if (time() - $_SESSION['timeOnlineUpdated'] > 60 * 15)
  729. $_SESSION['timeOnlineUpdated'] = time();
  730. $user_settings['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
  731. updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP'], 'total_time_logged_in' => $user_settings['total_time_logged_in']));
  732. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  733. cache_put_data('user_settings-' . $user_info['id'], $user_settings, 60);
  734. $user_info['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
  735. $_SESSION['timeOnlineUpdated'] = time();
  736. }
  737. }
  738. ?>