Completed
Push — release-2.1 ( 6f6d35...abeae7 )
by Mathias
08:46
created

ManageErrors.php ➔ ViewErrorLog()   F

Complexity

Conditions 49
Paths > 20000

Size

Total Lines 295
Code Lines 173

Duplication

Lines 2
Ratio 0.68 %

Importance

Changes 0
Metric Value
cc 49
eloc 173
nc 429496.7295
nop 0
dl 2
loc 295
rs 2
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
 * The main purpose of this file is to show a list of all errors that were
5
 * logged on the forum, and allow filtering and deleting them.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines http://www.simplemachines.org
11
 * @copyright 2017 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 Beta 4
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * View the forum's error log.
22
 * This function sets all the context up to show the error log for maintenance.
23
 * It requires the maintain_forum permission.
24
 * It is accessed from ?action=admin;area=logs;sa=errorlog.
25
 *
26
 * @uses the Errors template and error_log sub template.
27
 */
28
function ViewErrorLog()
29
{
30
	global $scripturl, $txt, $context, $modSettings, $user_profile, $filter, $smcFunc;
31
32
	// Viewing contents of a file?
33
	if (isset($_GET['file']))
34
		return ViewFile();
35
36
	// Check for the administrative permission to do this.
37
	isAllowedTo('admin_forum');
38
39
	// Templates, etc...
40
	loadLanguage('ManageMaintenance');
41
	loadTemplate('Errors');
42
43
	// You can filter by any of the following columns:
44
	$filters = array(
45
		'id_member' => array(
46
			'txt' => $txt['username'],
47
			'operator' => '=',
48
			'datatype' => 'int',
49
		),
50
		'ip' => array(
51
			'txt' => $txt['ip_address'],
52
			'operator' => '=',
53
			'datatype' => 'inet',
54
		),
55
		'session' => array(
56
			'txt' => $txt['session'],
57
			'operator' => 'LIKE',
58
			'datatype' => 'string',
59
		),
60
		'url' => array(
61
			'txt' => $txt['error_url'],
62
			'operator' => 'LIKE',
63
			'datatype' => 'string',
64
		),
65
		'message' => array(
66
			'txt' => $txt['error_message'],
67
			'operator' => 'LIKE',
68
			'datatype' => 'string',
69
		),
70
		'error_type' => array(
71
			'txt' => $txt['error_type'],
72
			'operator' => 'LIKE',
73
			'datatype' => 'string',
74
		),
75
		'file' => array(
76
			'txt' => $txt['file'],
77
			'operator' => 'LIKE',
78
			'datatype' => 'string',
79
		),
80
		'line' => array(
81
			'txt' => $txt['line'],
82
			'operator' => '=',
83
			'datatype' => 'int',
84
		),
85
	);
86
87
	// Set up the filtering...
88
	if (isset($_GET['value'], $_GET['filter']) && isset($filters[$_GET['filter']]))
89
		$filter = array(
90
			'variable' => $_GET['filter'],
91
			'value' => array(
92
				'sql' => in_array($_GET['filter'], array('message', 'url', 'file')) ? base64_decode(strtr($_GET['value'], array(' ' => '+'))) : $smcFunc['db_escape_wildcard_string']($_GET['value']),
93
			),
94
			'href' => ';filter=' . $_GET['filter'] . ';value=' . $_GET['value'],
95
			'entity' => $filters[$_GET['filter']]['txt']
96
		);
97
98
	// Deleting, are we?
99
	if (isset($_POST['delall']) || isset($_POST['delete']))
100
		deleteErrors();
101
102
	// Just how many errors are there?
103
	$result = $smcFunc['db_query']('', '
104
		SELECT COUNT(*)
105
		FROM {db_prefix}log_errors' . (isset($filter) ? '
106
		WHERE ' . $filter['variable'] . ' ' . $filters[$_GET['filter']]['operator'] . ' {' . $filters[$_GET['filter']]['datatype'] . ':filter}' : ''),
107
		array(
108
			'filter' => isset($filter) ? $filter['value']['sql'] : '',
109
		)
110
	);
111
	list ($num_errors) = $smcFunc['db_fetch_row']($result);
112
	$smcFunc['db_free_result']($result);
113
114
	// If this filter is empty...
115
	if ($num_errors == 0 && isset($filter))
116
		redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : ''));
117
118
	// Clean up start.
119 View Code Duplication
	if (!isset($_GET['start']) || $_GET['start'] < 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
120
		$_GET['start'] = 0;
121
122
	// Do we want to reverse error listing?
123
	$context['sort_direction'] = isset($_REQUEST['desc']) ? 'down' : 'up';
124
125
	// Set the page listing up.
126
	$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['defaultMaxListItems']);
