Passed
Push — dependabot/composer/mediawiki/... ( 7d6739 )
by
unknown
05:05
created
includes/Pages/RequestAction/PageCustomClose.php 1 patch
Indentation   +397 added lines, -397 removed lines patch added patch discarded remove patch
@@ -30,401 +30,401 @@
 block discarded – undo
30 30
 
31 31
 class PageCustomClose extends PageCloseRequest
32 32
 {
33
-    use RequestData;
34
-
35
-    public const CREATE_OAUTH = 'created-oauth';
36
-    public const CREATE_BOT = 'created-bot';
37
-
38
-    protected function main()
39
-    {
40
-        $database = $this->getDatabase();
41
-
42
-        $request = $this->getRequest($database);
43
-        $currentUser = User::getCurrent($this->getDatabase());
44
-
45
-        if ($request->getStatus() === RequestStatus::CLOSED) {
46
-            throw new ApplicationLogicException('Request is already closed');
47
-        }
48
-
49
-        // Dual-mode page
50
-        if (WebRequest::wasPosted()) {
51
-            $this->validateCSRFToken();
52
-            $success = $this->doCustomClose($currentUser, $request, $database);
53
-
54
-            if ($success) {
55
-                $this->redirect();
56
-            }
57
-        }
58
-        else {
59
-            $this->assignCSRFToken();
60
-            $this->showCustomCloseForm($database, $request);
61
-        }
62
-    }
63
-
64
-    /**
65
-     * @param $database
66
-     *
67
-     * @return Request
68
-     * @throws ApplicationLogicException
69
-     */
70
-    protected function getRequest(PdoDatabase $database)
71
-    {
72
-        $requestId = WebRequest::getInt('request');
73
-        if ($requestId === null) {
74
-            throw new ApplicationLogicException('Request ID not found');
75
-        }
76
-
77
-        /** @var Request $request */
78
-        $request = Request::getById($requestId, $database);
79
-
80
-        if ($request === false) {
81
-            throw new ApplicationLogicException('Request not found');
82
-        }
83
-
84
-        return $request;
85
-    }
86
-
87
-    /**
88
-     * @param PdoDatabase $database
89
-     *
90
-     * @return EmailTemplate|null
91
-     */
92
-    protected function getTemplate(PdoDatabase $database)
93
-    {
94
-        $templateId = WebRequest::getInt('template');
95
-        if ($templateId === null) {
96
-            return null;
97
-        }
98
-
99
-        /** @var EmailTemplate $template */
100
-        $template = EmailTemplate::getById($templateId, $database);
101
-        if ($template === false || !$template->getActive()) {
102
-            return null;
103
-        }
104
-
105
-        return $template;
106
-    }
107
-
108
-    /**
109
-     * @param $database
110
-     * @param $request
111
-     *
112
-     * @throws Exception
113
-     */
114
-    protected function showCustomCloseForm(PdoDatabase $database, Request $request)
115
-    {
116
-        $this->setHtmlTitle("Custom close");
117
-
118
-        $currentUser = User::getCurrent($database);
119
-        $preferencesManager = PreferenceManager::getForCurrent($database);
120
-        $config = $this->getSiteConfiguration();
121
-
122
-        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
123
-        if (!$allowedPrivateData) {
124
-            // we probably shouldn't be showing the user this form if they're not allowed to access private data...
125
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
126
-        }
127
-
128
-        $template = $this->getTemplate($database);
129
-
130
-        // Preload data
131
-        $this->assign('defaultAction', '');
132
-        $this->assign('defaultQueue', null);
133
-        $this->assign('preloadText', '');
134
-        $this->assign('preloadTitle', '');
135
-
136
-        if ($template !== null) {
137
-            $this->assign('defaultAction', $template->getDefaultAction());
138
-            $this->assign('defaultQueue', $template->getQueue());
139
-            $this->assign('preloadText', $template->getText());
140
-            $this->assign('preloadTitle', $template->getName());
141
-        }
142
-
143
-        // Static data
144
-        $this->assign('requestQueues', $requestQueues = RequestQueue::getEnabledQueues($database));
145
-
146
-        // request data
147
-        $this->assign('requestId', $request->getIp());
148
-        $this->assign('updateVersion', $request->getUpdateVersion());
149
-        $this->setupBasicData($request, $config);
150
-        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
151
-        $this->setupPrivateData($request, $config);
152
-        $this->setupRelatedRequests($request, $config, $database);
153
-
154
-        // IP location
155
-        $trustedIp = $this->getXffTrustProvider()->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
156
-        $this->assign('iplocation', $this->getLocationProvider()->getIpLocation($trustedIp));
157
-
158
-        // Confirmations
159
-        $this->assign('confirmEmailAlreadySent', $this->checkEmailAlreadySent($request));
160
-
161
-        $this->assign('canSkipCcMailingList', $this->barrierTest('skipCcMailingList', $currentUser));
162
-
163
-        $this->assign('allowWelcomeSkip', false);
164
-        $this->assign('forceWelcomeSkip', false);
165
-
166
-        $canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
167
-        $canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
168
-
169
-        $oauth = new OAuthUserHelper($currentUser, $this->getDatabase(), $this->getOAuthProtocolHelper(), $config);
170
-
171
-        $welcomeTemplate = $preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
172
-        if ($welcomeTemplate != 0) {
173
-            $this->assign('allowWelcomeSkip', true);
174
-
175
-            if (!$oauth->canWelcome()) {
176
-                $this->assign('forceWelcomeSkip', true);
177
-            }
178
-        }
179
-
180
-        $this->assign('preferredCreationMode', (int)$preferencesManager->getPreference(PreferenceManager::PREF_CREATION_MODE));
181
-
182
-        // disable options if there's a misconfiguration.
183
-        $canOauthCreate &= $oauth->canCreateAccount();
184
-        $canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
185
-
186
-        $this->assign('canOauthCreate', $canOauthCreate);
187
-        $this->assign('canBotCreate', $canBotCreate);
188
-
189
-        // template
190
-        $this->setTemplate('custom-close.tpl');
191
-    }
192
-
193
-    /**
194
-     * @param User        $currentUser
195
-     * @param Request     $request
196
-     * @param PdoDatabase $database
197
-     *
198
-     * @throws ApplicationLogicException
199
-     */
200
-    protected function doCustomClose(User $currentUser, Request $request, PdoDatabase $database) : bool
201
-    {
202
-        $messageBody = WebRequest::postString('msgbody');
203
-        if ($messageBody === null || trim($messageBody) === '') {
204
-            throw new ApplicationLogicException('Message body cannot be blank');
205
-        }
206
-
207
-        $ccMailingList = true;
208
-        if ($this->barrierTest('skipCcMailingList', $currentUser)) {
209
-            $ccMailingList = WebRequest::postBoolean('ccMailingList');
210
-        }
211
-
212
-        if ($request->getStatus() === RequestStatus::CLOSED) {
213
-            throw new ApplicationLogicException('Request is already closed');
214
-        }
215
-
216
-        if (!(WebRequest::postBoolean('confirmEmailAlreadySent'))
217
-        ) {
218
-            throw new ApplicationLogicException('Not all confirmations checked');
219
-        }
220
-
221
-        $action = WebRequest::postString('action');
222
-
223
-        if ($action === EmailTemplate::ACTION_CREATED || $action === EmailTemplate::ACTION_NOT_CREATED) {
224
-
225
-            if ($action === EmailTemplate::ACTION_CREATED) {
226
-                if ($this->checkAccountCreated($request)) {
227
-                    $this->assignCSRFToken();
228
-                    $this->showCustomCloseForm($database, $request);
229
-
230
-                    $this->assign("preloadText", $messageBody);
231
-                    $this->assign('preloadAction', $action);
232
-                    $this->assign('ccMailingList', $ccMailingList);
233
-                    $this->assign('showNonExistentAccountWarning', true);
234
-                    $this->assign('skipAutoWelcome', WebRequest::postBoolean('skipAutoWelcome'));
235
-
236
-                    return false;
237
-                }
238
-            }
239
-
240
-            // Close request
241
-            $this->closeRequest($request, $database, $action, $messageBody);
242
-
243
-            $this->processWelcome($action, null);
244
-
245
-            // Send the mail after the save, since save can be rolled back
246
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
247
-
248
-            return true;
249
-        }
250
-
251
-        if ($action === self::CREATE_OAUTH || $action === self::CREATE_BOT) {
252
-            $this->processAutoCreation($currentUser, $action, $request, $messageBody, $ccMailingList);
253
-
254
-            return true;
255
-        }
256
-
257
-        if ($action === 'mail') {
258
-            $request->setReserved(null);
259
-            $request->setUpdateVersion(WebRequest::postInt('updateversion'));
260
-            $request->save();
261
-
262
-            // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
263
-            // and be rolled back.
264
-
265
-            // Send mail
266
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
267
-
268
-            Logger::sentMail($database, $request, $messageBody);
269
-            Logger::unreserve($database, $request);
270
-
271
-            $this->getNotificationHelper()->sentMail($request);
272
-            SessionAlert::success("Sent mail to Request {$request->getId()}");
273
-
274
-            return true;
275
-        }
276
-
277
-        $targetQueue = RequestQueue::getByApiName($database, $action, 1);
278
-        if ($targetQueue !== false) {
279
-            // Defer to other state
280
-            $this->deferRequest($request, $database, $targetQueue, $messageBody);
281
-
282
-            // Send the mail after the save, since save can be rolled back
283
-            $this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
284
-
285
-            return true;
286
-        }
287
-
288
-        throw new ApplicationLogicException('Unknown action for custom close.');
289
-    }
290
-
291
-    /**
292
-     * @param Request     $request
293
-     * @param PdoDatabase $database
294
-     * @param string      $action
295
-     * @param string      $messageBody
296
-     *
297
-     * @throws Exception
298
-     * @throws OptimisticLockFailedException
299
-     */
300
-    protected function closeRequest(Request $request, PdoDatabase $database, $action, $messageBody)
301
-    {
302
-        $request->setStatus(RequestStatus::CLOSED);
303
-        $request->setQueue(null);
304
-        $request->setReserved(null);
305
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
306
-        $request->save();
307
-
308
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
309
-        // be rolled back.
310
-
311
-        if ($action == EmailTemplate::ACTION_CREATED) {
312
-            $logCloseType = 'custom-y';
313
-            $notificationCloseType = "Custom, Created";
314
-        }
315
-        else {
316
-            $logCloseType = 'custom-n';
317
-            $notificationCloseType = "Custom, Not Created";
318
-        }
319
-
320
-        Logger::closeRequest($database, $request, $logCloseType, $messageBody);
321
-        $this->getNotificationHelper()->requestClosed($request, $notificationCloseType);
322
-
323
-        $requestName = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
324
-        SessionAlert::success("Request {$request->getId()} ({$requestName}) closed as {$notificationCloseType}.");
325
-    }
326
-
327
-    /**
328
-     * @param Request      $request
329
-     * @param PdoDatabase  $database
330
-     * @param RequestQueue $targetQueue
331
-     * @param string       $messageBody
332
-     *
333
-     * @throws OptimisticLockFailedException
334
-     */
335
-    protected function deferRequest(
336
-        Request $request,
337
-        PdoDatabase $database,
338
-        RequestQueue $targetQueue,
339
-        $messageBody
340
-    ) {
341
-        $request->setStatus(RequestStatus::OPEN);
342
-        $request->setQueue($targetQueue->getId());
343
-        $request->setReserved(null);
344
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
345
-        $request->save();
346
-
347
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
348
-        // and be rolled back.
349
-
350
-        $deferToLog = $targetQueue->getLogName();
351
-        Logger::sentMail($database, $request, $messageBody);
352
-        Logger::deferRequest($database, $request, $deferToLog);
353
-
354
-        $this->getNotificationHelper()->requestDeferredWithMail($request);
355
-
356
-        $deferTo = htmlentities($targetQueue->getDisplayName(), ENT_COMPAT, 'UTF-8');
357
-        SessionAlert::success("Request {$request->getId()} deferred to $deferTo, sending an email.");
358
-    }
359
-
360
-    /**
361
-     * @param User    $currentUser
362
-     * @param string  $action
363
-     * @param Request $request
364
-     * @param string  $messageBody
365
-     * @param bool    $ccMailingList
366
-     *
367
-     * @throws AccessDeniedException
368
-     * @throws ApplicationLogicException
369
-     * @throws OptimisticLockFailedException
370
-     */
371
-    protected function processAutoCreation(User $currentUser, string $action, Request $request, string $messageBody, bool $ccMailingList): void
372
-    {
373
-        $db = $this->getDatabase();
374
-        $oauth = new OAuthUserHelper($currentUser, $db, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
375
-        $canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
376
-        $canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
377
-        $canOauthCreate &= $oauth->canCreateAccount();
378
-        $canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
379
-
380
-        $creationTaskClass = null;
381
-
382
-        if ($action === self::CREATE_OAUTH) {
383
-            if (!$canOauthCreate) {
384
-                throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
385
-            }
386
-
387
-            $creationTaskClass = UserCreationTask::class;
388
-        }
389
-
390
-        if ($action === self::CREATE_BOT) {
391
-            if (!$canBotCreate) {
392
-                throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
393
-            }
394
-
395
-            $creationTaskClass = BotCreationTask::class;
396
-        }
397
-
398
-        if ($creationTaskClass === null) {
399
-            throw new ApplicationLogicException('Cannot determine creation mode');
400
-        }
401
-
402
-        $request->setStatus(RequestStatus::JOBQUEUE);
403
-        $request->setReserved(null);
404
-        $request->save();
405
-
406
-        $parameters = [
407
-            'emailText' => $messageBody,
408
-            'ccMailingList' => $ccMailingList
409
-        ];
410
-
411
-        $creationTask = new JobQueue();
412
-        $creationTask->setDomain(1); // FIXME: domains!
413
-        $creationTask->setTask($creationTaskClass);
414
-        $creationTask->setRequest($request->getId());
415
-        $creationTask->setTriggerUserId($currentUser->getId());
416
-        $creationTask->setParameters(json_encode($parameters));
417
-        $creationTask->setDatabase($db);
418
-        $creationTask->save();
419
-
420
-        $creationTaskId = $creationTask->getId();
421
-
422
-        Logger::enqueuedJobQueue($db, $request);
423
-        $this->getNotificationHelper()->requestCloseQueued($request, 'Custom, Created');
424
-
425
-        SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
426
-
427
-        // forge this since it is actually a creation.
428
-        $this->processWelcome(EmailTemplate::ACTION_CREATED, $creationTaskId);
429
-    }
33
+	use RequestData;
34
+
35
+	public const CREATE_OAUTH = 'created-oauth';
36
+	public const CREATE_BOT = 'created-bot';
37
+
38
+	protected function main()
39
+	{
40
+		$database = $this->getDatabase();
41
+
42
+		$request = $this->getRequest($database);
43
+		$currentUser = User::getCurrent($this->getDatabase());
44
+
45
+		if ($request->getStatus() === RequestStatus::CLOSED) {
46
+			throw new ApplicationLogicException('Request is already closed');
47
+		}
48
+
49
+		// Dual-mode page
50
+		if (WebRequest::wasPosted()) {
51
+			$this->validateCSRFToken();
52
+			$success = $this->doCustomClose($currentUser, $request, $database);
53
+
54
+			if ($success) {
55
+				$this->redirect();
56
+			}
57
+		}
58
+		else {
59
+			$this->assignCSRFToken();
60
+			$this->showCustomCloseForm($database, $request);
61
+		}
62
+	}
63
+
64
+	/**
65
+	 * @param $database
66
+	 *
67
+	 * @return Request
68
+	 * @throws ApplicationLogicException
69
+	 */
70
+	protected function getRequest(PdoDatabase $database)
71
+	{
72
+		$requestId = WebRequest::getInt('request');
73
+		if ($requestId === null) {
74
+			throw new ApplicationLogicException('Request ID not found');
75
+		}
76
+
77
+		/** @var Request $request */
78
+		$request = Request::getById($requestId, $database);
79
+
80
+		if ($request === false) {
81
+			throw new ApplicationLogicException('Request not found');
82
+		}
83
+
84
+		return $request;
85
+	}
86
+
87
+	/**
88
+	 * @param PdoDatabase $database
89
+	 *
90
+	 * @return EmailTemplate|null
91
+	 */
92
+	protected function getTemplate(PdoDatabase $database)
93
+	{
94
+		$templateId = WebRequest::getInt('template');
95
+		if ($templateId === null) {
96
+			return null;
97
+		}
98
+
99
+		/** @var EmailTemplate $template */
100
+		$template = EmailTemplate::getById($templateId, $database);
101
+		if ($template === false || !$template->getActive()) {
102
+			return null;
103
+		}
104
+
105
+		return $template;
106
+	}
107
+
108
+	/**
109
+	 * @param $database
110
+	 * @param $request
111
+	 *
112
+	 * @throws Exception
113
+	 */
114
+	protected function showCustomCloseForm(PdoDatabase $database, Request $request)
115
+	{
116
+		$this->setHtmlTitle("Custom close");
117
+
118
+		$currentUser = User::getCurrent($database);
119
+		$preferencesManager = PreferenceManager::getForCurrent($database);
120
+		$config = $this->getSiteConfiguration();
121
+
122
+		$allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
123
+		if (!$allowedPrivateData) {
124
+			// we probably shouldn't be showing the user this form if they're not allowed to access private data...
125
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
126
+		}
127
+
128
+		$template = $this->getTemplate($database);
129
+
130
+		// Preload data
131
+		$this->assign('defaultAction', '');
132
+		$this->assign('defaultQueue', null);
133
+		$this->assign('preloadText', '');
134
+		$this->assign('preloadTitle', '');
135
+
136
+		if ($template !== null) {
137
+			$this->assign('defaultAction', $template->getDefaultAction());
138
+			$this->assign('defaultQueue', $template->getQueue());
139
+			$this->assign('preloadText', $template->getText());
140
+			$this->assign('preloadTitle', $template->getName());
141
+		}
142
+
143
+		// Static data
144
+		$this->assign('requestQueues', $requestQueues = RequestQueue::getEnabledQueues($database));
145
+
146
+		// request data
147
+		$this->assign('requestId', $request->getIp());
148
+		$this->assign('updateVersion', $request->getUpdateVersion());
149
+		$this->setupBasicData($request, $config);
150
+		$this->setupReservationDetails($request->getReserved(), $database, $currentUser);
151
+		$this->setupPrivateData($request, $config);
152
+		$this->setupRelatedRequests($request, $config, $database);
153
+
154
+		// IP location
155
+		$trustedIp = $this->getXffTrustProvider()->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
156
+		$this->assign('iplocation', $this->getLocationProvider()->getIpLocation($trustedIp));
157
+
158
+		// Confirmations
159
+		$this->assign('confirmEmailAlreadySent', $this->checkEmailAlreadySent($request));
160
+
161
+		$this->assign('canSkipCcMailingList', $this->barrierTest('skipCcMailingList', $currentUser));
162
+
163
+		$this->assign('allowWelcomeSkip', false);
164
+		$this->assign('forceWelcomeSkip', false);
165
+
166
+		$canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
167
+		$canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
168
+
169
+		$oauth = new OAuthUserHelper($currentUser, $this->getDatabase(), $this->getOAuthProtocolHelper(), $config);
170
+
171
+		$welcomeTemplate = $preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
172
+		if ($welcomeTemplate != 0) {
173
+			$this->assign('allowWelcomeSkip', true);
174
+
175
+			if (!$oauth->canWelcome()) {
176
+				$this->assign('forceWelcomeSkip', true);
177
+			}
178
+		}
179
+
180
+		$this->assign('preferredCreationMode', (int)$preferencesManager->getPreference(PreferenceManager::PREF_CREATION_MODE));
181
+
182
+		// disable options if there's a misconfiguration.
183
+		$canOauthCreate &= $oauth->canCreateAccount();
184
+		$canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
185
+
186
+		$this->assign('canOauthCreate', $canOauthCreate);
187
+		$this->assign('canBotCreate', $canBotCreate);
188
+
189
+		// template
190
+		$this->setTemplate('custom-close.tpl');
191
+	}
192
+
193
+	/**
194
+	 * @param User        $currentUser
195
+	 * @param Request     $request
196
+	 * @param PdoDatabase $database
197
+	 *
198
+	 * @throws ApplicationLogicException
199
+	 */
200
+	protected function doCustomClose(User $currentUser, Request $request, PdoDatabase $database) : bool
201
+	{
202
+		$messageBody = WebRequest::postString('msgbody');
203
+		if ($messageBody === null || trim($messageBody) === '') {
204
+			throw new ApplicationLogicException('Message body cannot be blank');
205
+		}
206
+
207
+		$ccMailingList = true;
208
+		if ($this->barrierTest('skipCcMailingList', $currentUser)) {
209
+			$ccMailingList = WebRequest::postBoolean('ccMailingList');
210
+		}
211
+
212
+		if ($request->getStatus() === RequestStatus::CLOSED) {
213
+			throw new ApplicationLogicException('Request is already closed');
214
+		}
215
+
216
+		if (!(WebRequest::postBoolean('confirmEmailAlreadySent'))
217
+		) {
218
+			throw new ApplicationLogicException('Not all confirmations checked');
219
+		}
220
+
221
+		$action = WebRequest::postString('action');
222
+
223
+		if ($action === EmailTemplate::ACTION_CREATED || $action === EmailTemplate::ACTION_NOT_CREATED) {
224
+
225
+			if ($action === EmailTemplate::ACTION_CREATED) {
226
+				if ($this->checkAccountCreated($request)) {
227
+					$this->assignCSRFToken();
228
+					$this->showCustomCloseForm($database, $request);
229
+
230
+					$this->assign("preloadText", $messageBody);
231
+					$this->assign('preloadAction', $action);
232
+					$this->assign('ccMailingList', $ccMailingList);
233
+					$this->assign('showNonExistentAccountWarning', true);
234
+					$this->assign('skipAutoWelcome', WebRequest::postBoolean('skipAutoWelcome'));
235
+
236
+					return false;
237
+				}
238
+			}
239
+
240
+			// Close request
241
+			$this->closeRequest($request, $database, $action, $messageBody);
242
+
243
+			$this->processWelcome($action, null);
244
+
245
+			// Send the mail after the save, since save can be rolled back
246
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
247
+
248
+			return true;
249
+		}
250
+
251
+		if ($action === self::CREATE_OAUTH || $action === self::CREATE_BOT) {
252
+			$this->processAutoCreation($currentUser, $action, $request, $messageBody, $ccMailingList);
253
+
254
+			return true;
255
+		}
256
+
257
+		if ($action === 'mail') {
258
+			$request->setReserved(null);
259
+			$request->setUpdateVersion(WebRequest::postInt('updateversion'));
260
+			$request->save();
261
+
262
+			// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
263
+			// and be rolled back.
264
+
265
+			// Send mail
266
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
267
+
268
+			Logger::sentMail($database, $request, $messageBody);
269
+			Logger::unreserve($database, $request);
270
+
271
+			$this->getNotificationHelper()->sentMail($request);
272
+			SessionAlert::success("Sent mail to Request {$request->getId()}");
273
+
274
+			return true;
275
+		}
276
+
277
+		$targetQueue = RequestQueue::getByApiName($database, $action, 1);
278
+		if ($targetQueue !== false) {
279
+			// Defer to other state
280
+			$this->deferRequest($request, $database, $targetQueue, $messageBody);
281
+
282
+			// Send the mail after the save, since save can be rolled back
283
+			$this->sendMail($request, $messageBody, $currentUser, $ccMailingList);
284
+
285
+			return true;
286
+		}
287
+
288
+		throw new ApplicationLogicException('Unknown action for custom close.');
289
+	}
290
+
291
+	/**
292
+	 * @param Request     $request
293
+	 * @param PdoDatabase $database
294
+	 * @param string      $action
295
+	 * @param string      $messageBody
296
+	 *
297
+	 * @throws Exception
298
+	 * @throws OptimisticLockFailedException
299
+	 */
300
+	protected function closeRequest(Request $request, PdoDatabase $database, $action, $messageBody)
301
+	{
302
+		$request->setStatus(RequestStatus::CLOSED);
303
+		$request->setQueue(null);
304
+		$request->setReserved(null);
305
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
306
+		$request->save();
307
+
308
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
309
+		// be rolled back.
310
+
311
+		if ($action == EmailTemplate::ACTION_CREATED) {
312
+			$logCloseType = 'custom-y';
313
+			$notificationCloseType = "Custom, Created";
314
+		}
315
+		else {
316
+			$logCloseType = 'custom-n';
317
+			$notificationCloseType = "Custom, Not Created";
318
+		}
319
+
320
+		Logger::closeRequest($database, $request, $logCloseType, $messageBody);
321
+		$this->getNotificationHelper()->requestClosed($request, $notificationCloseType);
322
+
323
+		$requestName = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
324
+		SessionAlert::success("Request {$request->getId()} ({$requestName}) closed as {$notificationCloseType}.");
325
+	}
326
+
327
+	/**
328
+	 * @param Request      $request
329
+	 * @param PdoDatabase  $database
330
+	 * @param RequestQueue $targetQueue
331
+	 * @param string       $messageBody
332
+	 *
333
+	 * @throws OptimisticLockFailedException
334
+	 */
335
+	protected function deferRequest(
336
+		Request $request,
337
+		PdoDatabase $database,
338
+		RequestQueue $targetQueue,
339
+		$messageBody
340
+	) {
341
+		$request->setStatus(RequestStatus::OPEN);
342
+		$request->setQueue($targetQueue->getId());
343
+		$request->setReserved(null);
344
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
345
+		$request->save();
346
+
347
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE
348
+		// and be rolled back.
349
+
350
+		$deferToLog = $targetQueue->getLogName();
351
+		Logger::sentMail($database, $request, $messageBody);
352
+		Logger::deferRequest($database, $request, $deferToLog);
353
+
354
+		$this->getNotificationHelper()->requestDeferredWithMail($request);
355
+
356
+		$deferTo = htmlentities($targetQueue->getDisplayName(), ENT_COMPAT, 'UTF-8');
357
+		SessionAlert::success("Request {$request->getId()} deferred to $deferTo, sending an email.");
358
+	}
359
+
360
+	/**
361
+	 * @param User    $currentUser
362
+	 * @param string  $action
363
+	 * @param Request $request
364
+	 * @param string  $messageBody
365
+	 * @param bool    $ccMailingList
366
+	 *
367
+	 * @throws AccessDeniedException
368
+	 * @throws ApplicationLogicException
369
+	 * @throws OptimisticLockFailedException
370
+	 */
371
+	protected function processAutoCreation(User $currentUser, string $action, Request $request, string $messageBody, bool $ccMailingList): void
372
+	{
373
+		$db = $this->getDatabase();
374
+		$oauth = new OAuthUserHelper($currentUser, $db, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
375
+		$canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $currentUser, 'RequestCreation');
376
+		$canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $currentUser, 'RequestCreation');
377
+		$canOauthCreate &= $oauth->canCreateAccount();
378
+		$canBotCreate &= $this->getSiteConfiguration()->getCreationBotPassword() !== null;
379
+
380
+		$creationTaskClass = null;
381
+
382
+		if ($action === self::CREATE_OAUTH) {
383
+			if (!$canOauthCreate) {
384
+				throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
385
+			}
386
+
387
+			$creationTaskClass = UserCreationTask::class;
388
+		}
389
+
390
+		if ($action === self::CREATE_BOT) {
391
+			if (!$canBotCreate) {
392
+				throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
393
+			}
394
+
395
+			$creationTaskClass = BotCreationTask::class;
396
+		}
397
+
398
+		if ($creationTaskClass === null) {
399
+			throw new ApplicationLogicException('Cannot determine creation mode');
400
+		}
401
+
402
+		$request->setStatus(RequestStatus::JOBQUEUE);
403
+		$request->setReserved(null);
404
+		$request->save();
405
+
406
+		$parameters = [
407
+			'emailText' => $messageBody,
408
+			'ccMailingList' => $ccMailingList
409
+		];
410
+
411
+		$creationTask = new JobQueue();
412
+		$creationTask->setDomain(1); // FIXME: domains!
413
+		$creationTask->setTask($creationTaskClass);
414
+		$creationTask->setRequest($request->getId());
415
+		$creationTask->setTriggerUserId($currentUser->getId());
416
+		$creationTask->setParameters(json_encode($parameters));
417
+		$creationTask->setDatabase($db);
418
+		$creationTask->save();
419
+
420
+		$creationTaskId = $creationTask->getId();
421
+
422
+		Logger::enqueuedJobQueue($db, $request);
423
+		$this->getNotificationHelper()->requestCloseQueued($request, 'Custom, Created');
424
+
425
+		SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
426
+
427
+		// forge this since it is actually a creation.
428
+		$this->processWelcome(EmailTemplate::ACTION_CREATED, $creationTaskId);
429
+	}
430 430
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageCreateRequest.php 1 patch
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -34,156 +34,156 @@
 block discarded – undo
34 34
  */
35 35
 class PageCreateRequest extends RequestActionBase
36 36
 {
37
-    /**
38
-     * Main function for this page, when no specific actions are called.
39
-     * @return void
40
-     * @throws AccessDeniedException
41
-     * @throws ApplicationLogicException
42
-     */
43
-    protected function main()
44
-    {
45
-        $this->checkPosted();
46
-
47
-        $database = $this->getDatabase();
48
-
49
-        $request = $this->getRequest($database);
50
-        $template = $this->getTemplate($database);
51
-        $creationMode = $this->getCreationMode();
52
-        $user = User::getCurrent($database);
53
-        $preferencesManager = PreferenceManager::getForCurrent($database);
54
-
55
-        $secMgr = $this->getSecurityManager();
56
-        if ($secMgr->allows('RequestCreation', PreferenceManager::CREATION_BOT, $user) !== SecurityManager::ALLOWED
57
-            && $creationMode === 'bot'
58
-        ) {
59
-            throw new AccessDeniedException($secMgr, $this->getDomainAccessManager());
60
-        }
61
-        elseif ($secMgr->allows('RequestCreation', PreferenceManager::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
62
-            && $creationMode === 'oauth'
63
-        ) {
64
-            throw new AccessDeniedException($secMgr, $this->getDomainAccessManager());
65
-        }
66
-
67
-        if ($request->getEmailSent()) {
68
-            throw new ApplicationLogicException('This requester has already had an email sent to them. Please fall back to manual creation or a custom close');
69
-        }
70
-
71
-        $request->setStatus(RequestStatus::JOBQUEUE);
72
-        $request->setReserved(null);
73
-        $request->save();
74
-
75
-        Logger::enqueuedJobQueue($database, $request);
76
-
77
-        $creationTaskId = $this->enqueueCreationTask($creationMode, $request, $template, $user, $database);
78
-
79
-        $welcomeTemplate = $preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
80
-        if ($welcomeTemplate !== null && !WebRequest::postBoolean('skipAutoWelcome')) {
81
-            $this->enqueueWelcomeTask($request, $creationTaskId, $user, $database);
82
-        }
83
-
84
-        $this->getNotificationHelper()->requestCloseQueued($request, $template->getName());
85
-
86
-        SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
87
-
88
-        $this->redirect();
89
-    }
90
-
91
-    protected function getCreationMode()
92
-    {
93
-        $creationMode = WebRequest::postString('mode');
94
-        if ($creationMode !== 'oauth' && $creationMode !== 'bot') {
95
-            throw new ApplicationLogicException('Unknown creation mode');
96
-        }
97
-
98
-        return $creationMode;
99
-    }
100
-
101
-    /**
102
-     * @param PdoDatabase $database
103
-     *
104
-     * @return EmailTemplate
105
-     * @throws ApplicationLogicException
106
-     */
107
-    protected function getTemplate(PdoDatabase $database)
108
-    {
109
-        $templateId = WebRequest::postInt('template');
110
-        if ($templateId === null) {
111
-            throw new ApplicationLogicException('No template specified');
112
-        }
113
-
114
-        /** @var EmailTemplate $template */
115
-        $template = EmailTemplate::getById($templateId, $database);
116
-        if ($template === false || !$template->getActive()) {
117
-            throw new ApplicationLogicException('Invalid or inactive template specified');
118
-        }
119
-
120
-        if ($template->getDefaultAction() !== EmailTemplate::ACTION_CREATED) {
121
-            throw new ApplicationLogicException('Specified template is not a creation template!');
122
-        }
123
-
124
-        return $template;
125
-    }
126
-
127
-    /**
128
-     * @param PdoDatabase $database
129
-     *
130
-     * @return Request
131
-     * @throws ApplicationLogicException
132
-     */
133
-    protected function getRequest(PdoDatabase $database)
134
-    {
135
-        $request = parent::getRequest($database);
136
-
137
-        if ($request->getStatus() == RequestStatus::CLOSED) {
138
-            throw new ApplicationLogicException('Request is already closed');
139
-        }
140
-
141
-        return $request;
142
-    }
143
-
144
-    /**
145
-     * @param               $creationMode
146
-     * @param Request       $request
147
-     * @param EmailTemplate $template
148
-     * @param User          $user
149
-     *
150
-     * @param PdoDatabase   $database
151
-     *
152
-     * @return int
153
-     * @throws ApplicationLogicException
154
-     */
155
-    protected function enqueueCreationTask(
156
-        $creationMode,
157
-        Request $request,
158
-        EmailTemplate $template,
159
-        User $user,
160
-        PdoDatabase $database
161
-    ) {
162
-        $creationTaskClass = null;
163
-
164
-        if ($creationMode == "oauth") {
165
-            $creationTaskClass = UserCreationTask::class;
166
-        }
167
-
168
-        if ($creationMode == "bot") {
169
-            $creationTaskClass = BotCreationTask::class;
170
-        }
171
-
172
-        if ($creationTaskClass === null) {
173
-            throw new ApplicationLogicException('Cannot determine creation mode');
174
-        }
175
-
176
-        $creationTask = new JobQueue();
177
-        $creationTask->setDomain(1); // FIXME: domains!
178
-        $creationTask->setTask($creationTaskClass);
179
-        $creationTask->setRequest($request->getId());
180
-        $creationTask->setEmailTemplate($template->getId());
181
-        $creationTask->setTriggerUserId($user->getId());
182
-        $creationTask->setDatabase($database);
183
-        $creationTask->save();
184
-
185
-        $creationTaskId = $creationTask->getId();
186
-
187
-        return $creationTaskId;
188
-    }
37
+	/**
38
+	 * Main function for this page, when no specific actions are called.
39
+	 * @return void
40
+	 * @throws AccessDeniedException
41
+	 * @throws ApplicationLogicException
42
+	 */
43
+	protected function main()
44
+	{
45
+		$this->checkPosted();
46
+
47
+		$database = $this->getDatabase();
48
+
49
+		$request = $this->getRequest($database);
50
+		$template = $this->getTemplate($database);
51
+		$creationMode = $this->getCreationMode();
52
+		$user = User::getCurrent($database);
53
+		$preferencesManager = PreferenceManager::getForCurrent($database);
54
+
55
+		$secMgr = $this->getSecurityManager();
56
+		if ($secMgr->allows('RequestCreation', PreferenceManager::CREATION_BOT, $user) !== SecurityManager::ALLOWED
57
+			&& $creationMode === 'bot'
58
+		) {
59
+			throw new AccessDeniedException($secMgr, $this->getDomainAccessManager());
60
+		}
61
+		elseif ($secMgr->allows('RequestCreation', PreferenceManager::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
62
+			&& $creationMode === 'oauth'
63
+		) {
64
+			throw new AccessDeniedException($secMgr, $this->getDomainAccessManager());
65
+		}
66
+
67
+		if ($request->getEmailSent()) {
68
+			throw new ApplicationLogicException('This requester has already had an email sent to them. Please fall back to manual creation or a custom close');
69
+		}
70
+
71
+		$request->setStatus(RequestStatus::JOBQUEUE);
72
+		$request->setReserved(null);
73
+		$request->save();
74
+
75
+		Logger::enqueuedJobQueue($database, $request);
76
+
77
+		$creationTaskId = $this->enqueueCreationTask($creationMode, $request, $template, $user, $database);
78
+
79
+		$welcomeTemplate = $preferencesManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
80
+		if ($welcomeTemplate !== null && !WebRequest::postBoolean('skipAutoWelcome')) {
81
+			$this->enqueueWelcomeTask($request, $creationTaskId, $user, $database);
82
+		}
83
+
84
+		$this->getNotificationHelper()->requestCloseQueued($request, $template->getName());
85
+
86
+		SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
87
+
88
+		$this->redirect();
89
+	}
90
+
91
+	protected function getCreationMode()
92
+	{
93
+		$creationMode = WebRequest::postString('mode');
94
+		if ($creationMode !== 'oauth' && $creationMode !== 'bot') {
95
+			throw new ApplicationLogicException('Unknown creation mode');
96
+		}
97
+
98
+		return $creationMode;
99
+	}
100
+
101
+	/**
102
+	 * @param PdoDatabase $database
103
+	 *
104
+	 * @return EmailTemplate
105
+	 * @throws ApplicationLogicException
106
+	 */
107
+	protected function getTemplate(PdoDatabase $database)
108
+	{
109
+		$templateId = WebRequest::postInt('template');
110
+		if ($templateId === null) {
111
+			throw new ApplicationLogicException('No template specified');
112
+		}
113
+
114
+		/** @var EmailTemplate $template */
115
+		$template = EmailTemplate::getById($templateId, $database);
116
+		if ($template === false || !$template->getActive()) {
117
+			throw new ApplicationLogicException('Invalid or inactive template specified');
118
+		}
119
+
120
+		if ($template->getDefaultAction() !== EmailTemplate::ACTION_CREATED) {
121
+			throw new ApplicationLogicException('Specified template is not a creation template!');
122
+		}
123
+
124
+		return $template;
125
+	}
126
+
127
+	/**
128
+	 * @param PdoDatabase $database
129
+	 *
130
+	 * @return Request
131
+	 * @throws ApplicationLogicException
132
+	 */
133
+	protected function getRequest(PdoDatabase $database)
134
+	{
135
+		$request = parent::getRequest($database);
136
+
137
+		if ($request->getStatus() == RequestStatus::CLOSED) {
138
+			throw new ApplicationLogicException('Request is already closed');
139
+		}
140
+
141
+		return $request;
142
+	}
143
+
144
+	/**
145
+	 * @param               $creationMode
146
+	 * @param Request       $request
147
+	 * @param EmailTemplate $template
148
+	 * @param User          $user
149
+	 *
150
+	 * @param PdoDatabase   $database
151
+	 *
152
+	 * @return int
153
+	 * @throws ApplicationLogicException
154
+	 */
155
+	protected function enqueueCreationTask(
156
+		$creationMode,
157
+		Request $request,
158
+		EmailTemplate $template,
159
+		User $user,
160
+		PdoDatabase $database
161
+	) {
162
+		$creationTaskClass = null;
163
+
164
+		if ($creationMode == "oauth") {
165
+			$creationTaskClass = UserCreationTask::class;
166
+		}
167
+
168
+		if ($creationMode == "bot") {
169
+			$creationTaskClass = BotCreationTask::class;
170
+		}
171
+
172
+		if ($creationTaskClass === null) {
173
+			throw new ApplicationLogicException('Cannot determine creation mode');
174
+		}
175
+
176
+		$creationTask = new JobQueue();
177
+		$creationTask->setDomain(1); // FIXME: domains!
178
+		$creationTask->setTask($creationTaskClass);
179
+		$creationTask->setRequest($request->getId());
180
+		$creationTask->setEmailTemplate($template->getId());
181
+		$creationTask->setTriggerUserId($user->getId());
182
+		$creationTask->setDatabase($database);
183
+		$creationTask->save();
184
+
185
+		$creationTaskId = $creationTask->getId();
186
+
187
+		return $creationTaskId;
188
+	}
189 189
 }
Please login to merge, or discard this patch.
includes/Pages/PageDomainManagement.php 1 patch
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -19,160 +19,160 @@
 block discarded – undo
19 19
 
20 20
 class PageDomainManagement extends InternalPageBase
21 21
 {
22
-    protected function main()
23
-    {
24
-        $this->setHtmlTitle('Domain Management');
25
-
26
-        $database = $this->getDatabase();
27
-        $currentUser = User::getCurrent($database);
28
-
29
-        /** @var Domain[] $domains */
30
-        $domains = Domain::getAll($database);
31
-
32
-        $templates = [];
33
-        foreach ($domains as $domain) {
34
-            if ($domain->getDefaultClose() !== null) {
35
-                $templates[$domain->getDefaultClose()] = EmailTemplate::getById($domain->getDefaultClose(), $database);
36
-            }
37
-        }
38
-
39
-        $canEdit = $this->barrierTest('edit', $currentUser);
40
-        $canEditAll = $this->barrierTest('editAll', $currentUser);
41
-        $canCreate = $this->barrierTest('create', $currentUser);
42
-        $this->assign('canEdit', $canEdit);
43
-        $this->assign('canEditAll', $canEditAll);
44
-        $this->assign('canCreate', $canCreate);
45
-
46
-        $this->assign('domains', $domains);
47
-        $this->assign('closeTemplates', $templates);
48
-        $this->assign('currentDomain', Domain::getCurrent($database));
49
-        $this->setTemplate('domain-management/main.tpl');
50
-    }
51
-
52
-    protected function create()
53
-    {
54
-        $this->setHtmlTitle('Domain Management');
55
-        $database = $this->getDatabase();
56
-        $currentUser = User::getCurrent($database);
57
-
58
-        // quickly check the user is allowed to edit all fields. If not, then they shouldn't be allowed to create
59
-        // new domains either. With any luck, a competent developer would never grant create without editAll to a role
60
-        // anyway, so this will never be hit.
61
-        if (!$this->barrierTest('editAll', $currentUser)) {
62
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
63
-        }
64
-
65
-        if (WebRequest::wasPosted()) {
66
-            $this->validateCSRFToken();
67
-
68
-            $domain = new Domain();
69
-            $domain->setDatabase($database);
70
-
71
-            $domain->setShortName(WebRequest::postString('shortName'));
72
-            $domain->setLongName(WebRequest::postString('longName'));
73
-            $domain->setWikiArticlePath(WebRequest::postString('articlePath'));
74
-            $domain->setWikiApiPath(WebRequest::postString('apiPath'));
75
-            $domain->setEnabled(WebRequest::postBoolean('enabled'));
76
-            $domain->setDefaultLanguage(WebRequest::postString('defaultLanguage'));
77
-            $domain->setDefaultClose(null);
78
-            $domain->setEmailReplyAddress(WebRequest::postString('emailReplyTo'));
79
-            $domain->setNotificationTarget(WebRequest::postString('notificationTarget'));
80
-            $domain->setLocalDocumentation(WebRequest::postString('localDocumentation'));
81
-
82
-            $domain->save();
83
-
84
-            Logger::domainCreated($database, $domain);
85
-            $this->redirect('domainManagement');
86
-        }
87
-        else {
88
-            $this->assignCSRFToken();
89
-
90
-            $this->assign('shortName', '');
91
-            $this->assign('longName', '');
92
-            $this->assign('articlePath', '');
93
-            $this->assign('apiPath', '');
94
-            $this->assign('enabled', false);
95
-            $this->assign('defaultLanguage', 'en');
96
-            $this->assign('emailReplyTo', '');
97
-            $this->assign('notificationTarget', '');
98
-            $this->assign('localDocumentation', '');
99
-
100
-            $this->assign('createMode', true);
101
-            $this->assign('canEditAll', true);
102
-
103
-            $this->setTemplate('domain-management/edit.tpl');
104
-        }
105
-    }
106
-
107
-    protected function edit()
108
-    {
109
-        $this->setHtmlTitle('Domain Management');
110
-        $database = $this->getDatabase();
111
-        $currentUser = User::getCurrent($database);
112
-
113
-        $canEditAll = $this->barrierTest('editAll', $currentUser);
114
-
115
-        /** @var Domain $domain */
116
-        $domain = Domain::getById(WebRequest::getInt('domain'), $database);
117
-
118
-        if (WebRequest::wasPosted()) {
119
-            $this->validateCSRFToken();
120
-
121
-            $domain->setLongName(WebRequest::postString('longName'));
122
-            $domain->setDefaultLanguage(WebRequest::postString('defaultLanguage'));
123
-            $domain->setLocalDocumentation(WebRequest::postString('localDocumentation'));
124
-
125
-            /** @var EmailTemplate|false $template */
126
-            $template = EmailTemplate::getById(WebRequest::postInt('defaultClose'), $database);
127
-            if ($template !== false
128
-                && $template->getActive()
129
-                && $template->getPreloadOnly() === false
130
-                && $template->getDefaultAction() === EmailTemplate::ACTION_CREATED) {
131
-                $domain->setDefaultClose(WebRequest::postInt('defaultClose'));
132
-            }
133
-            else {
134
-                SessionAlert::warning("Chosen email template is not valid for use as the default creation template");
135
-            }
136
-
137
-            if ($canEditAll) {
138
-                $domain->setWikiArticlePath(WebRequest::postString('articlePath'));
139
-                $domain->setWikiApiPath(WebRequest::postString('apiPath'));
140
-                $domain->setEnabled(WebRequest::postBoolean('enabled'));
141
-                $domain->setEmailReplyAddress(WebRequest::postString('emailReplyTo'));
142
-                $domain->setNotificationTarget(WebRequest::postString('notificationTarget'));
143
-            }
144
-
145
-            $domain->save();
146
-
147
-            Logger::domainEdited($database, $domain);
148
-            $this->redirect('domainManagement');
149
-        }
150
-        else {
151
-            $this->assignCSRFToken();
152
-
153
-            $templates = EmailTemplate::getActiveNonpreloadTemplates(
154
-                EmailTemplate::ACTION_CREATED,
155
-                $database,
156
-                $domain->getId());
157
-
158
-            $this->assign('closeTemplates', $templates);
159
-
160
-            $this->assign('shortName', $domain->getShortName());
161
-            $this->assign('longName', $domain->getLongName());
162
-            $this->assign('articlePath', $domain->getWikiArticlePath());
163
-            $this->assign('apiPath', $domain->getWikiApiPath());
164
-            $this->assign('enabled', $domain->isEnabled());
165
-            $this->assign('defaultClose', $domain->getDefaultClose());
166
-            $this->assign('defaultLanguage', $domain->getDefaultLanguage());
167
-            $this->assign('emailReplyTo', $domain->getEmailReplyAddress());
168
-            $this->assign('notificationTarget', $domain->getNotificationTarget());
169
-            $this->assign('localDocumentation', $domain->getLocalDocumentation());
170
-
171
-
172
-            $this->assign('createMode', false);
173
-            $this->assign('canEditAll', $canEditAll);
174
-
175
-            $this->setTemplate('domain-management/edit.tpl');
176
-        }
177
-    }
22
+	protected function main()
23
+	{
24
+		$this->setHtmlTitle('Domain Management');
25
+
26
+		$database = $this->getDatabase();
27
+		$currentUser = User::getCurrent($database);
28
+
29
+		/** @var Domain[] $domains */
30
+		$domains = Domain::getAll($database);
31
+
32
+		$templates = [];
33
+		foreach ($domains as $domain) {
34
+			if ($domain->getDefaultClose() !== null) {
35
+				$templates[$domain->getDefaultClose()] = EmailTemplate::getById($domain->getDefaultClose(), $database);
36
+			}
37
+		}
38
+
39
+		$canEdit = $this->barrierTest('edit', $currentUser);
40
+		$canEditAll = $this->barrierTest('editAll', $currentUser);
41
+		$canCreate = $this->barrierTest('create', $currentUser);
42
+		$this->assign('canEdit', $canEdit);
43
+		$this->assign('canEditAll', $canEditAll);
44
+		$this->assign('canCreate', $canCreate);
45
+
46
+		$this->assign('domains', $domains);
47
+		$this->assign('closeTemplates', $templates);
48
+		$this->assign('currentDomain', Domain::getCurrent($database));
49
+		$this->setTemplate('domain-management/main.tpl');
50
+	}
51
+
52
+	protected function create()
53
+	{
54
+		$this->setHtmlTitle('Domain Management');
55
+		$database = $this->getDatabase();
56
+		$currentUser = User::getCurrent($database);
57
+
58
+		// quickly check the user is allowed to edit all fields. If not, then they shouldn't be allowed to create
59
+		// new domains either. With any luck, a competent developer would never grant create without editAll to a role
60
+		// anyway, so this will never be hit.
61
+		if (!$this->barrierTest('editAll', $currentUser)) {
62
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
63
+		}
64
+
65
+		if (WebRequest::wasPosted()) {
66
+			$this->validateCSRFToken();
67
+
68
+			$domain = new Domain();
69
+			$domain->setDatabase($database);
70
+
71
+			$domain->setShortName(WebRequest::postString('shortName'));
72
+			$domain->setLongName(WebRequest::postString('longName'));
73
+			$domain->setWikiArticlePath(WebRequest::postString('articlePath'));
74
+			$domain->setWikiApiPath(WebRequest::postString('apiPath'));
75
+			$domain->setEnabled(WebRequest::postBoolean('enabled'));
76
+			$domain->setDefaultLanguage(WebRequest::postString('defaultLanguage'));
77
+			$domain->setDefaultClose(null);
78
+			$domain->setEmailReplyAddress(WebRequest::postString('emailReplyTo'));
79
+			$domain->setNotificationTarget(WebRequest::postString('notificationTarget'));
80
+			$domain->setLocalDocumentation(WebRequest::postString('localDocumentation'));
81
+
82
+			$domain->save();
83
+
84
+			Logger::domainCreated($database, $domain);
85
+			$this->redirect('domainManagement');
86
+		}
87
+		else {
88
+			$this->assignCSRFToken();
89
+
90
+			$this->assign('shortName', '');
91
+			$this->assign('longName', '');
92
+			$this->assign('articlePath', '');
93
+			$this->assign('apiPath', '');
94
+			$this->assign('enabled', false);
95
+			$this->assign('defaultLanguage', 'en');
96
+			$this->assign('emailReplyTo', '');
97
+			$this->assign('notificationTarget', '');
98
+			$this->assign('localDocumentation', '');
99
+
100
+			$this->assign('createMode', true);
101
+			$this->assign('canEditAll', true);
102
+
103
+			$this->setTemplate('domain-management/edit.tpl');
104
+		}
105
+	}
106
+
107
+	protected function edit()
108
+	{
109
+		$this->setHtmlTitle('Domain Management');
110
+		$database = $this->getDatabase();
111
+		$currentUser = User::getCurrent($database);
112
+
113
+		$canEditAll = $this->barrierTest('editAll', $currentUser);
114
+
115
+		/** @var Domain $domain */
116
+		$domain = Domain::getById(WebRequest::getInt('domain'), $database);
117
+
118
+		if (WebRequest::wasPosted()) {
119
+			$this->validateCSRFToken();
120
+
121
+			$domain->setLongName(WebRequest::postString('longName'));
122
+			$domain->setDefaultLanguage(WebRequest::postString('defaultLanguage'));
123
+			$domain->setLocalDocumentation(WebRequest::postString('localDocumentation'));
124
+
125
+			/** @var EmailTemplate|false $template */
126
+			$template = EmailTemplate::getById(WebRequest::postInt('defaultClose'), $database);
127
+			if ($template !== false
128
+				&& $template->getActive()
129
+				&& $template->getPreloadOnly() === false
130
+				&& $template->getDefaultAction() === EmailTemplate::ACTION_CREATED) {
131
+				$domain->setDefaultClose(WebRequest::postInt('defaultClose'));
132
+			}
133
+			else {
134
+				SessionAlert::warning("Chosen email template is not valid for use as the default creation template");
135
+			}
136
+
137
+			if ($canEditAll) {
138
+				$domain->setWikiArticlePath(WebRequest::postString('articlePath'));
139
+				$domain->setWikiApiPath(WebRequest::postString('apiPath'));
140
+				$domain->setEnabled(WebRequest::postBoolean('enabled'));
141
+				$domain->setEmailReplyAddress(WebRequest::postString('emailReplyTo'));
142
+				$domain->setNotificationTarget(WebRequest::postString('notificationTarget'));
143
+			}
144
+
145
+			$domain->save();
146
+
147
+			Logger::domainEdited($database, $domain);
148
+			$this->redirect('domainManagement');
149
+		}
150
+		else {
151
+			$this->assignCSRFToken();
152
+
153
+			$templates = EmailTemplate::getActiveNonpreloadTemplates(
154
+				EmailTemplate::ACTION_CREATED,
155
+				$database,
156
+				$domain->getId());
157
+
158
+			$this->assign('closeTemplates', $templates);
159
+
160
+			$this->assign('shortName', $domain->getShortName());
161
+			$this->assign('longName', $domain->getLongName());
162
+			$this->assign('articlePath', $domain->getWikiArticlePath());
163
+			$this->assign('apiPath', $domain->getWikiApiPath());
164
+			$this->assign('enabled', $domain->isEnabled());
165
+			$this->assign('defaultClose', $domain->getDefaultClose());
166
+			$this->assign('defaultLanguage', $domain->getDefaultLanguage());
167
+			$this->assign('emailReplyTo', $domain->getEmailReplyAddress());
168
+			$this->assign('notificationTarget', $domain->getNotificationTarget());
169
+			$this->assign('localDocumentation', $domain->getLocalDocumentation());
170
+
171
+
172
+			$this->assign('createMode', false);
173
+			$this->assign('canEditAll', $canEditAll);
174
+
175
+			$this->setTemplate('domain-management/edit.tpl');
176
+		}
177
+	}
178 178
 }
Please login to merge, or discard this patch.
includes/Pages/PageDomainSwitch.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -16,43 +16,43 @@
 block discarded – undo
16 16
 
17 17
 class PageDomainSwitch extends InternalPageBase
18 18
 {
19
-    /**
20
-     * @inheritDoc
21
-     */
22
-    protected function main()
23
-    {
24
-        if (!WebRequest::wasPosted()) {
25
-            $this->redirect('/');
19
+	/**
20
+	 * @inheritDoc
21
+	 */
22
+	protected function main()
23
+	{
24
+		if (!WebRequest::wasPosted()) {
25
+			$this->redirect('/');
26 26
 
27
-            return;
28
-        }
27
+			return;
28
+		}
29 29
 
30
-        $database = $this->getDatabase();
31
-        $currentUser = User::getCurrent($database);
30
+		$database = $this->getDatabase();
31
+		$currentUser = User::getCurrent($database);
32 32
 
33
-        /** @var Domain|false $newDomain */
34
-        $newDomain = Domain::getById(WebRequest::postInt('newdomain'), $database);
33
+		/** @var Domain|false $newDomain */
34
+		$newDomain = Domain::getById(WebRequest::postInt('newdomain'), $database);
35 35
 
36
-        if ($newDomain === false) {
37
-            $this->redirect('/');
36
+		if ($newDomain === false) {
37
+			$this->redirect('/');
38 38
 
39
-            return;
40
-        }
39
+			return;
40
+		}
41 41
 
42
-        $this->getDomainAccessManager()->switchDomain($currentUser, $newDomain);
42
+		$this->getDomainAccessManager()->switchDomain($currentUser, $newDomain);
43 43
 
44
-        // try to stay on the same page if possible.
45
-        // This only checks basic ACLs and not domain privileges, so this may still result in a 403.
44
+		// try to stay on the same page if possible.
45
+		// This only checks basic ACLs and not domain privileges, so this may still result in a 403.
46 46
 
47
-        $referrer = WebRequest::postString('referrer');
48
-        $priorPath = explode('/', $referrer);
49
-        $router = new RequestRouter();
50
-        $route = $router->getRouteFromPath($priorPath);
47
+		$referrer = WebRequest::postString('referrer');
48
+		$priorPath = explode('/', $referrer);
49
+		$router = new RequestRouter();
50
+		$route = $router->getRouteFromPath($priorPath);
51 51
 
52
-        if ($this->barrierTest($route[1], $currentUser, $route[0])) {
53
-            $this->redirect('/' . $referrer);
54
-        } else {
55
-            $this->redirect('/');
56
-        }
57
-    }
52
+		if ($this->barrierTest($route[1], $currentUser, $route[0])) {
53
+			$this->redirect('/' . $referrer);
54
+		} else {
55
+			$this->redirect('/');
56
+		}
57
+	}
58 58
 }
59 59
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/PageSearch.php 1 patch
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -20,199 +20,199 @@
 block discarded – undo
20 20
 
21 21
 class PageSearch extends PagedInternalPageBase
22 22
 {
23
-    use RequestListData;
24
-
25
-    /**
26
-     * Main function for this page, when no specific actions are called.
27
-     */
28
-    protected function main()
29
-    {
30
-        $this->setHtmlTitle('Search');
31
-
32
-        $database = $this->getDatabase();
33
-        $currentUser = User::getCurrent($database);
34
-
35
-        $this->assign('canSearchByComment', $this->barrierTest('byComment', $currentUser));
36
-        $this->assign('canSearchByEmail', $this->barrierTest('byEmail', $currentUser));
37
-        $this->assign('canSearchByIp', $this->barrierTest('byIp', $currentUser));
38
-        $this->assign('canSearchByName', $this->barrierTest('byName', $currentUser));
39
-        $this->assign('canSeeNonConfirmed', $this->barrierTest('allowNonConfirmed', $currentUser));
40
-
41
-        $this->setTemplate('search/main.tpl');
42
-
43
-        // Dual-mode page
44
-        if (WebRequest::getString('type') !== null) {
45
-            $searchType = WebRequest::getString('type');
46
-            $searchTerm = WebRequest::getString('term');
47
-
48
-            $excludeNonConfirmed = true;
49
-            if ($this->barrierTest('allowNonConfirmed', $currentUser)) {
50
-                $excludeNonConfirmed = WebRequest::getBoolean('excludeNonConfirmed');
51
-            }
52
-
53
-            $formParameters = [
54
-                'term' => $searchTerm,
55
-                'type' => $searchType,
56
-            ];
57
-
58
-            if ($excludeNonConfirmed) {
59
-                $formParameters['excludeNonConfirmed'] = true;
60
-            }
61
-
62
-            // FIXME: domains
63
-            $requestSearch = RequestSearchHelper::get($database, 1);
64
-            $this->setSearchHelper($requestSearch);
65
-            $this->setupLimits();
66
-
67
-            $validationError = "";
68
-            if (!$this->validateSearchParameters($searchType, $searchTerm, $validationError)) {
69
-                SessionAlert::error($validationError, "Search error");
70
-
71
-                $this->setupPageData(0, $formParameters);
72
-                $this->assign('hasResultset', false);
73
-
74
-                return;
75
-            }
76
-
77
-            // searchType known to be sane from the validate step above
78
-            if (!$this->barrierTest('by' . ucfirst($searchType), User::getCurrent($this->getDatabase()))) {
79
-                // only accessible by url munging, don't care about the UX
80
-                throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
81
-            }
82
-
83
-            if ($excludeNonConfirmed) {
84
-                $requestSearch->withConfirmedEmail();
85
-            }
86
-
87
-            switch ($searchType) {
88
-                case 'name':
89
-                    $this->getNameSearchResults($requestSearch, $searchTerm);
90
-                    break;
91
-                case 'email':
92
-                    $this->getEmailSearchResults($requestSearch, $searchTerm);
93
-                    break;
94
-                case 'ip':
95
-                    $this->getIpSearchResults($requestSearch, $searchTerm);
96
-                    break;
97
-                case 'comment':
98
-                    $this->getCommentSearchResults($requestSearch, $searchTerm);
99
-                    break;
100
-            }
101
-
102
-            /** @var Request[] $results */
103
-            $results = $requestSearch->getRecordCount($count)->fetch();
104
-            $this->setupPageData($count, $formParameters);
105
-
106
-            // deal with results
107
-            $this->assign('requests', $this->prepareRequestData($results));
108
-            $this->assign('resultCount', count($results));
109
-            $this->assign('hasResultset', true);
110
-
111
-            list($defaultSort, $defaultSortDirection) = WebRequest::requestListDefaultSort();
112
-            $this->assign('defaultSort', $defaultSort);
113
-            $this->assign('defaultSortDirection', $defaultSortDirection);
114
-        }
115
-        else {
116
-            $this->assign('type', 'name');
117
-            $this->assign('hasResultset', false);
118
-            $this->assign('limit', 50);
119
-            $this->assign('excludeNonConfirmed', true);
120
-        }
121
-    }
122
-
123
-    /**
124
-     * Gets search results by name
125
-     *
126
-     * @param RequestSearchHelper $searchHelper
127
-     * @param string              $searchTerm
128
-     */
129
-    private function getNameSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
130
-    {
131
-        $padded = '%' . $searchTerm . '%';
132
-        $searchHelper->byName($padded);
133
-    }
134
-
135
-    /**
136
-     * Gets search results by comment
137
-     *
138
-     * @param RequestSearchHelper $searchHelper
139
-     * @param string              $searchTerm
140
-     */
141
-    private function getCommentSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
142
-    {
143
-        $padded = '%' . $searchTerm . '%';
144
-        $searchHelper->byComment($padded);
145
-
146
-        $currentUser = User::getCurrent($this->getDatabase());
147
-        $commentSecurity = ['requester', 'user'];
148
-
149
-        if ($this->barrierTest('seeRestrictedComments', $currentUser, 'RequestData')) {
150
-            $commentSecurity[] = 'admin';
151
-        }
152
-
153
-        if ($this->barrierTest('seeCheckuserComments', $currentUser, 'RequestData')) {
154
-            $commentSecurity[] = 'checkuser';
155
-        }
156
-
157
-        $searchHelper->byCommentSecurity($commentSecurity);
158
-    }
159
-
160
-    /**
161
-     * Gets search results by email
162
-     *
163
-     * @param RequestSearchHelper $searchHelper
164
-     * @param string              $searchTerm
165
-     *
166
-     * @throws ApplicationLogicException
167
-     */
168
-    private function getEmailSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
169
-    {
170
-        if ($searchTerm === "@") {
171
-            throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
172
-        }
173
-
174
-        $padded = '%' . $searchTerm . '%';
175
-
176
-        $searchHelper->byEmailAddress($padded)->excludingPurgedData($this->getSiteConfiguration());
177
-    }
178
-
179
-    /**
180
-     * Gets search results by IP address or XFF IP address
181
-     *
182
-     * @param RequestSearchHelper $searchHelper
183
-     * @param string              $searchTerm
184
-     */
185
-    private function getIpSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
186
-    {
187
-        $searchHelper
188
-            ->byIp($searchTerm)
189
-            ->excludingPurgedData($this->getSiteConfiguration());
190
-    }
191
-
192
-    /**
193
-     * @param string $searchType
194
-     * @param string $searchTerm
195
-     *
196
-     * @param string $errorMessage
197
-     *
198
-     * @return bool true if parameters are valid
199
-     */
200
-    protected function validateSearchParameters($searchType, $searchTerm, &$errorMessage)
201
-    {
202
-        if (!in_array($searchType, array('name', 'email', 'ip', 'comment'))) {
203
-            $errorMessage = 'Unknown search type';
204
-
205
-            return false;
206
-        }
207
-
208
-        if ($searchTerm === '%' || $searchTerm === '' || $searchTerm === null) {
209
-            $errorMessage = 'No search term specified entered';
210
-
211
-            return false;
212
-        }
213
-
214
-        $errorMessage = "";
215
-
216
-        return true;
217
-    }
23
+	use RequestListData;
24
+
25
+	/**
26
+	 * Main function for this page, when no specific actions are called.
27
+	 */
28
+	protected function main()
29
+	{
30
+		$this->setHtmlTitle('Search');
31
+
32
+		$database = $this->getDatabase();
33
+		$currentUser = User::getCurrent($database);
34
+
35
+		$this->assign('canSearchByComment', $this->barrierTest('byComment', $currentUser));
36
+		$this->assign('canSearchByEmail', $this->barrierTest('byEmail', $currentUser));
37
+		$this->assign('canSearchByIp', $this->barrierTest('byIp', $currentUser));
38
+		$this->assign('canSearchByName', $this->barrierTest('byName', $currentUser));
39
+		$this->assign('canSeeNonConfirmed', $this->barrierTest('allowNonConfirmed', $currentUser));
40
+
41
+		$this->setTemplate('search/main.tpl');
42
+
43
+		// Dual-mode page
44
+		if (WebRequest::getString('type') !== null) {
45
+			$searchType = WebRequest::getString('type');
46
+			$searchTerm = WebRequest::getString('term');
47
+
48
+			$excludeNonConfirmed = true;
49
+			if ($this->barrierTest('allowNonConfirmed', $currentUser)) {
50
+				$excludeNonConfirmed = WebRequest::getBoolean('excludeNonConfirmed');
51
+			}
52
+
53
+			$formParameters = [
54
+				'term' => $searchTerm,
55
+				'type' => $searchType,
56
+			];
57
+
58
+			if ($excludeNonConfirmed) {
59
+				$formParameters['excludeNonConfirmed'] = true;
60
+			}
61
+
62
+			// FIXME: domains
63
+			$requestSearch = RequestSearchHelper::get($database, 1);
64
+			$this->setSearchHelper($requestSearch);
65
+			$this->setupLimits();
66
+
67
+			$validationError = "";
68
+			if (!$this->validateSearchParameters($searchType, $searchTerm, $validationError)) {
69
+				SessionAlert::error($validationError, "Search error");
70
+
71
+				$this->setupPageData(0, $formParameters);
72
+				$this->assign('hasResultset', false);
73
+
74
+				return;
75
+			}
76
+
77
+			// searchType known to be sane from the validate step above
78
+			if (!$this->barrierTest('by' . ucfirst($searchType), User::getCurrent($this->getDatabase()))) {
79
+				// only accessible by url munging, don't care about the UX
80
+				throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
81
+			}
82
+
83
+			if ($excludeNonConfirmed) {
84
+				$requestSearch->withConfirmedEmail();
85
+			}
86
+
87
+			switch ($searchType) {
88
+				case 'name':
89
+					$this->getNameSearchResults($requestSearch, $searchTerm);
90
+					break;
91
+				case 'email':
92
+					$this->getEmailSearchResults($requestSearch, $searchTerm);
93
+					break;
94
+				case 'ip':
95
+					$this->getIpSearchResults($requestSearch, $searchTerm);
96
+					break;
97
+				case 'comment':
98
+					$this->getCommentSearchResults($requestSearch, $searchTerm);
99
+					break;
100
+			}
101
+
102
+			/** @var Request[] $results */
103
+			$results = $requestSearch->getRecordCount($count)->fetch();
104
+			$this->setupPageData($count, $formParameters);
105
+
106
+			// deal with results
107
+			$this->assign('requests', $this->prepareRequestData($results));
108
+			$this->assign('resultCount', count($results));
109
+			$this->assign('hasResultset', true);
110
+
111
+			list($defaultSort, $defaultSortDirection) = WebRequest::requestListDefaultSort();
112
+			$this->assign('defaultSort', $defaultSort);
113
+			$this->assign('defaultSortDirection', $defaultSortDirection);
114
+		}
115
+		else {
116
+			$this->assign('type', 'name');
117
+			$this->assign('hasResultset', false);
118
+			$this->assign('limit', 50);
119
+			$this->assign('excludeNonConfirmed', true);
120
+		}
121
+	}
122
+
123
+	/**
124
+	 * Gets search results by name
125
+	 *
126
+	 * @param RequestSearchHelper $searchHelper
127
+	 * @param string              $searchTerm
128
+	 */
129
+	private function getNameSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
130
+	{
131
+		$padded = '%' . $searchTerm . '%';
132
+		$searchHelper->byName($padded);
133
+	}
134
+
135
+	/**
136
+	 * Gets search results by comment
137
+	 *
138
+	 * @param RequestSearchHelper $searchHelper
139
+	 * @param string              $searchTerm
140
+	 */
141
+	private function getCommentSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
142
+	{
143
+		$padded = '%' . $searchTerm . '%';
144
+		$searchHelper->byComment($padded);
145
+
146
+		$currentUser = User::getCurrent($this->getDatabase());
147
+		$commentSecurity = ['requester', 'user'];
148
+
149
+		if ($this->barrierTest('seeRestrictedComments', $currentUser, 'RequestData')) {
150
+			$commentSecurity[] = 'admin';
151
+		}
152
+
153
+		if ($this->barrierTest('seeCheckuserComments', $currentUser, 'RequestData')) {
154
+			$commentSecurity[] = 'checkuser';
155
+		}
156
+
157
+		$searchHelper->byCommentSecurity($commentSecurity);
158
+	}
159
+
160
+	/**
161
+	 * Gets search results by email
162
+	 *
163
+	 * @param RequestSearchHelper $searchHelper
164
+	 * @param string              $searchTerm
165
+	 *
166
+	 * @throws ApplicationLogicException
167
+	 */
168
+	private function getEmailSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
169
+	{
170
+		if ($searchTerm === "@") {
171
+			throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
172
+		}
173
+
174
+		$padded = '%' . $searchTerm . '%';
175
+
176
+		$searchHelper->byEmailAddress($padded)->excludingPurgedData($this->getSiteConfiguration());
177
+	}
178
+
179
+	/**
180
+	 * Gets search results by IP address or XFF IP address
181
+	 *
182
+	 * @param RequestSearchHelper $searchHelper
183
+	 * @param string              $searchTerm
184
+	 */
185
+	private function getIpSearchResults(RequestSearchHelper $searchHelper, string $searchTerm)
186
+	{
187
+		$searchHelper
188
+			->byIp($searchTerm)
189
+			->excludingPurgedData($this->getSiteConfiguration());
190
+	}
191
+
192
+	/**
193
+	 * @param string $searchType
194
+	 * @param string $searchTerm
195
+	 *
196
+	 * @param string $errorMessage
197
+	 *
198
+	 * @return bool true if parameters are valid
199
+	 */
200
+	protected function validateSearchParameters($searchType, $searchTerm, &$errorMessage)
201
+	{
202
+		if (!in_array($searchType, array('name', 'email', 'ip', 'comment'))) {
203
+			$errorMessage = 'Unknown search type';
204
+
205
+			return false;
206
+		}
207
+
208
+		if ($searchTerm === '%' || $searchTerm === '' || $searchTerm === null) {
209
+			$errorMessage = 'No search term specified entered';
210
+
211
+			return false;
212
+		}
213
+
214
+		$errorMessage = "";
215
+
216
+		return true;
217
+	}
218 218
 }
Please login to merge, or discard this patch.
includes/Pages/PageEmailManagement.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -21,206 +21,206 @@
 block discarded – undo
21 21
 
22 22
 class PageEmailManagement extends InternalPageBase
23 23
 {
24
-    /**
25
-     * Main function for this page, when no specific actions are called.
26
-     * @return void
27
-     */
28
-    protected function main()
29
-    {
30
-        $this->setHtmlTitle('Close Emails');
31
-
32
-        // Get all active email templates
33
-        // FIXME: domains!
34
-        $activeTemplates = EmailTemplate::getAllActiveTemplates(null, $this->getDatabase(), 1);
35
-        $inactiveTemplates = EmailTemplate::getAllInactiveTemplates($this->getDatabase(), 1);
36
-
37
-        $this->assign('activeTemplates', $activeTemplates);
38
-        $this->assign('inactiveTemplates', $inactiveTemplates);
39
-
40
-        $user = User::getCurrent($this->getDatabase());
41
-        $this->assign('canCreate', $this->barrierTest('create', $user));
42
-        $this->assign('canEdit', $this->barrierTest('edit', $user));
43
-
44
-        $this->setTemplate('email-management/main.tpl');
45
-    }
46
-
47
-    protected function view()
48
-    {
49
-        $this->setHtmlTitle('Close Emails');
50
-
51
-        $database = $this->getDatabase();
52
-        $template = $this->getTemplate($database);
53
-
54
-        // FIXME: domains!
55
-        /** @var Domain $domain */
56
-        $domain = Domain::getById(1, $database);
57
-
58
-        $this->assign('id', $template->getId());
59
-        $this->assign('emailTemplate', $template);
60
-        $this->assign('createdid', $domain->getDefaultClose());
61
-
62
-        $this->setTemplate('email-management/view.tpl');
63
-    }
64
-
65
-    /**
66
-     * @param PdoDatabase $database
67
-     *
68
-     * @return EmailTemplate
69
-     * @throws ApplicationLogicException
70
-     */
71
-    protected function getTemplate(PdoDatabase $database)
72
-    {
73
-        $templateId = WebRequest::getInt('id');
74
-        if ($templateId === null) {
75
-            throw new ApplicationLogicException('Template not specified');
76
-        }
77
-        $template = EmailTemplate::getById($templateId, $database);
78
-        if ($template === false || !is_a($template, EmailTemplate::class)) {
79
-            throw new ApplicationLogicException('Template not found');
80
-        }
81
-
82
-        return $template;
83
-    }
84
-
85
-    protected function edit()
86
-    {
87
-        $this->setHtmlTitle('Close Emails');
88
-
89
-        $database = $this->getDatabase();
90
-        $template = $this->getTemplate($database);
91
-
92
-        // FIXME: domains!
93
-        /** @var Domain $domain */
94
-        $domain = Domain::getById(1, $database);
95
-
96
-        $createdId = $domain->getDefaultClose();
97
-
98
-        $requestQueues = RequestQueue::getEnabledQueues($database);
99
-
100
-        if (WebRequest::wasPosted()) {
101
-            $this->validateCSRFToken();
102
-
103
-            $this->modifyTemplateData($template, $template->getId() === $createdId);
104
-
105
-            $other = EmailTemplate::getByName($template->getName(), $database, $domain->getId());
106
-            if ($other !== false && $other->getId() !== $template->getId()) {
107
-                throw new ApplicationLogicException('A template with this name already exists');
108
-            }
109
-
110
-            // optimistically lock on load of edit form
111
-            $updateVersion = WebRequest::postInt('updateversion');
112
-            $template->setUpdateVersion($updateVersion);
113
-
114
-            $template->save();
115
-            Logger::editedEmail($database, $template);
116
-            $this->getNotificationHelper()->emailEdited($template);
117
-            SessionAlert::success("Email template has been saved successfully.");
118
-
119
-            $this->redirect('emailManagement');
120
-        }
121
-        else {
122
-            $this->assignCSRFToken();
123
-            $this->assign('id', $template->getId());
124
-            $this->assign('emailTemplate', $template);
125
-            $this->assign('createdid', $createdId);
126
-            $this->assign('requestQueues', $requestQueues);
127
-
128
-            $this->setTemplate('email-management/edit.tpl');
129
-        }
130
-    }
131
-
132
-    /**
133
-     * @throws ApplicationLogicException
134
-     */
135
-    private function modifyTemplateData(EmailTemplate $template, bool $isDefaultTemplate): void
136
-    {
137
-        $name = WebRequest::postString('name');
138
-        if ($name === null || $name === '') {
139
-            throw new ApplicationLogicException('Name not specified');
140
-        }
141
-
142
-        $template->setName($name);
143
-
144
-        $text = WebRequest::postString('text');
145
-        if ($text === null || $text === '') {
146
-            throw new ApplicationLogicException('Text not specified');
147
-        }
148
-
149
-        $template->setText($text);
150
-
151
-        $jsquestion = WebRequest::postString('jsquestion');
152
-        if ($jsquestion === null || $jsquestion === '') {
153
-            throw new ApplicationLogicException('JS question not specified');
154
-        }
155
-        $template->setJsquestion($jsquestion);
156
-
157
-        if ($isDefaultTemplate) {
158
-            $template->setDefaultAction(EmailTemplate::ACTION_CREATED);
159
-            $template->setActive(true);
160
-            $template->setPreloadOnly(false);
161
-        }
162
-        else {
163
-            $defaultAction = WebRequest::postString('defaultaction');
164
-            switch ($defaultAction) {
165
-                case EmailTemplate::ACTION_NONE:
166
-                case EmailTemplate::ACTION_CREATED:
167
-                case EmailTemplate::ACTION_NOT_CREATED:
168
-                    $template->setDefaultAction($defaultAction);
169
-                    $template->setQueue(null);
170
-                    break;
171
-                default:
172
-                    $template->setDefaultAction(EmailTemplate::ACTION_DEFER);
173
-                    // FIXME: domains!
174
-                    $queue = RequestQueue::getByApiName($this->getDatabase(), $defaultAction, 1);
175
-                    $template->setQueue($queue->getId());
176
-                    break;
177
-            }
178
-
179
-            $template->setActive(WebRequest::postBoolean('active'));
180
-            $template->setPreloadOnly(WebRequest::postBoolean('preloadonly'));
181
-        }
182
-    }
183
-
184
-    protected function create()
185
-    {
186
-        $this->setHtmlTitle('Close Emails');
187
-
188
-        $database = $this->getDatabase();
189
-
190
-        $requestQueues = RequestQueue::getEnabledQueues($database);
191
-
192
-        if (WebRequest::wasPosted()) {
193
-            $this->validateCSRFToken();
194
-            $template = new EmailTemplate();
195
-            $template->setDatabase($database);
196
-
197
-            // FIXME: domains!
198
-            $template->setDomain(1);
199
-
200
-            $this->modifyTemplateData($template, false);
201
-
202
-            $other = EmailTemplate::getByName($template->getName(), $database, $template->getDomain());
203
-            if ($other !== false) {
204
-                throw new ApplicationLogicException('A template with this name already exists');
205
-            }
206
-
207
-            $template->save();
208
-
209
-            Logger::createEmail($database, $template);
210
-            $this->getNotificationHelper()->emailCreated($template);
211
-
212
-            SessionAlert::success("Email template has been saved successfully.");
213
-
214
-            $this->redirect('emailManagement');
215
-        }
216
-        else {
217
-            $this->assignCSRFToken();
218
-            $this->assign('id', -1);
219
-            $this->assign('emailTemplate', new EmailTemplate());
220
-            $this->assign('createdid', -2);
221
-
222
-            $this->assign('requestQueues', $requestQueues);
223
-            $this->setTemplate('email-management/edit.tpl');
224
-        }
225
-    }
24
+	/**
25
+	 * Main function for this page, when no specific actions are called.
26
+	 * @return void
27
+	 */
28
+	protected function main()
29
+	{
30
+		$this->setHtmlTitle('Close Emails');
31
+
32
+		// Get all active email templates
33
+		// FIXME: domains!
34
+		$activeTemplates = EmailTemplate::getAllActiveTemplates(null, $this->getDatabase(), 1);
35
+		$inactiveTemplates = EmailTemplate::getAllInactiveTemplates($this->getDatabase(), 1);
36
+
37
+		$this->assign('activeTemplates', $activeTemplates);
38
+		$this->assign('inactiveTemplates', $inactiveTemplates);
39
+
40
+		$user = User::getCurrent($this->getDatabase());
41
+		$this->assign('canCreate', $this->barrierTest('create', $user));
42
+		$this->assign('canEdit', $this->barrierTest('edit', $user));
43
+
44
+		$this->setTemplate('email-management/main.tpl');
45
+	}
46
+
47
+	protected function view()
48
+	{
49
+		$this->setHtmlTitle('Close Emails');
50
+
51
+		$database = $this->getDatabase();
52
+		$template = $this->getTemplate($database);
53
+
54
+		// FIXME: domains!
55
+		/** @var Domain $domain */
56
+		$domain = Domain::getById(1, $database);
57
+
58
+		$this->assign('id', $template->getId());
59
+		$this->assign('emailTemplate', $template);
60
+		$this->assign('createdid', $domain->getDefaultClose());
61
+
62
+		$this->setTemplate('email-management/view.tpl');
63
+	}
64
+
65
+	/**
66
+	 * @param PdoDatabase $database
67
+	 *
68
+	 * @return EmailTemplate
69
+	 * @throws ApplicationLogicException
70
+	 */
71
+	protected function getTemplate(PdoDatabase $database)
72
+	{
73
+		$templateId = WebRequest::getInt('id');
74
+		if ($templateId === null) {
75
+			throw new ApplicationLogicException('Template not specified');
76
+		}
77
+		$template = EmailTemplate::getById($templateId, $database);
78
+		if ($template === false || !is_a($template, EmailTemplate::class)) {
79
+			throw new ApplicationLogicException('Template not found');
80
+		}
81
+
82
+		return $template;
83
+	}
84
+
85
+	protected function edit()
86
+	{
87
+		$this->setHtmlTitle('Close Emails');
88
+
89
+		$database = $this->getDatabase();
90
+		$template = $this->getTemplate($database);
91
+
92
+		// FIXME: domains!
93
+		/** @var Domain $domain */
94
+		$domain = Domain::getById(1, $database);
95
+
96
+		$createdId = $domain->getDefaultClose();
97
+
98
+		$requestQueues = RequestQueue::getEnabledQueues($database);
99
+
100
+		if (WebRequest::wasPosted()) {
101
+			$this->validateCSRFToken();
102
+
103
+			$this->modifyTemplateData($template, $template->getId() === $createdId);
104
+
105
+			$other = EmailTemplate::getByName($template->getName(), $database, $domain->getId());
106
+			if ($other !== false && $other->getId() !== $template->getId()) {
107
+				throw new ApplicationLogicException('A template with this name already exists');
108
+			}
109
+
110
+			// optimistically lock on load of edit form
111
+			$updateVersion = WebRequest::postInt('updateversion');
112
+			$template->setUpdateVersion($updateVersion);
113
+
114
+			$template->save();
115
+			Logger::editedEmail($database, $template);
116
+			$this->getNotificationHelper()->emailEdited($template);
117
+			SessionAlert::success("Email template has been saved successfully.");
118
+
119
+			$this->redirect('emailManagement');
120
+		}
121
+		else {
122
+			$this->assignCSRFToken();
123
+			$this->assign('id', $template->getId());
124
+			$this->assign('emailTemplate', $template);
125
+			$this->assign('createdid', $createdId);
126
+			$this->assign('requestQueues', $requestQueues);
127
+
128
+			$this->setTemplate('email-management/edit.tpl');
129
+		}
130
+	}
131
+
132
+	/**
133
+	 * @throws ApplicationLogicException
134
+	 */
135
+	private function modifyTemplateData(EmailTemplate $template, bool $isDefaultTemplate): void
136
+	{
137
+		$name = WebRequest::postString('name');
138
+		if ($name === null || $name === '') {
139
+			throw new ApplicationLogicException('Name not specified');
140
+		}
141
+
142
+		$template->setName($name);
143
+
144
+		$text = WebRequest::postString('text');
145
+		if ($text === null || $text === '') {
146
+			throw new ApplicationLogicException('Text not specified');
147
+		}
148
+
149
+		$template->setText($text);
150
+
151
+		$jsquestion = WebRequest::postString('jsquestion');
152
+		if ($jsquestion === null || $jsquestion === '') {
153
+			throw new ApplicationLogicException('JS question not specified');
154
+		}
155
+		$template->setJsquestion($jsquestion);
156
+
157
+		if ($isDefaultTemplate) {
158
+			$template->setDefaultAction(EmailTemplate::ACTION_CREATED);
159
+			$template->setActive(true);
160
+			$template->setPreloadOnly(false);
161
+		}
162
+		else {
163
+			$defaultAction = WebRequest::postString('defaultaction');
164
+			switch ($defaultAction) {
165
+				case EmailTemplate::ACTION_NONE:
166
+				case EmailTemplate::ACTION_CREATED:
167
+				case EmailTemplate::ACTION_NOT_CREATED:
168
+					$template->setDefaultAction($defaultAction);
169
+					$template->setQueue(null);
170
+					break;
171
+				default:
172
+					$template->setDefaultAction(EmailTemplate::ACTION_DEFER);
173
+					// FIXME: domains!
174
+					$queue = RequestQueue::getByApiName($this->getDatabase(), $defaultAction, 1);
175
+					$template->setQueue($queue->getId());
176
+					break;
177
+			}
178
+
179
+			$template->setActive(WebRequest::postBoolean('active'));
180
+			$template->setPreloadOnly(WebRequest::postBoolean('preloadonly'));
181
+		}
182
+	}
183
+
184
+	protected function create()
185
+	{
186
+		$this->setHtmlTitle('Close Emails');
187
+
188
+		$database = $this->getDatabase();
189
+
190
+		$requestQueues = RequestQueue::getEnabledQueues($database);
191
+
192
+		if (WebRequest::wasPosted()) {
193
+			$this->validateCSRFToken();
194
+			$template = new EmailTemplate();
195
+			$template->setDatabase($database);
196
+
197
+			// FIXME: domains!
198
+			$template->setDomain(1);
199
+
200
+			$this->modifyTemplateData($template, false);
201
+
202
+			$other = EmailTemplate::getByName($template->getName(), $database, $template->getDomain());
203
+			if ($other !== false) {
204
+				throw new ApplicationLogicException('A template with this name already exists');
205
+			}
206
+
207
+			$template->save();
208
+
209
+			Logger::createEmail($database, $template);
210
+			$this->getNotificationHelper()->emailCreated($template);
211
+
212
+			SessionAlert::success("Email template has been saved successfully.");
213
+
214
+			$this->redirect('emailManagement');
215
+		}
216
+		else {
217
+			$this->assignCSRFToken();
218
+			$this->assign('id', -1);
219
+			$this->assign('emailTemplate', new EmailTemplate());
220
+			$this->assign('createdid', -2);
221
+
222
+			$this->assign('requestQueues', $requestQueues);
223
+			$this->setTemplate('email-management/edit.tpl');
224
+		}
225
+	}
226 226
 }
Please login to merge, or discard this patch.
includes/Pages/PageQueueManagement.php 1 patch
Indentation   +187 added lines, -187 removed lines patch added patch discarded remove patch
@@ -18,191 +18,191 @@
 block discarded – undo
18 18
 
19 19
 class PageQueueManagement extends InternalPageBase
20 20
 {
21
-    /** @var RequestQueueHelper */
22
-    private $helper;
23
-
24
-    public function __construct()
25
-    {
26
-        $this->helper = new RequestQueueHelper();
27
-    }
28
-
29
-    protected function main()
30
-    {
31
-        $this->setHtmlTitle('Request Queue Management');
32
-
33
-        $database = $this->getDatabase();
34
-        $queues = RequestQueue::getAllQueues($database);
35
-
36
-        $this->assign('queues', $queues);
37
-
38
-        $user = User::getCurrent($database);
39
-        $this->assign('canCreate', $this->barrierTest('create', $user));
40
-        $this->assign('canEdit', $this->barrierTest('edit', $user));
41
-
42
-        $this->setTemplate('queue-management/main.tpl');
43
-    }
44
-
45
-    protected function create()
46
-    {
47
-        if (WebRequest::wasPosted()) {
48
-            $this->validateCSRFToken();
49
-            $database = $this->getDatabase();
50
-
51
-            $queue = new RequestQueue();
52
-
53
-            $queue->setDatabase($database);
54
-            $queue->setDomain(1); // FIXME: domain
55
-
56
-            $queue->setHeader(WebRequest::postString('header'));
57
-            $queue->setDisplayName(WebRequest::postString('displayName'));
58
-            $queue->setApiName(WebRequest::postString('apiName'));
59
-            $queue->setEnabled(WebRequest::postBoolean('enabled'));
60
-            $queue->setDefault(WebRequest::postBoolean('default') && WebRequest::postBoolean('enabled'));
61
-            $queue->setDefaultAntispoof(WebRequest::postBoolean('antispoof') && WebRequest::postBoolean('enabled'));
62
-            $queue->setDefaultTitleBlacklist(WebRequest::postBoolean('titleblacklist') && WebRequest::postBoolean('enabled'));
63
-            $queue->setHelp(WebRequest::postString('help'));
64
-            $queue->setLogName(WebRequest::postString('logName'));
65
-
66
-            $proceed = true;
67
-
68
-            if (RequestQueue::getByApiName($database, $queue->getApiName(), 1) !== false) {
69
-                // FIXME: domain
70
-                SessionAlert::error("The chosen API name is already in use. Please choose another.");
71
-                $proceed = false;
72
-            }
73
-
74
-            if (preg_match('/^[A-Za-z][a-zA-Z0-9_-]*$/', $queue->getApiName()) !== 1) {
75
-                SessionAlert::error("The chosen API name contains invalid characters");
76
-                $proceed = false;
77
-            }
78
-
79
-            if (RequestQueue::getByDisplayName($database, $queue->getDisplayName(), 1) !== false) {
80
-                // FIXME: domain
81
-                SessionAlert::error("The chosen target display name is already in use. Please choose another.");
82
-                $proceed = false;
83
-            }
84
-
85
-            if (RequestQueue::getByHeader($database, $queue->getHeader(), 1) !== false) {
86
-                // FIXME: domain
87
-                SessionAlert::error("The chosen header is already in use. Please choose another.");
88
-                $proceed = false;
89
-            }
90
-
91
-            if ($proceed) {
92
-                $queue->save();
93
-                Logger::requestQueueCreated($database, $queue);
94
-                $this->redirect('queueManagement');
95
-            }
96
-            else {
97
-                $this->populateFromObject($queue);
98
-
99
-                $this->assign('createMode', true);
100
-                $this->setTemplate('queue-management/edit.tpl');
101
-            }
102
-        }
103
-        else {
104
-            $this->assign('header', null);
105
-            $this->assign('displayName', null);
106
-            $this->assign('apiName', null);
107
-            $this->assign('enabled', false);
108
-            $this->assign('antispoof', false);
109
-            $this->assign('isTarget', false);
110
-            $this->assign('titleblacklist', false);
111
-            $this->assign('default', false);
112
-            $this->assign('help', null);
113
-            $this->assign('logName', null);
114
-
115
-            $this->assignCSRFToken();
116
-            $this->assign('createMode', true);
117
-            $this->setTemplate('queue-management/edit.tpl');
118
-        }
119
-    }
120
-
121
-    protected function edit()
122
-    {
123
-        $database = $this->getDatabase();
124
-
125
-        $id = WebRequest::getInt('queue');
126
-        if ($id === null) {
127
-            $this->redirect('queueManagement');
128
-
129
-            return;
130
-        }
131
-
132
-        /** @var RequestQueue $queue */
133
-        $queue = RequestQueue::getById($id, $database);
134
-
135
-        if (WebRequest::wasPosted()) {
136
-            $this->validateCSRFToken();
137
-
138
-            $this->helper->configureDefaults(
139
-                $queue,
140
-                WebRequest::postBoolean('enabled'),
141
-                WebRequest::postBoolean('default'),
142
-                WebRequest::postBoolean('antispoof'),
143
-                WebRequest::postBoolean('titleblacklist'),
144
-                $this->helper->isEmailTemplateTarget($queue, $this->getDatabase()) || $this->helper->isRequestFormTarget($queue, $this->getDatabase()));
145
-
146
-            $queue->setHeader(WebRequest::postString('header'));
147
-            $queue->setDisplayName(WebRequest::postString('displayName'));
148
-            $queue->setHelp(WebRequest::postString('help'));
149
-
150
-            $proceed = true;
151
-
152
-            $foundRequestQueue = RequestQueue::getByDisplayName($database, $queue->getDisplayName(), 1);
153
-            if ($foundRequestQueue !== false && $foundRequestQueue->getId() !== $queue->getId()) {
154
-                // FIXME: domain
155
-                SessionAlert::error("The chosen target display name is already in use. Please choose another.");
156
-                $proceed = false;
157
-            }
158
-
159
-            $foundRequestQueue = RequestQueue::getByHeader($database, $queue->getHeader(), 1);
160
-            if ($foundRequestQueue !== false && $foundRequestQueue->getId() !== $queue->getId()) {
161
-                // FIXME: domain
162
-                SessionAlert::error("The chosen header is already in use. Please choose another.");
163
-                $proceed = false;
164
-            }
165
-
166
-            if ($proceed) {
167
-                Logger::requestQueueEdited($database, $queue);
168
-                $queue->save();
169
-                $this->redirect('queueManagement');
170
-            }
171
-            else {
172
-                $this->populateFromObject($queue);
173
-
174
-                $this->assign('createMode', false);
175
-                $this->setTemplate('queue-management/edit.tpl');
176
-            }
177
-        }
178
-        else {
179
-            $this->populateFromObject($queue);
180
-
181
-            $this->assign('createMode', false);
182
-            $this->setTemplate('queue-management/edit.tpl');
183
-        }
184
-    }
185
-
186
-    /**
187
-     * @param RequestQueue $queue
188
-     */
189
-    protected function populateFromObject(RequestQueue $queue): void
190
-    {
191
-        $this->assignCSRFToken();
192
-
193
-        $this->assign('header', $queue->getHeader());
194
-        $this->assign('displayName', $queue->getDisplayName());
195
-        $this->assign('apiName', $queue->getApiName());
196
-        $this->assign('enabled', $queue->isEnabled());
197
-        $this->assign('default', $queue->isDefault());
198
-        $this->assign('antispoof', $queue->isDefaultAntispoof());
199
-        $this->assign('titleblacklist', $queue->isDefaultTitleBlacklist());
200
-        $this->assign('help', $queue->getHelp());
201
-        $this->assign('logName', $queue->getLogName());
202
-
203
-        $isQueueTarget = $this->helper->isEmailTemplateTarget($queue, $this->getDatabase());
204
-        $isFormTarget = $this->helper->isRequestFormTarget($queue, $this->getDatabase());
205
-        $this->assign('isTarget', $isQueueTarget);
206
-        $this->assign('isFormTarget', $isFormTarget);
207
-    }
21
+	/** @var RequestQueueHelper */
22
+	private $helper;
23
+
24
+	public function __construct()
25
+	{
26
+		$this->helper = new RequestQueueHelper();
27
+	}
28
+
29
+	protected function main()
30
+	{
31
+		$this->setHtmlTitle('Request Queue Management');
32
+
33
+		$database = $this->getDatabase();
34
+		$queues = RequestQueue::getAllQueues($database);
35
+
36
+		$this->assign('queues', $queues);
37
+
38
+		$user = User::getCurrent($database);
39
+		$this->assign('canCreate', $this->barrierTest('create', $user));
40
+		$this->assign('canEdit', $this->barrierTest('edit', $user));
41
+
42
+		$this->setTemplate('queue-management/main.tpl');
43
+	}
44
+
45
+	protected function create()
46
+	{
47
+		if (WebRequest::wasPosted()) {
48
+			$this->validateCSRFToken();
49
+			$database = $this->getDatabase();
50
+
51
+			$queue = new RequestQueue();
52
+
53
+			$queue->setDatabase($database);
54
+			$queue->setDomain(1); // FIXME: domain
55
+
56
+			$queue->setHeader(WebRequest::postString('header'));
57
+			$queue->setDisplayName(WebRequest::postString('displayName'));
58
+			$queue->setApiName(WebRequest::postString('apiName'));
59
+			$queue->setEnabled(WebRequest::postBoolean('enabled'));
60
+			$queue->setDefault(WebRequest::postBoolean('default') && WebRequest::postBoolean('enabled'));
61
+			$queue->setDefaultAntispoof(WebRequest::postBoolean('antispoof') && WebRequest::postBoolean('enabled'));
62
+			$queue->setDefaultTitleBlacklist(WebRequest::postBoolean('titleblacklist') && WebRequest::postBoolean('enabled'));
63
+			$queue->setHelp(WebRequest::postString('help'));
64
+			$queue->setLogName(WebRequest::postString('logName'));
65
+
66
+			$proceed = true;
67
+
68
+			if (RequestQueue::getByApiName($database, $queue->getApiName(), 1) !== false) {
69
+				// FIXME: domain
70
+				SessionAlert::error("The chosen API name is already in use. Please choose another.");
71
+				$proceed = false;
72
+			}
73
+
74
+			if (preg_match('/^[A-Za-z][a-zA-Z0-9_-]*$/', $queue->getApiName()) !== 1) {
75
+				SessionAlert::error("The chosen API name contains invalid characters");
76
+				$proceed = false;
77
+			}
78
+
79
+			if (RequestQueue::getByDisplayName($database, $queue->getDisplayName(), 1) !== false) {
80
+				// FIXME: domain
81
+				SessionAlert::error("The chosen target display name is already in use. Please choose another.");
82
+				$proceed = false;
83
+			}
84
+
85
+			if (RequestQueue::getByHeader($database, $queue->getHeader(), 1) !== false) {
86
+				// FIXME: domain
87
+				SessionAlert::error("The chosen header is already in use. Please choose another.");
88
+				$proceed = false;
89
+			}
90
+
91
+			if ($proceed) {
92
+				$queue->save();
93
+				Logger::requestQueueCreated($database, $queue);
94
+				$this->redirect('queueManagement');
95
+			}
96
+			else {
97
+				$this->populateFromObject($queue);
98
+
99
+				$this->assign('createMode', true);
100
+				$this->setTemplate('queue-management/edit.tpl');
101
+			}
102
+		}
103
+		else {
104
+			$this->assign('header', null);
105
+			$this->assign('displayName', null);
106
+			$this->assign('apiName', null);
107
+			$this->assign('enabled', false);
108
+			$this->assign('antispoof', false);
109
+			$this->assign('isTarget', false);
110
+			$this->assign('titleblacklist', false);
111
+			$this->assign('default', false);
112
+			$this->assign('help', null);
113
+			$this->assign('logName', null);
114
+
115
+			$this->assignCSRFToken();
116
+			$this->assign('createMode', true);
117
+			$this->setTemplate('queue-management/edit.tpl');
118
+		}
119
+	}
120
+
121
+	protected function edit()
122
+	{
123
+		$database = $this->getDatabase();
124
+
125
+		$id = WebRequest::getInt('queue');
126
+		if ($id === null) {
127
+			$this->redirect('queueManagement');
128
+
129
+			return;
130
+		}
131
+
132
+		/** @var RequestQueue $queue */
133
+		$queue = RequestQueue::getById($id, $database);
134
+
135
+		if (WebRequest::wasPosted()) {
136
+			$this->validateCSRFToken();
137
+
138
+			$this->helper->configureDefaults(
139
+				$queue,
140
+				WebRequest::postBoolean('enabled'),
141
+				WebRequest::postBoolean('default'),
142
+				WebRequest::postBoolean('antispoof'),
143
+				WebRequest::postBoolean('titleblacklist'),
144
+				$this->helper->isEmailTemplateTarget($queue, $this->getDatabase()) || $this->helper->isRequestFormTarget($queue, $this->getDatabase()));
145
+
146
+			$queue->setHeader(WebRequest::postString('header'));
147
+			$queue->setDisplayName(WebRequest::postString('displayName'));
148
+			$queue->setHelp(WebRequest::postString('help'));
149
+
150
+			$proceed = true;
151
+
152
+			$foundRequestQueue = RequestQueue::getByDisplayName($database, $queue->getDisplayName(), 1);
153
+			if ($foundRequestQueue !== false && $foundRequestQueue->getId() !== $queue->getId()) {
154
+				// FIXME: domain
155
+				SessionAlert::error("The chosen target display name is already in use. Please choose another.");
156
+				$proceed = false;
157
+			}
158
+
159
+			$foundRequestQueue = RequestQueue::getByHeader($database, $queue->getHeader(), 1);
160
+			if ($foundRequestQueue !== false && $foundRequestQueue->getId() !== $queue->getId()) {
161
+				// FIXME: domain
162
+				SessionAlert::error("The chosen header is already in use. Please choose another.");
163
+				$proceed = false;
164
+			}
165
+
166
+			if ($proceed) {
167
+				Logger::requestQueueEdited($database, $queue);
168
+				$queue->save();
169
+				$this->redirect('queueManagement');
170
+			}
171
+			else {
172
+				$this->populateFromObject($queue);
173
+
174
+				$this->assign('createMode', false);
175
+				$this->setTemplate('queue-management/edit.tpl');
176
+			}
177
+		}
178
+		else {
179
+			$this->populateFromObject($queue);
180
+
181
+			$this->assign('createMode', false);
182
+			$this->setTemplate('queue-management/edit.tpl');
183
+		}
184
+	}
185
+
186
+	/**
187
+	 * @param RequestQueue $queue
188
+	 */
189
+	protected function populateFromObject(RequestQueue $queue): void
190
+	{
191
+		$this->assignCSRFToken();
192
+
193
+		$this->assign('header', $queue->getHeader());
194
+		$this->assign('displayName', $queue->getDisplayName());
195
+		$this->assign('apiName', $queue->getApiName());
196
+		$this->assign('enabled', $queue->isEnabled());
197
+		$this->assign('default', $queue->isDefault());
198
+		$this->assign('antispoof', $queue->isDefaultAntispoof());
199
+		$this->assign('titleblacklist', $queue->isDefaultTitleBlacklist());
200
+		$this->assign('help', $queue->getHelp());
201
+		$this->assign('logName', $queue->getLogName());
202
+
203
+		$isQueueTarget = $this->helper->isEmailTemplateTarget($queue, $this->getDatabase());
204
+		$isFormTarget = $this->helper->isRequestFormTarget($queue, $this->getDatabase());
205
+		$this->assign('isTarget', $isQueueTarget);
206
+		$this->assign('isFormTarget', $isFormTarget);
207
+	}
208 208
 }
209 209
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/Registration/PageRegisterOption.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -13,19 +13,19 @@
 block discarded – undo
13 13
 
14 14
 class PageRegisterOption extends InternalPageBase
15 15
 {
16
-    /**
17
-     * Main function for this page, when no specific actions are called.
18
-     * @return void
19
-     */
20
-    protected function main()
21
-    {
22
-        $this->assign('allowRegistration', $this->getSiteConfiguration()->isRegistrationAllowed());
23
-        $this->assign('domains', Domain::getAll($this->getDatabase()));
24
-        $this->setTemplate('registration/option.tpl');
25
-    }
16
+	/**
17
+	 * Main function for this page, when no specific actions are called.
18
+	 * @return void
19
+	 */
20
+	protected function main()
21
+	{
22
+		$this->assign('allowRegistration', $this->getSiteConfiguration()->isRegistrationAllowed());
23
+		$this->assign('domains', Domain::getAll($this->getDatabase()));
24
+		$this->setTemplate('registration/option.tpl');
25
+	}
26 26
 
27
-    protected function isProtectedPage()
28
-    {
29
-        return false;
30
-    }
27
+	protected function isProtectedPage()
28
+	{
29
+		return false;
30
+	}
31 31
 }
Please login to merge, or discard this patch.
includes/Pages/Registration/PageRegisterBase.php 1 patch
Indentation   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -24,255 +24,255 @@
 block discarded – undo
24 24
 
25 25
 abstract class PageRegisterBase extends InternalPageBase
26 26
 {
27
-    /**
28
-     * Main function for this page, when no specific actions are called.
29
-     * @throws AccessDeniedException
30
-     * @throws ApplicationLogicException
31
-     * @throws Exception
32
-     */
33
-    protected function main()
34
-    {
35
-        $useOAuthSignup = $this->getSiteConfiguration()->getUseOAuthSignup();
36
-        if (!$this->getSiteConfiguration()->isRegistrationAllowed()) {
37
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
38
-        }
39
-
40
-        // Dual-mode page
41
-        if (WebRequest::wasPosted()) {
42
-            $this->validateCSRFToken();
43
-
44
-            try {
45
-                $this->handlePost($useOAuthSignup);
46
-            }
47
-            catch (ApplicationLogicException $ex) {
48
-                SessionAlert::error($ex->getMessage());
49
-
50
-                $this->getDatabase()->rollBack();
51
-
52
-                $this->assignCSRFToken();
53
-                $this->assign("useOAuthSignup", $useOAuthSignup);
54
-                $this->applyErrorValues();
55
-                $this->setTemplate($this->getRegistrationTemplate());
56
-                $this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
57
-            }
58
-        }
59
-        else {
60
-            $domain = WebRequest::getString('d');
61
-            if ($domain === null) {
62
-                throw new ApplicationLogicException("No domain specified.");
63
-            }
64
-
65
-            /** @var Domain|false $domainObject */
66
-            $domainObject = Domain::getByShortName($domain, $this->getDatabase());
67
-            if ($domainObject === false || !$domainObject->isEnabled()) {
68
-                throw new ApplicationLogicException("Unknown domain or domain not enabled.");
69
-            }
70
-
71
-            $this->assign('localDocumentation', $domainObject->getLocalDocumentation());
72
-
73
-            $this->assignCSRFToken();
74
-            $this->assign("useOAuthSignup", $useOAuthSignup);
75
-            $this->setTemplate($this->getRegistrationTemplate());
76
-            $this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
77
-        }
78
-    }
79
-
80
-    protected abstract function getRegistrationTemplate();
81
-
82
-    protected function isProtectedPage()
83
-    {
84
-        return false;
85
-    }
86
-
87
-    /**
88
-     * @param string $emailAddress
89
-     *
90
-     * @throws ApplicationLogicException
91
-     */
92
-    protected function validateUniqueEmail($emailAddress)
93
-    {
94
-        $query = 'SELECT COUNT(id) FROM user WHERE email = :email';
95
-        $statement = $this->getDatabase()->prepare($query);
96
-        $statement->execute(array(':email' => $emailAddress));
97
-
98
-        if ($statement->fetchColumn() > 0) {
99
-            throw new ApplicationLogicException('That email address is already in use on this system.');
100
-        }
101
-
102
-        $statement->closeCursor();
103
-    }
104
-
105
-    /**
106
-     * @param $emailAddress
107
-     * @param $password
108
-     * @param $username
109
-     * @param $useOAuthSignup
110
-     * @param $confirmationId
111
-     * @param $onwikiUsername
112
-     * @param Domain|false $domainObject
113
-     *
114
-     * @throws ApplicationLogicException
115
-     */
116
-    protected function validateRequest(
117
-        $emailAddress,
118
-        $password,
119
-        $username,
120
-        $useOAuthSignup,
121
-        $confirmationId,
122
-        $onwikiUsername,
123
-        $domainObject
124
-    ) {
125
-        if (!WebRequest::postBoolean('guidelines')) {
126
-            throw new ApplicationLogicException('You must read the interface guidelines before your request may be submitted.');
127
-        }
128
-
129
-        if ($domainObject === false) {
130
-            throw new ApplicationLogicException('The chosen wiki does not exist on this tool.');
131
-        }
132
-
133
-        if (!$domainObject->isEnabled()) {
134
-            throw new ApplicationLogicException('The chosen wiki is not currently enabled on this tool.');
135
-        }
136
-
137
-        $this->validateGeneralInformation($emailAddress, $password, $username);
138
-        $this->validateUniqueEmail($emailAddress);
139
-        $this->validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername);
140
-    }
141
-
142
-    /**
143
-     * @param $useOAuthSignup
144
-     * @param $confirmationId
145
-     * @param $onwikiUsername
146
-     *
147
-     * @throws ApplicationLogicException
148
-     */
149
-    protected function validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername)
150
-    {
151
-        if (!$useOAuthSignup) {
152
-            if ($confirmationId === null || $confirmationId <= 0) {
153
-                throw new ApplicationLogicException('Please enter the revision id of your confirmation edit.');
154
-            }
155
-
156
-            if ($onwikiUsername === null) {
157
-                throw new ApplicationLogicException('Please specify your on-wiki username.');
158
-            }
159
-        }
160
-    }
161
-
162
-    /**
163
-     * @param $emailAddress
164
-     * @param $password
165
-     * @param $username
166
-     *
167
-     * @throws ApplicationLogicException
168
-     */
169
-    protected function validateGeneralInformation($emailAddress, $password, $username)
170
-    {
171
-        if ($emailAddress === null) {
172
-            throw new ApplicationLogicException('Your email address appears to be invalid!');
173
-        }
174
-
175
-        if ($password !== WebRequest::postString('newpasswordconfirm')) {
176
-            throw new ApplicationLogicException('Your passwords did not match, please try again.');
177
-        }
178
-
179
-        if (User::getByUsername($username, $this->getDatabase()) !== false) {
180
-            throw new ApplicationLogicException('That username is already in use on this system.');
181
-        }
182
-    }
183
-
184
-    /**
185
-     * @param $useOAuthSignup
186
-     *
187
-     * @throws ApplicationLogicException
188
-     * @throws Exception
189
-     */
190
-    protected function handlePost($useOAuthSignup)
191
-    {
192
-        // Get the data
193
-        $emailAddress = WebRequest::postEmail('email');
194
-        $password = WebRequest::postString('newpassword');
195
-        $username = WebRequest::postString('name');
196
-
197
-        // Only set if OAuth is disabled
198
-        $confirmationId = WebRequest::postInt('conf_revid');
199
-        $onwikiUsername = WebRequest::postString('wname');
200
-
201
-        $database = $this->getDatabase();
202
-        $domain = WebRequest::getString('d');
203
-        $domainObject = Domain::getByShortName($domain, $database);
204
-
205
-        // Do some validation
206
-        $this->validateRequest($emailAddress, $password, $username, $useOAuthSignup, $confirmationId,
207
-            $onwikiUsername, $domainObject);
208
-
209
-        $user = new User();
210
-        $user->setDatabase($database);
211
-
212
-        $user->setUsername($username);
213
-        $user->setEmail($emailAddress);
214
-
215
-        if (!$useOAuthSignup) {
216
-            $user->setOnWikiName($onwikiUsername);
217
-            $user->setConfirmationDiff($confirmationId);
218
-        }
219
-
220
-        $user->save();
221
-
222
-        $passwordCredentialProvider = new PasswordCredentialProvider($database, $this->getSiteConfiguration());
223
-        $passwordCredentialProvider->setCredential($user, 1, $password);
224
-
225
-        $defaultRole = $this->getDefaultRole();
226
-
227
-        $role = new UserRole();
228
-        $role->setDatabase($database);
229
-        $role->setUser($user->getId());
230
-        $role->setRole($defaultRole);
231
-        $role->setDomain($domainObject->getId()); // FIXME: domains
232
-        $role->save();
233
-
234
-        // Log now to get the signup date.
235
-        Logger::newUser($database, $user);
236
-        Logger::userRolesEdited($database, $user, 'Registration', array($defaultRole), array(), $domainObject->getId());
237
-
238
-        $userDomain = new UserDomain();
239
-        $userDomain->setDatabase($database);
240
-        $userDomain->setUser($user->getId());
241
-        $userDomain->setDomain($domainObject->getId());
242
-        $userDomain->save();
243
-
244
-        if ($useOAuthSignup) {
245
-            $oauthProtocolHelper = $this->getOAuthProtocolHelper();
246
-            $oauth = new OAuthUserHelper($user, $database, $oauthProtocolHelper, $this->getSiteConfiguration());
247
-
248
-            $authoriseUrl = $oauth->getRequestToken();
249
-            WebRequest::setOAuthPartialLogin($user);
250
-            $this->redirectUrl($authoriseUrl);
251
-        }
252
-        else {
253
-            // only notify if we're not using the oauth signup.
254
-            $this->getNotificationHelper()->userNew($user);
255
-            WebRequest::setLoggedInUser($user);
256
-            $this->getDomainAccessManager()->switchToDefaultDomain($user);
257
-            $this->redirect('preferences');
258
-        }
259
-    }
260
-
261
-    protected abstract function getDefaultRole();
262
-
263
-    /**
264
-     * Entry point for registration complete
265
-     * @throws Exception
266
-     */
267
-    protected function done()
268
-    {
269
-        $this->setTemplate('registration/alert-registrationcomplete.tpl');
270
-    }
271
-
272
-    protected function applyErrorValues()
273
-    {
274
-        $this->assign('tplUsername', WebRequest::postString('name'));
275
-        $this->assign('tplEmail', WebRequest::postString('email'));
276
-        $this->assign('tplWikipediaUsername', WebRequest::postString('wname'));
277
-        $this->assign('tplConfRevId', WebRequest::postInt('conf_revid'));
278
-    }}
27
+	/**
28
+	 * Main function for this page, when no specific actions are called.
29
+	 * @throws AccessDeniedException
30
+	 * @throws ApplicationLogicException
31
+	 * @throws Exception
32
+	 */
33
+	protected function main()
34
+	{
35
+		$useOAuthSignup = $this->getSiteConfiguration()->getUseOAuthSignup();
36
+		if (!$this->getSiteConfiguration()->isRegistrationAllowed()) {
37
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
38
+		}
39
+
40
+		// Dual-mode page
41
+		if (WebRequest::wasPosted()) {
42
+			$this->validateCSRFToken();
43
+
44
+			try {
45
+				$this->handlePost($useOAuthSignup);
46
+			}
47
+			catch (ApplicationLogicException $ex) {
48
+				SessionAlert::error($ex->getMessage());
49
+
50
+				$this->getDatabase()->rollBack();
51
+
52
+				$this->assignCSRFToken();
53
+				$this->assign("useOAuthSignup", $useOAuthSignup);
54
+				$this->applyErrorValues();
55
+				$this->setTemplate($this->getRegistrationTemplate());
56
+				$this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
57
+			}
58
+		}
59
+		else {
60
+			$domain = WebRequest::getString('d');
61
+			if ($domain === null) {
62
+				throw new ApplicationLogicException("No domain specified.");
63
+			}
64
+
65
+			/** @var Domain|false $domainObject */
66
+			$domainObject = Domain::getByShortName($domain, $this->getDatabase());
67
+			if ($domainObject === false || !$domainObject->isEnabled()) {
68
+				throw new ApplicationLogicException("Unknown domain or domain not enabled.");
69
+			}
70
+
71
+			$this->assign('localDocumentation', $domainObject->getLocalDocumentation());
72
+
73
+			$this->assignCSRFToken();
74
+			$this->assign("useOAuthSignup", $useOAuthSignup);
75
+			$this->setTemplate($this->getRegistrationTemplate());
76
+			$this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
77
+		}
78
+	}
79
+
80
+	protected abstract function getRegistrationTemplate();
81
+
82
+	protected function isProtectedPage()
83
+	{
84
+		return false;
85
+	}
86
+
87
+	/**
88
+	 * @param string $emailAddress
89
+	 *
90
+	 * @throws ApplicationLogicException
91
+	 */
92
+	protected function validateUniqueEmail($emailAddress)
93
+	{
94
+		$query = 'SELECT COUNT(id) FROM user WHERE email = :email';
95
+		$statement = $this->getDatabase()->prepare($query);
96
+		$statement->execute(array(':email' => $emailAddress));
97
+
98
+		if ($statement->fetchColumn() > 0) {
99
+			throw new ApplicationLogicException('That email address is already in use on this system.');
100
+		}
101
+
102
+		$statement->closeCursor();
103
+	}
104
+
105
+	/**
106
+	 * @param $emailAddress
107
+	 * @param $password
108
+	 * @param $username
109
+	 * @param $useOAuthSignup
110
+	 * @param $confirmationId
111
+	 * @param $onwikiUsername
112
+	 * @param Domain|false $domainObject
113
+	 *
114
+	 * @throws ApplicationLogicException
115
+	 */
116
+	protected function validateRequest(
117
+		$emailAddress,
118
+		$password,
119
+		$username,
120
+		$useOAuthSignup,
121
+		$confirmationId,
122
+		$onwikiUsername,
123
+		$domainObject
124
+	) {
125
+		if (!WebRequest::postBoolean('guidelines')) {
126
+			throw new ApplicationLogicException('You must read the interface guidelines before your request may be submitted.');
127
+		}
128
+
129
+		if ($domainObject === false) {
130
+			throw new ApplicationLogicException('The chosen wiki does not exist on this tool.');
131
+		}
132
+
133
+		if (!$domainObject->isEnabled()) {
134
+			throw new ApplicationLogicException('The chosen wiki is not currently enabled on this tool.');
135
+		}
136
+
137
+		$this->validateGeneralInformation($emailAddress, $password, $username);
138
+		$this->validateUniqueEmail($emailAddress);
139
+		$this->validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername);
140
+	}
141
+
142
+	/**
143
+	 * @param $useOAuthSignup
144
+	 * @param $confirmationId
145
+	 * @param $onwikiUsername
146
+	 *
147
+	 * @throws ApplicationLogicException
148
+	 */
149
+	protected function validateNonOAuthFields($useOAuthSignup, $confirmationId, $onwikiUsername)
150
+	{
151
+		if (!$useOAuthSignup) {
152
+			if ($confirmationId === null || $confirmationId <= 0) {
153
+				throw new ApplicationLogicException('Please enter the revision id of your confirmation edit.');
154
+			}
155
+
156
+			if ($onwikiUsername === null) {
157
+				throw new ApplicationLogicException('Please specify your on-wiki username.');
158
+			}
159
+		}
160
+	}
161
+
162
+	/**
163
+	 * @param $emailAddress
164
+	 * @param $password
165
+	 * @param $username
166
+	 *
167
+	 * @throws ApplicationLogicException
168
+	 */
169
+	protected function validateGeneralInformation($emailAddress, $password, $username)
170
+	{
171
+		if ($emailAddress === null) {
172
+			throw new ApplicationLogicException('Your email address appears to be invalid!');
173
+		}
174
+
175
+		if ($password !== WebRequest::postString('newpasswordconfirm')) {
176
+			throw new ApplicationLogicException('Your passwords did not match, please try again.');
177
+		}
178
+
179
+		if (User::getByUsername($username, $this->getDatabase()) !== false) {
180
+			throw new ApplicationLogicException('That username is already in use on this system.');
181
+		}
182
+	}
183
+
184
+	/**
185
+	 * @param $useOAuthSignup
186
+	 *
187
+	 * @throws ApplicationLogicException
188
+	 * @throws Exception
189
+	 */
190
+	protected function handlePost($useOAuthSignup)
191
+	{
192
+		// Get the data
193
+		$emailAddress = WebRequest::postEmail('email');
194
+		$password = WebRequest::postString('newpassword');
195
+		$username = WebRequest::postString('name');
196
+
197
+		// Only set if OAuth is disabled
198
+		$confirmationId = WebRequest::postInt('conf_revid');
199
+		$onwikiUsername = WebRequest::postString('wname');
200
+
201
+		$database = $this->getDatabase();
202
+		$domain = WebRequest::getString('d');
203
+		$domainObject = Domain::getByShortName($domain, $database);
204
+
205
+		// Do some validation
206
+		$this->validateRequest($emailAddress, $password, $username, $useOAuthSignup, $confirmationId,
207
+			$onwikiUsername, $domainObject);
208
+
209
+		$user = new User();
210
+		$user->setDatabase($database);
211
+
212
+		$user->setUsername($username);
213
+		$user->setEmail($emailAddress);
214
+
215
+		if (!$useOAuthSignup) {
216
+			$user->setOnWikiName($onwikiUsername);
217
+			$user->setConfirmationDiff($confirmationId);
218
+		}
219
+
220
+		$user->save();
221
+
222
+		$passwordCredentialProvider = new PasswordCredentialProvider($database, $this->getSiteConfiguration());
223
+		$passwordCredentialProvider->setCredential($user, 1, $password);
224
+
225
+		$defaultRole = $this->getDefaultRole();
226
+
227
+		$role = new UserRole();
228
+		$role->setDatabase($database);
229
+		$role->setUser($user->getId());
230
+		$role->setRole($defaultRole);
231
+		$role->setDomain($domainObject->getId()); // FIXME: domains
232
+		$role->save();
233
+
234
+		// Log now to get the signup date.
235
+		Logger::newUser($database, $user);
236
+		Logger::userRolesEdited($database, $user, 'Registration', array($defaultRole), array(), $domainObject->getId());
237
+
238
+		$userDomain = new UserDomain();
239
+		$userDomain->setDatabase($database);
240
+		$userDomain->setUser($user->getId());
241
+		$userDomain->setDomain($domainObject->getId());
242
+		$userDomain->save();
243
+
244
+		if ($useOAuthSignup) {
245
+			$oauthProtocolHelper = $this->getOAuthProtocolHelper();
246
+			$oauth = new OAuthUserHelper($user, $database, $oauthProtocolHelper, $this->getSiteConfiguration());
247
+
248
+			$authoriseUrl = $oauth->getRequestToken();
249
+			WebRequest::setOAuthPartialLogin($user);
250
+			$this->redirectUrl($authoriseUrl);
251
+		}
252
+		else {
253
+			// only notify if we're not using the oauth signup.
254
+			$this->getNotificationHelper()->userNew($user);
255
+			WebRequest::setLoggedInUser($user);
256
+			$this->getDomainAccessManager()->switchToDefaultDomain($user);
257
+			$this->redirect('preferences');
258
+		}
259
+	}
260
+
261
+	protected abstract function getDefaultRole();
262
+
263
+	/**
264
+	 * Entry point for registration complete
265
+	 * @throws Exception
266
+	 */
267
+	protected function done()
268
+	{
269
+		$this->setTemplate('registration/alert-registrationcomplete.tpl');
270
+	}
271
+
272
+	protected function applyErrorValues()
273
+	{
274
+		$this->assign('tplUsername', WebRequest::postString('name'));
275
+		$this->assign('tplEmail', WebRequest::postString('email'));
276
+		$this->assign('tplWikipediaUsername', WebRequest::postString('wname'));
277
+		$this->assign('tplConfRevId', WebRequest::postInt('conf_revid'));
278
+	}}
Please login to merge, or discard this patch.