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

GroupAct_Notify_Background::execute()   D

Complexity

Conditions 17
Paths 63

Size

Total Lines 132
Code Lines 72

Duplication

Lines 10
Ratio 7.58 %

Importance

Changes 0
Metric Value
cc 17
eloc 72
nc 63
nop 0
dl 10
loc 132
rs 4.8361
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 taks handles notifying someone that a user has
5
 * requeted to join a group they moderate.
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
/**
18
 * Class GroupAct_Notify_Background
19
 */
20
class GroupAct_Notify_Background extends SMF_BackgroundTask
21
{
22
    /**
23
     * This executes the task - loads up the information, puts the email in the queue and inserts alerts as needed.
24
     * @return bool Always returns true
25
     */
26
	public function execute()
27
	{
28
		global $sourcedir, $smcFunc, $language, $modSettings;
29
30
		// Get the details of all the members concerned...
31
		$request = $smcFunc['db_query']('', '
32
			SELECT lgr.id_request, lgr.id_member, lgr.id_group, mem.email_address,
33
				mem.lngfile, mem.member_name,  mg.group_name
34
			FROM {db_prefix}log_group_requests AS lgr
35
				INNER JOIN {db_prefix}members AS mem ON (mem.id_member = lgr.id_member)
36
				INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = lgr.id_group)
37
			WHERE lgr.id_request IN ({array_int:request_list})
38
			ORDER BY mem.lngfile',
39
			array(
40
				'request_list' => $this->_details['request_list'],
41
			)
42
		);
43
		$affected_users = array();
44
		$members = array();
45
		$alert_rows = array();
46
		while ($row = $smcFunc['db_fetch_assoc']($request))
47
		{
48
			$members[] = $row['id_member'];
49
			$row['lngfile'] = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
50
51
			// If we are approving, add them!
52
			if ($this->_details['status'] == 'approve')
53
			{
54
				// Hack in blank permissions so that allowedTo() will fail.
55
				require_once($sourcedir . '/Security.php');
56
				$user_info['permissions'] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$user_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $user_info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
57
58
				// For the moddlog
59
				$user_info['id'] = $this->_details['member_id'];
60
				$user_info['ip'] = $this->_details['member_ip'];
61
62
				require_once($sourcedir . '/Subs-Membergroups.php');
63
				addMembersToGroup($row['id_member'], $row['id_group'], 'auto', true);
64
			}
65
66
			// Build the required information array
67
			$affected_users[] = array(
68
				'rid' => $row['id_request'],
69
				'member_id' => $row['id_member'],
70
				'member_name' => $row['member_name'],
71
				'group_id' => $row['id_group'],
72
				'group_name' => $row['group_name'],
73
				'email' => $row['email_address'],
74
				'language' => $row['lngfile'],
75
			);
76
		}
77
		$smcFunc['db_free_result']($request);
78
79
		// Ensure everyone who is online gets their changes right away.
80
		updateSettings(array('settings_updated' => time()));
81
82
		if (!empty($affected_users))
83
		{
84
			require_once($sourcedir . '/Subs-Notify.php');
85
			$prefs = getNotifyPrefs($members, array('groupr_approved', 'groupr_rejected'), true);
86
87
			// They are being approved?
88
			if ($this->_details['status'] == 'approve')
89
			{
90
				$pref_name = 'approved';
91
				$email_template_name = 'mc_group_approve';
92
				$email_message_id_prefix = 'grpapp';
93
			}
94
			// Otherwise, they are getting rejected (With or without a reason).
95
			else
96
			{
97
				$pref_name = 'rejected';
98
				$email_template_name = empty($custom_reason) ? 'mc_group_reject' : 'mc_group_reject_reason';
0 ignored issues
show
Bug introduced by
The variable $custom_reason seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
99
				$email_message_id_prefix = 'grprej';
100
			}
101
102
			// Same as for approving, kind of.
103
			foreach ($affected_users as $user)
104
			{
105
				$pref = !empty($prefs[$user['member_id']]['groupr_' . $pref_name]) ? $prefs[$user['member_id']]['groupr_' . $pref_name] : 0;
106
				$custom_reason = isset($this->_details['reason']) && isset($this->_details['reason'][$user['rid']]) ? $this->_details['reason'][$user['rid']] : '';
107
108
				if ($pref & 0x01)
109
				{
110
					$alert_rows[] = array(
111
						'alert_time' => time(),
112
						'id_member' => $user['member_id'],
113
						'content_type' => 'groupr',
114
						'content_id' => 0,
115
						'content_action' => $pref_name,
116
						'is_read' => 0,
117
						'extra' => $smcFunc['json_encode'](array('group_name' => $user['group_name'], 'reason' => !empty($custom_reason) ? '<br><br>' . $custom_reason : '')),
118
					);
119
					updateMemberData($user['member_id'], array('alerts' => '+'));
120
				}
121
122
				if ($pref & 0x02)
123
				{
124
					// Emails are a bit complicated. We have to do language stuff.
125
					require_once($sourcedir . '/Subs-Post.php');
126
					require_once($sourcedir . '/ScheduledTasks.php');
127
					loadEssentialThemeData();
128
129
					$replacements = array(
130
						'USERNAME' => $user['member_name'],
131
						'GROUPNAME' => $user['group_name'],
132
					);
133
134
					if (!empty($custom_reason))
135
						$replacements['REASON'] = $custom_reason;
136
137
					$emaildata = loadEmailTemplate($email_template_name, $replacements, $user['language']);
138
139
					sendmail($user['email'], $emaildata['subject'], $emaildata['body'], null, $email_message_id_prefix . $user['rid'], $emaildata['is_html'], 2);
140
				}
141
			}
142
143
			// Insert the alerts if any
144 View Code Duplication
			if (!empty($alert_rows))
145
				$smcFunc['db_insert']('',
146
					'{db_prefix}user_alerts',
147
					array(
148
						'alert_time' => 'int', 'id_member' => 'int', 'content_type' => 'string',
149
						'content_id' => 'int', 'content_action' => 'string', 'is_read' => 'int', 'extra' => 'string',
150
					),
151
					$alert_rows,
152
					array()
153
				);
154
		}
155
156
		return true;
157
	}
158
}
159
160
?>