127
	$context['start'] = $_GET['start'];
128
129
	// Update the error count
130
	if (!isset($filter))
131
		$context['num_errors'] = $num_errors;
132
	else
133
	{
134
		// We want all errors, not just the number of filtered messages...
135
		$query = $smcFunc['db_query']('', '
136
			SELECT COUNT(id_error)
137
			FROM {db_prefix}log_errors',
138
			array()
139
		);
140
141
		list($context['num_errors']) = $smcFunc['db_fetch_row']($query);
142
		$smcFunc['db_free_result']($query);
143
	}
144
145
	// Find and sort out the errors.
146
	$request = $smcFunc['db_query']('', '
147
		SELECT id_error, id_member, ip, url, log_time, message, session, error_type, file, line
148
		FROM {db_prefix}log_errors' . (isset($filter) ? '
149
		WHERE ' . $filter['variable'] . ' ' . $filters[$_GET['filter']]['operator'] . ' {' . $filters[$_GET['filter']]['datatype'] . ':filter}' : '') . '
150
		ORDER BY id_error ' . ($context['sort_direction'] == 'down' ? 'DESC' : '') . '
151
		LIMIT {int:start}, {int:max}',
152
		array(
153
			'filter' => isset($filter) ? $filter['value']['sql'] : '',
154
			'start' => $_GET['start'],
155
			'max' => $modSettings['defaultMaxListItems'],
156
		)
157
	);
158
	$context['errors'] = array();
159
	$members = array();
160
161
	for ($i = 0; $row = $smcFunc['db_fetch_assoc']($request); $i++)
162
	{
163
		$search_message = preg_replace('~&lt;span class=&quot;remove&quot;&gt;(.+?)&lt;/span&gt;~', '%', $smcFunc['db_escape_wildcard_string']($row['message']));
164
		if ($search_message == $filter['value']['sql'])
165
			$search_message = $smcFunc['db_escape_wildcard_string']($row['message']);
166
		$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>'));
167
168
		$context['errors'][$row['id_error']] = array(
169
			'member' => array(
170
				'id' => $row['id_member'],
171
				'ip' => inet_dtop($row['ip']),
172
				'session' => $row['session']
173
			),
174
			'time' => timeformat($row['log_time']),
175
			'timestamp' => $row['log_time'],
176
			'url' => array(
177
				'html' => $smcFunc['htmlspecialchars'](strpos($row['url'], 'cron.php') === false ? (substr($row['url'], 0, 1) == '?' ? $scripturl : '') . $row['url'] : $row['url']),
178
				'href' => base64_encode($smcFunc['db_escape_wildcard_string']($row['url']))
179
			),
180
			'message' => array(
181
				'html' => $show_message,
182
				'href' => base64_encode($search_message)
183
			),
184
			'id' => $row['id_error'],
185
			'error_type' => array(
186
				'type' => $row['error_type'],
187
				'name' => isset($txt['errortype_' . $row['error_type']]) ? $txt['errortype_' . $row['error_type']] : $row['error_type'],
188
			),
189
			'file' => array(),
190
		);
191
		if (!empty($row['file']) && !empty($row['line']))
192
		{
193
			// Eval'd files rarely point to the right location and cause havoc for linking, so don't link them.
194
			$linkfile = strpos($row['file'], 'eval') === false || strpos($row['file'], '?') === false; // De Morgan's Law.  Want this true unless both are present.
195
196
			$context['errors'][$row['id_error']]['file'] = array(
197
				'file' => $row['file'],
198
				'line' => $row['line'],
199
				'href' => $scripturl . '?action=admin;area=logs;sa=errorlog;file=' . base64_encode($row['file']) . ';line=' . $row['line'],
200
				'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'],
201
				'search' => base64_encode($row['file']),
202
			);
203
		}
204
205
		// Make a list of members to load later.
206
		$members[$row['id_member']] = $row['id_member'];
207
	}
208
	$smcFunc['db_free_result']($request);
209
210
	// Load the member data.
211
	if (!empty($members))
212
	{
213
		// Get some additional member info...
214
		$request = $smcFunc['db_query']('', '
215
			SELECT id_member, member_name, real_name
216
			FROM {db_prefix}members
217
			WHERE id_member IN ({array_int:member_list})
218
			LIMIT {int:members}',
219
			array(
220
				'member_list' => $members,
221
				'members' => count($members),
222
			)
223
		);
224
		while ($row = $smcFunc['db_fetch_assoc']($request))
225
			$members[$row['id_member']] = $row;
226
		$smcFunc['db_free_result']($request);
227
228
		// This is a guest...
229
		$members[0] = array(
230
			'id_member' => 0,
231
			'member_name' => '',
232
			'real_name' => $txt['guest_title']
233
		);
234
235
		// Go through each error and tack the data on.
236
		foreach ($context['errors'] as $id => $dummy)
237
		{
238
			$memID = $context['errors'][$id]['member']['id'];
239
			$context['errors'][$id]['member']['username'] = $members[$memID]['member_name'];
240
			$context['errors'][$id]['member']['name'] = $members[$memID]['real_name'];
241
			$context['errors'][$id]['member']['href'] = empty($memID) ? '' : $scripturl . '?action=profile;u=' . $memID;
242
			$context['errors'][$id]['member']['link'] = empty($memID) ? $txt['guest_title'] : '<a href="' . $scripturl . '?action=profile;u=' . $memID . '">' . $context['errors'][$id]['member']['name'] . '</a>';
243
		}
244
	}
