Failed Conditions
Pull Request — newinternal-bugfixing (#286)
by Simon
06:57 queued 03:32
created
includes/Pages/RequestAction/PageComment.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -15,51 +15,51 @@
 block discarded – undo
15 15
 
16 16
 class PageComment extends RequestActionBase
17 17
 {
18
-    /**
19
-     * Main function for this page, when no specific actions are called.
20
-     * @return void
21
-     */
22
-    protected function main()
23
-    {
24
-        $this->checkPosted();
25
-        $database = $this->getDatabase();
26
-        $request = $this->getRequest($database);
18
+	/**
19
+	 * Main function for this page, when no specific actions are called.
20
+	 * @return void
21
+	 */
22
+	protected function main()
23
+	{
24
+		$this->checkPosted();
25
+		$database = $this->getDatabase();
26
+		$request = $this->getRequest($database);
27 27
 
28
-        $commentText = WebRequest::postString('comment');
29
-        if ($commentText === false || $commentText == '') {
30
-            $this->redirect('viewRequest', null, array('id' => $request->getId()));
28
+		$commentText = WebRequest::postString('comment');
29
+		if ($commentText === false || $commentText == '') {
30
+			$this->redirect('viewRequest', null, array('id' => $request->getId()));
31 31
 
32
-            return;
33
-        }
32
+			return;
33
+		}
34 34
 
35
-        //Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
36
-        $ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
37
-        $ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
35
+		//Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
36
+		$ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
37
+		$ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
38 38
 
39
-        $overridePolicy = WebRequest::postBoolean('privpol-check-override');
39
+		$overridePolicy = WebRequest::postBoolean('privpol-check-override');
40 40
 
41
-        if ((preg_match($ipv4Regex, $commentText) || preg_match($ipv6Regex, $commentText)) && !$overridePolicy) {
42
-            $this->assignCSRFToken();
43
-            $this->assign("request", $request);
44
-            $this->assign("comment", $commentText);
45
-            $this->setTemplate("privpol-warning.tpl");
41
+		if ((preg_match($ipv4Regex, $commentText) || preg_match($ipv6Regex, $commentText)) && !$overridePolicy) {
42
+			$this->assignCSRFToken();
43
+			$this->assign("request", $request);
44
+			$this->assign("comment", $commentText);
45
+			$this->setTemplate("privpol-warning.tpl");
46 46
 
47
-            return;
48
-        }
47
+			return;
48
+		}
49 49
 
50
-        $visibility = WebRequest::postBoolean('adminOnly') ? 'admin' : 'user';
50
+		$visibility = WebRequest::postBoolean('adminOnly') ? 'admin' : 'user';
51 51
 
52
-        $comment = new Comment();
53
-        $comment->setDatabase($database);
52
+		$comment = new Comment();
53
+		$comment->setDatabase($database);
54 54
 
55
-        $comment->setRequest($request->getId());
56
-        $comment->setVisibility($visibility);
57
-        $comment->setUser(User::getCurrent($database)->getId());
58
-        $comment->setComment($commentText);
55
+		$comment->setRequest($request->getId());
56
+		$comment->setVisibility($visibility);
57
+		$comment->setUser(User::getCurrent($database)->getId());
58
+		$comment->setComment($commentText);
59 59
 
60
-        $comment->save();
60
+		$comment->save();
61 61
 
62
-        $this->getNotificationHelper()->commentCreated($comment, $request);
63
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
64
-    }
62
+		$this->getNotificationHelper()->commentCreated($comment, $request);
63
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
64
+	}
65 65
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageReservation.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -17,58 +17,58 @@
 block discarded – undo
17 17
 
18 18
 class PageReservation extends RequestActionBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no specific actions are called.
22
-     * @throws ApplicationLogicException
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->checkPosted();
27
-        $database = $this->getDatabase();
28
-        $request = $this->getRequest($database);
20
+	/**
21
+	 * Main function for this page, when no specific actions are called.
22
+	 * @throws ApplicationLogicException
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->checkPosted();
27
+		$database = $this->getDatabase();
28
+		$request = $this->getRequest($database);
29 29
 
30
-        $closureDate = $request->getClosureDate();
30
+		$closureDate = $request->getClosureDate();
31 31
 
32
-        $date = new DateTime();
33
-        $date->modify("-7 days");
34
-        $oneweek = $date->format("Y-m-d H:i:s");
32
+		$date = new DateTime();
33
+		$date->modify("-7 days");
34
+		$oneweek = $date->format("Y-m-d H:i:s");
35 35
 
36
-        $currentUser = User::getCurrent($database);
37
-        if ($request->getStatus() == "Closed" && $closureDate < $oneweek) {
38
-            if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
39
-                throw new ApplicationLogicException(
40
-                    "You are not allowed to reserve a request that has been closed for over a week.");
41
-            }
42
-        }
36
+		$currentUser = User::getCurrent($database);
37
+		if ($request->getStatus() == "Closed" && $closureDate < $oneweek) {
38
+			if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
39
+				throw new ApplicationLogicException(
40
+					"You are not allowed to reserve a request that has been closed for over a week.");
41
+			}
42
+		}
43 43
 
44
-        if ($request->getReserved() !== null && $request->getReserved() != $currentUser->getId()) {
45
-            throw new ApplicationLogicException("Request is already reserved!");
46
-        }
44
+		if ($request->getReserved() !== null && $request->getReserved() != $currentUser->getId()) {
45
+			throw new ApplicationLogicException("Request is already reserved!");
46
+		}
47 47
 
48
-        if ($request->getReserved() === null) {
49
-            // Check the number of requests a user has reserved already
50
-            $doubleReserveCountQuery = $database->prepare("SELECT COUNT(*) FROM request WHERE reserved = :userid;");
51
-            $doubleReserveCountQuery->bindValue(":userid", $currentUser->getId());
52
-            $doubleReserveCountQuery->execute();
53
-            $doubleReserveCount = $doubleReserveCountQuery->fetchColumn();
54
-            $doubleReserveCountQuery->closeCursor();
48
+		if ($request->getReserved() === null) {
49
+			// Check the number of requests a user has reserved already
50
+			$doubleReserveCountQuery = $database->prepare("SELECT COUNT(*) FROM request WHERE reserved = :userid;");
51
+			$doubleReserveCountQuery->bindValue(":userid", $currentUser->getId());
52
+			$doubleReserveCountQuery->execute();
53
+			$doubleReserveCount = $doubleReserveCountQuery->fetchColumn();
54
+			$doubleReserveCountQuery->closeCursor();
55 55
 
56
-            // User already has at least one reserved.
57
-            if ($doubleReserveCount != 0) {
58
-                SessionAlert::warning("You have multiple requests reserved!");
59
-            }
56
+			// User already has at least one reserved.
57
+			if ($doubleReserveCount != 0) {
58
+				SessionAlert::warning("You have multiple requests reserved!");
59
+			}
60 60
 
61
-            $request->setReserved($currentUser->getId());
62
-            $request->setUpdateVersion(WebRequest::postInt('updateversion'));
63
-            $request->save();
61
+			$request->setReserved($currentUser->getId());
62
+			$request->setUpdateVersion(WebRequest::postInt('updateversion'));
63
+			$request->save();
64 64
 
65
-            Logger::reserve($database, $request);
65
+			Logger::reserve($database, $request);
66 66
 
67
-            $this->getNotificationHelper()->requestReserved($request);
67
+			$this->getNotificationHelper()->requestReserved($request);
68 68
 
69
-            SessionAlert::success("Reserved request {$request->getId()}.");
70
-        }
69
+			SessionAlert::success("Reserved request {$request->getId()}.");
70
+		}
71 71
 
72
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
73
-    }
72
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
73
+	}
74 74
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageCloseRequest.php 1 patch
Indentation   +236 added lines, -236 removed lines patch added patch discarded remove patch
@@ -20,240 +20,240 @@
 block discarded – undo
20 20
 
21 21
 class PageCloseRequest extends RequestActionBase
22 22
 {
23
-    protected function main()
24
-    {
25
-        $this->processClose();
26
-    }
27
-
28
-    /**
29
-     * Main function for this page, when no specific actions are called.
30
-     * @throws ApplicationLogicException
31
-     */
32
-    final protected function processClose()
33
-    {
34
-        $this->checkPosted();
35
-        $database = $this->getDatabase();
36
-
37
-        $currentUser = User::getCurrent($database);
38
-        $template = $this->getTemplate($database);
39
-        $request = $this->getRequest($database);
40
-
41
-        if ($request->getStatus() === 'Closed') {
42
-            throw new ApplicationLogicException('Request is already closed');
43
-        }
44
-
45
-        if ($this->confirmEmailAlreadySent($request, $template)) {
46
-            return;
47
-        }
48
-
49
-        if ($this->confirmReserveOverride($request, $template, $currentUser, $database)) {
50
-            return;
51
-        }
52
-
53
-        if ($this->confirmAccountCreated($request, $template)) {
54
-            return;
55
-        }
56
-
57
-        // I think we're good here...
58
-        $request->setStatus('Closed');
59
-        $request->setReserved(null);
60
-
61
-        Logger::closeRequest($database, $request, $template->getId(), null);
62
-
63
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
64
-        $request->save();
65
-
66
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
67
-        // be rolled back.
68
-
69
-        $this->getNotificationHelper()->requestClosed($request, $template->getName());
70
-        SessionAlert::success("Request {$request->getId()} has been closed");
71
-
72
-        $this->sendMail($request, $template->getText(), $currentUser, false);
73
-
74
-        $this->redirect();
75
-    }
76
-
77
-    /**
78
-     * @param PdoDatabase $database
79
-     *
80
-     * @return EmailTemplate
81
-     * @throws ApplicationLogicException
82
-     */
83
-    protected function getTemplate(PdoDatabase $database)
84
-    {
85
-        $templateId = WebRequest::postInt('template');
86
-        if ($templateId === null) {
87
-            throw new ApplicationLogicException('No template specified');
88
-        }
89
-
90
-        /** @var EmailTemplate $template */
91
-        $template = EmailTemplate::getById($templateId, $database);
92
-        if ($template === false || !$template->getActive()) {
93
-            throw new ApplicationLogicException('Invalid or inactive template specified');
94
-        }
95
-
96
-        return $template;
97
-    }
98
-
99
-    /**
100
-     * @param Request       $request
101
-     * @param EmailTemplate $template
102
-     *
103
-     * @return bool
104
-     */
105
-    protected function confirmEmailAlreadySent(Request $request, EmailTemplate $template)
106
-    {
107
-        if ($this->checkEmailAlreadySent($request)) {
108
-            $this->showConfirmation($request, $template, 'close-confirmations/email-sent.tpl');
109
-
110
-            return true;
111
-        }
112
-
113
-        return false;
114
-    }
115
-
116
-    protected function checkEmailAlreadySent(Request $request)
117
-    {
118
-        if ($request->getEmailSent() && !WebRequest::postBoolean('emailSentOverride')) {
119
-            return true;
120
-        }
121
-
122
-        return false;
123
-    }
124
-
125
-    protected function checkReserveOverride(Request $request, User $currentUser)
126
-    {
127
-        $reservationId = $request->getReserved();
128
-
129
-        if ($reservationId !== 0 && $reservationId !== null) {
130
-            if (!WebRequest::postBoolean('reserveOverride')) {
131
-                if ($currentUser->getId() !== $reservationId) {
132
-                    return true;
133
-                }
134
-            }
135
-        }
136
-
137
-        return false;
138
-    }
139
-
140
-    /**
141
-     * @param Request       $request
142
-     * @param EmailTemplate $template
143
-     * @param User          $currentUser
144
-     * @param PdoDatabase   $database
145
-     *
146
-     * @return bool
147
-     */
148
-    protected function confirmReserveOverride(
149
-        Request $request,
150
-        EmailTemplate $template,
151
-        User $currentUser,
152
-        PdoDatabase $database
153
-    ) {
154
-        if ($this->checkReserveOverride($request, $currentUser)) {
155
-            $this->assign('reserveUser', User::getById($request->getReserved(), $database)->getUsername());
156
-            $this->showConfirmation($request, $template, 'close-confirmations/reserve-override.tpl');
157
-
158
-            return true;
159
-        }
160
-
161
-        return false;
162
-    }
163
-
164
-    /**
165
-     * @param Request       $request
166
-     * @param EmailTemplate $template
167
-     *
168
-     * @return bool
169
-     * @throws \Waca\Exceptions\CurlException
170
-     */
171
-    protected function confirmAccountCreated(Request $request, EmailTemplate $template)
172
-    {
173
-        if ($this->checkAccountCreated($request, $template)) {
174
-            $this->showConfirmation($request, $template, 'close-confirmations/account-created.tpl');
175
-
176
-            return true;
177
-        }
178
-
179
-        return false;
180
-    }
181
-
182
-    protected function checkAccountCreated(Request $request, EmailTemplate $template)
183
-    {
184
-        if ($template->getDefaultAction() === EmailTemplate::CREATED && !WebRequest::postBoolean('createOverride')) {
185
-            $parameters = array(
186
-                'action'  => 'query',
187
-                'list'    => 'users',
188
-                'format'  => 'php',
189
-                'ususers' => $request->getName(),
190
-            );
191
-
192
-            $content = $this->getHttpHelper()->get($this->getSiteConfiguration()->getMediawikiWebServiceEndpoint(),
193
-                $parameters);
194
-
195
-            $apiResult = unserialize($content);
196
-            $exists = !isset($apiResult['query']['users']['0']['missing']);
197
-
198
-            if (!$exists) {
199
-                return true;
200
-            }
201
-        }
202
-
203
-        return false;
204
-    }
205
-
206
-    /**
207
-     * @param Request $request
208
-     * @param string  $mailText
209
-     * @param User    $currentUser
210
-     * @param boolean $ccMailingList
211
-     */
212
-    protected function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
213
-    {
214
-        $headers = array(
215
-            'X-ACC-Request' => $request->getId(),
216
-            'X-ACC-UserID'  => $currentUser->getId(),
217
-        );
218
-
219
-        if ($ccMailingList) {
220
-            $headers['Cc'] = '[email protected]';
221
-        }
222
-
223
-        $helper = $this->getEmailHelper();
224
-
225
-        $emailSig = $currentUser->getEmailSig();
226
-        if ($emailSig !== '' || $emailSig !== null) {
227
-            $emailSig = "\n\n" . $emailSig;
228
-        }
229
-
230
-        $subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
231
-        $content = $mailText . $emailSig;
232
-
233
-        $helper->sendMail($request->getEmail(), $subject, $content, $headers);
234
-
235
-        $request->setEmailSent(true);
236
-    }
237
-
238
-    /**
239
-     * @param Request       $request
240
-     * @param EmailTemplate $template
241
-     * @param string        $templateName
242
-     *
243
-     * @throws Exception
244
-     * @return void
245
-     */
246
-    protected function showConfirmation(Request $request, EmailTemplate $template, $templateName)
247
-    {
248
-        $this->assignCSRFToken();
249
-
250
-        $this->assign('request', $request->getId());
251
-        $this->assign('template', $template->getId());
252
-
253
-        $this->assign('emailSentOverride', WebRequest::postBoolean('emailSentOverride') ? 'true' : 'false');
254
-        $this->assign('reserveOverride', WebRequest::postBoolean('reserveOverride') ? 'true' : 'false');
255
-        $this->assign('createOverride', WebRequest::postBoolean('createOverride') ? 'true' : 'false');
256
-
257
-        $this->setTemplate($templateName);
258
-    }
23
+	protected function main()
24
+	{
25
+		$this->processClose();
26
+	}
27
+
28
+	/**
29
+	 * Main function for this page, when no specific actions are called.
30
+	 * @throws ApplicationLogicException
31
+	 */
32
+	final protected function processClose()
33
+	{
34
+		$this->checkPosted();
35
+		$database = $this->getDatabase();
36
+
37
+		$currentUser = User::getCurrent($database);
38
+		$template = $this->getTemplate($database);
39
+		$request = $this->getRequest($database);
40
+
41
+		if ($request->getStatus() === 'Closed') {
42
+			throw new ApplicationLogicException('Request is already closed');
43
+		}
44
+
45
+		if ($this->confirmEmailAlreadySent($request, $template)) {
46
+			return;
47
+		}
48
+
49
+		if ($this->confirmReserveOverride($request, $template, $currentUser, $database)) {
50
+			return;
51
+		}
52
+
53
+		if ($this->confirmAccountCreated($request, $template)) {
54
+			return;
55
+		}
56
+
57
+		// I think we're good here...
58
+		$request->setStatus('Closed');
59
+		$request->setReserved(null);
60
+
61
+		Logger::closeRequest($database, $request, $template->getId(), null);
62
+
63
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
64
+		$request->save();
65
+
66
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
67
+		// be rolled back.
68
+
69
+		$this->getNotificationHelper()->requestClosed($request, $template->getName());
70
+		SessionAlert::success("Request {$request->getId()} has been closed");
71
+
72
+		$this->sendMail($request, $template->getText(), $currentUser, false);
73
+
74
+		$this->redirect();
75
+	}
76
+
77
+	/**
78
+	 * @param PdoDatabase $database
79
+	 *
80
+	 * @return EmailTemplate
81
+	 * @throws ApplicationLogicException
82
+	 */
83
+	protected function getTemplate(PdoDatabase $database)
84
+	{
85
+		$templateId = WebRequest::postInt('template');
86
+		if ($templateId === null) {
87
+			throw new ApplicationLogicException('No template specified');
88
+		}
89
+
90
+		/** @var EmailTemplate $template */
91
+		$template = EmailTemplate::getById($templateId, $database);
92
+		if ($template === false || !$template->getActive()) {
93
+			throw new ApplicationLogicException('Invalid or inactive template specified');
94
+		}
95
+
96
+		return $template;
97
+	}
98
+
99
+	/**
100
+	 * @param Request       $request
101
+	 * @param EmailTemplate $template
102
+	 *
103
+	 * @return bool
104
+	 */
105
+	protected function confirmEmailAlreadySent(Request $request, EmailTemplate $template)
106
+	{
107
+		if ($this->checkEmailAlreadySent($request)) {
108
+			$this->showConfirmation($request, $template, 'close-confirmations/email-sent.tpl');
109
+
110
+			return true;
111
+		}
112
+
113
+		return false;
114
+	}
115
+
116
+	protected function checkEmailAlreadySent(Request $request)
117
+	{
118
+		if ($request->getEmailSent() && !WebRequest::postBoolean('emailSentOverride')) {
119
+			return true;
120
+		}
121
+
122
+		return false;
123
+	}
124
+
125
+	protected function checkReserveOverride(Request $request, User $currentUser)
126
+	{
127
+		$reservationId = $request->getReserved();
128
+
129
+		if ($reservationId !== 0 && $reservationId !== null) {
130
+			if (!WebRequest::postBoolean('reserveOverride')) {
131
+				if ($currentUser->getId() !== $reservationId) {
132
+					return true;
133
+				}
134
+			}
135
+		}
136
+
137
+		return false;
138
+	}
139
+
140
+	/**
141
+	 * @param Request       $request
142
+	 * @param EmailTemplate $template
143
+	 * @param User          $currentUser
144
+	 * @param PdoDatabase   $database
145
+	 *
146
+	 * @return bool
147
+	 */
148
+	protected function confirmReserveOverride(
149
+		Request $request,
150
+		EmailTemplate $template,
151
+		User $currentUser,
152
+		PdoDatabase $database
153
+	) {
154
+		if ($this->checkReserveOverride($request, $currentUser)) {
155
+			$this->assign('reserveUser', User::getById($request->getReserved(), $database)->getUsername());
156
+			$this->showConfirmation($request, $template, 'close-confirmations/reserve-override.tpl');
157
+
158
+			return true;
159
+		}
160
+
161
+		return false;
162
+	}
163
+
164
+	/**
165
+	 * @param Request       $request
166
+	 * @param EmailTemplate $template
167
+	 *
168
+	 * @return bool
169
+	 * @throws \Waca\Exceptions\CurlException
170
+	 */
171
+	protected function confirmAccountCreated(Request $request, EmailTemplate $template)
172
+	{
173
+		if ($this->checkAccountCreated($request, $template)) {
174
+			$this->showConfirmation($request, $template, 'close-confirmations/account-created.tpl');
175
+
176
+			return true;
177
+		}
178
+
179
+		return false;
180
+	}
181
+
182
+	protected function checkAccountCreated(Request $request, EmailTemplate $template)
183
+	{
184
+		if ($template->getDefaultAction() === EmailTemplate::CREATED && !WebRequest::postBoolean('createOverride')) {
185
+			$parameters = array(
186
+				'action'  => 'query',
187
+				'list'    => 'users',
188
+				'format'  => 'php',
189
+				'ususers' => $request->getName(),
190
+			);
191
+
192
+			$content = $this->getHttpHelper()->get($this->getSiteConfiguration()->getMediawikiWebServiceEndpoint(),
193
+				$parameters);
194
+
195
+			$apiResult = unserialize($content);
196
+			$exists = !isset($apiResult['query']['users']['0']['missing']);
197
+
198
+			if (!$exists) {
199
+				return true;
200
+			}
201
+		}
202
+
203
+		return false;
204
+	}
205
+
206
+	/**
207
+	 * @param Request $request
208
+	 * @param string  $mailText
209
+	 * @param User    $currentUser
210
+	 * @param boolean $ccMailingList
211
+	 */
212
+	protected function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
213
+	{
214
+		$headers = array(
215
+			'X-ACC-Request' => $request->getId(),
216
+			'X-ACC-UserID'  => $currentUser->getId(),
217
+		);
218
+
219
+		if ($ccMailingList) {
220
+			$headers['Cc'] = '[email protected]';
221
+		}
222
+
223
+		$helper = $this->getEmailHelper();
224
+
225
+		$emailSig = $currentUser->getEmailSig();
226
+		if ($emailSig !== '' || $emailSig !== null) {
227
+			$emailSig = "\n\n" . $emailSig;
228
+		}
229
+
230
+		$subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
231
+		$content = $mailText . $emailSig;
232
+
233
+		$helper->sendMail($request->getEmail(), $subject, $content, $headers);
234
+
235
+		$request->setEmailSent(true);
236
+	}
237
+
238
+	/**
239
+	 * @param Request       $request
240
+	 * @param EmailTemplate $template
241
+	 * @param string        $templateName
242
+	 *
243
+	 * @throws Exception
244
+	 * @return void
245
+	 */
246
+	protected function showConfirmation(Request $request, EmailTemplate $template, $templateName)
247
+	{
248
+		$this->assignCSRFToken();
249
+
250
+		$this->assign('request', $request->getId());
251
+		$this->assign('template', $template->getId());
252
+
253
+		$this->assign('emailSentOverride', WebRequest::postBoolean('emailSentOverride') ? 'true' : 'false');
254
+		$this->assign('reserveOverride', WebRequest::postBoolean('reserveOverride') ? 'true' : 'false');
255
+		$this->assign('createOverride', WebRequest::postBoolean('createOverride') ? 'true' : 'false');
256
+
257
+		$this->setTemplate($templateName);
258
+	}
259 259
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageDeferRequest.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -17,57 +17,57 @@
 block discarded – undo
17 17
 
18 18
 class PageDeferRequest extends RequestActionBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no specific actions are called.
22
-     * @throws ApplicationLogicException
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->checkPosted();
27
-        $database = $this->getDatabase();
28
-        $request = $this->getRequest($database);
29
-        $currentUser = User::getCurrent($database);
20
+	/**
21
+	 * Main function for this page, when no specific actions are called.
22
+	 * @throws ApplicationLogicException
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->checkPosted();
27
+		$database = $this->getDatabase();
28
+		$request = $this->getRequest($database);
29
+		$currentUser = User::getCurrent($database);
30 30
 
31
-        $target = WebRequest::postString('target');
32
-        $requestStates = $this->getSiteConfiguration()->getRequestStates();
31
+		$target = WebRequest::postString('target');
32
+		$requestStates = $this->getSiteConfiguration()->getRequestStates();
33 33
 
34
-        if (!array_key_exists($target, $requestStates)) {
35
-            throw new ApplicationLogicException('Defer target not valid');
36
-        }
34
+		if (!array_key_exists($target, $requestStates)) {
35
+			throw new ApplicationLogicException('Defer target not valid');
36
+		}
37 37
 
38
-        if ($request->getStatus() == $target) {
39
-            SessionAlert::warning('This request is already in the specified queue.');
40
-            $this->redirect('viewRequest', null, array('id' => $request->getId()));
38
+		if ($request->getStatus() == $target) {
39
+			SessionAlert::warning('This request is already in the specified queue.');
40
+			$this->redirect('viewRequest', null, array('id' => $request->getId()));
41 41
 
42
-            return;
43
-        }
42
+			return;
43
+		}
44 44
 
45
-        $closureDate = $request->getClosureDate();
46
-        $date = new DateTime();
47
-        $date->modify("-7 days");
48
-        $oneweek = $date->format("Y-m-d H:i:s");
45
+		$closureDate = $request->getClosureDate();
46
+		$date = new DateTime();
47
+		$date->modify("-7 days");
48
+		$oneweek = $date->format("Y-m-d H:i:s");
49 49
 
50 50
 
51
-        if ($request->getStatus() == "Closed" && $closureDate < $oneweek) {
52
-            if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
53
-                throw new ApplicationLogicException(
54
-                    "You are not allowed to re-open a request that has been closed for over a week.");
55
-            }
56
-        }
51
+		if ($request->getStatus() == "Closed" && $closureDate < $oneweek) {
52
+			if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
53
+				throw new ApplicationLogicException(
54
+					"You are not allowed to re-open a request that has been closed for over a week.");
55
+			}
56
+		}
57 57
 
58
-        $request->setReserved(null);
59
-        $request->setStatus($target);
60
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
61
-        $request->save();
58
+		$request->setReserved(null);
59
+		$request->setStatus($target);
60
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
61
+		$request->save();
62 62
 
63
-        $deto = $requestStates[$target]['deferto'];
64
-        $detolog = $requestStates[$target]['defertolog'];
63
+		$deto = $requestStates[$target]['deferto'];
64
+		$detolog = $requestStates[$target]['defertolog'];
65 65
 
66
-        Logger::deferRequest($database, $request, $detolog);
66
+		Logger::deferRequest($database, $request, $detolog);
67 67
 
68
-        $this->getNotificationHelper()->requestDeferred($request);
69
-        SessionAlert::success("Request {$request->getId()} deferred to {$deto}");
68
+		$this->getNotificationHelper()->requestDeferred($request);
69
+		SessionAlert::success("Request {$request->getId()} deferred to {$deto}");
70 70
 
71
-        $this->redirect();
72
-    }
71
+		$this->redirect();
72
+	}
73 73
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageCustomClose.php 1 patch
Indentation   +260 added lines, -260 removed lines patch added patch discarded remove patch
@@ -23,264 +23,264 @@
 block discarded – undo
23 23
 
24 24
 class PageCustomClose extends PageCloseRequest
25 25
 {
26
-    use RequestData;
27
-
28
-    protected function main()
29
-    {
30
-        $database = $this->getDatabase();
31
-
32
-        $request = $this->getRequest($database);
33
-        $currentUser = User::getCurrent($this->getDatabase());
34
-
35
-        if ($request->getStatus() === 'Closed') {
36
-            throw new ApplicationLogicException('Request is already closed');
37
-        }
38
-
39
-        // Dual-mode page
40
-        if (WebRequest::wasPosted()) {
41
-            $this->validateCSRFToken();
42
-            $this->doCustomClose($currentUser, $request, $database);
43
-
44
-            $this->redirect();
45
-        }
46
-        else {
47
-            $this->assignCSRFToken();
48
-            $this->showCustomCloseForm($database, $request);
49
-        }
50
-    }
51
-
52
-    /**
53
-     * @param $database
54
-     *
55
-     * @return Request
56
-     * @throws ApplicationLogicException
57
-     */
58
-    protected function getRequest(PdoDatabase $database)
59
-    {
60
-        $requestId = WebRequest::getInt('request');
61
-        if ($requestId === null) {
62
-            throw new ApplicationLogicException('Request ID not found');
63
-        }
64
-
65
-        /** @var Request $request */
66
-        $request = Request::getById($requestId, $database);
67
-
68
-        if ($request === false) {
69
-            throw new ApplicationLogicException('Request not found');
70
-        }
71
-
72
-        return $request;
73
-    }
74
-
75
-    /**
76
-     * @param PdoDatabase $database
77
-     *
78
-     * @return EmailTemplate|null
79
-     */
80
-    protected function getTemplate(PdoDatabase $database)
81
-    {
82
-        $templateId = WebRequest::getInt('template');
83
-        if ($templateId === null) {
84
-            return null;
85
-        }
86
-
87
-        /** @var EmailTemplate $template */
88
-        $template = EmailTemplate::getById($templateId, $database);
89
-        if ($template === false || !$template->getActive()) {
90
-            return null;
91
-        }
92
-
93
-        return $template;
94
-    }
95
-
96
-    /**
97
-     * @param $database
98
-     * @param $request
99
-     *
100
-     * @throws Exception
101
-     */
102
-    protected function showCustomCloseForm(PdoDatabase $database, Request $request)
103
-    {
104
-        $currentUser = User::getCurrent($database);
105
-        $config = $this->getSiteConfiguration();
106
-
107
-        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
108
-        if (!$allowedPrivateData) {
109
-            // we probably shouldn't be showing the user this form if they're not allowed to access private data...
110
-            throw new AccessDeniedException($this->getSecurityManager());
111
-        }
112
-
113
-        $template = $this->getTemplate($database);
114
-
115
-        // Preload data
116
-        $this->assign('defaultAction', '');
117
-        $this->assign('preloadText', '');
118
-        $this->assign('preloadTitle', '');
119
-
120
-        if ($template !== null) {
121
-            $this->assign('defaultAction', $template->getDefaultAction());
122
-            $this->assign('preloadText', $template->getText());
123
-            $this->assign('preloadTitle', $template->getName());
124
-        }
125
-
126
-        // Static data
127
-        $this->assign('requeststates', $config->getRequestStates());
128
-
129
-        // request data
130
-        $this->assign('requestId', $request->getIp());
131
-        $this->assign('updateVersion', $request->getUpdateVersion());
132
-        $this->setupBasicData($request, $config);
133
-        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
134
-        $this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
135
-
136
-        // IP location
137
-        $trustedIp = $this->getXffTrustProvider()->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
138
-        $this->assign('iplocation', $this->getLocationProvider()->getIpLocation($trustedIp));
139
-
140
-        // Confirmations
141
-        $this->assign('confirmEmailAlreadySent', $this->checkEmailAlreadySent($request));
142
-        $this->assign('confirmReserveOverride', $this->checkReserveOverride($request, $currentUser));
143
-
144
-        $this->assign('canSkipCcMailingList', $this->barrierTest('skipCcMailingList', $currentUser));
145
-
146
-        // template
147
-        $this->setTemplate('custom-close.tpl');
148
-    }
149
-
150
-    /**
151
-     * @param User        $currentUser
152
-     * @param Request     $request
153
-     * @param PdoDatabase $database
154
-     *
155
-     * @throws ApplicationLogicException
156
-     */
157
-    protected function doCustomClose(User $currentUser, Request $request, PdoDatabase $database)
158
-    {
159
-        $messageBody = WebRequest::postString('msgbody');
160
-        if ($messageBody === null || trim($messageBody) === '') {
161
-            throw new ApplicationLogicException('Message body cannot be blank');
162
-        }
163
-
164
-        $ccMailingList = true;
165
-        if ($this->barrierTest('skipCcMailingList', $currentUser)) {
166
-            $ccMailingList = WebRequest::postBoolean('ccMailingList');
167
-        }
168
-
169
-        if ($request->getStatus() === 'Closed') {
170
-            throw new ApplicationLogicException('Request is already closed');
171
-        }
172
-
173
-        if (!(WebRequest::postBoolean('confirmEmailAlreadySent')
174
-            && WebRequest::postBoolean('confirmReserveOverride'))
175
-        ) {
176
-            throw new ApplicationLogicException('Not all confirmations checked');
177
-        }
178
-
179
-        $action = WebRequest::postString('action');
180
-        $availableRequestStates = $this->getSiteConfiguration()->getRequestStates();
181
-
182
-        if ($action === EmailTemplate::CREATED || $action === EmailTemplate::NOT_CREATED) {
183
-            // Close request
184
-            $this->closeRequest($request, $database, $action, $messageBody);
185
-
186
-            // Send the mail after the save, since save can be rolled back
187
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
188
-        }
189
-        else {
190
-            if (array_key_exists($action, $availableRequestStates)) {
191
-                // Defer to other state
192
-                $this->deferRequest($request, $database, $action, $availableRequestStates, $messageBody);
193
-
194
-                // Send the mail after the save, since save can be rolled back
195
-                $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
196
-            }
197
-            else {
198
-                $request->setReserved(null);
199
-                $request->setUpdateVersion(WebRequest::postInt('updateversion'));
200
-                $request->save();
201
-
202
-                // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
203
-                // and be rolled back.
204
-
205
-                // Send mail
206
-                $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
207
-
208
-                Logger::sentMail($database, $request, $messageBody);
209
-                Logger::unreserve($database, $request);
210
-
211
-                $this->getNotificationHelper()->sentMail($request);
212
-                SessionAlert::success("Sent mail to Request {$request->getId()}");
213
-            }
214
-        }
215
-    }
216
-
217
-    /**
218
-     * @param Request     $request
219
-     * @param PdoDatabase $database
220
-     * @param string      $action
221
-     * @param string      $messageBody
222
-     *
223
-     * @throws Exception
224
-     * @throws OptimisticLockFailedException
225
-     */
226
-    protected function closeRequest(Request $request, PdoDatabase $database, $action, $messageBody)
227
-    {
228
-        $request->setStatus('Closed');
229
-        $request->setReserved(null);
230
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
231
-        $request->save();
232
-
233
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
234
-        // be rolled back.
235
-
236
-        if ($action == EmailTemplate::CREATED) {
237
-            $logCloseType = 'custom-y';
238
-            $notificationCloseType = "Custom, Created";
239
-        }
240
-        else {
241
-            $logCloseType = 'custom-n';
242
-            $notificationCloseType = "Custom, Not Created";
243
-        }
244
-
245
-        Logger::closeRequest($database, $request, $logCloseType, $messageBody);
246
-        $this->getNotificationHelper()->requestClosed($request, $notificationCloseType);
247
-
248
-        $requestName = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
249
-        SessionAlert::success("Request {$request->getId()} ({$requestName}) marked as 'Done'.");
250
-    }
251
-
252
-    /**
253
-     * @param Request     $request
254
-     * @param PdoDatabase $database
255
-     * @param string      $action
256
-     * @param             $availableRequestStates
257
-     * @param string      $messageBody
258
-     *
259
-     * @throws Exception
260
-     * @throws OptimisticLockFailedException
261
-     */
262
-    protected function deferRequest(
263
-        Request $request,
264
-        PdoDatabase $database,
265
-        $action,
266
-        $availableRequestStates,
267
-        $messageBody
268
-    ) {
269
-        $request->setStatus($action);
270
-        $request->setReserved(null);
271
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
272
-        $request->save();
273
-
274
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
275
-        // and be rolled back.
276
-
277
-        $deferToLog = $availableRequestStates[$action]['defertolog'];
278
-        Logger::sentMail($database, $request, $messageBody);
279
-        Logger::deferRequest($database, $request, $deferToLog);
280
-
281
-        $this->getNotificationHelper()->requestDeferredWithMail($request);
282
-
283
-        $deferTo = $availableRequestStates[$action]['deferto'];
284
-        SessionAlert::success("Request {$request->getId()} deferred to $deferTo, sending an email.");
285
-    }
26
+	use RequestData;
27
+
28
+	protected function main()
29
+	{
30
+		$database = $this->getDatabase();
31
+
32
+		$request = $this->getRequest($database);
33
+		$currentUser = User::getCurrent($this->getDatabase());
34
+
35
+		if ($request->getStatus() === 'Closed') {
36
+			throw new ApplicationLogicException('Request is already closed');
37
+		}
38
+
39
+		// Dual-mode page
40
+		if (WebRequest::wasPosted()) {
41
+			$this->validateCSRFToken();
42
+			$this->doCustomClose($currentUser, $request, $database);
43
+
44
+			$this->redirect();
45
+		}
46
+		else {
47
+			$this->assignCSRFToken();
48
+			$this->showCustomCloseForm($database, $request);
49
+		}
50
+	}
51
+
52
+	/**
53
+	 * @param $database
54
+	 *
55
+	 * @return Request
56
+	 * @throws ApplicationLogicException
57
+	 */
58
+	protected function getRequest(PdoDatabase $database)
59
+	{
60
+		$requestId = WebRequest::getInt('request');
61
+		if ($requestId === null) {
62
+			throw new ApplicationLogicException('Request ID not found');
63
+		}
64
+
65
+		/** @var Request $request */
66
+		$request = Request::getById($requestId, $database);
67
+
68
+		if ($request === false) {
69
+			throw new ApplicationLogicException('Request not found');
70
+		}
71
+
72
+		return $request;
73
+	}
74
+
75
+	/**
76
+	 * @param PdoDatabase $database
77
+	 *
78
+	 * @return EmailTemplate|null
79
+	 */
80
+	protected function getTemplate(PdoDatabase $database)
81
+	{
82
+		$templateId = WebRequest::getInt('template');
83
+		if ($templateId === null) {
84
+			return null;
85
+		}
86
+
87
+		/** @var EmailTemplate $template */
88
+		$template = EmailTemplate::getById($templateId, $database);
89
+		if ($template === false || !$template->getActive()) {
90
+			return null;
91
+		}
92
+
93
+		return $template;
94
+	}
95
+
96
+	/**
97
+	 * @param $database
98
+	 * @param $request
99
+	 *
100
+	 * @throws Exception
101
+	 */
102
+	protected function showCustomCloseForm(PdoDatabase $database, Request $request)
103
+	{
104
+		$currentUser = User::getCurrent($database);
105
+		$config = $this->getSiteConfiguration();
106
+
107
+		$allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
108
+		if (!$allowedPrivateData) {
109
+			// we probably shouldn't be showing the user this form if they're not allowed to access private data...
110
+			throw new AccessDeniedException($this->getSecurityManager());
111
+		}
112
+
113
+		$template = $this->getTemplate($database);
114
+
115
+		// Preload data
116
+		$this->assign('defaultAction', '');
117
+		$this->assign('preloadText', '');
118
+		$this->assign('preloadTitle', '');
119
+
120
+		if ($template !== null) {
121
+			$this->assign('defaultAction', $template->getDefaultAction());
122
+			$this->assign('preloadText', $template->getText());
123
+			$this->assign('preloadTitle', $template->getName());
124
+		}
125
+
126
+		// Static data
127
+		$this->assign('requeststates', $config->getRequestStates());
128
+
129
+		// request data
130
+		$this->assign('requestId', $request->getIp());
131
+		$this->assign('updateVersion', $request->getUpdateVersion());
132
+		$this->setupBasicData($request, $config);
133
+		$this->setupReservationDetails($request->getReserved(), $database, $currentUser);
134
+		$this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
135
+
136
+		// IP location
137
+		$trustedIp = $this->getXffTrustProvider()->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
138
+		$this->assign('iplocation', $this->getLocationProvider()->getIpLocation($trustedIp));
139
+
140
+		// Confirmations
141
+		$this->assign('confirmEmailAlreadySent', $this->checkEmailAlreadySent($request));
142
+		$this->assign('confirmReserveOverride', $this->checkReserveOverride($request, $currentUser));
143
+
144
+		$this->assign('canSkipCcMailingList', $this->barrierTest('skipCcMailingList', $currentUser));
145
+
146
+		// template
147
+		$this->setTemplate('custom-close.tpl');
148
+	}
149
+
150
+	/**
151
+	 * @param User        $currentUser
152
+	 * @param Request     $request
153
+	 * @param PdoDatabase $database
154
+	 *
155
+	 * @throws ApplicationLogicException
156
+	 */
157
+	protected function doCustomClose(User $currentUser, Request $request, PdoDatabase $database)
158
+	{
159
+		$messageBody = WebRequest::postString('msgbody');
160
+		if ($messageBody === null || trim($messageBody) === '') {
161
+			throw new ApplicationLogicException('Message body cannot be blank');
162
+		}
163
+
164
+		$ccMailingList = true;
165
+		if ($this->barrierTest('skipCcMailingList', $currentUser)) {
166
+			$ccMailingList = WebRequest::postBoolean('ccMailingList');
167
+		}
168
+
169
+		if ($request->getStatus() === 'Closed') {
170
+			throw new ApplicationLogicException('Request is already closed');
171
+		}
172
+
173
+		if (!(WebRequest::postBoolean('confirmEmailAlreadySent')
174
+			&& WebRequest::postBoolean('confirmReserveOverride'))
175
+		) {
176
+			throw new ApplicationLogicException('Not all confirmations checked');
177
+		}
178
+
179
+		$action = WebRequest::postString('action');
180
+		$availableRequestStates = $this->getSiteConfiguration()->getRequestStates();
181
+
182
+		if ($action === EmailTemplate::CREATED || $action === EmailTemplate::NOT_CREATED) {
183
+			// Close request
184
+			$this->closeRequest($request, $database, $action, $messageBody);
185
+
186
+			// Send the mail after the save, since save can be rolled back
187
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
188
+		}
189
+		else {
190
+			if (array_key_exists($action, $availableRequestStates)) {
191
+				// Defer to other state
192
+				$this->deferRequest($request, $database, $action, $availableRequestStates, $messageBody);
193
+
194
+				// Send the mail after the save, since save can be rolled back
195
+				$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
196
+			}
197
+			else {
198
+				$request->setReserved(null);
199
+				$request->setUpdateVersion(WebRequest::postInt('updateversion'));
200
+				$request->save();
201
+
202
+				// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
203
+				// and be rolled back.
204
+
205
+				// Send mail
206
+				$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
207
+
208
+				Logger::sentMail($database, $request, $messageBody);
209
+				Logger::unreserve($database, $request);
210
+
211
+				$this->getNotificationHelper()->sentMail($request);
212
+				SessionAlert::success("Sent mail to Request {$request->getId()}");
213
+			}
214
+		}
215
+	}
216
+
217
+	/**
218
+	 * @param Request     $request
219
+	 * @param PdoDatabase $database
220
+	 * @param string      $action
221
+	 * @param string      $messageBody
222
+	 *
223
+	 * @throws Exception
224
+	 * @throws OptimisticLockFailedException
225
+	 */
226
+	protected function closeRequest(Request $request, PdoDatabase $database, $action, $messageBody)
227
+	{
228
+		$request->setStatus('Closed');
229
+		$request->setReserved(null);
230
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
231
+		$request->save();
232
+
233
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
234
+		// be rolled back.
235
+
236
+		if ($action == EmailTemplate::CREATED) {
237
+			$logCloseType = 'custom-y';
238
+			$notificationCloseType = "Custom, Created";
239
+		}
240
+		else {
241
+			$logCloseType = 'custom-n';
242
+			$notificationCloseType = "Custom, Not Created";
243
+		}
244
+
245
+		Logger::closeRequest($database, $request, $logCloseType, $messageBody);
246
+		$this->getNotificationHelper()->requestClosed($request, $notificationCloseType);
247
+
248
+		$requestName = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
249
+		SessionAlert::success("Request {$request->getId()} ({$requestName}) marked as 'Done'.");
250
+	}
251
+
252
+	/**
253
+	 * @param Request     $request
254
+	 * @param PdoDatabase $database
255
+	 * @param string      $action
256
+	 * @param             $availableRequestStates
257
+	 * @param string      $messageBody
258
+	 *
259
+	 * @throws Exception
260
+	 * @throws OptimisticLockFailedException
261
+	 */
262
+	protected function deferRequest(
263
+		Request $request,
264
+		PdoDatabase $database,
265
+		$action,
266
+		$availableRequestStates,
267
+		$messageBody
268
+	) {
269
+		$request->setStatus($action);
270
+		$request->setReserved(null);
271
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
272
+		$request->save();
273
+
274
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
275
+		// and be rolled back.
276
+
277
+		$deferToLog = $availableRequestStates[$action]['defertolog'];
278
+		Logger::sentMail($database, $request, $messageBody);
279
+		Logger::deferRequest($database, $request, $deferToLog);
280
+
281
+		$this->getNotificationHelper()->requestDeferredWithMail($request);
282
+
283
+		$deferTo = $availableRequestStates[$action]['deferto'];
284
+		SessionAlert::success("Request {$request->getId()} deferred to $deferTo, sending an email.");
285
+	}
286 286
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageSendToUser.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -17,43 +17,43 @@
 block discarded – undo
17 17
 
18 18
 class PageSendToUser extends RequestActionBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no specific actions are called.
22
-     * @throws ApplicationLogicException
23
-     * @throws Exception
24
-     */
25
-    protected function main()
26
-    {
27
-        $this->checkPosted();
28
-        $database = $this->getDatabase();
29
-        $request = $this->getRequest($database);
30
-
31
-        if ($request->getReserved() !== User::getCurrent($database)->getId()) {
32
-            throw new ApplicationLogicException('You don\'t have this request reserved!');
33
-        }
34
-
35
-        $username = WebRequest::postString('user');
36
-        if ($username === null) {
37
-            throw new ApplicationLogicException('User must be specified');
38
-        }
39
-
40
-        $user = User::getByUsername($username, $database);
41
-        if ($user === false) {
42
-            throw new ApplicationLogicException('User not found');
43
-        }
44
-
45
-        if (!$user->isActive()) {
46
-            throw new ApplicationLogicException('User is currently not active on the tool');
47
-        }
48
-
49
-        $request->setReserved($user->getId());
50
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
51
-        $request->save();
52
-
53
-        Logger::sendReservation($database, $request, $user);
54
-        $this->getNotificationHelper()->requestReservationSent($request, $user);
55
-        SessionAlert::success("Reservation sent successfully");
56
-
57
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
58
-    }
20
+	/**
21
+	 * Main function for this page, when no specific actions are called.
22
+	 * @throws ApplicationLogicException
23
+	 * @throws Exception
24
+	 */
25
+	protected function main()
26
+	{
27
+		$this->checkPosted();
28
+		$database = $this->getDatabase();
29
+		$request = $this->getRequest($database);
30
+
31
+		if ($request->getReserved() !== User::getCurrent($database)->getId()) {
32
+			throw new ApplicationLogicException('You don\'t have this request reserved!');
33
+		}
34
+
35
+		$username = WebRequest::postString('user');
36
+		if ($username === null) {
37
+			throw new ApplicationLogicException('User must be specified');
38
+		}
39
+
40
+		$user = User::getByUsername($username, $database);
41
+		if ($user === false) {
42
+			throw new ApplicationLogicException('User not found');
43
+		}
44
+
45
+		if (!$user->isActive()) {
46
+			throw new ApplicationLogicException('User is currently not active on the tool');
47
+		}
48
+
49
+		$request->setReserved($user->getId());
50
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
51
+		$request->save();
52
+
53
+		Logger::sendReservation($database, $request, $user);
54
+		$this->getNotificationHelper()->requestReservationSent($request, $user);
55
+		SessionAlert::success("Reservation sent successfully");
56
+
57
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
58
+	}
59 59
 }
Please login to merge, or discard this patch.
includes/Pages/PageForgotPassword.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -17,149 +17,149 @@
 block discarded – undo
17 17
 
18 18
 class PageForgotPassword extends InternalPageBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no specific actions are called.
22
-     *
23
-     * This is the forgotten password reset form
24
-     * @category Security-Critical
25
-     */
26
-    protected function main()
27
-    {
28
-        if (WebRequest::wasPosted()) {
29
-            $this->validateCSRFToken();
30
-            $username = WebRequest::postString('username');
31
-            $email = WebRequest::postEmail('email');
32
-            $database = $this->getDatabase();
33
-
34
-            if ($username === null || trim($username) === "" || $email === null || trim($email) === "") {
35
-                throw new ApplicationLogicException("Both username and email address must be specified!");
36
-            }
37
-
38
-            $user = User::getByUsername($username, $database);
39
-            $this->sendResetMail($user, $email);
40
-
41
-            SessionAlert::success('<strong>Your password reset request has been completed.</strong> Please check your e-mail.');
42
-
43
-            $this->redirect('login');
44
-        }
45
-        else {
46
-            $this->assignCSRFToken();
47
-            $this->setTemplate('forgot-password/forgotpw.tpl');
48
-        }
49
-    }
50
-
51
-    /**
52
-     * Sends a reset email if the user is authenticated
53
-     *
54
-     * @param User|boolean $user  The user located from the database, or false. Doesn't really matter, since we do the
55
-     *                            check anyway within this method and silently skip if we don't have a user.
56
-     * @param string       $email The provided email address
57
-     */
58
-    private function sendResetMail($user, $email)
59
-    {
60
-        // If the user isn't found, or the email address is wrong, skip sending the details silently.
61
-        if (!$user instanceof User) {
62
-            return;
63
-        }
64
-
65
-        if (strtolower($user->getEmail()) === strtolower($email)) {
66
-            $clientIp = $this->getXffTrustProvider()
67
-                ->getTrustedClientIp(WebRequest::remoteAddress(), WebRequest::forwardedAddress());
68
-
69
-            $this->assign("user", $user);
70
-            $this->assign("hash", $user->getForgottenPasswordHash());
71
-            $this->assign("remoteAddress", $clientIp);
72
-
73
-            $emailContent = $this->fetchTemplate('forgot-password/reset-mail.tpl');
74
-
75
-            $this->getEmailHelper()->sendMail($user->getEmail(), "", $emailContent);
76
-        }
77
-    }
78
-
79
-    /**
80
-     * Entry point for the reset action
81
-     *
82
-     * This is the reset password part of the form.
83
-     * @category Security-Critical
84
-     */
85
-    protected function reset()
86
-    {
87
-        $si = WebRequest::getString('si');
88
-        $id = WebRequest::getString('id');
89
-
90
-        if ($si === null || trim($si) === "" || $id === null || trim($id) === "") {
91
-            throw new ApplicationLogicException("Link not valid, please ensure it has copied correctly");
92
-        }
93
-
94
-        $database = $this->getDatabase();
95
-        $user = $this->getResettingUser($id, $database, $si);
96
-
97
-        // Dual mode
98
-        if (WebRequest::wasPosted()) {
99
-            $this->validateCSRFToken();
100
-            try {
101
-                $this->doReset($user);
102
-            }
103
-            catch (ApplicationLogicException $ex) {
104
-                SessionAlert::error($ex->getMessage());
105
-                $this->redirect('forgotPassword', 'reset', array('si' => $si, 'id' => $id));
106
-
107
-                return;
108
-            }
109
-        }
110
-        else {
111
-            $this->assignCSRFToken();
112
-            $this->assign('user', $user);
113
-            $this->setTemplate('forgot-password/forgotpwreset.tpl');
114
-        }
115
-    }
116
-
117
-    /**
118
-     * Gets the user resetting their password from the database, or throwing an exception if that is not possible.
119
-     *
120
-     * @param integer     $id       The ID of the user to retrieve
121
-     * @param PdoDatabase $database The database object to use
122
-     * @param string      $si       The reset hash provided
123
-     *
124
-     * @return User
125
-     * @throws ApplicationLogicException
126
-     */
127
-    private function getResettingUser($id, $database, $si)
128
-    {
129
-        $user = User::getById($id, $database);
130
-
131
-        if ($user === false || $user->getForgottenPasswordHash() !== $si || $user->isCommunityUser()) {
132
-            throw new ApplicationLogicException("User not found");
133
-        }
134
-
135
-        return $user;
136
-    }
137
-
138
-    /**
139
-     * Performs the setting of the new password
140
-     *
141
-     * @param User $user The user to set the password for
142
-     *
143
-     * @throws ApplicationLogicException
144
-     */
145
-    private function doReset(User $user)
146
-    {
147
-        $pw = WebRequest::postString('pw');
148
-        $pw2 = WebRequest::postString('pw2');
149
-
150
-        if ($pw !== $pw2) {
151
-            throw new ApplicationLogicException('Passwords do not match!');
152
-        }
153
-
154
-        $user->setPassword($pw);
155
-        $user->save();
156
-
157
-        SessionAlert::success('You may now log in!');
158
-        $this->redirect('login');
159
-    }
160
-
161
-    protected function isProtectedPage()
162
-    {
163
-        return false;
164
-    }
20
+	/**
21
+	 * Main function for this page, when no specific actions are called.
22
+	 *
23
+	 * This is the forgotten password reset form
24
+	 * @category Security-Critical
25
+	 */
26
+	protected function main()
27
+	{
28
+		if (WebRequest::wasPosted()) {
29
+			$this->validateCSRFToken();
30
+			$username = WebRequest::postString('username');
31
+			$email = WebRequest::postEmail('email');
32
+			$database = $this->getDatabase();
33
+
34
+			if ($username === null || trim($username) === "" || $email === null || trim($email) === "") {
35
+				throw new ApplicationLogicException("Both username and email address must be specified!");
36
+			}
37
+
38
+			$user = User::getByUsername($username, $database);
39
+			$this->sendResetMail($user, $email);
40
+
41
+			SessionAlert::success('<strong>Your password reset request has been completed.</strong> Please check your e-mail.');
42
+
43
+			$this->redirect('login');
44
+		}
45
+		else {
46
+			$this->assignCSRFToken();
47
+			$this->setTemplate('forgot-password/forgotpw.tpl');
48
+		}
49
+	}
50
+
51
+	/**
52
+	 * Sends a reset email if the user is authenticated
53
+	 *
54
+	 * @param User|boolean $user  The user located from the database, or false. Doesn't really matter, since we do the
55
+	 *                            check anyway within this method and silently skip if we don't have a user.
56
+	 * @param string       $email The provided email address
57
+	 */
58
+	private function sendResetMail($user, $email)
59
+	{
60
+		// If the user isn't found, or the email address is wrong, skip sending the details silently.
61
+		if (!$user instanceof User) {
62
+			return;
63
+		}
64
+
65
+		if (strtolower($user->getEmail()) === strtolower($email)) {
66
+			$clientIp = $this->getXffTrustProvider()
67
+				->getTrustedClientIp(WebRequest::remoteAddress(), WebRequest::forwardedAddress());
68
+
69
+			$this->assign("user", $user);
70
+			$this->assign("hash", $user->getForgottenPasswordHash());
71
+			$this->assign("remoteAddress", $clientIp);
72
+
73
+			$emailContent = $this->fetchTemplate('forgot-password/reset-mail.tpl');
74
+
75
+			$this->getEmailHelper()->sendMail($user->getEmail(), "", $emailContent);
76
+		}
77
+	}
78
+
79
+	/**
80
+	 * Entry point for the reset action
81
+	 *
82
+	 * This is the reset password part of the form.
83
+	 * @category Security-Critical
84
+	 */
85
+	protected function reset()
86
+	{
87
+		$si = WebRequest::getString('si');
88
+		$id = WebRequest::getString('id');
89
+
90
+		if ($si === null || trim($si) === "" || $id === null || trim($id) === "") {
91
+			throw new ApplicationLogicException("Link not valid, please ensure it has copied correctly");
92
+		}
93
+
94
+		$database = $this->getDatabase();
95
+		$user = $this->getResettingUser($id, $database, $si);
96
+
97
+		// Dual mode
98
+		if (WebRequest::wasPosted()) {
99
+			$this->validateCSRFToken();
100
+			try {
101
+				$this->doReset($user);
102
+			}
103
+			catch (ApplicationLogicException $ex) {
104
+				SessionAlert::error($ex->getMessage());
105
+				$this->redirect('forgotPassword', 'reset', array('si' => $si, 'id' => $id));
106
+
107
+				return;
108
+			}
109
+		}
110
+		else {
111
+			$this->assignCSRFToken();
112
+			$this->assign('user', $user);
113
+			$this->setTemplate('forgot-password/forgotpwreset.tpl');
114
+		}
115
+	}
116
+
117
+	/**
118
+	 * Gets the user resetting their password from the database, or throwing an exception if that is not possible.
119
+	 *
120
+	 * @param integer     $id       The ID of the user to retrieve
121
+	 * @param PdoDatabase $database The database object to use
122
+	 * @param string      $si       The reset hash provided
123
+	 *
124
+	 * @return User
125
+	 * @throws ApplicationLogicException
126
+	 */
127
+	private function getResettingUser($id, $database, $si)
128
+	{
129
+		$user = User::getById($id, $database);
130
+
131
+		if ($user === false || $user->getForgottenPasswordHash() !== $si || $user->isCommunityUser()) {
132
+			throw new ApplicationLogicException("User not found");
133
+		}
134
+
135
+		return $user;
136
+	}
137
+
138
+	/**
139
+	 * Performs the setting of the new password
140
+	 *
141
+	 * @param User $user The user to set the password for
142
+	 *
143
+	 * @throws ApplicationLogicException
144
+	 */
145
+	private function doReset(User $user)
146
+	{
147
+		$pw = WebRequest::postString('pw');
148
+		$pw2 = WebRequest::postString('pw2');
149
+
150
+		if ($pw !== $pw2) {
151
+			throw new ApplicationLogicException('Passwords do not match!');
152
+		}
153
+
154
+		$user->setPassword($pw);
155
+		$user->save();
156
+
157
+		SessionAlert::success('You may now log in!');
158
+		$this->redirect('login');
159
+	}
160
+
161
+	protected function isProtectedPage()
162
+	{
163
+		return false;
164
+	}
165 165
 }
