Failed Conditions
Branch release-2.1 (4e22cf)
by Rick
06:39
created

ReportToMod.php ➔ ReportToModerator()   F

Complexity

Conditions 25
Paths 18432

Size

Total Lines 131
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 54
nc 18432
nop 0
dl 0
loc 131
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 functions in this file deal with reporting posts or profiles to mods and admins
5
 * Simple Machines Forum (SMF)
6
 *
7
 * @package SMF
8
 * @author Simple Machines http://www.simplemachines.org
9
 * @copyright 2017 Simple Machines and individual contributors
10
 * @license http://www.simplemachines.org/about/smf/license.php BSD
11
 *
12
 * @version 2.1 Beta 4
13
 */
14
15
if (!defined('SMF'))
16
	die('No direct access...');
17
18
/**
19
 * Report a post or profile to the moderator... ask for a comment.
20
 * Gathers data from the user to report abuse to the moderator(s).
21
 * Uses the ReportToModerator template, main sub template.
22
 * Requires the report_any permission.
23
 * Uses ReportToModerator2() if post data was sent.
24
 * Accessed through ?action=reporttm.
25
 */
26
function ReportToModerator()
27
{
28
	global $txt, $topic, $context, $smcFunc, $scripturl, $sourcedir;
29
30
	$context['robot_no_index'] = true;
31
	$context['comment_body'] = '';
32
33
	// No guests!
34
	is_not_guest();
35
36
	// You can't use this if it's off or you are not allowed to do it.
37
	// If we don't have the ID of something to report, we'll die with a no_access error below
38
	if (isset($_REQUEST['msg']))
39
		isAllowedTo('report_any');
40
	elseif (isset($_REQUEST['u']))
41
		isAllowedTo('report_user');
42
43
	// Previewing or modifying?
44
	if (isset($_POST['preview']) && !isset($_POST['save']))
45
	{
46
		require_once($sourcedir . '/Subs-Post.php');
47
48
		// Set up the preview message.
49
		$context['preview_message'] = $smcFunc['htmlspecialchars']($_POST['comment'], ENT_QUOTES);
50
		preparsecode($context['preview_message']);
51
52
		// We censor for your protection...
53
		censorText($context['preview_message']);
54
55
		$context['comment_body'] = !empty($_POST['comment']) ? trim($_POST['comment']) : '';
56
	}
57
58
	// If they're posting, it should be processed by ReportToModerator2.
59
	if ((isset($_POST[$context['session_var']]) || isset($_POST['save'])) && empty($context['post_errors']) && !isset($_POST['preview']))
60
		ReportToModerator2();
61
62
	// We need a message ID or user ID to check!
63
	if (empty($_REQUEST['msg']) && empty($_REQUEST['mid']) && empty($_REQUEST['u']))
64
		fatal_lang_error('no_access', false);
65
66
	// For compatibility, accept mid, but we should be using msg. (not the flavor kind!)
67
	if (!empty($_REQUEST['msg']) || !empty($_REQUEST['mid']))
68
		$_REQUEST['msg'] = empty($_REQUEST['msg']) ? (int) $_REQUEST['mid'] : (int) $_REQUEST['msg'];
69
	// msg and mid empty - assume we're reporting a user
70
	elseif (!empty($_REQUEST['u']))
71
		$_REQUEST['u'] = (int) $_REQUEST['u'];
72
73
	// Set up some form values
74
	$context['report_type'] = isset($_REQUEST['msg']) ? 'msg' : 'u';
75
	$context['reported_item'] = isset($_REQUEST['msg']) ? $_REQUEST['msg'] : $_REQUEST['u'];
76
77
	if (isset($_REQUEST['msg']))
78
	{
79
		// Check the message's ID - don't want anyone reporting a post they can't even see!
80
		$result = $smcFunc['db_query']('', '
81
			SELECT m.id_msg, m.id_member, t.id_member_started
82
			FROM {db_prefix}messages AS m
83
				INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
84
			WHERE m.id_msg = {int:id_msg}
85
				AND m.id_topic = {int:current_topic}
86
			LIMIT 1',
87
			array(
88
				'current_topic' => $topic,
89
				'id_msg' => $_REQUEST['msg'],
90
			)
91
		);
92
		if ($smcFunc['db_num_rows']($result) == 0)
93
			fatal_lang_error('no_board', false);
94
		list ($_REQUEST['msg'], $member, $starter) = $smcFunc['db_fetch_row']($result);
0 ignored issues
show
Unused Code introduced by
The assignment to $member is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Unused Code introduced by
The assignment to $starter is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
95
		$smcFunc['db_free_result']($result);
96
97
98
		// This is here so that the user could, in theory, be redirected back to the topic.
99
		$context['start'] = $_REQUEST['start'];
100
		$context['message_id'] = $_REQUEST['msg'];
101
102
		// The submit URL is different for users than it is for posts
103
		$context['submit_url'] = $scripturl . '?action=reporttm;msg=' . $_REQUEST['msg'] . ';topic=' . $topic;
104
	}
105
	else
106
	{
107
		// Check the user's ID
108
		$result = $smcFunc['db_query']('', '
109
			SELECT id_member, real_name, member_name
110
			FROM {db_prefix}members
111
			WHERE id_member = {int:current_user}',
112
			array(
113
				'current_user' => $_REQUEST['u'],
114
			)
115
		);
116
117
		if ($smcFunc['db_num_rows']($result) == 0)
118
			fatal_lang_error('no_user', false);
119
		list($_REQUEST['u'], $display_name, $username) = $smcFunc['db_fetch_row']($result);
0 ignored issues
show
Unused Code introduced by
The assignment to $username is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
120
121
		$context['current_user'] = $_REQUEST['u'];
122
		$context['submit_url'] = $scripturl . '?action=reporttm;u=' . $_REQUEST['u'];
123
	}
124
125
	$context['comment_body'] = !isset($_POST['comment']) ? '' : trim($_POST['comment']);
126
127
	$context['page_title'] = $context['report_type'] == 'msg' ? $txt['report_to_mod'] : sprintf($txt['report_profile'], $display_name);
0 ignored issues
show
Bug introduced by
The variable $display_name does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
128
	$context['notice'] = $context['report_type'] == 'msg' ? $txt['report_to_mod_func'] : $txt['report_profile_func'];
129
130
	// Show the inputs for the comment, etc.
131
	loadLanguage('Post');
132
	loadTemplate('ReportToMod');
133
134
	addInlineJavaScript('
135
	var error_box = $("#error_box");
136
	$("#report_comment").keyup(function() {
137
		var post_too_long = $("#error_post_too_long");
138
		if ($(this).val().length > 254)
139
		{
140
			if (post_too_long.length == 0)
141
			{
142
				error_box.show();
143
				if ($.trim(error_box.html()) == \'\')
144
					error_box.append("<ul id=\'error_list\'></ul>");
145
146
				$("#error_list").append("<li id=\'error_post_too_long\' class=\'error\'>" + ' . JavaScriptEscape($txt['post_too_long']) . ' + "</li>");
147
			}
148
		}
149
		else
150
		{
151
			post_too_long.remove();
152
			if ($("#error_list li").length == 0)
153
				error_box.hide();
154
		}
155
	});', true);
156
}
157
158
/**
159
 * Send the emails.
160
 * Sends off emails to all the moderators.
161
 * Sends to administrators and global moderators. (1 and 2)
162
 * Called by ReportToModerator(), and thus has the same permission and setting requirements as it does.
163
 * Accessed through ?action=reporttm when posting.
164
 */
165
function ReportToModerator2()
166
{
167
	global $txt, $sourcedir, $context, $smcFunc;
168
169
	// Sorry, no guests allowed... Probably just trying to spam us anyway
170
	is_not_guest();
171
172
	// You must have the proper permissions!
173
	if (isset($_REQUEST['msg']))
174
		isAllowedTo('report_any');
175
	else
176
		isAllowedTo('report_user');
177
178
	// Make sure they aren't spamming.
179
	spamProtection('reporttm');
180
181
	require_once($sourcedir . '/Subs-Post.php');
182
183
	// Prevent double submission of this form.
184
	checkSubmitOnce('check');
185
186
	// No errors, yet.
187
	$post_errors = array();
188
189
	// Check their session.
190
	if (checkSession('post', '', false) != '')
191
		$post_errors[] = 'session_timeout';
192
193
	// Make sure we have a comment and it's clean.
194
	if (!isset($_POST['comment']) || $smcFunc['htmltrim']($_POST['comment']) === '')
195
		$post_errors[] = 'no_comment';
196
197
	$poster_comment = strtr($smcFunc['htmlspecialchars']($_POST['comment']), array("\r" => '', "\t" => ''));
198
199
	if ($smcFunc['strlen']($poster_comment) > 254)
200
		$post_errors[] = 'post_too_long';
201
202
	// Any errors?
203 View Code Duplication
	if (!empty($post_errors))
204
	{
205
		loadLanguage('Errors');
206
207
		$context['post_errors'] = array();
208
		foreach ($post_errors as $post_error)
209
			$context['post_errors'][$post_error] = $txt['error_' . $post_error];
210
211
		return ReportToModerator();
212
	}
213
214
	if (isset($_POST['msg']))
215
	{
216
		// Handle this elsewhere to keep things from getting too long
217
		reportPost($_POST['msg'], $poster_comment);
218
	}
219
	else
220
	{
221
		reportUser($_POST['u'], $poster_comment);
222
	}
223
}
224
225
/**
226
 * Actually reports a post using information specified from a form
227
 *
228
 * @param int $msg The ID of the post being reported
229
 * @param string $reason The reason specified for reporting the post
230
 */
231
function reportPost($msg, $reason)
232
{
233
	global $context, $smcFunc, $user_info, $topic;
234
235
	// Get the basic topic information, and make sure they can see it.
236
	$_POST['msg'] = (int) $msg;
237
238
	$request = $smcFunc['db_query']('', '
239
		SELECT m.id_topic, m.id_board, m.subject, m.body, m.id_member AS id_poster, m.poster_name, mem.real_name
240
		FROM {db_prefix}messages AS m
241
			LEFT JOIN {db_prefix}members AS mem ON (m.id_member = mem.id_member)
242
		WHERE m.id_msg = {int:id_msg}
243
			AND m.id_topic = {int:current_topic}
244
		LIMIT 1',
245
		array(
246
			'current_topic' => $topic,
247
			'id_msg' => $_POST['msg'],
248
		)
249
	);
250
	if ($smcFunc['db_num_rows']($request) == 0)
251
		fatal_lang_error('no_board', false);
252
	$message = $smcFunc['db_fetch_assoc']($request);
253
	$smcFunc['db_free_result']($request);
254
255
	$request = $smcFunc['db_query']('', '
256
		SELECT id_report, ignore_all
257
		FROM {db_prefix}log_reported
258
		WHERE id_msg = {int:id_msg}
259
			AND (closed = {int:not_closed} OR ignore_all = {int:ignored})
260
		ORDER BY ignore_all DESC',
261
		array(
262
			'id_msg' => $_POST['msg'],
263
			'not_closed' => 0,
264
			'ignored' => 1,
265
		)
266
	);
267 View Code Duplication
	if ($smcFunc['db_num_rows']($request) != 0)
268
		list ($id_report, $ignore) = $smcFunc['db_fetch_row']($request);
269
270
	$smcFunc['db_free_result']($request);
271
272
	// If we're just going to ignore these, then who gives a monkeys...
273
	if (!empty($ignore))
274
		redirectexit('topic=' . $topic . '.msg' . $_POST['msg'] . '#msg' . $_POST['msg']);
275
276
	// Already reported? My god, we could be dealing with a real rogue here...
277
	if (!empty($id_report))
278
		$smcFunc['db_query']('', '
279
			UPDATE {db_prefix}log_reported
280
			SET num_reports = num_reports + 1, time_updated = {int:current_time}
281
			WHERE id_report = {int:id_report}',
282
			array(
283
				'current_time' => time(),
284
				'id_report' => $id_report,
285
			)
286
		);
287
	// Otherwise, we shall make one!
288
	else
289
	{
290
		if (empty($message['real_name']))
291
			$message['real_name'] = $message['poster_name'];
292
293
		$id_report = $smcFunc['db_insert']('',
294
			'{db_prefix}log_reported',
295
			array(
296
				'id_msg' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'id_member' => 'int', 'membername' => 'string',
297
				'subject' => 'string', 'body' => 'string', 'time_started' => 'int', 'time_updated' => 'int',
298
				'num_reports' => 'int', 'closed' => 'int',
299
			),
300
			array(
301
				$_POST['msg'], $message['id_topic'], $message['id_board'], $message['id_poster'], $message['real_name'],
302
				$message['subject'], $message['body'], time(), time(), 1, 0,
303
			),
304
			array('id_report'),
305
			1
306
		);
307
	}
308
309
	// Now just add our report...
310 View Code Duplication
	if ($id_report)
311
	{
312
		$smcFunc['db_insert']('',
313
			'{db_prefix}log_reported_comments',
314
			array(
315
				'id_report' => 'int', 'id_member' => 'int', 'membername' => 'string',
316
				'member_ip' => 'inet', 'comment' => 'string', 'time_sent' => 'int',
317
			),
318
			array(
319
				$id_report, $user_info['id'], $user_info['name'],
320
				$user_info['ip'], $reason, time(),
321
			),
322
			array('id_comment')
323
		);
324
325
		// And get ready to notify people.
326
		$smcFunc['db_insert']('insert',
327
			'{db_prefix}background_tasks',
328
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
329
			array('$sourcedir/tasks/MsgReport-Notify.php', 'MsgReport_Notify_Background', $smcFunc['json_encode'](array(
330
				'report_id' => $id_report,
331
				'msg_id' => $_POST['msg'],
332
				'topic_id' => $message['id_topic'],
333
				'board_id' => $message['id_board'],
334
				'sender_id' => $context['user']['id'],
335
				'sender_name' => $context['user']['name'],
336
				'time' => time(),
337
			)), 0),
338
			array('id_task')
339
		);
340
	}
341
342
	// Keep track of when the mod reports get updated, that way we know when we need to look again.
343
	updateSettings(array('last_mod_report_action' => time()));
344
345
	// Back to the post we reported!
346
	redirectexit('reportsent;topic=' . $topic . '.msg' . $_POST['msg'] . '#msg' . $_POST['msg']);
347
}
348
349
/**
350
 * Actually reports a user's profile using information specified from a form
351
 *
352
 * @param int $id_member The ID of the member whose profile is being reported
353
 * @param string $reason The reason specified by the reporter for this report
354
 */
355
function reportUser($id_member, $reason)
356
{
357
	global $context, $smcFunc, $user_info;
358
359
	// Get the basic topic information, and make sure they can see it.
360
	$_POST['u'] = (int) $id_member;
361
362
	$request = $smcFunc['db_query']('', '
363
		SELECT id_member, real_name, member_name
364
		FROM {db_prefix}members
365
		WHERE id_member = {int:id_member}',
366
		array(
367
			'id_member' => $_POST['u']
368
		)
369
	);
370
	if ($smcFunc['db_num_rows']($request) == 0)
371
		fatal_lang_error('no_user', false);
372
	$user = $smcFunc['db_fetch_assoc']($request);
373
	$smcFunc['db_free_result']($request);
374
375
	$user_name = un_htmlspecialchars($user['real_name']) . ($user['real_name'] != $user['member_name'] ? ' (' . $user['member_name'] . ')' : '');
376
377
	$request = $smcFunc['db_query']('', '
378
		SELECT id_report, ignore_all
379
		FROM {db_prefix}log_reported
380
		WHERE id_member = {int:id_member}
381
			AND id_msg = {int:not_a_reported_post}
382
			AND (closed = {int:not_closed} OR ignore_all = {int:ignored})
383
		ORDER BY ignore_all DESC',
384
		array(
385
			'id_member' => $_POST['u'],
386
			'not_a_reported_post' => 0,
387
			'not_closed' => 0,
388
			'ignored' => 1,
389
		)
390
	);
391 View Code Duplication
	if ($smcFunc['db_num_rows']($request) != 0)
392
		list ($id_report, $ignore) = $smcFunc['db_fetch_row']($request);
393
394
	$smcFunc['db_free_result']($request);
395
396
	// If we're just going to ignore these, then who gives a monkeys...
397
	if (!empty($ignore))
398
		redirectexit('action=profile;u=' . $_POST['u']);
399
400
	// Already reported? My god, we could be dealing with a real rogue here...
401
	if (!empty($id_report))
402
		$smcFunc['db_query']('', '
403
			UPDATE {db_prefix}log_reported
404
			SET num_reports = num_reports + 1, time_updated = {int:current_time}
405
			WHERE id_report = {int:id_report}',
406
			array(
407
				'current_time' => time(),
408
				'id_report' => $id_report,
409
			)
410
		);
411
	// Otherwise, we shall make one!
412
	else
413
	{
414
		$id_report = $smcFunc['db_insert']('',
415
			'{db_prefix}log_reported',
416
			array(
417
				'id_msg' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'id_member' => 'int', 'membername' => 'string',
418
				'subject' => 'string', 'body' => 'string', 'time_started' => 'int', 'time_updated' => 'int',
419
				'num_reports' => 'int', 'closed' => 'int',
420
			),
421
			array(
422
				0, 0, 0, $user['id_member'], $user_name,
423
				'', '', time(), time(), 1, 0,
424
			),
425
			array('id_report'),
426
			1
427
		);
428
	}
429
430
	// Now just add our report...
431 View Code Duplication
	if ($id_report)
432
	{
433
		$smcFunc['db_insert']('',
434
			'{db_prefix}log_reported_comments',
435
			array(
436
				'id_report' => 'int', 'id_member' => 'int', 'membername' => 'string',
437
				'member_ip' => 'inet', 'comment' => 'string', 'time_sent' => 'int',
438
			),
439
			array(
440
				$id_report, $user_info['id'], $user_info['name'],
441
				$user_info['ip'], $reason, time(),
442
			),
443
			array('id_comment')
444
		);
445
446
		// And get ready to notify people.
447
		$smcFunc['db_insert']('insert',
448
			'{db_prefix}background_tasks',
449
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
450
			array('$sourcedir/tasks/MemberReport-Notify.php', 'MemberReport_Notify_Background', $smcFunc['json_encode'](array(
451
				'report_id' => $id_report,
452
				'user_id' => $user['id_member'],
453
				'user_name' => $user_name,
454
				'sender_id' => $context['user']['id'],
455
				'sender_name' => $context['user']['name'],
456
				'comment' => $reason,
457
				'time' => time(),
458
			)), 0),
459
			array('id_task')
460
		);
461
	}
462
463
	// Keep track of when the mod reports get updated, that way we know when we need to look again.
464
	updateSettings(array('last_mod_report_action' => time()));
465
466
	// Back to the post we reported!
467
	redirectexit('reportsent;action=profile;u=' . $id_member);
468
}
469
470
?>