245
246
	// Filtering anything?
247
	if (isset($filter))
248
	{
249
		$context['filter'] = &$filter;
250
251
		// Set the filtering context.
252
		if ($filter['variable'] == 'id_member')
253
		{
254
			$id = $filter['value']['sql'];
255
			loadMemberData($id, false, 'minimal');
256
			$context['filter']['value']['html'] = '<a href="' . $scripturl . '?action=profile;u=' . $id . '">' . $user_profile[$id]['real_name'] . '</a>';
257
		}
258
		elseif ($filter['variable'] == 'url')
259
			$context['filter']['value']['html'] = '\'' . strtr($smcFunc['htmlspecialchars']((substr($filter['value']['sql'], 0, 1) == '?' ? $scripturl : '') . $filter['value']['sql']), array('\_' => '_')) . '\'';
260
		elseif ($filter['variable'] == 'message')
261
		{
262
			$context['filter']['value']['html'] = '\'' . strtr($smcFunc['htmlspecialchars']($filter['value']['sql']), array("\n" => '<br>', '&lt;br /&gt;' => '<br>', "\t" => '&nbsp;&nbsp;&nbsp;', '\_' => '_', '\\%' => '%', '\\\\' => '\\')) . '\'';
263
			$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']);
264
		}
265
		elseif ($filter['variable'] == 'error_type')
266
		{
267
			$context['filter']['value']['html'] = '\'' . strtr($smcFunc['htmlspecialchars']($filter['value']['sql']), array("\n" => '<br>', '&lt;br /&gt;' => '<br>', "\t" => '&nbsp;&nbsp;&nbsp;', '\_' => '_', '\\%' => '%', '\\\\' => '\\')) . '\'';
268
		}
269
		else
270
			$context['filter']['value']['html'] = &$filter['value']['sql'];
271
	}
272
273
	$context['error_types'] = array();
274
275
	$context['error_types']['all'] = array(
276
		'label' => $txt['errortype_all'],
277
		'description' => isset($txt['errortype_all_desc']) ? $txt['errortype_all_desc'] : '',
278
		'url' => $scripturl . '?action=admin;area=logs;sa=errorlog' . ($context['sort_direction'] == 'down' ? ';desc' : ''),
279
		'is_selected' => empty($filter),
280
	);
281
282
	$sum = 0;
283
	// What type of errors do we have and how many do we have?
284
	$request = $smcFunc['db_query']('', '
285
		SELECT error_type, COUNT(*) AS num_errors
286
		FROM {db_prefix}log_errors
287
		GROUP BY error_type
288
		ORDER BY error_type = {string:critical_type} DESC, error_type ASC',
289
		array(
290
			'critical_type' => 'critical',
291
		)
292
	);
293
	while ($row = $smcFunc['db_fetch_assoc']($request))
294
	{
295
		// Total errors so far?
296
		$sum += $row['num_errors'];
297
298
		$context['error_types'][$sum] = array(
299
			'label' => (isset($txt['errortype_' . $row['error_type']]) ? $txt['errortype_' . $row['error_type']] : $row['error_type']) . ' (' . $row['num_errors'] . ')',
300
			'description' => isset($txt['errortype_' . $row['error_type'] . '_desc']) ? $txt['errortype_' . $row['error_type'] . '_desc'] : '',
301
			'url' => $scripturl . '?action=admin;area=logs;sa=errorlog' . ($context['sort_direction'] == 'down' ? ';desc' : '') . ';filter=error_type;value=' . $row['error_type'],
302
			'is_selected' => isset($filter) && $filter['value']['sql'] == $smcFunc['db_escape_wildcard_string']($row['error_type']),
303
		);
304
	}
305
	$smcFunc['db_free_result']($request);
306
307
	// Update the all errors tab with the total number of errors
308
	$context['error_types']['all']['label'] .= ' (' . $sum . ')';
309
310
	// Finally, work out what is the last tab!
311
	if (isset($context['error_types'][$sum]))
312
		$context['error_types'][$sum]['is_last'] = true;