Please login to merge, or discard this patch.
includes/Pages/PageLogin.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -20,137 +20,137 @@
 block discarded – undo
20 20
  */
21 21
 class PageLogin extends InternalPageBase
22 22
 {
23
-    /**
24
-     * Main function for this page, when no specific actions are called.
25
-     */
26
-    protected function main()
27
-    {
28
-        // Start by enforcing HTTPS
29
-        if ($this->getSiteConfiguration()->getUseStrictTransportSecurity() !== false) {
30
-            if (WebRequest::isHttps()) {
31
-                // Client can clearly use HTTPS, so let's enforce it for all connections.
32
-                if (!headers_sent()) {
33
-                    header("Strict-Transport-Security: max-age=15768000");
34
-                }
35
-            }
36
-            else {
37
-                // This is the login form, not the request form. We need protection here.
38
-                $this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
39
-
40
-                return;
41
-            }
42
-        }
43
-
44
-        if (WebRequest::wasPosted()) {
45
-            // POST. Do some authentication.
46
-            $this->validateCSRFToken();
47
-
48
-            $user = null;
49
-            try {
50
-                $user = $this->getAuthenticatingUser();
51
-            }
52
-            catch (ApplicationLogicException $ex) {
53
-                SessionAlert::error($ex->getMessage());
54
-                $this->redirect('login');
55
-
56
-                return;
57
-            }
58
-
59
-            // Touch force logout
60
-            $user->setForceLogout(false);
61
-            $user->save();
62
-
63
-            if ($this->getSiteConfiguration()->getEnforceOAuth()) {
64
-                if (!$user->isOAuthLinked()) {
65
-                    $oauthHelper = $this->getOAuthHelper();
66
-
67
-                    $requestToken = $oauthHelper->getRequestToken();
68
-                    $user->setOAuthRequestToken($requestToken->key);
69
-                    $user->setOAuthRequestSecret($requestToken->secret);
70
-                    $user->save();
71
-
72
-                    WebRequest::setPartialLogin($user);
73
-                    $this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
74
-
75
-                    return;
76
-                }
77
-            }
78
-
79
-            // User is partially linked to OAuth. This is not allowed. Enforce it for this user.
80
-            if ($user->getOnWikiName() === '##OAUTH##') {
81
-                $oauthHelper = $this->getOAuthHelper();
82
-
83
-                $requestToken = $oauthHelper->getRequestToken();
84
-                $user->setOAuthRequestToken($requestToken->key);
85
-                $user->setOAuthRequestSecret($requestToken->secret);
86
-                $user->save();
87
-
88
-                WebRequest::setPartialLogin($user);
89
-                $this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
90
-
91
-                return;
92
-            }
93
-
94
-            WebRequest::setLoggedInUser($user);
95
-
96
-            $this->goBackWhenceYouCame($user);
97
-        }
98
-        else {
99
-            // GET. Show the form
100
-            $this->assignCSRFToken();
101
-            $this->setTemplate("login.tpl");
102
-        }
103
-    }
104
-
105
-    /**
106
-     * @return User
107
-     * @throws ApplicationLogicException
108
-     */
109
-    private function getAuthenticatingUser()
110
-    {
111
-        $username = WebRequest::postString("username");
112
-        $password = WebRequest::postString("password");
113
-
114
-        if ($username === null || $password === null || $username === "" || $password === "") {
115
-            throw new ApplicationLogicException("No username/password specified");
116
-        }
117
-
118
-        /** @var User $user */
119
-        $user = User::getByUsername($username, $this->getDatabase());
120
-
121
-        if ($user == false || !$user->authenticate($password)) {
122
-            throw new ApplicationLogicException("Authentication failed");
123
-        }
124
-
125
-        return $user;
126
-    }
127
-
128
-    protected function isProtectedPage()
129
-    {
130
-        return false;
131
-    }
132
-
133
-    /**
134
-     * Redirect the user back to wherever they came from after a successful login
135
-     *
136
-     * @param User $user
137
-     */
138
-    private function goBackWhenceYouCame(User $user)
139
-    {
140
-        // Redirect to wherever the user came from
141
-        $redirectDestination = WebRequest::clearPostLoginRedirect();
142
-        if ($redirectDestination !== null) {
143
-            $this->redirectUrl($redirectDestination);
144
-        }
145
-        else {
146
-            if ($user->isNewUser()) {
147
-                // home page isn't allowed, go to preferences instead
148
-                $this->redirect('preferences');
149
-            }
150
-            else {
151
-                // go to the home page
152
-                $this->redirect('');
153
-            }
154
-        }
155
-    }
23
+	/**
24
+	 * Main function for this page, when no specific actions are called.
25
+	 */
26
+	protected function main()
27
+	{
28
+		// Start by enforcing HTTPS
29
+		if ($this->getSiteConfiguration()->getUseStrictTransportSecurity() !== false) {
30
+			if (WebRequest::isHttps()) {
31
+				// Client can clearly use HTTPS, so let's enforce it for all connections.
32
+				if (!headers_sent()) {
33
+					header("Strict-Transport-Security: max-age=15768000");
34
+				}
35
+			}
36
+			else {
37
+				// This is the login form, not the request form. We need protection here.
38
+				$this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
39
+
40
+				return;
41
+			}
42
+		}
43
+
44
+		if (WebRequest::wasPosted()) {
45
+			// POST. Do some authentication.
46
+			$this->validateCSRFToken();
47
+
48
+			$user = null;
49
+			try {
50
+				$user = $this->getAuthenticatingUser();
51
+			}
52
+			catch (ApplicationLogicException $ex) {
53
+				SessionAlert::error($ex->getMessage());
54
+				$this->redirect('login');
55
+
56
+				return;
57
+			}
58
+
59
+			// Touch force logout
60
+			$user->setForceLogout(false);
61
+			$user->save();
62
+
63
+			if ($this->getSiteConfiguration()->getEnforceOAuth()) {
64
+				if (!$user->isOAuthLinked()) {
65
+					$oauthHelper = $this->getOAuthHelper();
66
+
67
+					$requestToken = $oauthHelper->getRequestToken();
68
+					$user->setOAuthRequestToken($requestToken->key);
69
+					$user->setOAuthRequestSecret($requestToken->secret);
70
+					$user->save();
71
+
72
+					WebRequest::setPartialLogin($user);
73
+					$this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
74
+
75
+					return;
76
+				}
77
+			}
78
+
79
+			// User is partially linked to OAuth. This is not allowed. Enforce it for this user.
80
+			if ($user->getOnWikiName() === '##OAUTH##') {
81
+				$oauthHelper = $this->getOAuthHelper();
82
+
83
+				$requestToken = $oauthHelper->getRequestToken();
84
+				$user->setOAuthRequestToken($requestToken->key);
85
+				$user->setOAuthRequestSecret($requestToken->secret);
86
+				$user->save();
87
+
88
+				WebRequest::setPartialLogin($user);
89
+				$this->redirectUrl($oauthHelper->getAuthoriseUrl($requestToken->key));
90
+
91
+				return;
92
+			}
93
+
94
+			WebRequest::setLoggedInUser($user);
95
+
96
+			$this->goBackWhenceYouCame($user);
97
+		}
98
+		else {
99
+			// GET. Show the form
100
+			$this->assignCSRFToken();
101
+			$this->setTemplate("login.tpl");
102
+		}
103
+	}
104
+
105
+	/**
106
+	 * @return User
107
+	 * @throws ApplicationLogicException
108
+	 */
109
+	private function getAuthenticatingUser()
110
+	{
111
+		$username = WebRequest::postString("username");
112
+		$password = WebRequest::postString("password");
113
+
114
+		if ($username === null || $password === null || $username === "" || $password === "") {
115
+			throw new ApplicationLogicException("No username/password specified");
116
+		}
117
+
118
+		/** @var User $user */
119
+		$user = User::getByUsername($username, $this->getDatabase());
120
+
121
+		if ($user == false || !$user->authenticate($password)) {
122
+			throw new ApplicationLogicException("Authentication failed");
123
+		}
124
+
125
+		return $user;
126
+	}
127
+
128
+	protected function isProtectedPage()
129
+	{
130
+		return false;
131
+	}
132
+
133
+	/**
134
+	 * Redirect the user back to wherever they came from after a successful login
135
+	 *
136
+	 * @param User $user
137
+	 */
138
+	private function goBackWhenceYouCame(User $user)
139
+	{
140
+		// Redirect to wherever the user came from
141
+		$redirectDestination = WebRequest::clearPostLoginRedirect();
142
+		if ($redirectDestination !== null) {
143
+			$this->redirectUrl($redirectDestination);
144
+		}
145
+		else {
146
+			if ($user->isNewUser()) {
147
+				// home page isn't allowed, go to preferences instead
148
+				$this->redirect('preferences');
149
+			}
150
+			else {
151
+				// go to the home page
152
+				$this->redirect('');
153
+			}
154
+		}
155
+	}
156 156
 }
