PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/sources/admin/ManageErrors.php

https://github.com/Arantor/Elkarte
PHP | 387 lines | 259 code | 50 blank | 78 comment | 48 complexity | cb14b62dc3bfec4d1e06772333e2395b MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * The main purpose of this file is to show a list of all errors that were
  16. * logged on the forum, and allow filtering and deleting them.
  17. *
  18. */
  19. if (!defined('ELKARTE'))
  20. die('No access...');
  21. /**
  22. * View the forum's error log.
  23. * This function sets all the context up to show the error log for maintenance.
  24. * It requires the maintain_forum permission.
  25. * It is accessed from ?action=admin;area=logs;sa=errorlog.
  26. *
  27. * @uses the Errors template and error_log sub template.
  28. */
  29. function ViewErrorLog()
  30. {
  31. global $scripturl, $txt, $context, $modSettings, $user_profile, $filter, $themedir, $smcFunc;
  32. // Viewing contents of a file?
  33. if (isset($_GET['file']))
  34. return ViewFile();
  35. // Check for the administrative permission to do this.
  36. isAllowedTo('admin_forum');
  37. // Templates, etc...
  38. loadLanguage('ManageMaintenance');
  39. loadTemplate('Errors');
  40. // You can filter by any of the following columns:
  41. $filters = array(
  42. 'id_member' => $txt['username'],
  43. 'ip' => $txt['ip_address'],
  44. 'session' => $txt['session'],
  45. 'url' => $txt['error_url'],
  46. 'message' => $txt['error_message'],
  47. 'error_type' => $txt['error_type'],
  48. 'file' => $txt['file'],
  49. 'line' => $txt['line'],
  50. );
  51. // Set up the filtering...
  52. if (isset($_GET['value'], $_GET['filter']) && isset($filters[$_GET['filter']]))
  53. $filter = array(
  54. 'variable' => $_GET['filter'],
  55. 'value' => array(
  56. 'sql' => in_array($_GET['filter'], array('message', 'url', 'file')) ? base64_decode(strtr($_GET['value'], array(' ' => '+'))) : $smcFunc['db_escape_wildcard_string']($_GET['value']),
  57. ),
  58. 'href' => ';filter=' . $_GET['filter'] . ';value=' . $_GET['value'],
  59. 'entity' => $filters[$_GET['filter']]
  60. );
  61. elseif (isset($_GET['filter']) || isset($_GET['value']))
  62. unset($_GET['filter'], $_GET['value']);
  63. // Deleting, are we?
  64. if (isset($_POST['delall']) || isset($_POST['delete']))
  65. deleteErrors();
  66. // Just how many errors are there?
  67. $result = $smcFunc['db_query']('', '
  68. SELECT COUNT(*)
  69. FROM {db_prefix}log_errors' . (isset($filter) ? '
  70. WHERE ' . $filter['variable'] . ' LIKE {string:filter}' : ''),
  71. array(
  72. 'filter' => isset($filter) ? $filter['value']['sql'] : '',
  73. )
  74. );
  75. list ($num_errors) = $smcFunc['db_fetch_row']($result);
  76. $smcFunc['db_free_result']($result);
  77. // If this filter is empty...
  78. if ($num_errors == 0 && isset($filter))
  79. redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : ''));
  80. // Clean up start.
  81. if (!isset($_GET['start']) || $_GET['start'] < 0)
  82. $_GET['start'] = 0;
  83. // Do we want to reverse error listing?
  84. $context['sort_direction'] = isset($_REQUEST['desc']) ? 'down' : 'up';
  85. // Set the page listing up.
  86. $context['page_index'] = constructPageIndex($scripturl . '?action=admin;area=logs;sa=errorlog' . ($context['sort_direction'] == 'down' ? ';desc' : '') . (isset($filter) ? $filter['href'] : ''), $_GET['start'], $num_errors, $modSettings['defaultMaxMessages']);
  87. $context['start'] = $_GET['start'];
  88. // Find and sort out the errors.
  89. $request = $smcFunc['db_query']('', '
  90. SELECT id_error, id_member, ip, url, log_time, message, session, error_type, file, line
  91. FROM {db_prefix}log_errors' . (isset($filter) ? '
  92. WHERE ' . $filter['variable'] . ' LIKE {string:filter}' : '') . '
  93. ORDER BY id_error ' . ($context['sort_direction'] == 'down' ? 'DESC' : '') . '
  94. LIMIT ' . $_GET['start'] . ', ' . $modSettings['defaultMaxMessages'],
  95. array(
  96. 'filter' => isset($filter) ? $filter['value']['sql'] : '',
  97. )
  98. );
  99. $context['errors'] = array();
  100. $members = array();
  101. for ($i = 0; $row = $smcFunc['db_fetch_assoc']($request); $i ++)
  102. {
  103. $search_message = preg_replace('~&lt;span class=&quot;remove&quot;&gt;(.+?)&lt;/span&gt;~', '%', $smcFunc['db_escape_wildcard_string']($row['message']));
  104. if ($search_message == $filter['value']['sql'])
  105. $search_message = $smcFunc['db_escape_wildcard_string']($row['message']);
  106. $show_message = strtr(strtr(preg_replace('~&lt;span class=&quot;remove&quot;&gt;(.+?)&lt;/span&gt;~', '$1', $row['message']), array("\r" => '', '<br />' => "\n", '<' => '&lt;', '>' => '&gt;', '"' => '&quot;')), array("\n" => '<br />'));
  107. $context['errors'][$row['id_error']] = array(
  108. 'alternate' => $i %2 == 0,
  109. 'member' => array(
  110. 'id' => $row['id_member'],
  111. 'ip' => $row['ip'],
  112. 'session' => $row['session']
  113. ),
  114. 'time' => timeformat($row['log_time']),
  115. 'timestamp' => $row['log_time'],
  116. 'url' => array(
  117. 'html' => htmlspecialchars((substr($row['url'], 0, 1) == '?' ? $scripturl : '') . $row['url']),
  118. 'href' => base64_encode($smcFunc['db_escape_wildcard_string']($row['url']))
  119. ),
  120. 'message' => array(
  121. 'html' => $show_message,
  122. 'href' => base64_encode($search_message)
  123. ),
  124. 'id' => $row['id_error'],
  125. 'error_type' => array(
  126. 'type' => $row['error_type'],
  127. 'name' => isset($txt['errortype_'.$row['error_type']]) ? $txt['errortype_'.$row['error_type']] : $row['error_type'],
  128. ),
  129. 'file' => array(),
  130. );
  131. if (!empty($row['file']) && !empty($row['line']))
  132. {
  133. // Eval'd files rarely point to the right location and cause havoc for linking, so don't link them.
  134. $linkfile = strpos($row['file'], 'eval') === false || strpos($row['file'], '?') === false; // De Morgan's Law. Want this true unless both are present.
  135. $context['errors'][$row['id_error']]['file'] = array(
  136. 'file' => $row['file'],
  137. 'line' => $row['line'],
  138. 'href' => $scripturl . '?action=admin;area=logs;sa=errorlog;file=' . base64_encode($row['file']) . ';line=' . $row['line'],
  139. 'link' => $linkfile ? '<a href="' . $scripturl . '?action=admin;area=logs;sa=errorlog;file=' . base64_encode($row['file']) . ';line=' . $row['line'] . '" onclick="return reqWin(this.href, 600, 480, false);">' . $row['file'] . '</a>' : $row['file'],
  140. 'search' => base64_encode($row['file']),
  141. );
  142. }
  143. // Make a list of members to load later.
  144. $members[$row['id_member']] = $row['id_member'];
  145. }
  146. $smcFunc['db_free_result']($request);
  147. // Load the member data.
  148. if (!empty($members))
  149. {
  150. // Get some additional member info...
  151. $request = $smcFunc['db_query']('', '
  152. SELECT id_member, member_name, real_name
  153. FROM {db_prefix}members
  154. WHERE id_member IN ({array_int:member_list})
  155. LIMIT ' . count($members),
  156. array(
  157. 'member_list' => $members,
  158. )
  159. );
  160. while ($row = $smcFunc['db_fetch_assoc']($request))
  161. $members[$row['id_member']] = $row;
  162. $smcFunc['db_free_result']($request);
  163. // This is a guest...
  164. $members[0] = array(
  165. 'id_member' => 0,
  166. 'member_name' => '',
  167. 'real_name' => $txt['guest_title']
  168. );
  169. // Go through each error and tack the data on.
  170. foreach ($context['errors'] as $id => $dummy)
  171. {
  172. $memID = $context['errors'][$id]['member']['id'];
  173. $context['errors'][$id]['member']['username'] = $members[$memID]['member_name'];
  174. $context['errors'][$id]['member']['name'] = $members[$memID]['real_name'];
  175. $context['errors'][$id]['member']['href'] = empty($memID) ? '' : $scripturl . '?action=profile;u=' . $memID;
  176. $context['errors'][$id]['member']['link'] = empty($memID) ? $txt['guest_title'] : '<a href="' . $scripturl . '?action=profile;u=' . $memID . '">' . $context['errors'][$id]['member']['name'] . '</a>';
  177. }
  178. }
  179. // Filtering anything?
  180. if (isset($filter))
  181. {
  182. $context['filter'] = &$filter;
  183. // Set the filtering context.
  184. if ($filter['variable'] == 'id_member')
  185. {
  186. $id = $filter['value']['sql'];
  187. loadMemberData($id, false, 'minimal');
  188. $context['filter']['value']['html'] = '<a href="' . $scripturl . '?action=profile;u=' . $id . '">' . $user_profile[$id]['real_name'] . '</a>';
  189. }
  190. elseif ($filter['variable'] == 'url')
  191. $context['filter']['value']['html'] = '\'' . strtr(htmlspecialchars((substr($filter['value']['sql'], 0, 1) == '?' ? $scripturl : '') . $filter['value']['sql']), array('\_' => '_')) . '\'';
  192. elseif ($filter['variable'] == 'message')
  193. {
  194. $context['filter']['value']['html'] = '\'' . strtr(htmlspecialchars($filter['value']['sql']), array("\n" => '<br />', '&lt;br /&gt;' => '<br />', "\t" => '&nbsp;&nbsp;&nbsp;', '\_' => '_', '\\%' => '%', '\\\\' => '\\')) . '\'';
  195. $context['filter']['value']['html'] = preg_replace('~&amp;lt;span class=&amp;quot;remove&amp;quot;&amp;gt;(.+?)&amp;lt;/span&amp;gt;~', '$1', $context['filter']['value']['html']);
  196. }
  197. elseif ($filter['variable'] == 'error_type')
  198. {
  199. $context['filter']['value']['html'] = '\'' . strtr(htmlspecialchars($filter['value']['sql']), array("\n" => '<br />', '&lt;br /&gt;' => '<br />', "\t" => '&nbsp;&nbsp;&nbsp;', '\_' => '_', '\\%' => '%', '\\\\' => '\\')) . '\'';
  200. }
  201. else
  202. $context['filter']['value']['html'] = &$filter['value']['sql'];
  203. }
  204. $context['error_types'] = array();
  205. $context['error_types']['all'] = array(
  206. 'label' => $txt['errortype_all'],
  207. 'description' => isset($txt['errortype_all_desc']) ? $txt['errortype_all_desc'] : '',
  208. 'url' => $scripturl . '?action=admin;area=logs;sa=errorlog' . ($context['sort_direction'] == 'down' ? ';desc' : ''),
  209. 'is_selected' => empty($filter),
  210. );
  211. $sum = 0;
  212. // What type of errors do we have and how many do we have?
  213. $request = $smcFunc['db_query']('', '
  214. SELECT error_type, COUNT(*) AS num_errors
  215. FROM {db_prefix}log_errors
  216. GROUP BY error_type
  217. ORDER BY error_type = {string:critical_type} DESC, error_type ASC',
  218. array(
  219. 'critical_type' => 'critical',
  220. )
  221. );
  222. while ($row = $smcFunc['db_fetch_assoc']($request))
  223. {
  224. // Total errors so far?
  225. $sum += $row['num_errors'];
  226. $context['error_types'][$sum] = array(
  227. 'label' => (isset($txt['errortype_' . $row['error_type']]) ? $txt['errortype_' . $row['error_type']] : $row['error_type']) . ' (' . $row['num_errors'] . ')',
  228. 'description' => isset($txt['errortype_' . $row['error_type'] . '_desc']) ? $txt['errortype_' . $row['error_type'] . '_desc'] : '',
  229. 'url' => $scripturl . '?action=admin;area=logs;sa=errorlog' . ($context['sort_direction'] == 'down' ? ';desc' : '') . ';filter=error_type;value=' . $row['error_type'],
  230. 'is_selected' => isset($filter) && $filter['value']['sql'] == $smcFunc['db_escape_wildcard_string']($row['error_type']),
  231. );
  232. }
  233. $smcFunc['db_free_result']($request);
  234. // Update the all errors tab with the total number of errors
  235. $context['error_types']['all']['label'] .= ' (' . $sum . ')';
  236. // Finally, work out what is the last tab!
  237. if (isset($context['error_types'][$sum]))
  238. $context['error_types'][$sum]['is_last'] = true;
  239. else
  240. $context['error_types']['all']['is_last'] = true;
  241. // And this is pretty basic ;).
  242. $context['page_title'] = $txt['errlog'];
  243. $context['has_filter'] = isset($filter);
  244. $context['sub_template'] = 'error_log';
  245. createToken('admin-el');
  246. }
  247. /**
  248. * Delete all or some of the errors in the error log.
  249. * It applies any necessary filters to deletion.
  250. * This should only be called by ViewErrorLog().
  251. * It attempts to TRUNCATE the table to reset the auto_increment.
  252. * Redirects back to the error log when done.
  253. */
  254. function deleteErrors()
  255. {
  256. global $filter, $smcFunc;
  257. // Make sure the session exists and is correct; otherwise, might be a hacker.
  258. checkSession();
  259. validateToken('admin-el');
  260. // Delete all or just some?
  261. if (isset($_POST['delall']) && !isset($filter))
  262. $smcFunc['db_query']('truncate_table', '
  263. TRUNCATE {db_prefix}log_errors',
  264. array(
  265. )
  266. );
  267. // Deleting all with a filter?
  268. elseif (isset($_POST['delall']) && isset($filter))
  269. $smcFunc['db_query']('', '
  270. DELETE FROM {db_prefix}log_errors
  271. WHERE ' . $filter['variable'] . ' LIKE {string:filter}',
  272. array(
  273. 'filter' => $filter['value']['sql'],
  274. )
  275. );
  276. // Just specific errors?
  277. elseif (!empty($_POST['delete']))
  278. {
  279. $smcFunc['db_query']('', '
  280. DELETE FROM {db_prefix}log_errors
  281. WHERE id_error IN ({array_int:error_list})',
  282. array(
  283. 'error_list' => array_unique($_POST['delete']),
  284. )
  285. );
  286. // Go back to where we were.
  287. redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : '') . ';start=' . $_GET['start'] . (isset($filter) ? ';filter=' . $_GET['filter'] . ';value=' . $_GET['value'] : ''));
  288. }
  289. // Back to the error log!
  290. redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : ''));
  291. }
  292. /**
  293. * View a file specified in $_REQUEST['file'], with php highlighting on it
  294. * Preconditions:
  295. * - file must be readable,
  296. * - full file path must be base64 encoded,
  297. * - user must have admin_forum permission.
  298. * The line number number is specified by $_REQUEST['line']...
  299. * The function will try to get the 20 lines before and after the specified line.
  300. */
  301. function ViewFile()
  302. {
  303. global $context, $txt;
  304. // Check for the administrative permission to do this.
  305. isAllowedTo('admin_forum');
  306. // Decode the file and get the line
  307. $file = realpath(base64_decode($_REQUEST['file']));
  308. $line = isset($_REQUEST['line']) ? (int) $_REQUEST['line'] : 0;
  309. // Make sure things are normalized
  310. $real_board = realpath(BOARDDIR);
  311. $real_source = realpath(SOURCEDIR);
  312. $real_cache = realpath(CACHEDIR);
  313. // Make sure the file requested is one they are allowed to look at
  314. $excluded = array('settings.php', 'settings_bak.php');
  315. $basename = strtolower(basename($file));
  316. $ext = strrchr($basename, '.');
  317. if ($ext !== '.php' || (strpos($file, $real_board) === false && strpos($file, $real_source) === false) || strpos($file, $real_cache) !== false || in_array($basename, $excluded) || !is_readable($file))
  318. fatal_lang_error('error_bad_file', true, array(htmlspecialchars($file)));
  319. // get the min and max lines
  320. $min = $line - 20 <= 0 ? 1 : $line - 20;
  321. $max = $line + 21; // One additional line to make everything work out correctly
  322. if ($max <= 0 || $min >= $max)
  323. fatal_lang_error('error_bad_line');
  324. $file_data = explode('<br />', highlight_php_code(htmlspecialchars(implode('', file($file)))));
  325. // We don't want to slice off too many so lets make sure we stop at the last one
  326. $max = min($max, max(array_keys($file_data)));
  327. $file_data = array_slice($file_data, $min-1, $max - $min);
  328. $context['file_data'] = array(
  329. 'contents' => $file_data,
  330. 'min' => $min,
  331. 'target' => $line,
  332. 'file' => strtr($file, array('"' => '\\"')),
  333. );
  334. loadTemplate('Errors');
  335. $context['template_layers'] = array();
  336. $context['sub_template'] = 'show_file';
  337. }