Passed
Pull Request — release-2.1 (#5074)
by John
05:59
created

Logging.php ➔ writeLog()   F

Complexity

Conditions 38
Paths 7208

Size

Total Lines 132

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 38
nc 7208
nop 1
dl 0
loc 132
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file concerns itself with logging, whether in the database or files.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines http://www.simplemachines.org
10
 * @copyright 2018 Simple Machines and individual contributors
11
 * @license http://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 Beta 4
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Truncate the GET array to a specified length
21
 * @param array $arr The array to truncate
22
 * @param int $max_length The upperbound on the length
23
 *
24
 * @return array The truncated array
25
 */
26
function truncateArray($arr, $max_length=1900)
27
{
28
	$curr_length = 0;
29
	foreach ($arr as $key => $value)
30
		if (is_array($value))
31
			foreach ($value as $key2 => $value2)
32
				$curr_length += strlen ($value2);
33
		else
34
			$curr_length += strlen ($value);
35
	if ($curr_length <= $max_length)
36
		return $arr;
37
	else
38
	{
39
		// Truncate each element's value to a reasonable length
40
		$param_max = floor($max_length/count($arr));
41
		foreach ($arr as $key => &$value)
42
			if (is_array($value))
43
				foreach ($value as $key2 => &$value2)
44
					$value2 = substr($value2, 0, $param_max - strlen($key) - 5);
0 ignored issues
show
Bug introduced by
$param_max - strlen($key) - 5 of type double is incompatible with the type integer expected by parameter $length of substr(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

44
					$value2 = substr($value2, 0, /** @scrutinizer ignore-type */ $param_max - strlen($key) - 5);
Loading history...
45
			else
46
				$value = substr($value, 0, $param_max - strlen($key) - 5);
47
		return $arr;
48
	}
49
}
50
51
/**
52
 * Put this user in the online log.
53
 *
54
 * @param bool $force Whether to force logging the data
55
 */
56
function writeLog($force = false)
57
{
58
	global $user_info, $user_settings, $context, $modSettings, $settings, $topic, $board, $smcFunc, $sourcedir;
59
60
	// 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.
61
	if (!empty($settings['display_who_viewing']) && ($topic || $board))
62
	{
63
		// Take the opposite approach!
64
		$force = true;
65
		// Don't update for every page - this isn't wholly accurate but who cares.
66
		if ($topic)
67
		{
68
			if (isset($_SESSION['last_topic_id']) && $_SESSION['last_topic_id'] == $topic)
69
				$force = false;
70
			$_SESSION['last_topic_id'] = $topic;
71
		}
72
	}
73
74
	// Are they a spider we should be tracking? Mode = 1 gets tracked on its spider check...
75
	if (!empty($user_info['possibly_robot']) && !empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1)
76
	{
77
		require_once($sourcedir . '/ManageSearchEngines.php');
78
		logSpider();
79
	}
80
81
	// Don't mark them as online more than every so often.
82
	if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= (time() - 8) && !$force)
83
		return;
84
85
	if (!empty($modSettings['who_enabled']))
86
	{
87
		$encoded_get = truncateArray($_GET) + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
88
89
		// In the case of a dlattach action, session_var may not be set.
90
		if (!isset($context['session_var']))
91
			$context['session_var'] = $_SESSION['session_var'];
92
93
		unset($encoded_get['sesc'], $encoded_get[$context['session_var']]);
94
		$encoded_get = $smcFunc['json_encode']($encoded_get);
95
	}
96
	else
97
		$encoded_get = '';
98
99
	// Guests use 0, members use their session ID.
100
	$session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
101
102
	// Grab the last all-of-SMF-specific log_online deletion time.
103
	$do_delete = cache_get_data('log_online-update', 30) < time() - 30;
104
105
	// If the last click wasn't a long time ago, and there was a last click...
106
	if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - $modSettings['lastActive'] * 20)
107
	{
108
		if ($do_delete)
109
		{
110
			$smcFunc['db_query']('delete_log_online_interval', '
111
				DELETE FROM {db_prefix}log_online
112
				WHERE log_time < {int:log_time}
113
					AND session != {string:session}',
114
				array(
115
					'log_time' => time() - $modSettings['lastActive'] * 60,
116
					'session' => $session_id,
117
				)
118
			);
119
120
			// Cache when we did it last.
121
			cache_put_data('log_online-update', time(), 30);
122
		}
123
124
		$smcFunc['db_query']('', '
125
			UPDATE {db_prefix}log_online
126
			SET log_time = {int:log_time}, ip = {inet:ip}, url = {string:url}
127
			WHERE session = {string:session}',
128
			array(
129
				'log_time' => time(),
130
				'ip' => $user_info['ip'],
131
				'url' => $encoded_get,
132
				'session' => $session_id,
133
			)
134
		);
135
136
		// Guess it got deleted.
137
		if ($smcFunc['db_affected_rows']() == 0)
138
			$_SESSION['log_time'] = 0;
139
	}
140
	else
141
		$_SESSION['log_time'] = 0;
142
143
	// Otherwise, we have to delete and insert.
144
	if (empty($_SESSION['log_time']))
145
	{
146
		if ($do_delete || !empty($user_info['id']))
147
			$smcFunc['db_query']('', '
148
				DELETE FROM {db_prefix}log_online
149
				WHERE ' . ($do_delete ? 'log_time < {int:log_time}' : '') . ($do_delete && !empty($user_info['id']) ? ' OR ' : '') . (empty($user_info['id']) ? '' : 'id_member = {int:current_member}'),
150
				array(
151
					'current_member' => $user_info['id'],
152
					'log_time' => time() - $modSettings['lastActive'] * 60,
153
				)
154
			);
155
156
		$smcFunc['db_insert']($do_delete ? 'ignore' : 'replace',
157
			'{db_prefix}log_online',
158
			array('session' => 'string', 'id_member' => 'int', 'id_spider' => 'int', 'log_time' => 'int', 'ip' => 'inet', 'url' => 'string'),
159
			array($session_id, $user_info['id'], empty($_SESSION['id_robot']) ? 0 : $_SESSION['id_robot'], time(), $user_info['ip'], $encoded_get),
160
			array('session')
161
		);
162
	}
163
164
	// Mark your session as being logged.
165
	$_SESSION['log_time'] = time();
166
167
	// Well, they are online now.
168
	if (empty($_SESSION['timeOnlineUpdated']))
169
		$_SESSION['timeOnlineUpdated'] = time();
170
171
	// Set their login time, if not already done within the last minute.
172
	if (SMF != 'SSI' && !empty($user_info['last_login']) && $user_info['last_login'] < time() - 60 && (!isset($_REQUEST['action']) || !in_array($_REQUEST['action'], array('.xml', 'login2', 'logintfa'))))
0 ignored issues
show
introduced by
The condition SMF != 'SSI' is always false.
Loading history...
173
	{
174
		// Don't count longer than 15 minutes.
175
		if (time() - $_SESSION['timeOnlineUpdated'] > 60 * 15)
176
			$_SESSION['timeOnlineUpdated'] = time();
177
178
		$user_settings['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
179
		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']));
180
181
		if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
182
			cache_put_data('user_settings-' . $user_info['id'], $user_settings, 60);
183
184
		$user_info['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
185
		$_SESSION['timeOnlineUpdated'] = time();
186
	}
187
}
188
189
/**
190
 * Logs the last database error into a file.
191
 * Attempts to use the backup file first, to store the last database error
192
 * and only update db_last_error.php if the first was successful.
193
 */
194
function logLastDatabaseError()
195
{
196
	global $boarddir, $cachedir;
197
198
	// Make a note of the last modified time in case someone does this before us
199
	$last_db_error_change = @filemtime($cachedir . '/db_last_error.php');
200
201
	// save the old file before we do anything
202
	$file = $cachedir . '/db_last_error.php';
203
	$dberror_backup_fail = !@is_writable($cachedir . '/db_last_error_bak.php') || !@copy($file, $cachedir . '/db_last_error_bak.php');
204
	$dberror_backup_fail = !$dberror_backup_fail ? (!file_exists($cachedir . '/db_last_error_bak.php') || filesize($cachedir . '/db_last_error_bak.php') === 0) : $dberror_backup_fail;
205
206
	clearstatcache();
207
	if (filemtime($cachedir . '/db_last_error.php') === $last_db_error_change)
208
	{
209
		// Write the change
210
		$write_db_change =  '<' . '?' . "php\n" . '$db_last_error = ' . time() . ';' . "\n" . '?' . '>';
211
		$written_bytes = file_put_contents($cachedir . '/db_last_error.php', $write_db_change, LOCK_EX);
212
213
		// survey says ...
214
		if ($written_bytes !== strlen($write_db_change) && !$dberror_backup_fail)
215
		{
216
			// Oops. maybe we have no more disk space left, or some other troubles, troubles...
217
			// Copy the file back and run for your life!
218
			@copy($cachedir . '/db_last_error_bak.php', $cachedir . '/db_last_error.php');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

218
			/** @scrutinizer ignore-unhandled */ @copy($cachedir . '/db_last_error_bak.php', $cachedir . '/db_last_error.php');

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
219
		}
220
		else
221
		{
222
			@touch($boarddir . '/' . 'Settings.php');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for touch(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

222
			/** @scrutinizer ignore-unhandled */ @touch($boarddir . '/' . 'Settings.php');

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
223
			return true;
224
		}
225
	}
226
227
	return false;
228
}
229
230
/**
231
 * This function shows the debug information tracked when $db_show_debug = true
232
 * in Settings.php
233
 */
234
function displayDebug()
235
{
236
	global $context, $scripturl, $boarddir, $sourcedir, $cachedir, $settings, $modSettings;
237
	global $db_cache, $db_count, $cache_misses, $cache_count_misses, $db_show_debug, $cache_count, $cache_hits, $smcFunc, $txt;
238
239
	// Add to Settings.php if you want to show the debugging information.
240
	if (!isset($db_show_debug) || $db_show_debug !== true || (isset($_GET['action']) && $_GET['action'] == 'viewquery'))
241
		return;
242
243
	if (empty($_SESSION['view_queries']))
244
		$_SESSION['view_queries'] = 0;
245
	if (empty($context['debug']['language_files']))
246
		$context['debug']['language_files'] = array();
247
	if (empty($context['debug']['sheets']))
248
		$context['debug']['sheets'] = array();
249
250
	$files = get_included_files();
251
	$total_size = 0;
252
	for ($i = 0, $n = count($files); $i < $n; $i++)
253
	{
254
		if (file_exists($files[$i]))
255
			$total_size += filesize($files[$i]);
256
		$files[$i] = strtr($files[$i], array($boarddir => '.', $sourcedir => '(Sources)', $cachedir => '(Cache)', $settings['actual_theme_dir'] => '(Current Theme)'));
257
	}
258
259
	$warnings = 0;
260
	if (!empty($db_cache))
261
	{
262
		foreach ($db_cache as $q => $query_data)
263
		{
264
			if (!empty($query_data['w']))
265
				$warnings += count($query_data['w']);
266
		}
267
268
		$_SESSION['debug'] = &$db_cache;
269
	}
270
271
	// Gotta have valid HTML ;).
272
	$temp = ob_get_contents();
273
	ob_clean();
274
275
	echo preg_replace('~</body>\s*</html>~', '', $temp), '
276
<div class="smalltext" style="text-align: left; margin: 1ex;">
277
	', $txt['debug_browser'], $context['browser_body_id'], ' <em>(', implode('</em>, <em>', array_reverse(array_keys($context['browser'], true))), ')</em><br>
278
	', $txt['debug_templates'], count($context['debug']['templates']), ': <em>', implode('</em>, <em>', $context['debug']['templates']), '</em>.<br>
279
	', $txt['debug_subtemplates'], count($context['debug']['sub_templates']), ': <em>', implode('</em>, <em>', $context['debug']['sub_templates']), '</em>.<br>
280
	', $txt['debug_language_files'], count($context['debug']['language_files']), ': <em>', implode('</em>, <em>', $context['debug']['language_files']), '</em>.<br>
281
	', $txt['debug_stylesheets'], count($context['debug']['sheets']), ': <em>', implode('</em>, <em>', $context['debug']['sheets']), '</em>.<br>
282
	', $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>
283
	',(isset($context['debug']['instances']) ? ($txt['debug_instances'] . (empty($context['debug']['instances']) ? 0 : count($context['debug']['instances'])) . ' (<a href="javascript:void(0);" onclick="document.getElementById(\'debug_instances\').style.display = \'inline\'; this.style.display = \'none\'; return false;">'. $txt['debug_show'] .'</a><span id="debug_instances" style="display: none;"><em>'. implode('</em>, <em>', array_keys($context['debug']['instances'])) .'</em></span>)'. '<br>') : ''),'
284
	', $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>';
285
286
	if (function_exists('memory_get_peak_usage'))
287
		echo $txt['debug_memory_use'], ceil(memory_get_peak_usage() / 1024), $txt['debug_kb'], '<br>';
288
289
	// What tokens are active?
290
	if (isset($_SESSION['token']))
291
		echo $txt['debug_tokens'] . '<em>' . implode(',</em> <em>', array_keys($_SESSION['token'])), '</em>.<br>';
292
293
	if (!empty($modSettings['cache_enable']) && !empty($cache_hits))
294
	{
295
		$missed_entries = array();
296
		$entries = array();
297
		$total_t = 0;
298
		$total_s = 0;
299
		foreach ($cache_hits as $cache_hit)
300
		{
301
			$entries[] = $cache_hit['d'] . ' ' . $cache_hit['k'] . ': ' . sprintf($txt['debug_cache_seconds_bytes'], comma_format($cache_hit['t'], 5), $cache_hit['s']);
302
			$total_t += $cache_hit['t'];
303
			$total_s += $cache_hit['s'];
304
		}
305
		if (!isset($cache_misses))
306
			$cache_misses = array();
307
		foreach ($cache_misses as $missed)
308
			$missed_entries[] = $missed['d'] . ' ' . $missed['k'];
309
310
		echo '
311
	', $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>
312
	', $txt['debug_cache_misses'], $cache_count_misses, ': (<a href="javascript:void(0);" onclick="document.getElementById(\'debug_cache_misses_info\').style.display = \'inline\'; this.style.display = \'none\'; return false;">', $txt['debug_show'], '</a><span id="debug_cache_misses_info" style="display: none;"><em>', implode('</em>, <em>', $missed_entries), '</em></span>)<br>';
313
	}
314
315
	echo '
316
	<a href="', $scripturl, '?action=viewquery" target="_blank" rel="noopener">', $warnings == 0 ? sprintf($txt['debug_queries_used'], (int) $db_count) : sprintf($txt['debug_queries_used_and_warnings'], (int) $db_count, $warnings), '</a><br>
0 ignored issues
show
introduced by
The condition $warnings == 0 is always true.
Loading history...
317
	<br>';
318
319
	if ($_SESSION['view_queries'] == 1 && !empty($db_cache))
320
		foreach ($db_cache as $q => $query_data)
321
		{
322
			$is_select = strpos(trim($query_data['q']), 'SELECT') === 0 || preg_match('~^INSERT(?: IGNORE)? INTO \w+(?:\s+\([^)]+\))?\s+SELECT .+$~s', trim($query_data['q'])) != 0;
323
			// Temporary tables created in earlier queries are not explainable.
324
			if ($is_select)
325
			{
326
				foreach (array('log_topics_unread', 'topics_posted_in', 'tmp_log_search_topics', 'tmp_log_search_messages') as $tmp)
327
					if (strpos(trim($query_data['q']), $tmp) !== false)
328
					{
329
						$is_select = false;
330
						break;
331
					}
332
			}
333
			// But actual creation of the temporary tables are.
334
			elseif (preg_match('~^CREATE TEMPORARY TABLE .+?SELECT .+$~s', trim($query_data['q'])) != 0)
335
				$is_select = true;
336
337
			// Make the filenames look a bit better.
338
			if (isset($query_data['f']))
339
				$query_data['f'] = preg_replace('~^' . preg_quote($boarddir, '~') . '~', '...', $query_data['f']);
340
341
			echo '
342
	<strong>', $is_select ? '<a href="' . $scripturl . '?action=viewquery;qq=' . ($q + 1) . '#qq' . $q . '" target="_blank" rel="noopener" style="text-decoration: none;">' : '', nl2br(str_replace("\t", '&nbsp;&nbsp;&nbsp;', $smcFunc['htmlspecialchars'](ltrim($query_data['q'], "\n\r")))) . ($is_select ? '</a></strong>' : '</strong>') . '<br>
343
	&nbsp;&nbsp;&nbsp;';
344
			if (!empty($query_data['f']) && !empty($query_data['l']))
345
				echo sprintf($txt['debug_query_in_line'], $query_data['f'], $query_data['l']);
346
347
			if (isset($query_data['s'], $query_data['t']) && isset($txt['debug_query_which_took_at']))
348
				echo sprintf($txt['debug_query_which_took_at'], round($query_data['t'], 8), round($query_data['s'], 8)) . '<br>';
349
			elseif (isset($query_data['t']))
350
				echo sprintf($txt['debug_query_which_took'], round($query_data['t'], 8)) . '<br>';
351
			echo '
352
	<br>';
353
		}
354
355
	echo '
356
	<a href="' . $scripturl . '?action=viewquery;sa=hide">', $txt['debug_' . (empty($_SESSION['view_queries']) ? 'show' : 'hide') . '_queries'], '</a>
357
</div></body></html>';
358
}
359
360
/**
361
 * Track Statistics.
362
 * Caches statistics changes, and flushes them if you pass nothing.
363
 * If '+' is used as a value, it will be incremented.
364
 * It does not actually commit the changes until the end of the page view.
365
 * It depends on the trackStats setting.
366
 *
367
 * @param array $stats An array of data
368
 * @return bool Whether or not the info was updated successfully
369
 */
370
function trackStats($stats = array())
371
{
372
	global $modSettings, $smcFunc;
373
	static $cache_stats = array();
374
375
	if (empty($modSettings['trackStats']))
376
		return false;
377
	if (!empty($stats))
378
		return $cache_stats = array_merge($cache_stats, $stats);
379
	elseif (empty($cache_stats))
380
		return false;
381
382
	$setStringUpdate = '';
383
	$insert_keys = array();
384
	$date = strftime('%Y-%m-%d', forum_time(false));
385
	$update_parameters = array(
386
		'current_date' => $date,
387
	);
388
	foreach ($cache_stats as $field => $change)
389
	{
390
		$setStringUpdate .= '
391
			' . $field . ' = ' . ($change === '+' ? $field . ' + 1' : '{int:' . $field . '}') . ',';
392
393
		if ($change === '+')
394
			$cache_stats[$field] = 1;
395
		else
396
			$update_parameters[$field] = $change;
397
		$insert_keys[$field] = 'int';
398
	}
399
400
	$smcFunc['db_query']('', '
401
		UPDATE {db_prefix}log_activity
402
		SET' . substr($setStringUpdate, 0, -1) . '
403
		WHERE date = {date:current_date}',
404
		$update_parameters
405
	);
406
	if ($smcFunc['db_affected_rows']() == 0)
407
	{
408
		$smcFunc['db_insert']('ignore',
409
			'{db_prefix}log_activity',
410
			array_merge($insert_keys, array('date' => 'date')),
411
			array_merge($cache_stats, array($date)),
412
			array('date')
413
		);
414
	}
415
416
	// Don't do this again.
417
	$cache_stats = array();
418
419
	return true;
420
}
421
422
/**
423
 * This function logs an action in the respective log. (database log)
424
 * You should use {@link logActions()} instead.
425
 * @example logAction('remove', array('starter' => $id_member_started));
426
 *
427
 * @param string $action The action to log
428
 * @param array $extra = array() An array of additional data
429
 * @param string $log_type What type of log ('admin', 'moderate', etc.)
430
 * @return int The ID of the row containing the logged data
431
 */
432
function logAction($action, $extra = array(), $log_type = 'moderate')
433
{
434
	return logActions(array(array(
435
		'action' => $action,
436
		'log_type' => $log_type,
437
		'extra' => $extra,
438
	)));
439
}
440
441
/**
442
 * Log changes to the forum, such as moderation events or administrative changes.
443
 * This behaves just like logAction() in SMF 2.0, except that it is designed to log multiple actions at once.
444
 *
445
 * @param array $logs An array of log data
446
 * @return int The last logged ID
447
 */
448
function logActions($logs)
449
{
450
	global $modSettings, $user_info, $smcFunc, $sourcedir;
451
452
	$inserts = array();
453
	$log_types = array(
454
		'moderate' => 1,
455
		'user' => 2,
456
		'admin' => 3,
457
	);
458
459
	// Make sure this particular log is enabled first...
460
	if (empty($modSettings['modlog_enabled']))
461
		unset ($log_types['moderate']);
462
	if (empty($modSettings['userlog_enabled']))
463
		unset ($log_types['user']);
464
	if (empty($modSettings['adminlog_enabled']))
465
		unset ($log_types['admin']);
466
467
	call_integration_hook('integrate_log_types', array(&$log_types));
468
469
	foreach ($logs as $log)
470
	{
471
		if (!isset($log_types[$log['log_type']]))
472
			return false;
473
474
		if (!is_array($log['extra']))
475
			trigger_error('logActions(): data is not an array with action \'' . $log['action'] . '\'', E_USER_NOTICE);
476
477
		// Pull out the parts we want to store separately, but also make sure that the data is proper
478
		if (isset($log['extra']['topic']))
479
		{
480
			if (!is_numeric($log['extra']['topic']))
481
				trigger_error('logActions(): data\'s topic is not a number', E_USER_NOTICE);
482
			$topic_id = empty($log['extra']['topic']) ? 0 : (int) $log['extra']['topic'];
483
			unset($log['extra']['topic']);
484
		}
485
		else
486
			$topic_id = 0;
487
488
		if (isset($log['extra']['message']))
489
		{
490
			if (!is_numeric($log['extra']['message']))
491
				trigger_error('logActions(): data\'s message is not a number', E_USER_NOTICE);
492
			$msg_id = empty($log['extra']['message']) ? 0 : (int) $log['extra']['message'];
493
			unset($log['extra']['message']);
494
		}
495
		else
496
			$msg_id = 0;
497
498
		// @todo cache this?
499
		// Is there an associated report on this?
500
		if (in_array($log['action'], array('move', 'remove', 'split', 'merge')))
501
		{
502
			$request = $smcFunc['db_query']('', '
503
				SELECT id_report
504
				FROM {db_prefix}log_reported
505
				WHERE {raw:column_name} = {int:reported}
506
				LIMIT 1',
507
				array(
508
					'column_name' => !empty($msg_id) ? 'id_msg' : 'id_topic',
509
					'reported' => !empty($msg_id) ? $msg_id : $topic_id,
510
			));
511
512
			// Alright, if we get any result back, update open reports.
513
			if ($smcFunc['db_num_rows']($request) > 0)
514
			{
515
				require_once($sourcedir . '/ModerationCenter.php');
516
				require_once($sourcedir . '/Subs-ReportedContent.php');
517
				updateSettings(array('last_mod_report_action' => time()));
518
				recountOpenReports('posts');
519
			}
520
			$smcFunc['db_free_result']($request);
521
		}
522
523
		if (isset($log['extra']['member']) && !is_numeric($log['extra']['member']))
524
			trigger_error('logActions(): data\'s member is not a number', E_USER_NOTICE);
525
526
		if (isset($log['extra']['board']))
527
		{
528
			if (!is_numeric($log['extra']['board']))
529
				trigger_error('logActions(): data\'s board is not a number', E_USER_NOTICE);
530
			$board_id = empty($log['extra']['board']) ? 0 : (int) $log['extra']['board'];
531
			unset($log['extra']['board']);
532
		}
533
		else
534
			$board_id = 0;
535
536
		if (isset($log['extra']['board_to']))
537
		{
538
			if (!is_numeric($log['extra']['board_to']))
539
				trigger_error('logActions(): data\'s board_to is not a number', E_USER_NOTICE);
540
			if (empty($board_id))
541
			{
542
				$board_id = empty($log['extra']['board_to']) ? 0 : (int) $log['extra']['board_to'];
543
				unset($log['extra']['board_to']);
544
			}
545
		}
546
547
		if (isset($log['extra']['member_affected']))
548
			$memID = $log['extra']['member_affected'];
549
		else
550
			$memID = $user_info['id'];
551
		
552
		if (isset($user_info['ip']))
553
			$memIP = $user_info['ip'];
554
		else
555
			$memIP = 'null';
556
557
		$inserts[] = array(
558
			time(), $log_types[$log['log_type']], $memID, $memIP, $log['action'],
559
			$board_id, $topic_id, $msg_id, $smcFunc['json_encode']($log['extra']),
560
		);
561
	}
562
563
	$id_action = $smcFunc['db_insert']('',
564
		'{db_prefix}log_actions',
565
		array(
566
			'log_time' => 'int', 'id_log' => 'int', 'id_member' => 'int', 'ip' => 'inet', 'action' => 'string',
567
			'id_board' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534',
568
		),
569
		$inserts,
570
		array('id_action'),
571
		1
572
	);
573
574
	return $id_action;
575
}
576
577
?>