Please login to merge, or discard this patch.
includes/Pages/PageUserManagement.php 2 patches
Indentation   +529 added lines, -529 removed lines patch added patch discarded remove patch
@@ -23,533 +23,533 @@
 block discarded – undo
23 23
  */
24 24
 class PageUserManagement extends InternalPageBase
25 25
 {
26
-    /** @var string */
27
-    private $adminMailingList = '[email protected]';
28
-
29
-    /**
30
-     * Main function for this page, when no specific actions are called.
31
-     */
32
-    protected function main()
33
-    {
34
-        $this->setHtmlTitle('User Management');
35
-
36
-        $database = $this->getDatabase();
37
-        $currentUser = User::getCurrent($database);
38
-
39
-        if (WebRequest::getBoolean("showAll")) {
40
-            $this->assign("showAll", true);
41
-
42
-            $this->assign("suspendedUsers",
43
-                UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch());
44
-            $this->assign("declinedUsers", UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch());
45
-
46
-            UserSearchHelper::get($database)->getRoleMap($roleMap);
47
-        }
48
-        else {
49
-            $this->assign("showAll", false);
50
-            $this->assign("suspendedUsers", array());
51
-            $this->assign("declinedUsers", array());
52
-
53
-            UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
54
-        }
55
-
56
-        $this->assign('newUsers', UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch());
57
-        $this->assign('normalUsers',
58
-            UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch());
59
-        $this->assign('adminUsers',
60
-            UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch());
61
-        $this->assign('checkUsers',
62
-            UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch());
63
-        $this->assign('toolRoots',
64
-            UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch());
65
-
66
-        $this->assign('roles', $roleMap);
67
-
68
-        $this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
69
-            return UserSearchHelper::get($database)->fetchColumn('username');
70
-        });
71
-
72
-        $this->assign('canApprove', $this->barrierTest('approve', $currentUser));
73
-        $this->assign('canDecline', $this->barrierTest('decline', $currentUser));
74
-        $this->assign('canRename', $this->barrierTest('rename', $currentUser));
75
-        $this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
76
-        $this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
77
-        $this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
78
-
79
-        $this->setTemplate("usermanagement/main.tpl");
80
-    }
81
-
82
-    #region Access control
83
-
84
-    /**
85
-     * Action target for editing the roles assigned to a user
86
-     */
87
-    protected function editRoles()
88
-    {
89
-        $this->setHtmlTitle('User Management');
90
-        $database = $this->getDatabase();
91
-        $userId = WebRequest::getInt('user');
92
-
93
-        /** @var User $user */
94
-        $user = User::getById($userId, $database);
95
-
96
-        if ($user === false) {
97
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
98
-        }
99
-
100
-        $roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database));
101
-
102
-        // Dual-mode action
103
-        if (WebRequest::wasPosted()) {
104
-            $this->validateCSRFToken();
105
-
106
-            $reason = WebRequest::postString('reason');
107
-            if ($reason === false || trim($reason) === '') {
108
-                throw new ApplicationLogicException('No reason specified for roles change');
109
-            }
110
-
111
-            /** @var UserRole[] $delete */
112
-            $delete = array();
113
-            /** @var string[] $delete */
114
-            $add = array();
115
-
116
-            foreach ($roleData as $name => $r) {
117
-                if ($r['allowEdit'] !== 1) {
118
-                    // not allowed, to touch this, so ignore it
119
-                    continue;
120
-                }
121
-
122
-                $newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
123
-                if ($newValue !== $r['active']) {
124
-                    if ($newValue === 0) {
125
-                        $delete[] = $r['object'];
126
-                    }
127
-
128
-                    if ($newValue === 1) {
129
-                        $add[] = $name;
130
-                    }
131
-                }
132
-            }
133
-
134
-            // Check there's something to do
135
-            if ((count($add) + count($delete)) === 0) {
136
-                $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
137
-                SessionAlert::warning('No changes made to roles.');
138
-
139
-                return;
140
-            }
141
-
142
-            $removed = array();
143
-
144
-            /** @var UserRole $d */
145
-            foreach ($delete as $d) {
146
-                $removed[] = $d->getRole();
147
-                $d->delete();
148
-            }
149
-
150
-            foreach ($add as $x) {
151
-                $a = new UserRole();
152
-                $a->setUser($user->getId());
153
-                $a->setRole($x);
154
-                $a->setDatabase($database);
155
-                $a->save();
156
-            }
157
-
158
-            Logger::userRolesEdited($database, $user, $reason, $add, $removed);
159
-
160
-            // dummy save for optimistic locking. If this fails, the entire txn will roll back.
161
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
162
-            $user->save();
163
-
164
-            $this->getNotificationHelper()->userRolesEdited($user, $reason);
165
-            SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
166
-
167
-            $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
168
-            return;
169
-        }
170
-        else {
171
-            $this->assignCSRFToken();
172
-            $this->setTemplate('usermanagement/roleedit.tpl');
173
-            $this->assign('user', $user);
174
-            $this->assign('roleData', $roleData);
175
-        }
176
-    }
177
-
178
-    /**
179
-     * Action target for suspending users
180
-     *
181
-     * @throws ApplicationLogicException
182
-     */
183
-    protected function suspend()
184
-    {
185
-        $this->setHtmlTitle('User Management');
186
-
187
-        $database = $this->getDatabase();
188
-
189
-        $userId = WebRequest::getInt('user');
190
-
191
-        /** @var User $user */
192
-        $user = User::getById($userId, $database);
193
-
194
-        if ($user === false) {
195
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
196
-        }
197
-
198
-        if ($user->isSuspended()) {
199
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
200
-        }
201
-
202
-        // Dual-mode action
203
-        if (WebRequest::wasPosted()) {
204
-            $this->validateCSRFToken();
205
-            $reason = WebRequest::postString('reason');
206
-
207
-            if ($reason === null || trim($reason) === "") {
208
-                throw new ApplicationLogicException('No reason provided');
209
-            }
210
-
211
-            $user->setStatus(User::STATUS_SUSPENDED);
212
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
213
-            $user->save();
214
-            Logger::suspendedUser($database, $user, $reason);
215
-
216
-            $this->getNotificationHelper()->userSuspended($user, $reason);
217
-            SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
218
-
219
-            // send email
220
-            $this->sendStatusChangeEmail(
221
-                'Your WP:ACC account has been suspended',
222
-                'usermanagement/emails/suspended.tpl',
223
-                $reason,
224
-                $user,
225
-                User::getCurrent($database)->getUsername()
226
-            );
227
-
228
-            $this->redirect('userManagement');
229
-
230
-            return;
231
-        }
232
-        else {
233
-            $this->assignCSRFToken();
234
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
235
-            $this->assign('user', $user);
236
-            $this->assign('status', 'Suspended');
237
-            $this->assign("showReason", true);
238
-        }
239
-    }
240
-
241
-    /**
242
-     * Entry point for the decline action
243
-     *
244
-     * @throws ApplicationLogicException
245
-     */
246
-    protected function decline()
247
-    {
248
-        $this->setHtmlTitle('User Management');
249
-
250
-        $database = $this->getDatabase();
251
-
252
-        $userId = WebRequest::getInt('user');
253
-        $user = User::getById($userId, $database);
254
-
255
-        if ($user === false) {
256
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
257
-        }
258
-
259
-        if (!$user->isNewUser()) {
260
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
261
-        }
262
-
263
-        // Dual-mode action
264
-        if (WebRequest::wasPosted()) {
265
-            $this->validateCSRFToken();
266
-            $reason = WebRequest::postString('reason');
267
-
268
-            if ($reason === null || trim($reason) === "") {
269
-                throw new ApplicationLogicException('No reason provided');
270
-            }
271
-
272
-            $user->setStatus(User::STATUS_DECLINED);
273
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
274
-            $user->save();
275
-            Logger::declinedUser($database, $user, $reason);
276
-
277
-            $this->getNotificationHelper()->userDeclined($user, $reason);
278
-            SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
279
-
280
-            // send email
281
-            $this->sendStatusChangeEmail(
282
-                'Your WP:ACC account has been declined',
283
-                'usermanagement/emails/declined.tpl',
284
-                $reason,
285
-                $user,
286
-                User::getCurrent($database)->getUsername()
287
-            );
288
-
289
-            $this->redirect('userManagement');
290
-
291
-            return;
292
-        }
293
-        else {
294
-            $this->assignCSRFToken();
295
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
296
-            $this->assign('user', $user);
297
-            $this->assign('status', 'Declined');
298
-            $this->assign("showReason", true);
299
-        }
300
-    }
301
-
302
-    /**
303
-     * Entry point for the approve action
304
-     *
305
-     * @throws ApplicationLogicException
306
-     */
307
-    protected function approve()
308
-    {
309
-        $this->setHtmlTitle('User Management');
310
-
311
-        $database = $this->getDatabase();
312
-
313
-        $userId = WebRequest::getInt('user');
314
-        $user = User::getById($userId, $database);
315
-
316
-        if ($user === false) {
317
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
318
-        }
319
-
320
-        if ($user->isActive()) {
321
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
322
-        }
323
-
324
-        // Dual-mode action
325
-        if (WebRequest::wasPosted()) {
326
-            $this->validateCSRFToken();
327
-            $user->setStatus(User::STATUS_ACTIVE);
328
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
329
-            $user->save();
330
-            Logger::approvedUser($database, $user);
331
-
332
-            $this->getNotificationHelper()->userApproved($user);
333
-            SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
334
-
335
-            // send email
336
-            $this->sendStatusChangeEmail(
337
-                'Your WP:ACC account has been approved',
338
-                'usermanagement/emails/approved.tpl',
339
-                null,
340
-                $user,
341
-                User::getCurrent($database)->getUsername()
342
-            );
343
-
344
-            $this->redirect("userManagement");
345
-
346
-            return;
347
-        }
348
-        else {
349
-            $this->assignCSRFToken();
350
-            $this->setTemplate("usermanagement/changelevel-reason.tpl");
351
-            $this->assign("user", $user);
352
-            $this->assign("status", "User");
353
-            $this->assign("showReason", false);
354
-        }
355
-    }
356
-
357
-    #endregion
358
-
359
-    #region Renaming / Editing
360
-
361
-    /**
362
-     * Entry point for the rename action
363
-     *
364
-     * @throws ApplicationLogicException
365
-     */
366
-    protected function rename()
367
-    {
368
-        $this->setHtmlTitle('User Management');
369
-
370
-        $database = $this->getDatabase();
371
-
372
-        $userId = WebRequest::getInt('user');
373
-        $user = User::getById($userId, $database);
374
-
375
-        if ($user === false) {
376
-            throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
377
-        }
378
-
379
-        // Dual-mode action
380
-        if (WebRequest::wasPosted()) {
381
-            $this->validateCSRFToken();
382
-            $newUsername = WebRequest::postString('newname');
383
-
384
-            if ($newUsername === null || trim($newUsername) === "") {
385
-                throw new ApplicationLogicException('The new username cannot be empty');
386
-            }
387
-
388
-            if (User::getByUsername($newUsername, $database) != false) {
389
-                throw new ApplicationLogicException('The new username already exists');
390
-            }
391
-
392
-            $oldUsername = $user->getUsername();
393
-            $user->setUsername($newUsername);
394
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
395
-
396
-            $user->save();
397
-
398
-            $logEntryData = serialize(array(
399
-                'old' => $oldUsername,
400
-                'new' => $newUsername,
401
-            ));
402
-
403
-            Logger::renamedUser($database, $user, $logEntryData);
404
-
405
-            SessionAlert::quick("Changed User "
406
-                . htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
407
-                . " name to "
408
-                . htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
409
-
410
-            $this->getNotificationHelper()->userRenamed($user, $oldUsername);
411
-
412
-            // send an email to the user.
413
-            $this->assign('targetUsername', $user->getUsername());
414
-            $this->assign('toolAdmin', User::getCurrent($database)->getUsername());
415
-            $this->assign('oldUsername', $oldUsername);
416
-            $this->assign('mailingList', $this->adminMailingList);
417
-
418
-            $this->getEmailHelper()->sendMail(
419
-                $user->getEmail(),
420
-                'Your username on WP:ACC has been changed',
421
-                $this->fetchTemplate('usermanagement/emails/renamed.tpl'),
422
-                array('Reply-To' => $this->adminMailingList)
423
-            );
424
-
425
-            $this->redirect("userManagement");
426
-
427
-            return;
428
-        }
429
-        else {
430
-            $this->assignCSRFToken();
431
-            $this->setTemplate('usermanagement/renameuser.tpl');
432
-            $this->assign('user', $user);
433
-        }
434
-    }
435
-
436
-    /**
437
-     * Entry point for the edit action
438
-     *
439
-     * @throws ApplicationLogicException
440
-     */
441
-    protected function editUser()
442
-    {
443
-        $this->setHtmlTitle('User Management');
444
-
445
-        $database = $this->getDatabase();
446
-
447
-        $userId = WebRequest::getInt('user');
448
-        $user = User::getById($userId, $database);
449
-
450
-        if ($user === false) {
451
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
452
-        }
453
-
454
-        // Dual-mode action
455
-        if (WebRequest::wasPosted()) {
456
-            $this->validateCSRFToken();
457
-            $newEmail = WebRequest::postEmail('user_email');
458
-            $newOnWikiName = WebRequest::postString('user_onwikiname');
459
-
460
-            if ($newEmail === null) {
461
-                throw new ApplicationLogicException('Invalid email address');
462
-            }
463
-
464
-            if (!$user->isOAuthLinked()) {
465
-                if (trim($newOnWikiName) == "") {
466
-                    throw new ApplicationLogicException('New on-wiki username cannot be blank');
467
-                }
468
-
469
-                $user->setOnWikiName($newOnWikiName);
470
-            }
471
-
472
-            $user->setEmail($newEmail);
473
-
474
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
475
-
476
-            $user->save();
477
-
478
-            Logger::userPreferencesChange($database, $user);
479
-            $this->getNotificationHelper()->userPrefChange($user);
480
-            SessionAlert::quick('Changes to user\'s preferences have been saved');
481
-
482
-            $this->redirect("userManagement");
483
-
484
-            return;
485
-        }
486
-        else {
487
-            $this->assignCSRFToken();
488
-            $this->setTemplate('usermanagement/edituser.tpl');
489
-            $this->assign('user', $user);
490
-        }
491
-    }
492
-
493
-    #endregion
494
-
495
-    /**
496
-     * Sends a status change email to the user.
497
-     *
498
-     * @param string      $subject           The subject of the email
499
-     * @param string      $template          The smarty template to use
500
-     * @param string|null $reason            The reason for performing the status change
501
-     * @param User        $user              The user affected
502
-     * @param string      $toolAdminUsername The tool admin's username who is making the edit
503
-     */
504
-    private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
505
-    {
506
-        $this->assign('targetUsername', $user->getUsername());
507
-        $this->assign('toolAdmin', $toolAdminUsername);
508
-        $this->assign('actionReason', $reason);
509
-        $this->assign('mailingList', $this->adminMailingList);
510
-
511
-        $this->getEmailHelper()->sendMail(
512
-            $user->getEmail(),
513
-            $subject,
514
-            $this->fetchTemplate($template),
515
-            array('Reply-To' => $this->adminMailingList)
516
-        );
517
-    }
518
-
519
-    /**
520
-     * @param UserRole[] $activeRoles
521
-     *
522
-     * @return array
523
-     */
524
-    private function getRoleData($activeRoles)
525
-    {
526
-        $availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
527
-
528
-        $currentUser = User::getCurrent($this->getDatabase());
529
-        $this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
530
-
531
-        $initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
532
-
533
-        $roleData = array();
534
-        foreach ($availableRoles as $role => $data) {
535
-            $intersection = array_intersect($data['editableBy'], $userRoles);
536
-
537
-            $roleData[$role] = $initialValue;
538
-            $roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
539
-            $roleData[$role]['description'] = $data['description'];
540
-        }
541
-
542
-        foreach ($activeRoles as $role) {
543
-            if (!isset($roleData[$role->getRole()])) {
544
-                // This value is no longer available in the configuration, allow changing (aka removing) it.
545
-                $roleData[$role->getRole()] = $initialValue;
546
-                $roleData[$role->getRole()]['allowEdit'] = 1;
547
-            }
548
-
549
-            $roleData[$role->getRole()]['object'] = $role;
550
-            $roleData[$role->getRole()]['active'] = 1;
551
-        }
552
-
553
-        return $roleData;
554
-    }
26
+	/** @var string */
27
+	private $adminMailingList = '[email protected]';
28
+
29
+	/**
30
+	 * Main function for this page, when no specific actions are called.
31
+	 */
32
+	protected function main()
33
+	{
34
+		$this->setHtmlTitle('User Management');
35
+
36
+		$database = $this->getDatabase();
37
+		$currentUser = User::getCurrent($database);
38
+
39
+		if (WebRequest::getBoolean("showAll")) {
40
+			$this->assign("showAll", true);
41
+
42
+			$this->assign("suspendedUsers",
43
+				UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch());
44
+			$this->assign("declinedUsers", UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch());
45
+
46
+			UserSearchHelper::get($database)->getRoleMap($roleMap);
47
+		}
48
+		else {
49
+			$this->assign("showAll", false);
50
+			$this->assign("suspendedUsers", array());
51
+			$this->assign("declinedUsers", array());
52
+
53
+			UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
54
+		}
55
+
56
+		$this->assign('newUsers', UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch());
57
+		$this->assign('normalUsers',
58
+			UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch());
59
+		$this->assign('adminUsers',
60
+			UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch());
61
+		$this->assign('checkUsers',
62
+			UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch());
63
+		$this->assign('toolRoots',
64
+			UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch());
65
+
66
+		$this->assign('roles', $roleMap);
67
+
68
+		$this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
69
+			return UserSearchHelper::get($database)->fetchColumn('username');
70
+		});
71
+
72
+		$this->assign('canApprove', $this->barrierTest('approve', $currentUser));
73
+		$this->assign('canDecline', $this->barrierTest('decline', $currentUser));
74
+		$this->assign('canRename', $this->barrierTest('rename', $currentUser));
75
+		$this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
76
+		$this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
77
+		$this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
78
+
79
+		$this->setTemplate("usermanagement/main.tpl");
80
+	}
81
+
82
+	#region Access control
83
+
84
+	/**
85
+	 * Action target for editing the roles assigned to a user
86
+	 */
87
+	protected function editRoles()
88
+	{
89
+		$this->setHtmlTitle('User Management');
90
+		$database = $this->getDatabase();
91
+		$userId = WebRequest::getInt('user');
92
+
93
+		/** @var User $user */
94
+		$user = User::getById($userId, $database);
95
+
96
+		if ($user === false) {
97
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
98
+		}
99
+
100
+		$roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database));
101
+
102
+		// Dual-mode action
103
+		if (WebRequest::wasPosted()) {
104
+			$this->validateCSRFToken();
105
+
106
+			$reason = WebRequest::postString('reason');
107
+			if ($reason === false || trim($reason) === '') {
108
+				throw new ApplicationLogicException('No reason specified for roles change');
109
+			}
110
+
111
+			/** @var UserRole[] $delete */
112
+			$delete = array();
113
+			/** @var string[] $delete */
114
+			$add = array();
115
+
116
+			foreach ($roleData as $name => $r) {
117
+				if ($r['allowEdit'] !== 1) {
118
+					// not allowed, to touch this, so ignore it
119
+					continue;
120
+				}
121
+
122
+				$newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
123
+				if ($newValue !== $r['active']) {
124
+					if ($newValue === 0) {
125
+						$delete[] = $r['object'];
126
+					}
127
+
128
+					if ($newValue === 1) {
129
+						$add[] = $name;
130
+					}
131
+				}
132
+			}
133
+
134
+			// Check there's something to do
135
+			if ((count($add) + count($delete)) === 0) {
136
+				$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
137
+				SessionAlert::warning('No changes made to roles.');
138
+
139
+				return;
140
+			}
141
+
142
+			$removed = array();
143
+
144
+			/** @var UserRole $d */
145
+			foreach ($delete as $d) {
146
+				$removed[] = $d->getRole();
147
+				$d->delete();
148
+			}
149
+
150
+			foreach ($add as $x) {
151
+				$a = new UserRole();
152
+				$a->setUser($user->getId());
153
+				$a->setRole($x);
154
+				$a->setDatabase($database);
155
+				$a->save();
156
+			}
157
+
158
+			Logger::userRolesEdited($database, $user, $reason, $add, $removed);
159
+
160
+			// dummy save for optimistic locking. If this fails, the entire txn will roll back.
161
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
162
+			$user->save();
163
+
164
+			$this->getNotificationHelper()->userRolesEdited($user, $reason);
165
+			SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
166
+
167
+			$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
168
+			return;
169
+		}
170
+		else {
171
+			$this->assignCSRFToken();
172
+			$this->setTemplate('usermanagement/roleedit.tpl');
173
+			$this->assign('user', $user);
174
+			$this->assign('roleData', $roleData);
175
+		}
176
+	}
177
+
178
+	/**
179
+	 * Action target for suspending users
180
+	 *
181
+	 * @throws ApplicationLogicException
182
+	 */
183
+	protected function suspend()
184
+	{
185
+		$this->setHtmlTitle('User Management');
186
+
187
+		$database = $this->getDatabase();
188
+
189
+		$userId = WebRequest::getInt('user');
190
+
191
+		/** @var User $user */
192
+		$user = User::getById($userId, $database);
193
+
194
+		if ($user === false) {
195
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
196
+		}
197
+
198
+		if ($user->isSuspended()) {
199
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
200
+		}
201
+
202
+		// Dual-mode action
203
+		if (WebRequest::wasPosted()) {
204
+			$this->validateCSRFToken();
205
+			$reason = WebRequest::postString('reason');
206
+
207
+			if ($reason === null || trim($reason) === "") {
208
+				throw new ApplicationLogicException('No reason provided');
209
+			}
210
+
211
+			$user->setStatus(User::STATUS_SUSPENDED);
212
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
213
+			$user->save();
214
+			Logger::suspendedUser($database, $user, $reason);
215
+
216
+			$this->getNotificationHelper()->userSuspended($user, $reason);
217
+			SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
218
+
219
+			// send email
220
+			$this->sendStatusChangeEmail(
221
+				'Your WP:ACC account has been suspended',
222
+				'usermanagement/emails/suspended.tpl',
223
+				$reason,
224
+				$user,
225
+				User::getCurrent($database)->getUsername()
226
+			);
227
+
228
+			$this->redirect('userManagement');
229
+
230
+			return;
231
+		}
232
+		else {
233
+			$this->assignCSRFToken();
234
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
235
+			$this->assign('user', $user);
236
+			$this->assign('status', 'Suspended');
237
+			$this->assign("showReason", true);
238
+		}
239
+	}
240
+
241
+	/**
242
+	 * Entry point for the decline action
243
+	 *
244
+	 * @throws ApplicationLogicException
245
+	 */
246
+	protected function decline()
247
+	{
248
+		$this->setHtmlTitle('User Management');
249
+
250
+		$database = $this->getDatabase();
251
+
252
+		$userId = WebRequest::getInt('user');
253
+		$user = User::getById($userId, $database);
254
+
255
+		if ($user === false) {
256
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
257
+		}
258
+
259
+		if (!$user->isNewUser()) {
260
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
261
+		}
262
+
263
+		// Dual-mode action
264
+		if (WebRequest::wasPosted()) {
265
+			$this->validateCSRFToken();
266
+			$reason = WebRequest::postString('reason');
267
+
268
+			if ($reason === null || trim($reason) === "") {
269
+				throw new ApplicationLogicException('No reason provided');
270
+			}
271
+
272
+			$user->setStatus(User::STATUS_DECLINED);
273
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
274
+			$user->save();
275
+			Logger::declinedUser($database, $user, $reason);
276
+
277
+			$this->getNotificationHelper()->userDeclined($user, $reason);
278
+			SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
279
+
280
+			// send email
281
+			$this->sendStatusChangeEmail(
282
+				'Your WP:ACC account has been declined',
283
+				'usermanagement/emails/declined.tpl',
284
+				$reason,
285
+				$user,
286
+				User::getCurrent($database)->getUsername()
287
+			);
288
+
289
+			$this->redirect('userManagement');
290
+
291
+			return;
292
+		}
293
+		else {
294
+			$this->assignCSRFToken();
295
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
296
+			$this->assign('user', $user);
297
+			$this->assign('status', 'Declined');
298
+			$this->assign("showReason", true);
299
+		}
300
+	}
301
+
302
+	/**
303
+	 * Entry point for the approve action
304
+	 *
305
+	 * @throws ApplicationLogicException
306
+	 */
307
+	protected function approve()
308
+	{
309
+		$this->setHtmlTitle('User Management');
310
+
311
+		$database = $this->getDatabase();
312
+
313
+		$userId = WebRequest::getInt('user');
314
+		$user = User::getById($userId, $database);
315
+
316
+		if ($user === false) {
317
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
318
+		}
319
+
320
+		if ($user->isActive()) {
321
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
322
+		}
323
+
324
+		// Dual-mode action
325
+		if (WebRequest::wasPosted()) {
326
+			$this->validateCSRFToken();
327
+			$user->setStatus(User::STATUS_ACTIVE);
328
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
329
+			$user->save();
330
+			Logger::approvedUser($database, $user);
331
+
332
+			$this->getNotificationHelper()->userApproved($user);
333
+			SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
334
+
335
+			// send email
336
+			$this->sendStatusChangeEmail(
337
+				'Your WP:ACC account has been approved',
338
+				'usermanagement/emails/approved.tpl',
339
+				null,
340
+				$user,
341
+				User::getCurrent($database)->getUsername()
342
+			);
343
+
344
+			$this->redirect("userManagement");
345
+
346
+			return;
347
+		}
348
+		else {
349
+			$this->assignCSRFToken();
350
+			$this->setTemplate("usermanagement/changelevel-reason.tpl");
351
+			$this->assign("user", $user);
352
+			$this->assign("status", "User");
353
+			$this->assign("showReason", false);
354
+		}
355
+	}
356
+
357
+	#endregion
358
+
359
+	#region Renaming / Editing
360
+
361
+	/**
362
+	 * Entry point for the rename action
363
+	 *
364
+	 * @throws ApplicationLogicException
365
+	 */
366
+	protected function rename()
367
+	{
368
+		$this->setHtmlTitle('User Management');
369
+
370
+		$database = $this->getDatabase();
371
+
372
+		$userId = WebRequest::getInt('user');
373
+		$user = User::getById($userId, $database);
374
+
375
+		if ($user === false) {
376
+			throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
377
+		}
378
+
379
+		// Dual-mode action
380
+		if (WebRequest::wasPosted()) {
381
+			$this->validateCSRFToken();
382
+			$newUsername = WebRequest::postString('newname');
383
+
384
+			if ($newUsername === null || trim($newUsername) === "") {
385
+				throw new ApplicationLogicException('The new username cannot be empty');
386
+			}
387
+
388
+			if (User::getByUsername($newUsername, $database) != false) {
389
+				throw new ApplicationLogicException('The new username already exists');
390
+			}
391
+
392
+			$oldUsername = $user->getUsername();
393
+			$user->setUsername($newUsername);
394
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
395
+
396
+			$user->save();
397
+
398
+			$logEntryData = serialize(array(
399
+				'old' => $oldUsername,
400
+				'new' => $newUsername,
401
+			));
402
+
403
+			Logger::renamedUser($database, $user, $logEntryData);
404
+
405
+			SessionAlert::quick("Changed User "
406
+				. htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
407
+				. " name to "
408
+				. htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
409
+
410
+			$this->getNotificationHelper()->userRenamed($user, $oldUsername);
411
+
412
+			// send an email to the user.
413
+			$this->assign('targetUsername', $user->getUsername());
414
+			$this->assign('toolAdmin', User::getCurrent($database)->getUsername());
415
+			$this->assign('oldUsername', $oldUsername);
416
+			$this->assign('mailingList', $this->adminMailingList);
417
+
418
+			$this->getEmailHelper()->sendMail(
419
+				$user->getEmail(),
420
+				'Your username on WP:ACC has been changed',
421
+				$this->fetchTemplate('usermanagement/emails/renamed.tpl'),
422
+				array('Reply-To' => $this->adminMailingList)
423
+			);
424
+
425
+			$this->redirect("userManagement");
426
+
427
+			return;
428
+		}
429
+		else {
430
+			$this->assignCSRFToken();
431
+			$this->setTemplate('usermanagement/renameuser.tpl');
432
+			$this->assign('user', $user);
433
+		}
434
+	}
435
+
436
+	/**
437
+	 * Entry point for the edit action
438
+	 *
439
+	 * @throws ApplicationLogicException
440
+	 */
441
+	protected function editUser()
442
+	{
443
+		$this->setHtmlTitle('User Management');
444
+
445
+		$database = $this->getDatabase();
446
+
447
+		$userId = WebRequest::getInt('user');
448
+		$user = User::getById($userId, $database);
449
+
450
+		if ($user === false) {
451
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
452
+		}
453
+
454
+		// Dual-mode action
455
+		if (WebRequest::wasPosted()) {
456
+			$this->validateCSRFToken();
457
+			$newEmail = WebRequest::postEmail('user_email');
458
+			$newOnWikiName = WebRequest::postString('user_onwikiname');
459
+
460
+			if ($newEmail === null) {
461
+				throw new ApplicationLogicException('Invalid email address');
462
+			}
463
+
464
+			if (!$user->isOAuthLinked()) {
465
+				if (trim($newOnWikiName) == "") {
466
+					throw new ApplicationLogicException('New on-wiki username cannot be blank');
467
+				}
468
+
469
+				$user->setOnWikiName($newOnWikiName);
470
+			}
471
+
472
+			$user->setEmail($newEmail);
473
+
474
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
475
+
476
+			$user->save();
477
+
478
+			Logger::userPreferencesChange($database, $user);
479
+			$this->getNotificationHelper()->userPrefChange($user);
480
+			SessionAlert::quick('Changes to user\'s preferences have been saved');
481
+
482
+			$this->redirect("userManagement");
483
+
484
+			return;
485
+		}
486
+		else {
487
+			$this->assignCSRFToken();
488
+			$this->setTemplate('usermanagement/edituser.tpl');
489
+			$this->assign('user', $user);
490
+		}
491
+	}
492
+
493
+	#endregion
494
+
495
+	/**
496
+	 * Sends a status change email to the user.
497
+	 *
498
+	 * @param string      $subject           The subject of the email
499
+	 * @param string      $template          The smarty template to use
500
+	 * @param string|null $reason            The reason for performing the status change
501
+	 * @param User        $user              The user affected
502
+	 * @param string      $toolAdminUsername The tool admin's username who is making the edit
503
+	 */
504
+	private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
505
+	{
506
+		$this->assign('targetUsername', $user->getUsername());
507
+		$this->assign('toolAdmin', $toolAdminUsername);
508
+		$this->assign('actionReason', $reason);
509
+		$this->assign('mailingList', $this->adminMailingList);
510
+
511
+		$this->getEmailHelper()->sendMail(
512
+			$user->getEmail(),
513
+			$subject,
514
+			$this->fetchTemplate($template),
515
+			array('Reply-To' => $this->adminMailingList)
516
+		);
517
+	}
518
+
519
+	/**
520
+	 * @param UserRole[] $activeRoles
521
+	 *
522
+	 * @return array
523
+	 */
524
+	private function getRoleData($activeRoles)
525
+	{
526
+		$availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
527
+
528
+		$currentUser = User::getCurrent($this->getDatabase());
529
+		$this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
530
+
531
+		$initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
532
+
533
+		$roleData = array();
534
+		foreach ($availableRoles as $role => $data) {
535
+			$intersection = array_intersect($data['editableBy'], $userRoles);
536
+
537
+			$roleData[$role] = $initialValue;
538
+			$roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
539
+			$roleData[$role]['description'] = $data['description'];
540
+		}
541
+
542
+		foreach ($activeRoles as $role) {
543
+			if (!isset($roleData[$role->getRole()])) {
544
+				// This value is no longer available in the configuration, allow changing (aka removing) it.
545
+				$roleData[$role->getRole()] = $initialValue;
546
+				$roleData[$role->getRole()]['allowEdit'] = 1;
547
+			}
548
+
549
+			$roleData[$role->getRole()]['object'] = $role;
550
+			$roleData[$role->getRole()]['active'] = 1;
551
+		}
552
+
553
+		return $roleData;
554
+	}
555 555
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
                     continue;
120 120
                 }
