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

/sources/Logging.php

https://github.com/Arantor/Elkarte
PHP | 531 lines | 368 code | 71 blank | 92 comment | 89 complexity | 15e0ce7f0cbeddf2ad4f5489ff2eb976 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. * This file concerns itself with logging, whether in the database or files.
  16. *
  17. */
  18. if (!defined('ELKARTE'))
  19. die('No access...');
  20. /**
  21. * Put this user in the online log.
  22. *
  23. * @param bool $force = false
  24. */
  25. function writeLog($force = false)
  26. {
  27. global $user_info, $user_settings, $context, $modSettings, $settings, $topic, $board, $smcFunc;
  28. // 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.
  29. if (!empty($settings['display_who_viewing']) && ($topic || $board))
  30. {
  31. // Take the opposite approach!
  32. $force = true;
  33. // Don't update for every page - this isn't wholly accurate but who cares.
  34. if ($topic)
  35. {
  36. if (isset($_SESSION['last_topic_id']) && $_SESSION['last_topic_id'] == $topic)
  37. $force = false;
  38. $_SESSION['last_topic_id'] = $topic;
  39. }
  40. }
  41. // Are they a spider we should be tracking? Mode = 1 gets tracked on its spider check...
  42. if (!empty($user_info['possibly_robot']) && !empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1)
  43. {
  44. require_once(ADMINDIR . '/ManageSearchEngines.php');
  45. logSpider();
  46. }
  47. // Don't mark them as online more than every so often.
  48. if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= (time() - 8) && !$force)
  49. return;
  50. if (!empty($modSettings['who_enabled']))
  51. {
  52. $serialized = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
  53. // In the case of a dlattach action, session_var may not be set.
  54. if (!isset($context['session_var']))
  55. $context['session_var'] = $_SESSION['session_var'];
  56. unset($serialized['sesc'], $serialized[$context['session_var']]);
  57. $serialized = serialize($serialized);
  58. }
  59. else
  60. $serialized = '';
  61. // Guests use 0, members use their session ID.
  62. $session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
  63. // Grab the last all-of-ELKARTE-specific log_online deletion time.
  64. $do_delete = cache_get_data('log_online-update', 30) < time() - 30;
  65. // If the last click wasn't a long time ago, and there was a last click...
  66. if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - $modSettings['lastActive'] * 20)
  67. {
  68. if ($do_delete)
  69. {
  70. $smcFunc['db_query']('delete_log_online_interval', '
  71. DELETE FROM {db_prefix}log_online
  72. WHERE log_time < {int:log_time}
  73. AND session != {string:session}',
  74. array(
  75. 'log_time' => time() - $modSettings['lastActive'] * 60,
  76. 'session' => $session_id,
  77. )
  78. );
  79. // Cache when we did it last.
  80. cache_put_data('log_online-update', time(), 30);
  81. }
  82. $smcFunc['db_query']('', '
  83. UPDATE {db_prefix}log_online
  84. SET log_time = {int:log_time}, ip = IFNULL(INET_ATON({string:ip}), 0), url = {string:url}
  85. WHERE session = {string:session}',
  86. array(
  87. 'log_time' => time(),
  88. 'ip' => $user_info['ip'],
  89. 'url' => $serialized,
  90. 'session' => $session_id,
  91. )
  92. );
  93. // Guess it got deleted.
  94. if ($smcFunc['db_affected_rows']() == 0)
  95. $_SESSION['log_time'] = 0;
  96. }
  97. else
  98. $_SESSION['log_time'] = 0;
  99. // Otherwise, we have to delete and insert.
  100. if (empty($_SESSION['log_time']))
  101. {
  102. if ($do_delete || !empty($user_info['id']))
  103. $smcFunc['db_query']('', '
  104. DELETE FROM {db_prefix}log_online
  105. WHERE ' . ($do_delete ? 'log_time < {int:log_time}' : '') . ($do_delete && !empty($user_info['id']) ? ' OR ' : '') . (empty($user_info['id']) ? '' : 'id_member = {int:current_member}'),
  106. array(
  107. 'current_member' => $user_info['id'],
  108. 'log_time' => time() - $modSettings['lastActive'] * 60,
  109. )
  110. );
  111. $smcFunc['db_insert']($do_delete ? 'ignore' : 'replace',
  112. '{db_prefix}log_online',
  113. array('session' => 'string', 'id_member' => 'int', 'id_spider' => 'int', 'log_time' => 'int', 'ip' => 'raw', 'url' => 'string'),
  114. array($session_id, $user_info['id'], empty($_SESSION['id_robot']) ? 0 : $_SESSION['id_robot'], time(), 'IFNULL(INET_ATON(\'' . $user_info['ip'] . '\'), 0)', $serialized),
  115. array('session')
  116. );
  117. }
  118. // Mark your session as being logged.
  119. $_SESSION['log_time'] = time();
  120. // Well, they are online now.
  121. if (empty($_SESSION['timeOnlineUpdated']))
  122. $_SESSION['timeOnlineUpdated'] = time();
  123. // Set their login time, if not already done within the last minute.
  124. if (ELKARTE != 'SSI' && !empty($user_info['last_login']) && $user_info['last_login'] < time() - 60)
  125. {
  126. // Don't count longer than 15 minutes.
  127. if (time() - $_SESSION['timeOnlineUpdated'] > 60 * 15)
  128. $_SESSION['timeOnlineUpdated'] = time();
  129. $user_settings['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
  130. 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']));
  131. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  132. cache_put_data('user_settings-' . $user_info['id'], $user_settings, 60);
  133. $user_info['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
  134. $_SESSION['timeOnlineUpdated'] = time();
  135. }
  136. }
  137. /**
  138. * Logs the last database error into a file.
  139. * Attempts to use the backup file first, to store the last database error
  140. * and only update db_last_error.php if the first was successful.
  141. */
  142. function logLastDatabaseError()
  143. {
  144. // Make a note of the last modified time in case someone does this before us
  145. $last_db_error_change = @filemtime(BOARDDIR . '/db_last_error.php');
  146. // save the old file before we do anything
  147. $file = BOARDDIR . '/db_last_error.php';
  148. $dberror_backup_fail = !@is_writable(BOARDDIR . '/db_last_error_bak.php') || !@copy($file, BOARDDIR . '/db_last_error_bak.php');
  149. $dberror_backup_fail = !$dberror_backup_fail ? (!file_exists(BOARDDIR . '/db_last_error_bak.php') || filesize(BOARDDIR . '/db_last_error_bak.php') === 0) : $dberror_backup_fail;
  150. clearstatcache();
  151. if (filemtime(BOARDDIR . '/db_last_error.php') === $last_db_error_change)
  152. {
  153. // Write the change
  154. $write_db_change = '<' . '?' . "php\n" . '$db_last_error = ' . time() . ';';
  155. $written_bytes = file_put_contents(BOARDDIR . '/db_last_error.php', $write_db_change, LOCK_EX);
  156. // survey says ...
  157. if ($written_bytes !== strlen($write_db_change) && !$dberror_backup_fail)
  158. {
  159. // Oops. maybe we have no more disk space left, or some other troubles, troubles...
  160. // Copy the file back and run for your life!
  161. @copy(BOARDDIR . '/db_last_error_bak.php', BOARDDIR . '/db_last_error.php');
  162. }
  163. else
  164. {
  165. @touch(BOARDDIR . '/' . 'Settings.php');
  166. return true;
  167. }
  168. }
  169. return false;
  170. }
  171. /**
  172. * This function shows the debug information tracked when $db_show_debug = true
  173. * in Settings.php
  174. */
  175. function displayDebug()
  176. {
  177. global $context, $scripturl, $modSettings;
  178. global $db_cache, $db_count, $db_show_debug, $cache_count, $cache_hits, $txt;
  179. // Add to Settings.php if you want to show the debugging information.
  180. if (!isset($db_show_debug) || $db_show_debug !== true || (isset($_GET['action']) && $_GET['action'] == 'viewquery'))
  181. return;
  182. if (empty($_SESSION['view_queries']))
  183. $_SESSION['view_queries'] = 0;
  184. if (empty($context['debug']['language_files']))
  185. $context['debug']['language_files'] = array();
  186. if (empty($context['debug']['sheets']))
  187. $context['debug']['sheets'] = array();
  188. $files = get_included_files();
  189. $total_size = 0;
  190. for ($i = 0, $n = count($files); $i < $n; $i++)
  191. {
  192. if (file_exists($files[$i]))
  193. $total_size += filesize($files[$i]);
  194. $files[$i] = strtr($files[$i], array(BOARDDIR => '.'));
  195. }
  196. $warnings = 0;
  197. if (!empty($db_cache))
  198. {
  199. foreach ($db_cache as $q => $qq)
  200. {
  201. if (!empty($qq['w']))
  202. $warnings += count($qq['w']);
  203. }
  204. $_SESSION['debug'] = &$db_cache;
  205. }
  206. // Gotta have valid HTML ;).
  207. $temp = ob_get_contents();
  208. ob_clean();
  209. echo preg_replace('~</body>\s*</html>~', '', $temp), '
  210. <div class="smalltext" style="text-align: left; margin: 1ex;">
  211. ', $txt['debug_browser'], $context['browser_body_id'], ' <em>(', implode('</em>, <em>', array_reverse(array_keys($context['browser'], true))), ')</em><br />
  212. ', $txt['debug_templates'], count($context['debug']['templates']), ': <em>', implode('</em>, <em>', $context['debug']['templates']), '</em>.<br />
  213. ', $txt['debug_subtemplates'], count($context['debug']['sub_templates']), ': <em>', implode('</em>, <em>', $context['debug']['sub_templates']), '</em>.<br />
  214. ', $txt['debug_language_files'], count($context['debug']['language_files']), ': <em>', implode('</em>, <em>', $context['debug']['language_files']), '</em>.<br />
  215. ', $txt['debug_stylesheets'], count($context['debug']['sheets']), ': <em>', implode('</em>, <em>', $context['debug']['sheets']), '</em>.<br />
  216. ', $txt['debug_hooks'], empty($context['debug']['hooks']) ? 0 : count($context['debug']['hooks']) . ' (<a href="javascript:void(0);" onclick="document.getElementById(\'debug_hooks\').style.display = \'inline\'; this.style.display = \'none\'; return false;">', $txt['debug_show'], '</a><span id="debug_hooks" style="display: none;"><em>' . implode('</em>, <em>', $context['debug']['hooks']), '</em></span>)', '<br />
  217. ', $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 />';
  218. // What tokens are active?
  219. if (isset($_SESSION['token']))
  220. {
  221. $token_list = array();
  222. foreach ($_SESSION['token'] as $key => $data)
  223. $token_list[] = $key;
  224. echo $txt['debug_tokens'] . '<em>' . implode(',</em> <em>', $token_list), '</em>.<br />';
  225. }
  226. if (!empty($modSettings['cache_enable']) && !empty($cache_hits))
  227. {
  228. $entries = array();
  229. $total_t = 0;
  230. $total_s = 0;
  231. foreach ($cache_hits as $cache_hit)
  232. {
  233. $entries[] = $cache_hit['d'] . ' ' . $cache_hit['k'] . ': ' . sprintf($txt['debug_cache_seconds_bytes'], comma_format($cache_hit['t'], 5), $cache_hit['s']);
  234. $total_t += $cache_hit['t'];
  235. $total_s += $cache_hit['s'];
  236. }
  237. echo '
  238. ', $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 />';
  239. }
  240. echo '
  241. <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 />
  242. <br />';
  243. if ($_SESSION['view_queries'] == 1 && !empty($db_cache))
  244. foreach ($db_cache as $q => $qq)
  245. {
  246. $is_select = strpos(trim($qq['q']), 'SELECT') === 0 || preg_match('~^INSERT(?: IGNORE)? INTO \w+(?:\s+\([^)]+\))?\s+SELECT .+$~s', trim($qq['q'])) != 0;
  247. // Temporary tables created in earlier queries are not explainable.
  248. if ($is_select)
  249. {
  250. foreach (array('log_topics_unread', 'topics_posted_in', 'tmp_log_search_topics', 'tmp_log_search_messages') as $tmp)
  251. if (strpos(trim($qq['q']), $tmp) !== false)
  252. {
  253. $is_select = false;
  254. break;
  255. }
  256. }
  257. // But actual creation of the temporary tables are.
  258. elseif (preg_match('~^CREATE TEMPORARY TABLE .+?SELECT .+$~s', trim($qq['q'])) != 0)
  259. $is_select = true;
  260. // Make the filenames look a bit better.
  261. if (isset($qq['f']))
  262. $qq['f'] = preg_replace('~^' . preg_quote(BOARDDIR, '~') . '~', '...', $qq['f']);
  263. echo '
  264. <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 />
  265. &nbsp;&nbsp;&nbsp;';
  266. if (!empty($qq['f']) && !empty($qq['l']))
  267. echo sprintf($txt['debug_query_in_line'], $qq['f'], $qq['l']);
  268. if (isset($qq['s'], $qq['t']) && isset($txt['debug_query_which_took_at']))
  269. echo sprintf($txt['debug_query_which_took_at'], round($qq['t'], 8), round($qq['s'], 8)) . '<br />';
  270. elseif (isset($qq['t']))
  271. echo sprintf($txt['debug_query_which_took'], round($qq['t'], 8)) . '<br />';
  272. echo '
  273. <br />';
  274. }
  275. echo '
  276. <a href="' . $scripturl . '?action=viewquery;sa=hide">', $txt['debug_' . (empty($_SESSION['view_queries']) ? 'show' : 'hide') . '_queries'], '</a>
  277. </div></body></html>';
  278. }
  279. /**
  280. * Track Statistics.
  281. * Caches statistics changes, and flushes them if you pass nothing.
  282. * If '+' is used as a value, it will be incremented.
  283. * It does not actually commit the changes until the end of the page view.
  284. * It depends on the trackStats setting.
  285. *
  286. * @param array $stats = array()
  287. * @return boolean|array
  288. */
  289. function trackStats($stats = array())
  290. {
  291. global $modSettings, $smcFunc;
  292. static $cache_stats = array();
  293. if (empty($modSettings['trackStats']))
  294. return false;
  295. if (!empty($stats))
  296. return $cache_stats = array_merge($cache_stats, $stats);
  297. elseif (empty($cache_stats))
  298. return false;
  299. $setStringUpdate = '';
  300. $insert_keys = array();
  301. $date = strftime('%Y-%m-%d', forum_time(false));
  302. $update_parameters = array(
  303. 'current_date' => $date,
  304. );
  305. foreach ($cache_stats as $field => $change)
  306. {
  307. $setStringUpdate .= '
  308. ' . $field . ' = ' . ($change === '+' ? $field . ' + 1' : '{int:' . $field . '}') . ',';
  309. if ($change === '+')
  310. $cache_stats[$field] = 1;
  311. else
  312. $update_parameters[$field] = $change;
  313. $insert_keys[$field] = 'int';
  314. }
  315. $smcFunc['db_query']('', '
  316. UPDATE {db_prefix}log_activity
  317. SET' . substr($setStringUpdate, 0, -1) . '
  318. WHERE date = {date:current_date}',
  319. $update_parameters
  320. );
  321. if ($smcFunc['db_affected_rows']() == 0)
  322. {
  323. $smcFunc['db_insert']('ignore',
  324. '{db_prefix}log_activity',
  325. array_merge($insert_keys, array('date' => 'date')),
  326. array_merge($cache_stats, array($date)),
  327. array('date')
  328. );
  329. }
  330. // Don't do this again.
  331. $cache_stats = array();
  332. return true;
  333. }
  334. /**
  335. * This function logs an action in the respective log. (database log)
  336. * You should use {@link logActions()} instead.
  337. * @example logAction('remove', array('starter' => $id_member_started));
  338. *
  339. * @deprecated
  340. *
  341. * @param string $action
  342. * @param array $extra = array()
  343. * @param string $log_type options: 'moderate', 'admin', ...etc.
  344. */
  345. function logAction($action, $extra = array(), $log_type = 'moderate')
  346. {
  347. return logActions(array(array(
  348. 'action' => $action,
  349. 'log_type' => $log_type,
  350. 'extra' => $extra,
  351. )));
  352. }
  353. /**
  354. * Log changes to the forum, such as moderation events or administrative changes.
  355. * This behaves just like logAction() did, except that it is designed to log multiple actions at once.
  356. *
  357. * @param array $logs
  358. * @return the last logged ID
  359. */
  360. function logActions($logs)
  361. {
  362. global $modSettings, $user_info, $smcFunc;
  363. $inserts = array();
  364. $log_types = array(
  365. 'moderate' => 1,
  366. 'user' => 2,
  367. 'admin' => 3,
  368. );
  369. call_integration_hook('integrate_log_types', array($log_types));
  370. // No point in doing anything, if the log isn't even enabled.
  371. if (empty($modSettings['modlog_enabled']))
  372. return false;
  373. foreach ($logs as $log)
  374. {
  375. if (!isset($log_types[$log['log_type']]))
  376. return false;
  377. if (!is_array($log['extra']))
  378. trigger_error('logActions(): data is not an array with action \'' . $action . '\'', E_USER_NOTICE);
  379. // Pull out the parts we want to store separately, but also make sure that the data is proper
  380. if (isset($log['extra']['topic']))
  381. {
  382. if (!is_numeric($log['extra']['topic']))
  383. trigger_error('logActions(): data\'s topic is not a number', E_USER_NOTICE);
  384. $topic_id = empty($log['extra']['topic']) ? 0 : (int) $log['extra']['topic'];
  385. unset($log['extra']['topic']);
  386. }
  387. else
  388. $topic_id = 0;
  389. if (isset($log['extra']['message']))
  390. {
  391. if (!is_numeric($log['extra']['message']))
  392. trigger_error('logActions(): data\'s message is not a number', E_USER_NOTICE);
  393. $msg_id = empty($log['extra']['message']) ? 0 : (int) $log['extra']['message'];
  394. unset($log['extra']['message']);
  395. }
  396. else
  397. $msg_id = 0;
  398. // @todo cache this?
  399. // Is there an associated report on this?
  400. if (in_array($log['action'], array('move', 'remove', 'split', 'merge')))
  401. {
  402. $request = $smcFunc['db_query']('', '
  403. SELECT id_report
  404. FROM {db_prefix}log_reported
  405. WHERE {raw:column_name} = {int:reported}
  406. LIMIT 1',
  407. array(
  408. 'column_name' => !empty($msg_id) ? 'id_msg' : 'id_topic',
  409. 'reported' => !empty($msg_id) ? $msg_id : $topic_id,
  410. ));
  411. // Alright, if we get any result back, update open reports.
  412. if ($smcFunc['db_num_rows']($request) > 0)
  413. {
  414. require_once(SUBSDIR . '/Moderation.subs.php');
  415. updateSettings(array('last_mod_report_action' => time()));
  416. recountOpenReports();
  417. }
  418. $smcFunc['db_free_result']($request);
  419. }
  420. if (isset($log['extra']['member']) && !is_numeric($log['extra']['member']))
  421. trigger_error('logActions(): data\'s member is not a number', E_USER_NOTICE);
  422. if (isset($log['extra']['board']))
  423. {
  424. if (!is_numeric($log['extra']['board']))
  425. trigger_error('logActions(): data\'s board is not a number', E_USER_NOTICE);
  426. $board_id = empty($log['extra']['board']) ? 0 : (int) $log['extra']['board'];
  427. unset($log['extra']['board']);
  428. }
  429. else
  430. $board_id = 0;
  431. if (isset($log['extra']['board_to']))
  432. {
  433. if (!is_numeric($log['extra']['board_to']))
  434. trigger_error('logActions(): data\'s board_to is not a number', E_USER_NOTICE);
  435. if (empty($board_id))
  436. {
  437. $board_id = empty($log['extra']['board_to']) ? 0 : (int) $log['extra']['board_to'];
  438. unset($log['extra']['board_to']);
  439. }
  440. }
  441. if (isset($log['extra']['member_affected']))
  442. $memID = $log['extra']['member_affected'];
  443. else
  444. $memID = $user_info['id'];
  445. $inserts[] = array(
  446. time(), $log_types[$log['log_type']], $memID, $user_info['ip'], $log['action'],
  447. $board_id, $topic_id, $msg_id, serialize($log['extra']),
  448. );
  449. }
  450. $smcFunc['db_insert']('',
  451. '{db_prefix}log_actions',
  452. array(
  453. 'log_time' => 'int', 'id_log' => 'int', 'id_member' => 'int', 'ip' => 'string-16', 'action' => 'string',
  454. 'id_board' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534',
  455. ),
  456. $inserts,
  457. array('id_action')
  458. );
  459. return $smcFunc['db_insert_id']('{db_prefix}log_actions', 'id_action');
  460. }