313
	else
314
		$context['error_types']['all']['is_last'] = true;
315
316
	// And this is pretty basic ;).
317
	$context['page_title'] = $txt['errlog'];
318
	$context['has_filter'] = isset($filter);
319
	$context['sub_template'] = 'error_log';
320
321
	createToken('admin-el');
322
}
323
324
/**
325
 * Delete all or some of the errors in the error log.
326
 * It applies any necessary filters to deletion.
327
 * This should only be called by ViewErrorLog().
328
 * It attempts to TRUNCATE the table to reset the auto_increment.
329
 * Redirects back to the error log when done.
330
 */
331
function deleteErrors()
332
{
333
	global $filter, $smcFunc;
334
335
	// Make sure the session exists and is correct; otherwise, might be a hacker.
336
	checkSession();
337
	validateToken('admin-el');
338
339
	// Delete all or just some?
340
	if (isset($_POST['delall']) && !isset($filter))
341
		$smcFunc['db_query']('truncate_table', '
342
			TRUNCATE {db_prefix}log_errors',
343
			array(
344
			)
345
		);
346
	// Deleting all with a filter?
347
	elseif (isset($_POST['delall']) && isset($filter))
348
		$smcFunc['db_query']('', '
349
			DELETE FROM {db_prefix}log_errors
350
			WHERE ' . $filter['variable'] . ' LIKE {string:filter}',
351
			array(
352
				'filter' => $filter['value']['sql'],
353
			)
354
		);
355
	// Just specific errors?
356
	elseif (!empty($_POST['delete']))
357
	{
358
		$smcFunc['db_query']('', '
359
			DELETE FROM {db_prefix}log_errors
360
			WHERE id_error IN ({array_int:error_list})',
361
			array(
362
				'error_list' => array_unique($_POST['delete']),
363
			)
364
		);
365
366
		// Go back to where we were.
367
		redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : '') . ';start=' . $_GET['start'] . (isset($filter) ? ';filter=' . $_GET['filter'] . ';value=' . $_GET['value'] : ''));
368
	}
369
370
	// Back to the error log!
371
	redirectexit('action=admin;area=logs;sa=errorlog' . (isset($_REQUEST['desc']) ? ';desc' : ''));
372
}
373
374
/**
375
 * View a file specified in $_REQUEST['file'], with php highlighting on it
376
 * Preconditions:
377
 *  - file must be readable,
378
 *  - full file path must be base64 encoded,
379
 *  - user must have admin_forum permission.
380
 * The line number number is specified by $_REQUEST['line']...
381
 * The function will try to get the 20 lines before and after the specified line.
382
 */
383
function ViewFile()
384
{
385
	global $context, $boarddir, $sourcedir, $cachedir, $smcFunc;
386
387
	// Check for the administrative permission to do this.
388
	isAllowedTo('admin_forum');
389
390
	// Decode the file and get the line
391
	$file = realpath(base64_decode($_REQUEST['file']));
392
	$real_board = realpath($boarddir);
393
	$real_source = realpath($sourcedir);
394
	$real_cache = realpath($cachedir);
395
	$basename = strtolower(basename($file));
396
	$ext = strrchr($basename, '.');
397
	$line = isset($_REQUEST['line']) ? (int) $_REQUEST['line'] : 0;
398
399
	// Make sure the file we are looking for is one they are allowed to look at
400
	if ($ext != '.php' || (strpos($file, $real_board) === false && strpos($file, $real_source) === false) || ($basename == 'settings.php' || $basename == 'settings_bak.php') || strpos($file, $real_cache) !== false || !is_readable($file))
401
		fatal_lang_error('error_bad_file', true, array($smcFunc['htmlspecialchars']($file)));
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|false.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
402
403
	// get the min and max lines
404
	$min = $line - 20 <= 0 ? 1 : $line - 20;
405
	$max = $line + 21; // One additional line to make everything work out correctly
406
407
	if ($max <= 0 || $min >= $max)
408
		fatal_lang_error('error_bad_line');
409
410
	$file_data = explode('<br />', highlight_php_code($smcFunc['htmlspecialchars'](implode('', file($file)))));
411
412
	// We don't want to slice off too many so lets make sure we stop at the last one
413
	$max = min($max, max(array_keys($file_data)));
414
415
	$file_data = array_slice($file_data, $min - 1, $max - $min);
416
417
	$context['file_data'] = array(
418
		'contents' => $file_data,
419
		'min' => $min,
420
		'target' => $line,
421
		'file' => strtr($file, array('"' => '\\"')),
422
	);
423
424
	loadTemplate('Errors');
425
	$context['template_layers'] = array();
426
	$context['sub_template'] = 'show_file';
427
428
}
429
430
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...