121 121
 
122
-                $newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
122
+                $newValue = WebRequest::postBoolean('role-'.$name) ? 1 : 0;
123 123
                 if ($newValue !== $r['active']) {
124 124
                     if ($newValue === 0) {
125 125
                         $delete[] = $r['object'];
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
             $user->save();
163 163
 
164 164
             $this->getNotificationHelper()->userRolesEdited($user, $reason);
165
-            SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
165
+            SessionAlert::quick('Roles changed for user '.htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
166 166
 
167 167
             $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
168 168
             return;
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
             Logger::suspendedUser($database, $user, $reason);
215 215
 
216 216
             $this->getNotificationHelper()->userSuspended($user, $reason);
217
-            SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
217
+            SessionAlert::quick('Suspended user '.htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
218 218
 
219 219
             // send email
220 220
             $this->sendStatusChangeEmail(
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
             Logger::declinedUser($database, $user, $reason);
276 276
 
277 277
             $this->getNotificationHelper()->userDeclined($user, $reason);
278
-            SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
278
+            SessionAlert::quick('Declined user '.htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
279 279
 
280 280
             // send email
281 281
             $this->sendStatusChangeEmail(
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
             Logger::approvedUser($database, $user);
331 331
 
332 332
             $this->getNotificationHelper()->userApproved($user);
333
-            SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
333
+            SessionAlert::quick('Approved user '.htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
334 334
 
335 335
             // send email
336 336
             $this->sendStatusChangeEmail(
Please login to merge, or discard this patch.