Test Setup Failed
Push — irc-comment-visibility-fix ( 1f25c9...574aa6 )
by Michael
10:52
created
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/PageUserManagement.php 1 patch
Indentation   +594 added lines, -594 removed lines patch added patch discarded remove patch
@@ -26,598 +26,598 @@
 block discarded – undo
26 26
  */
27 27
 class PageUserManagement extends InternalPageBase
28 28
 {
29
-    // FIXME: domains
30
-    /** @var string */
31
-    private $adminMailingList = '[email protected]';
32
-
33
-    /**
34
-     * Main function for this page, when no specific actions are called.
35
-     */
36
-    protected function main()
37
-    {
38
-        $this->setHtmlTitle('User Management');
39
-
40
-        $database = $this->getDatabase();
41
-        $currentUser = User::getCurrent($database);
42
-
43
-        $userSearchRequest = WebRequest::getString('usersearch');
44
-        if ($userSearchRequest !== null) {
45
-            $searchedUser = User::getByUsername($userSearchRequest, $database);
46
-            if ($searchedUser !== false) {
47
-                $this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
48
-                return;
49
-            }
50
-        }
51
-
52
-        // A bit hacky, but it's better than my last solution of creating an object for each user and passing that to
53
-        // the template. I still don't have a particularly good way of handling this.
54
-        OAuthUserHelper::prepareTokenCountStatement($database);
55
-
56
-        if (WebRequest::getBoolean("showAll")) {
57
-            $this->assign("showAll", true);
58
-
59
-            $suspendedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch();
60
-            $this->assign("suspendedUsers", $suspendedUsers);
61
-
62
-            $declinedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch();
63
-            $this->assign("declinedUsers", $declinedUsers);
64
-
65
-            UserSearchHelper::get($database)->getRoleMap($roleMap);
66
-        }
67
-        else {
68
-            $this->assign("showAll", false);
69
-            $this->assign("suspendedUsers", array());
70
-            $this->assign("declinedUsers", array());
71
-
72
-            UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
73
-        }
74
-
75
-        $newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
76
-        $normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
77
-        $adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
78
-        $checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
79
-        $toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
80
-        $this->assign('newUsers', $newUsers);
81
-        $this->assign('normalUsers', $normalUsers);
82
-        $this->assign('adminUsers', $adminUsers);
83
-        $this->assign('checkUsers', $checkUsers);
84
-        $this->assign('toolRoots', $toolRoots);
85
-
86
-        $this->assign('roles', $roleMap);
87
-
88
-        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
89
-
90
-        $this->assign('canApprove', $this->barrierTest('approve', $currentUser));
91
-        $this->assign('canDecline', $this->barrierTest('decline', $currentUser));
92
-        $this->assign('canRename', $this->barrierTest('rename', $currentUser));
93
-        $this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
94
-        $this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
95
-        $this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
96
-
97
-        // FIXME: domains!
98
-        /** @var Domain $domain */
99
-        $domain = Domain::getById(1, $this->getDatabase());
100
-        $this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
101
-
102
-        $this->setTemplate("usermanagement/main.tpl");
103
-    }
104
-
105
-    #region Access control
106
-
107
-    /**
108
-     * Action target for editing the roles assigned to a user
109
-     */
110
-    protected function editRoles()
111
-    {
112
-        $this->setHtmlTitle('User Management');
113
-        $database = $this->getDatabase();
114
-        $userId = WebRequest::getInt('user');
115
-
116
-        /** @var User $user */
117
-        $user = User::getById($userId, $database);
118
-
119
-        if ($user === false || $user->isCommunityUser()) {
120
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
121
-        }
122
-
123
-        $roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database, 1)); // FIXME: domains
124
-
125
-        // Dual-mode action
126
-        if (WebRequest::wasPosted()) {
127
-            $this->validateCSRFToken();
128
-
129
-            $reason = WebRequest::postString('reason');
130
-            if ($reason === false || trim($reason) === '') {
131
-                throw new ApplicationLogicException('No reason specified for roles change');
132
-            }
133
-
134
-            /** @var UserRole[] $delete */
135
-            $delete = array();
136
-            /** @var string[] $delete */
137
-            $add = array();
138
-
139
-            foreach ($roleData as $name => $r) {
140
-                if ($r['allowEdit'] !== 1) {
141
-                    // not allowed, to touch this, so ignore it
142
-                    continue;
143
-                }
144
-
145
-                $newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
146
-                if ($newValue !== $r['active']) {
147
-                    if ($newValue === 0) {
148
-                        $delete[] = $r['object'];
149
-                    }
150
-
151
-                    if ($newValue === 1) {
152
-                        $add[] = $name;
153
-                    }
154
-                }
155
-            }
156
-
157
-            // Check there's something to do
158
-            if ((count($add) + count($delete)) === 0) {
159
-                $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
160
-                SessionAlert::warning('No changes made to roles.');
161
-
162
-                return;
163
-            }
164
-
165
-            $removed = array();
166
-
167
-            /** @var UserRole $d */
168
-            foreach ($delete as $d) {
169
-                $removed[] = $d->getRole();
170
-                $d->delete();
171
-            }
172
-
173
-            foreach ($add as $x) {
174
-                $a = new UserRole();
175
-                $a->setUser($user->getId());
176
-                $a->setRole($x);
177
-                $a->setDomain(1); // FIXME: domains
178
-                $a->setDatabase($database);
179
-                $a->save();
180
-            }
181
-
182
-            Logger::userRolesEdited($database, $user, $reason, $add, $removed, 1); // FIXME: domains
183
-
184
-            // dummy save for optimistic locking. If this fails, the entire txn will roll back.
185
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
186
-            $user->save();
187
-
188
-            $this->getNotificationHelper()->userRolesEdited($user, $reason);
189
-            SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
190
-
191
-            $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
192
-
193
-            return;
194
-        }
195
-        else {
196
-            $this->assignCSRFToken();
197
-            $this->setTemplate('usermanagement/roleedit.tpl');
198
-            $this->assign('user', $user);
199
-            $this->assign('roleData', $roleData);
200
-        }
201
-    }
202
-
203
-    /**
204
-     * Action target for suspending users
205
-     *
206
-     * @throws ApplicationLogicException
207
-     */
208
-    protected function suspend()
209
-    {
210
-        $this->setHtmlTitle('User Management');
211
-
212
-        $database = $this->getDatabase();
213
-
214
-        $userId = WebRequest::getInt('user');
215
-
216
-        /** @var User $user */
217
-        $user = User::getById($userId, $database);
218
-
219
-        if ($user === false || $user->isCommunityUser()) {
220
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
221
-        }
222
-
223
-        if ($user->isSuspended()) {
224
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
225
-        }
226
-
227
-        // Dual-mode action
228
-        if (WebRequest::wasPosted()) {
229
-            $this->validateCSRFToken();
230
-            $reason = WebRequest::postString('reason');
231
-
232
-            if ($reason === null || trim($reason) === "") {
233
-                throw new ApplicationLogicException('No reason provided');
234
-            }
235
-
236
-            $user->setStatus(User::STATUS_SUSPENDED);
237
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
238
-            $user->save();
239
-            Logger::suspendedUser($database, $user, $reason);
240
-
241
-            $this->getNotificationHelper()->userSuspended($user, $reason);
242
-            SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
243
-
244
-            // send email
245
-            $this->sendStatusChangeEmail(
246
-                'Your WP:ACC account has been suspended',
247
-                'usermanagement/emails/suspended.tpl',
248
-                $reason,
249
-                $user,
250
-                User::getCurrent($database)->getUsername()
251
-            );
252
-
253
-            $this->redirect('userManagement');
254
-
255
-            return;
256
-        }
257
-        else {
258
-            $this->assignCSRFToken();
259
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
260
-            $this->assign('user', $user);
261
-            $this->assign('status', 'Suspended');
262
-            $this->assign("showReason", true);
263
-
264
-            if (WebRequest::getString('preload')) {
265
-                $this->assign('preload', WebRequest::getString('preload'));
266
-            }
267
-        }
268
-    }
269
-
270
-    /**
271
-     * Entry point for the decline action
272
-     *
273
-     * @throws ApplicationLogicException
274
-     */
275
-    protected function decline()
276
-    {
277
-        $this->setHtmlTitle('User Management');
278
-
279
-        $database = $this->getDatabase();
280
-
281
-        $userId = WebRequest::getInt('user');
282
-        $user = User::getById($userId, $database);
283
-
284
-        if ($user === false || $user->isCommunityUser()) {
285
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
286
-        }
287
-
288
-        if (!$user->isNewUser()) {
289
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
290
-        }
291
-
292
-        // Dual-mode action
293
-        if (WebRequest::wasPosted()) {
294
-            $this->validateCSRFToken();
295
-            $reason = WebRequest::postString('reason');
296
-
297
-            if ($reason === null || trim($reason) === "") {
298
-                throw new ApplicationLogicException('No reason provided');
299
-            }
300
-
301
-            $user->setStatus(User::STATUS_DECLINED);
302
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
303
-            $user->save();
304
-            Logger::declinedUser($database, $user, $reason);
305
-
306
-            $this->getNotificationHelper()->userDeclined($user, $reason);
307
-            SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
308
-
309
-            // send email
310
-            $this->sendStatusChangeEmail(
311
-                'Your WP:ACC account has been declined',
312
-                'usermanagement/emails/declined.tpl',
313
-                $reason,
314
-                $user,
315
-                User::getCurrent($database)->getUsername()
316
-            );
317
-
318
-            $this->redirect('userManagement');
319
-
320
-            return;
321
-        }
322
-        else {
323
-            $this->assignCSRFToken();
324
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
325
-            $this->assign('user', $user);
326
-            $this->assign('status', 'Declined');
327
-            $this->assign("showReason", true);
328
-        }
329
-    }
330
-
331
-    /**
332
-     * Entry point for the approve action
333
-     *
334
-     * @throws ApplicationLogicException
335
-     */
336
-    protected function approve()
337
-    {
338
-        $this->setHtmlTitle('User Management');
339
-
340
-        $database = $this->getDatabase();
341
-
342
-        $userId = WebRequest::getInt('user');
343
-        $user = User::getById($userId, $database);
344
-
345
-        if ($user === false || $user->isCommunityUser()) {
346
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
347
-        }
348
-
349
-        if ($user->isActive()) {
350
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
351
-        }
352
-
353
-        // Dual-mode action
354
-        if (WebRequest::wasPosted()) {
355
-            $this->validateCSRFToken();
356
-            $user->setStatus(User::STATUS_ACTIVE);
357
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
358
-            $user->save();
359
-            Logger::approvedUser($database, $user);
360
-
361
-            $this->getNotificationHelper()->userApproved($user);
362
-            SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
363
-
364
-            // send email
365
-            $this->sendStatusChangeEmail(
366
-                'Your WP:ACC account has been approved',
367
-                'usermanagement/emails/approved.tpl',
368
-                null,
369
-                $user,
370
-                User::getCurrent($database)->getUsername()
371
-            );
372
-
373
-            $this->redirect("userManagement");
374
-
375
-            return;
376
-        }
377
-        else {
378
-            $this->assignCSRFToken();
379
-            $this->setTemplate("usermanagement/changelevel-reason.tpl");
380
-            $this->assign("user", $user);
381
-            $this->assign("status", "Active");
382
-            $this->assign("showReason", false);
383
-        }
384
-    }
385
-
386
-    #endregion
387
-
388
-    #region Renaming / Editing
389
-
390
-    /**
391
-     * Entry point for the rename action
392
-     *
393
-     * @throws ApplicationLogicException
394
-     */
395
-    protected function rename()
396
-    {
397
-        $this->setHtmlTitle('User Management');
398
-
399
-        $database = $this->getDatabase();
400
-
401
-        $userId = WebRequest::getInt('user');
402
-        $user = User::getById($userId, $database);
403
-
404
-        if ($user === false || $user->isCommunityUser()) {
405
-            throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
406
-        }
407
-
408
-        // Dual-mode action
409
-        if (WebRequest::wasPosted()) {
410
-            $this->validateCSRFToken();
411
-            $newUsername = WebRequest::postString('newname');
412
-
413
-            if ($newUsername === null || trim($newUsername) === "") {
414
-                throw new ApplicationLogicException('The new username cannot be empty');
415
-            }
416
-
417
-            if (User::getByUsername($newUsername, $database) != false) {
418
-                throw new ApplicationLogicException('The new username already exists');
419
-            }
420
-
421
-            $oldUsername = $user->getUsername();
422
-            $user->setUsername($newUsername);
423
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
424
-
425
-            $user->save();
426
-
427
-            $logEntryData = serialize(array(
428
-                'old' => $oldUsername,
429
-                'new' => $newUsername,
430
-            ));
431
-
432
-            Logger::renamedUser($database, $user, $logEntryData);
433
-
434
-            SessionAlert::quick("Changed User "
435
-                . htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
436
-                . " name to "
437
-                . htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
438
-
439
-            $this->getNotificationHelper()->userRenamed($user, $oldUsername);
440
-
441
-            // send an email to the user.
442
-            $this->assign('targetUsername', $user->getUsername());
443
-            $this->assign('toolAdmin', User::getCurrent($database)->getUsername());
444
-            $this->assign('oldUsername', $oldUsername);
445
-            $this->assign('mailingList', $this->adminMailingList);
446
-
447
-            // FIXME: domains!
448
-            /** @var Domain $domain */
449
-            $domain = Domain::getById(1, $database);
450
-            $this->getEmailHelper()->sendMail(
451
-                $this->adminMailingList,
452
-                $user->getEmail(),
453
-                'Your username on WP:ACC has been changed',
454
-                $this->fetchTemplate('usermanagement/emails/renamed.tpl')
455
-            );
456
-
457
-            $this->redirect("userManagement");
458
-
459
-            return;
460
-        }
461
-        else {
462
-            $this->assignCSRFToken();
463
-            $this->setTemplate('usermanagement/renameuser.tpl');
464
-            $this->assign('user', $user);
465
-        }
466
-    }
467
-
468
-    /**
469
-     * Entry point for the edit action
470
-     *
471
-     * @throws ApplicationLogicException
472
-     */
473
-    protected function editUser()
474
-    {
475
-        $this->setHtmlTitle('User Management');
476
-
477
-        $database = $this->getDatabase();
478
-
479
-        $userId = WebRequest::getInt('user');
480
-        $user = User::getById($userId, $database);
481
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
482
-
483
-        if ($user === false || $user->isCommunityUser()) {
484
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
485
-        }
486
-
487
-        // FIXME: domains
488
-        $prefs = new PreferenceManager($database, $user->getId(), 1);
489
-
490
-        // Dual-mode action
491
-        if (WebRequest::wasPosted()) {
492
-            $this->validateCSRFToken();
493
-            $newEmail = WebRequest::postEmail('user_email');
494
-            $newOnWikiName = WebRequest::postString('user_onwikiname');
495
-
496
-            if ($newEmail === null) {
497
-                throw new ApplicationLogicException('Invalid email address');
498
-            }
499
-
500
-            if ($this->validateUnusedEmail($newEmail, $userId)) {
501
-                throw new ApplicationLogicException('The specified email address is already in use.');
502
-            }
503
-
504
-            if (!($oauth->isFullyLinked() || $oauth->isPartiallyLinked())) {
505
-                if (trim($newOnWikiName) == "") {
506
-                    throw new ApplicationLogicException('New on-wiki username cannot be blank');
507
-                }
508
-
509
-                $user->setOnWikiName($newOnWikiName);
510
-            }
511
-
512
-            $user->setEmail($newEmail);
513
-
514
-            $prefs->setLocalPreference(PreferenceManager::PREF_CREATION_MODE, WebRequest::postInt('creationmode'));
515
-
516
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
517
-
518
-            $user->save();
519
-
520
-            Logger::userPreferencesChange($database, $user);
521
-            $this->getNotificationHelper()->userPrefChange($user);
522
-            SessionAlert::quick('Changes to user\'s preferences have been saved');
523
-
524
-            $this->redirect("userManagement");
525
-
526
-            return;
527
-        }
528
-        else {
529
-            $this->assignCSRFToken();
530
-            $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
531
-                $this->getSiteConfiguration());
532
-            $this->setTemplate('usermanagement/edituser.tpl');
533
-            $this->assign('user', $user);
534
-            $this->assign('oauth', $oauth);
535
-
536
-            $this->assign('preferredCreationMode', (int)$prefs->getPreference(PreferenceManager::PREF_CREATION_MODE));
537
-            $this->assign('emailSignature', $prefs->getPreference(PreferenceManager::PREF_EMAIL_SIGNATURE));
538
-
539
-            $this->assign('canManualCreate',
540
-                $this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation'));
541
-            $this->assign('canOauthCreate',
542
-                $this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation'));
543
-            $this->assign('canBotCreate',
544
-                $this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation'));
545
-        }
546
-    }
547
-
548
-    #endregion
549
-
550
-    private function validateUnusedEmail(string $email, int $userId) : bool {
551
-        $query = 'SELECT COUNT(id) FROM user WHERE email = :email AND id <> :uid';
552
-        $statement = $this->getDatabase()->prepare($query);
553
-        $statement->execute(array(':email' => $email, ':uid' => $userId));
554
-        $inUse = $statement->fetchColumn() > 0;
555
-        $statement->closeCursor();
556
-
557
-        return $inUse;
558
-    }
559
-
560
-    /**
561
-     * Sends a status change email to the user.
562
-     *
563
-     * @param string      $subject           The subject of the email
564
-     * @param string      $template          The smarty template to use
565
-     * @param string|null $reason            The reason for performing the status change
566
-     * @param User        $user              The user affected
567
-     * @param string      $toolAdminUsername The tool admin's username who is making the edit
568
-     */
569
-    private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
570
-    {
571
-        $this->assign('targetUsername', $user->getUsername());
572
-        $this->assign('toolAdmin', $toolAdminUsername);
573
-        $this->assign('actionReason', $reason);
574
-        $this->assign('mailingList', $this->adminMailingList);
575
-
576
-        // FIXME: domains!
577
-        /** @var Domain $domain */
578
-        $domain = Domain::getById(1, $this->getDatabase());
579
-        $this->getEmailHelper()->sendMail(
580
-            $this->adminMailingList,
581
-            $user->getEmail(),
582
-            $subject,
583
-            $this->fetchTemplate($template)
584
-        );
585
-    }
586
-
587
-    /**
588
-     * @param UserRole[] $activeRoles
589
-     *
590
-     * @return array
591
-     */
592
-    private function getRoleData($activeRoles)
593
-    {
594
-        $availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
595
-
596
-        $currentUser = User::getCurrent($this->getDatabase());
597
-        $this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
598
-
599
-        $initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
600
-
601
-        $roleData = array();
602
-        foreach ($availableRoles as $role => $data) {
603
-            $intersection = array_intersect($data['editableBy'], $userRoles);
604
-
605
-            $roleData[$role] = $initialValue;
606
-            $roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
607
-            $roleData[$role]['description'] = $data['description'];
608
-        }
609
-
610
-        foreach ($activeRoles as $role) {
611
-            if (!isset($roleData[$role->getRole()])) {
612
-                // This value is no longer available in the configuration, allow changing (aka removing) it.
613
-                $roleData[$role->getRole()] = $initialValue;
614
-                $roleData[$role->getRole()]['allowEdit'] = 1;
615
-            }
616
-
617
-            $roleData[$role->getRole()]['object'] = $role;
618
-            $roleData[$role->getRole()]['active'] = 1;
619
-        }
620
-
621
-        return $roleData;
622
-    }
29
+	// FIXME: domains
30
+	/** @var string */
31
+	private $adminMailingList = '[email protected]';
32
+
33
+	/**
34
+	 * Main function for this page, when no specific actions are called.
35
+	 */
36
+	protected function main()
37
+	{
38
+		$this->setHtmlTitle('User Management');
39
+
40
+		$database = $this->getDatabase();
41
+		$currentUser = User::getCurrent($database);
42
+
43
+		$userSearchRequest = WebRequest::getString('usersearch');
44
+		if ($userSearchRequest !== null) {
45
+			$searchedUser = User::getByUsername($userSearchRequest, $database);
46
+			if ($searchedUser !== false) {
47
+				$this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
48
+				return;
49
+			}
50
+		}
51
+
52
+		// A bit hacky, but it's better than my last solution of creating an object for each user and passing that to
53
+		// the template. I still don't have a particularly good way of handling this.
54
+		OAuthUserHelper::prepareTokenCountStatement($database);
55
+
56
+		if (WebRequest::getBoolean("showAll")) {
57
+			$this->assign("showAll", true);
58
+
59
+			$suspendedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch();
60
+			$this->assign("suspendedUsers", $suspendedUsers);
61
+
62
+			$declinedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch();
63
+			$this->assign("declinedUsers", $declinedUsers);
64
+
65
+			UserSearchHelper::get($database)->getRoleMap($roleMap);
66
+		}
67
+		else {
68
+			$this->assign("showAll", false);
69
+			$this->assign("suspendedUsers", array());
70
+			$this->assign("declinedUsers", array());
71
+
72
+			UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
73
+		}
74
+
75
+		$newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
76
+		$normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
77
+		$adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
78
+		$checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
79
+		$toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
80
+		$this->assign('newUsers', $newUsers);
81
+		$this->assign('normalUsers', $normalUsers);
82
+		$this->assign('adminUsers', $adminUsers);
83
+		$this->assign('checkUsers', $checkUsers);
84
+		$this->assign('toolRoots', $toolRoots);
85
+
86
+		$this->assign('roles', $roleMap);
87
+
88
+		$this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
89
+
90
+		$this->assign('canApprove', $this->barrierTest('approve', $currentUser));
91
+		$this->assign('canDecline', $this->barrierTest('decline', $currentUser));
92
+		$this->assign('canRename', $this->barrierTest('rename', $currentUser));
93
+		$this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
94
+		$this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
95
+		$this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
96
+
97
+		// FIXME: domains!
98
+		/** @var Domain $domain */
99
+		$domain = Domain::getById(1, $this->getDatabase());
100
+		$this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
101
+
102
+		$this->setTemplate("usermanagement/main.tpl");
103
+	}
104
+
105
+	#region Access control
106
+
107
+	/**
108
+	 * Action target for editing the roles assigned to a user
109
+	 */
110
+	protected function editRoles()
111
+	{
112
+		$this->setHtmlTitle('User Management');
113
+		$database = $this->getDatabase();
114
+		$userId = WebRequest::getInt('user');
115
+
116
+		/** @var User $user */
117
+		$user = User::getById($userId, $database);
118
+
119
+		if ($user === false || $user->isCommunityUser()) {
120
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
121
+		}
122
+
123
+		$roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database, 1)); // FIXME: domains
124
+
125
+		// Dual-mode action
126
+		if (WebRequest::wasPosted()) {
127
+			$this->validateCSRFToken();
128
+
129
+			$reason = WebRequest::postString('reason');
130
+			if ($reason === false || trim($reason) === '') {
131
+				throw new ApplicationLogicException('No reason specified for roles change');
132
+			}
133
+
134
+			/** @var UserRole[] $delete */
135
+			$delete = array();
136
+			/** @var string[] $delete */
137
+			$add = array();
138
+
139
+			foreach ($roleData as $name => $r) {
140
+				if ($r['allowEdit'] !== 1) {
141
+					// not allowed, to touch this, so ignore it
142
+					continue;
143
+				}
144
+
145
+				$newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
146
+				if ($newValue !== $r['active']) {
147
+					if ($newValue === 0) {
148
+						$delete[] = $r['object'];
149
+					}
150
+
151
+					if ($newValue === 1) {
152
+						$add[] = $name;
153
+					}
154
+				}
155
+			}
156
+
157
+			// Check there's something to do
158
+			if ((count($add) + count($delete)) === 0) {
159
+				$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
160
+				SessionAlert::warning('No changes made to roles.');
161
+
162
+				return;
163
+			}
164
+
165
+			$removed = array();
166
+
167
+			/** @var UserRole $d */
168
+			foreach ($delete as $d) {
169
+				$removed[] = $d->getRole();
170
+				$d->delete();
171
+			}
172
+
173
+			foreach ($add as $x) {
174
+				$a = new UserRole();
175
+				$a->setUser($user->getId());
176
+				$a->setRole($x);
177
+				$a->setDomain(1); // FIXME: domains
178
+				$a->setDatabase($database);
179
+				$a->save();
180
+			}
181
+
182
+			Logger::userRolesEdited($database, $user, $reason, $add, $removed, 1); // FIXME: domains
183
+
184
+			// dummy save for optimistic locking. If this fails, the entire txn will roll back.
185
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
186
+			$user->save();
187
+
188
+			$this->getNotificationHelper()->userRolesEdited($user, $reason);
189
+			SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
190
+
191
+			$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
192
+
193
+			return;
194
+		}
195
+		else {
196
+			$this->assignCSRFToken();
197
+			$this->setTemplate('usermanagement/roleedit.tpl');
198
+			$this->assign('user', $user);
199
+			$this->assign('roleData', $roleData);
200
+		}
201
+	}
202
+
203
+	/**
204
+	 * Action target for suspending users
205
+	 *
206
+	 * @throws ApplicationLogicException
207
+	 */
208
+	protected function suspend()
209
+	{
210
+		$this->setHtmlTitle('User Management');
211
+
212
+		$database = $this->getDatabase();
213
+
214
+		$userId = WebRequest::getInt('user');
215
+
216
+		/** @var User $user */
217
+		$user = User::getById($userId, $database);
218
+
219
+		if ($user === false || $user->isCommunityUser()) {
220
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
221
+		}
222
+
223
+		if ($user->isSuspended()) {
224
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
225
+		}
226
+
227
+		// Dual-mode action
228
+		if (WebRequest::wasPosted()) {
229
+			$this->validateCSRFToken();
230
+			$reason = WebRequest::postString('reason');
231
+
232
+			if ($reason === null || trim($reason) === "") {
233
+				throw new ApplicationLogicException('No reason provided');
234
+			}
235
+
236
+			$user->setStatus(User::STATUS_SUSPENDED);
237
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
238
+			$user->save();
239
+			Logger::suspendedUser($database, $user, $reason);
240
+
241
+			$this->getNotificationHelper()->userSuspended($user, $reason);
242
+			SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
243
+
244
+			// send email
245
+			$this->sendStatusChangeEmail(
246
+				'Your WP:ACC account has been suspended',
247
+				'usermanagement/emails/suspended.tpl',
248
+				$reason,
249
+				$user,
250
+				User::getCurrent($database)->getUsername()
251
+			);
252
+
253
+			$this->redirect('userManagement');
254
+
255
+			return;
256
+		}
257
+		else {
258
+			$this->assignCSRFToken();
259
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
260
+			$this->assign('user', $user);
261
+			$this->assign('status', 'Suspended');
262
+			$this->assign("showReason", true);
263
+
264
+			if (WebRequest::getString('preload')) {
265
+				$this->assign('preload', WebRequest::getString('preload'));
266
+			}
267
+		}
268
+	}
269
+
270
+	/**
271
+	 * Entry point for the decline action
272
+	 *
273
+	 * @throws ApplicationLogicException
274
+	 */
275
+	protected function decline()
276
+	{
277
+		$this->setHtmlTitle('User Management');
278
+
279
+		$database = $this->getDatabase();
280
+
281
+		$userId = WebRequest::getInt('user');
282
+		$user = User::getById($userId, $database);
283
+
284
+		if ($user === false || $user->isCommunityUser()) {
285
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
286
+		}
287
+
288
+		if (!$user->isNewUser()) {
289
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
290
+		}
291
+
292
+		// Dual-mode action
293
+		if (WebRequest::wasPosted()) {
294
+			$this->validateCSRFToken();
295
+			$reason = WebRequest::postString('reason');
296
+
297
+			if ($reason === null || trim($reason) === "") {
298
+				throw new ApplicationLogicException('No reason provided');
299
+			}
300
+
301
+			$user->setStatus(User::STATUS_DECLINED);
302
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
303
+			$user->save();
304
+			Logger::declinedUser($database, $user, $reason);
305
+
306
+			$this->getNotificationHelper()->userDeclined($user, $reason);
307
+			SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
308
+
309
+			// send email
310
+			$this->sendStatusChangeEmail(
311
+				'Your WP:ACC account has been declined',
312
+				'usermanagement/emails/declined.tpl',
313
+				$reason,
314
+				$user,
315
+				User::getCurrent($database)->getUsername()
316
+			);
317
+
318
+			$this->redirect('userManagement');
319
+
320
+			return;
321
+		}
322
+		else {
323
+			$this->assignCSRFToken();
324
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
325
+			$this->assign('user', $user);
326
+			$this->assign('status', 'Declined');
327
+			$this->assign("showReason", true);
328
+		}
329
+	}
330
+
331
+	/**
332
+	 * Entry point for the approve action
333
+	 *
334
+	 * @throws ApplicationLogicException
335
+	 */
336
+	protected function approve()
337
+	{
338
+		$this->setHtmlTitle('User Management');
339
+
340
+		$database = $this->getDatabase();
341
+
342
+		$userId = WebRequest::getInt('user');
343
+		$user = User::getById($userId, $database);
344
+
345
+		if ($user === false || $user->isCommunityUser()) {
346
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
347
+		}
348
+
349
+		if ($user->isActive()) {
350
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
351
+		}
352
+
353
+		// Dual-mode action
354
+		if (WebRequest::wasPosted()) {
355
+			$this->validateCSRFToken();
356
+			$user->setStatus(User::STATUS_ACTIVE);
357
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
358
+			$user->save();
359
+			Logger::approvedUser($database, $user);
360
+
361
+			$this->getNotificationHelper()->userApproved($user);
362
+			SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
363
+
364
+			// send email
365
+			$this->sendStatusChangeEmail(
366
+				'Your WP:ACC account has been approved',
367
+				'usermanagement/emails/approved.tpl',
368
+				null,
369
+				$user,
370
+				User::getCurrent($database)->getUsername()
371
+			);
372
+
373
+			$this->redirect("userManagement");
374
+
375
+			return;
376
+		}
377
+		else {
378
+			$this->assignCSRFToken();
379
+			$this->setTemplate("usermanagement/changelevel-reason.tpl");
380
+			$this->assign("user", $user);
381
+			$this->assign("status", "Active");
382
+			$this->assign("showReason", false);
383
+		}
384
+	}
385
+
386
+	#endregion
387
+
388
+	#region Renaming / Editing
389
+
390
+	/**
391
+	 * Entry point for the rename action
392
+	 *
393
+	 * @throws ApplicationLogicException
394
+	 */
395
+	protected function rename()
396
+	{
397
+		$this->setHtmlTitle('User Management');
398
+
399
+		$database = $this->getDatabase();
400
+
401
+		$userId = WebRequest::getInt('user');
402
+		$user = User::getById($userId, $database);
403
+
404
+		if ($user === false || $user->isCommunityUser()) {
405
+			throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
406
+		}
407
+
408
+		// Dual-mode action
409
+		if (WebRequest::wasPosted()) {
410
+			$this->validateCSRFToken();
411
+			$newUsername = WebRequest::postString('newname');
412
+
413
+			if ($newUsername === null || trim($newUsername) === "") {
414
+				throw new ApplicationLogicException('The new username cannot be empty');
415
+			}
416
+
417
+			if (User::getByUsername($newUsername, $database) != false) {
418
+				throw new ApplicationLogicException('The new username already exists');
419
+			}
420
+
421
+			$oldUsername = $user->getUsername();
422
+			$user->setUsername($newUsername);
423
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
424
+
425
+			$user->save();
426
+
427
+			$logEntryData = serialize(array(
428
+				'old' => $oldUsername,
429
+				'new' => $newUsername,
430
+			));
431
+
432
+			Logger::renamedUser($database, $user, $logEntryData);
433
+
434
+			SessionAlert::quick("Changed User "
435
+				. htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
436
+				. " name to "
437
+				. htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
438
+
439
+			$this->getNotificationHelper()->userRenamed($user, $oldUsername);
440
+
441
+			// send an email to the user.
442
+			$this->assign('targetUsername', $user->getUsername());
443
+			$this->assign('toolAdmin', User::getCurrent($database)->getUsername());
444
+			$this->assign('oldUsername', $oldUsername);
445
+			$this->assign('mailingList', $this->adminMailingList);
446
+
447
+			// FIXME: domains!
448
+			/** @var Domain $domain */
449
+			$domain = Domain::getById(1, $database);
450
+			$this->getEmailHelper()->sendMail(
451
+				$this->adminMailingList,
452
+				$user->getEmail(),
453
+				'Your username on WP:ACC has been changed',
454
+				$this->fetchTemplate('usermanagement/emails/renamed.tpl')
455
+			);
456
+
457
+			$this->redirect("userManagement");
458
+
459
+			return;
460
+		}
461
+		else {
462
+			$this->assignCSRFToken();
463
+			$this->setTemplate('usermanagement/renameuser.tpl');
464
+			$this->assign('user', $user);
465
+		}
466
+	}
467
+
468
+	/**
469
+	 * Entry point for the edit action
470
+	 *
471
+	 * @throws ApplicationLogicException
472
+	 */
473
+	protected function editUser()
474
+	{
475
+		$this->setHtmlTitle('User Management');
476
+
477
+		$database = $this->getDatabase();
478
+
479
+		$userId = WebRequest::getInt('user');
480
+		$user = User::getById($userId, $database);
481
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
482
+
483
+		if ($user === false || $user->isCommunityUser()) {
484
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
485
+		}
486
+
487
+		// FIXME: domains
488
+		$prefs = new PreferenceManager($database, $user->getId(), 1);
489
+
490
+		// Dual-mode action
491
+		if (WebRequest::wasPosted()) {
492
+			$this->validateCSRFToken();
493
+			$newEmail = WebRequest::postEmail('user_email');
494
+			$newOnWikiName = WebRequest::postString('user_onwikiname');
495
+
496
+			if ($newEmail === null) {
497
+				throw new ApplicationLogicException('Invalid email address');
498
+			}
499
+
500
+			if ($this->validateUnusedEmail($newEmail, $userId)) {
501
+				throw new ApplicationLogicException('The specified email address is already in use.');
502
+			}
503
+
504
+			if (!($oauth->isFullyLinked() || $oauth->isPartiallyLinked())) {
505
+				if (trim($newOnWikiName) == "") {
506
+					throw new ApplicationLogicException('New on-wiki username cannot be blank');
507
+				}
508
+
509
+				$user->setOnWikiName($newOnWikiName);
510
+			}
511
+
512
+			$user->setEmail($newEmail);
513
+
514
+			$prefs->setLocalPreference(PreferenceManager::PREF_CREATION_MODE, WebRequest::postInt('creationmode'));
515
+
516
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
517
+
518
+			$user->save();
519
+
520
+			Logger::userPreferencesChange($database, $user);
521
+			$this->getNotificationHelper()->userPrefChange($user);
522
+			SessionAlert::quick('Changes to user\'s preferences have been saved');
523
+
524
+			$this->redirect("userManagement");
525
+
526
+			return;
527
+		}
528
+		else {
529
+			$this->assignCSRFToken();
530
+			$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
531
+				$this->getSiteConfiguration());
532
+			$this->setTemplate('usermanagement/edituser.tpl');
533
+			$this->assign('user', $user);
534
+			$this->assign('oauth', $oauth);
535
+
536
+			$this->assign('preferredCreationMode', (int)$prefs->getPreference(PreferenceManager::PREF_CREATION_MODE));
537
+			$this->assign('emailSignature', $prefs->getPreference(PreferenceManager::PREF_EMAIL_SIGNATURE));
538
+
539
+			$this->assign('canManualCreate',
540
+				$this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation'));
541
+			$this->assign('canOauthCreate',
542
+				$this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation'));
543
+			$this->assign('canBotCreate',
544
+				$this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation'));
545
+		}
546
+	}
547
+
548
+	#endregion
549
+
550
+	private function validateUnusedEmail(string $email, int $userId) : bool {
551
+		$query = 'SELECT COUNT(id) FROM user WHERE email = :email AND id <> :uid';
552
+		$statement = $this->getDatabase()->prepare($query);
553
+		$statement->execute(array(':email' => $email, ':uid' => $userId));
554
+		$inUse = $statement->fetchColumn() > 0;
555
+		$statement->closeCursor();
556
+
557
+		return $inUse;
558
+	}
559
+
560
+	/**
561
+	 * Sends a status change email to the user.
562
+	 *
563
+	 * @param string      $subject           The subject of the email
564
+	 * @param string      $template          The smarty template to use
565
+	 * @param string|null $reason            The reason for performing the status change
566
+	 * @param User        $user              The user affected
567
+	 * @param string      $toolAdminUsername The tool admin's username who is making the edit
568
+	 */
569
+	private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
570
+	{
571
+		$this->assign('targetUsername', $user->getUsername());
572
+		$this->assign('toolAdmin', $toolAdminUsername);
573
+		$this->assign('actionReason', $reason);
574
+		$this->assign('mailingList', $this->adminMailingList);
575
+
576
+		// FIXME: domains!
577
+		/** @var Domain $domain */
578
+		$domain = Domain::getById(1, $this->getDatabase());
579
+		$this->getEmailHelper()->sendMail(
580
+			$this->adminMailingList,
581
+			$user->getEmail(),
582
+			$subject,
583
+			$this->fetchTemplate($template)
584
+		);
585
+	}
586
+
587
+	/**
588
+	 * @param UserRole[] $activeRoles
589
+	 *
590
+	 * @return array
591
+	 */
592
+	private function getRoleData($activeRoles)
593
+	{
594
+		$availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
595
+
596
+		$currentUser = User::getCurrent($this->getDatabase());
597
+		$this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
598
+
599
+		$initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
600
+
601
+		$roleData = array();
602
+		foreach ($availableRoles as $role => $data) {
603
+			$intersection = array_intersect($data['editableBy'], $userRoles);
604
+
605
+			$roleData[$role] = $initialValue;
606
+			$roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
607
+			$roleData[$role]['description'] = $data['description'];
608
+		}
609
+
610
+		foreach ($activeRoles as $role) {
611
+			if (!isset($roleData[$role->getRole()])) {
612
+				// This value is no longer available in the configuration, allow changing (aka removing) it.
613
+				$roleData[$role->getRole()] = $initialValue;
614
+				$roleData[$role->getRole()]['allowEdit'] = 1;
615
+			}
616
+
617
+			$roleData[$role->getRole()]['object'] = $role;
618
+			$roleData[$role->getRole()]['active'] = 1;
619
+		}
620
+
621
+		return $roleData;
622
+	}
623 623
 }
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.
includes/Pages/PageJobQueue.php 1 patch
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -28,309 +28,309 @@
 block discarded – undo
28 28
 
29 29
 class PageJobQueue extends PagedInternalPageBase
30 30
 {
31
-    /**
32
-     * Main function for this page, when no specific actions are called.
33
-     * @return void
34
-     */
35
-    protected function main()
36
-    {
37
-        $this->setHtmlTitle('Job Queue Management');
38
-
39
-        $this->prepareMaps();
40
-
41
-        $database = $this->getDatabase();
42
-
43
-        /** @var JobQueue[] $jobList */
44
-        // FIXME: domains
45
-        $jobList = JobQueueSearchHelper::get($database, 1)
46
-            ->statusIn([
47
-                JobQueue::STATUS_QUEUED,
48
-                JobQueue::STATUS_READY,
49
-                JobQueue::STATUS_WAITING,
50
-                JobQueue::STATUS_RUNNING,
51
-                JobQueue::STATUS_FAILED,
52
-            ])
53
-            ->notAcknowledged()
54
-            ->fetch();
55
-
56
-        $userIds = array();
57
-        $requestIds = array();
58
-
59
-        foreach ($jobList as $job) {
60
-            $userIds[] = $job->getTriggerUserId();
61
-            $requestIds[] = $job->getRequest();
62
-
63
-            $job->setDatabase($database);
64
-        }
65
-
66
-        $this->assign('canSeeAll', $this->barrierTest('all', User::getCurrent($database)));
67
-
68
-        $this->assign('users', UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username'));
69
-        // FIXME: domains
70
-        $this->assign('requests', RequestSearchHelper::get($database, 1)->inIds($requestIds)->fetchMap('name'));
71
-
72
-        $this->assign('joblist', $jobList);
73
-        $this->setTemplate('jobqueue/main.tpl');
74
-    }
75
-
76
-    protected function all()
77
-    {
78
-        $this->setHtmlTitle('All Jobs');
79
-
80
-        $this->prepareMaps();
81
-
82
-        $database = $this->getDatabase();
83
-
84
-        // FIXME: domains
85
-        $searchHelper = JobQueueSearchHelper::get($database, 1);
86
-        $this->setSearchHelper($searchHelper);
87
-        $this->setupLimits();
88
-
89
-        $filterUser = WebRequest::getString('filterUser');
90
-        $filterTask = WebRequest::getString('filterTask');
91
-        $filterStatus = WebRequest::getString('filterStatus');
92
-        $filterRequest = WebRequest::getString('filterRequest');
93
-        $order = WebRequest::getString('order');
94
-
95
-        if ($filterUser !== null) {
96
-            $searchHelper->byUser(User::getByUsername($filterUser, $database)->getId());
97
-        }
98
-
99
-        if ($filterTask !== null) {
100
-            $searchHelper->byTask($filterTask);
101
-        }
102
-
103
-        if ($filterStatus !== null) {
104
-            $searchHelper->byStatus($filterStatus);
105
-        }
106
-
107
-        if ($filterRequest !== null) {
108
-            $searchHelper->byRequest($filterRequest);
109
-        }
31
+	/**
32
+	 * Main function for this page, when no specific actions are called.
33
+	 * @return void
34
+	 */
35
+	protected function main()
36
+	{
37
+		$this->setHtmlTitle('Job Queue Management');
38
+
39
+		$this->prepareMaps();
40
+
41
+		$database = $this->getDatabase();
42
+
43
+		/** @var JobQueue[] $jobList */
44
+		// FIXME: domains
45
+		$jobList = JobQueueSearchHelper::get($database, 1)
46
+			->statusIn([
47
+				JobQueue::STATUS_QUEUED,
48
+				JobQueue::STATUS_READY,
49
+				JobQueue::STATUS_WAITING,
50
+				JobQueue::STATUS_RUNNING,
51
+				JobQueue::STATUS_FAILED,
52
+			])
53
+			->notAcknowledged()
54
+			->fetch();
55
+
56
+		$userIds = array();
57
+		$requestIds = array();
58
+
59
+		foreach ($jobList as $job) {
60
+			$userIds[] = $job->getTriggerUserId();
61
+			$requestIds[] = $job->getRequest();
62
+
63
+			$job->setDatabase($database);
64
+		}
65
+
66
+		$this->assign('canSeeAll', $this->barrierTest('all', User::getCurrent($database)));
67
+
68
+		$this->assign('users', UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username'));
69
+		// FIXME: domains
70
+		$this->assign('requests', RequestSearchHelper::get($database, 1)->inIds($requestIds)->fetchMap('name'));
71
+
72
+		$this->assign('joblist', $jobList);
73
+		$this->setTemplate('jobqueue/main.tpl');
74
+	}
75
+
76
+	protected function all()
77
+	{
78
+		$this->setHtmlTitle('All Jobs');
79
+
80
+		$this->prepareMaps();
81
+
82
+		$database = $this->getDatabase();
83
+
84
+		// FIXME: domains
85
+		$searchHelper = JobQueueSearchHelper::get($database, 1);
86
+		$this->setSearchHelper($searchHelper);
87
+		$this->setupLimits();
88
+
89
+		$filterUser = WebRequest::getString('filterUser');
90
+		$filterTask = WebRequest::getString('filterTask');
91
+		$filterStatus = WebRequest::getString('filterStatus');
92
+		$filterRequest = WebRequest::getString('filterRequest');
93
+		$order = WebRequest::getString('order');
94
+
95
+		if ($filterUser !== null) {
96
+			$searchHelper->byUser(User::getByUsername($filterUser, $database)->getId());
97
+		}
98
+
99
+		if ($filterTask !== null) {
100
+			$searchHelper->byTask($filterTask);
101
+		}
102
+
103
+		if ($filterStatus !== null) {
104
+			$searchHelper->byStatus($filterStatus);
105
+		}
106
+
107
+		if ($filterRequest !== null) {
108
+			$searchHelper->byRequest($filterRequest);
109
+		}
110 110
         
111
-        if ($order === null) {
112
-            $searchHelper->newestFirst();
113
-        }
114
-
115
-        /** @var JobQueue[] $jobList */
116
-        $jobList = $searchHelper->getRecordCount($count)->fetch();
111
+		if ($order === null) {
112
+			$searchHelper->newestFirst();
113
+		}
114
+
115
+		/** @var JobQueue[] $jobList */
116
+		$jobList = $searchHelper->getRecordCount($count)->fetch();
117 117
 
118
-        $this->setupPageData($count, array(
119
-            'filterUser' => $filterUser,
120
-            'filterTask' => $filterTask,
121
-            'filterStatus' => $filterStatus,
122
-            'filterRequest' => $filterRequest,
123
-            'order' => $order,
124
-        ));
118
+		$this->setupPageData($count, array(
119
+			'filterUser' => $filterUser,
120
+			'filterTask' => $filterTask,
121
+			'filterStatus' => $filterStatus,
122
+			'filterRequest' => $filterRequest,
123
+			'order' => $order,
124
+		));
125 125
 
126
-        $userIds = array();
127
-        $requestIds = array();
126
+		$userIds = array();
127
+		$requestIds = array();
128 128
 
129
-        foreach ($jobList as $job) {
130
-            $userIds[] = $job->getTriggerUserId();
131
-            $requestIds[] = $job->getRequest();
129
+		foreach ($jobList as $job) {
130
+			$userIds[] = $job->getTriggerUserId();
131
+			$requestIds[] = $job->getRequest();
132 132
 
133
-            $job->setDatabase($database);
134
-        }
133
+			$job->setDatabase($database);
134
+		}
135 135
 
136
-        $this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
137
-            return UserSearchHelper::get($database)->fetchColumn('username');
138
-        });
136
+		$this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
137
+			return UserSearchHelper::get($database)->fetchColumn('username');
138
+		});
139 139
 
140
-        $this->assign('users', UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username'));
141
-        // FIXME: domains!
142
-        $this->assign('requests', RequestSearchHelper::get($database, 1)->inIds($requestIds)->fetchMap('name'));
140
+		$this->assign('users', UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username'));
141
+		// FIXME: domains!
142
+		$this->assign('requests', RequestSearchHelper::get($database, 1)->inIds($requestIds)->fetchMap('name'));
143 143
 
144
-        $this->assign('joblist', $jobList);
144
+		$this->assign('joblist', $jobList);
145 145
 
146
-        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
146
+		$this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
147 147
 
148
-        $this->setTemplate('jobqueue/all.tpl');
149
-    }
148
+		$this->setTemplate('jobqueue/all.tpl');
149
+	}
150 150
 
151
-    protected function view()
152
-    {
153
-        $jobId = WebRequest::getInt('id');
154
-        $database = $this->getDatabase();
151
+	protected function view()
152
+	{
153
+		$jobId = WebRequest::getInt('id');
154
+		$database = $this->getDatabase();
155 155
 
156
-        if ($jobId === null) {
157
-            throw new ApplicationLogicException('No job specified');
158
-        }
156
+		if ($jobId === null) {
157
+			throw new ApplicationLogicException('No job specified');
158
+		}
159 159
 
160
-        /** @var JobQueue $job */
161
-        $job = JobQueue::getById($jobId, $database);
160
+		/** @var JobQueue $job */
161
+		$job = JobQueue::getById($jobId, $database);
162 162
 
163
-        if ($job === false) {
164
-            throw new ApplicationLogicException('Could not find requested job');
165
-        }
163
+		if ($job === false) {
164
+			throw new ApplicationLogicException('Could not find requested job');
165
+		}
166 166
 
167
-        $this->prepareMaps();
167
+		$this->prepareMaps();
168 168
 
169
-        $this->assign('user', User::getById($job->getTriggerUserId(), $database));
170
-        $this->assign('request', Request::getById($job->getRequest(), $database));
171
-        $this->assign('emailTemplate', EmailTemplate::getById($job->getEmailTemplate(), $database));
172
-        $this->assign('parent', JobQueue::getById($job->getParent(), $database));
169
+		$this->assign('user', User::getById($job->getTriggerUserId(), $database));
170
+		$this->assign('request', Request::getById($job->getRequest(), $database));
171
+		$this->assign('emailTemplate', EmailTemplate::getById($job->getEmailTemplate(), $database));
172
+		$this->assign('parent', JobQueue::getById($job->getParent(), $database));
173 173
 
174
-        /** @var Log[] $logs */
175
-        // FIXME: domains
176
-        $logs = LogSearchHelper::get($database, 1)->byObjectType('JobQueue')
177
-            ->byObjectId($job->getId())->getRecordCount($logCount)->fetch();
178
-        if ($logCount === 0) {
179
-            $this->assign('log', array());
180
-        }
181
-        else {
182
-            list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
174
+		/** @var Log[] $logs */
175
+		// FIXME: domains
176
+		$logs = LogSearchHelper::get($database, 1)->byObjectType('JobQueue')
177
+			->byObjectId($job->getId())->getRecordCount($logCount)->fetch();
178
+		if ($logCount === 0) {
179
+			$this->assign('log', array());
180
+		}
181
+		else {
182
+			list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
183 183
 
184
-            $this->assign("log", $logData);
185
-            $this->assign("users", $users);
186
-        }
184
+			$this->assign("log", $logData);
185
+			$this->assign("users", $users);
186
+		}
187 187
 
188
-        $this->assignCSRFToken();
188
+		$this->assignCSRFToken();
189 189
 
190
-        $this->assign('job', $job);
190
+		$this->assign('job', $job);
191 191
 
192
-        $this->assign('canAcknowledge', $this->barrierTest('acknowledge', User::getCurrent($database)));
193
-        $this->assign('canRequeue', $this->barrierTest('requeue', User::getCurrent($database)));
194
-        $this->assign('canCancel', $this->barrierTest('cancel', User::getCurrent($database)));
192
+		$this->assign('canAcknowledge', $this->barrierTest('acknowledge', User::getCurrent($database)));
193
+		$this->assign('canRequeue', $this->barrierTest('requeue', User::getCurrent($database)));
194
+		$this->assign('canCancel', $this->barrierTest('cancel', User::getCurrent($database)));
195 195
 
196
-        if ($job->getTask() === UserCreationTask::class || $job->getTask() === BotCreationTask::class) {
197
-            if ($job->getEmailTemplate() === null) {
198
-                $params = json_decode($job->getParameters());
196
+		if ($job->getTask() === UserCreationTask::class || $job->getTask() === BotCreationTask::class) {
197
+			if ($job->getEmailTemplate() === null) {
198
+				$params = json_decode($job->getParameters());
199 199
 
200
-                if (isset($params->emailText)) {
201
-                    $this->assign("creationEmailText", $params->emailText);
202
-                }
203
-            }
204
-        }
200
+				if (isset($params->emailText)) {
201
+					$this->assign("creationEmailText", $params->emailText);
202
+				}
203
+			}
204
+		}
205 205
 
206
-        $this->setHtmlTitle('Job #{$job->getId()|escape}');
207
-        $this->setTemplate('jobqueue/view.tpl');
208
-    }
206
+		$this->setHtmlTitle('Job #{$job->getId()|escape}');
207
+		$this->setTemplate('jobqueue/view.tpl');
208
+	}
209 209
 
210
-    protected function acknowledge()
211
-    {
212
-        if (!WebRequest::wasPosted()) {
213
-            throw new ApplicationLogicException('This page does not support GET methods.');
214
-        }
210
+	protected function acknowledge()
211
+	{
212
+		if (!WebRequest::wasPosted()) {
213
+			throw new ApplicationLogicException('This page does not support GET methods.');
214
+		}
215 215
 
216
-        $this->validateCSRFToken();
216
+		$this->validateCSRFToken();
217 217
 
218
-        $jobId = WebRequest::postInt('job');
219
-        $database = $this->getDatabase();
218
+		$jobId = WebRequest::postInt('job');
219
+		$database = $this->getDatabase();
220 220
 
221
-        if ($jobId === null) {
222
-            throw new ApplicationLogicException('No job specified');
223
-        }
221
+		if ($jobId === null) {
222
+			throw new ApplicationLogicException('No job specified');
223
+		}
224 224
 
225
-        /** @var JobQueue $job */
226
-        $job = JobQueue::getById($jobId, $database);
225
+		/** @var JobQueue $job */
226
+		$job = JobQueue::getById($jobId, $database);
227 227
 
228
-        if ($job === false) {
229
-            throw new ApplicationLogicException('Could not find requested job');
230
-        }
228
+		if ($job === false) {
229
+			throw new ApplicationLogicException('Could not find requested job');
230
+		}
231 231
 
232
-        $job->setUpdateVersion(WebRequest::postInt('updateVersion'));
233
-        $job->setAcknowledged(true);
234
-        $job->save();
232
+		$job->setUpdateVersion(WebRequest::postInt('updateVersion'));
233
+		$job->setAcknowledged(true);
234
+		$job->save();
235 235
 
236
-        Logger::backgroundJobAcknowledged($database, $job);
236
+		Logger::backgroundJobAcknowledged($database, $job);
237 237
 
238
-        $this->redirect('jobQueue', 'view', array('id' => $jobId));
239
-    }
240
-
241
-    protected function cancel()
242
-    {
243
-        if (!WebRequest::wasPosted()) {
244
-            throw new ApplicationLogicException('This page does not support GET methods.');
245
-        }
246
-
247
-        $this->validateCSRFToken();
248
-
249
-        $jobId = WebRequest::postInt('job');
250
-        $database = $this->getDatabase();
251
-
252
-        if ($jobId === null) {
253
-            throw new ApplicationLogicException('No job specified');
254
-        }
255
-
256
-        /** @var JobQueue $job */
257
-        $job = JobQueue::getById($jobId, $database);
258
-
259
-        if ($job === false) {
260
-            throw new ApplicationLogicException('Could not find requested job');
261
-        }
262
-
263
-        if ($job->getStatus() !== JobQueue::STATUS_READY
264
-            && $job->getStatus() !== JobQueue::STATUS_QUEUED
265
-            && $job->getStatus() === JobQueue::STATUS_WAITING) {
266
-            throw new ApplicationLogicException('Cannot cancel job not queued for execution');
267
-        }
268
-
269
-        $job->setUpdateVersion(WebRequest::postInt('updateVersion'));
270
-        $job->setStatus(JobQueue::STATUS_CANCELLED);
271
-        $job->setError("Manually cancelled");
272
-        $job->setAcknowledged(null);
273
-        $job->save();
274
-
275
-        Logger::backgroundJobCancelled($this->getDatabase(), $job);
276
-
277
-        $this->redirect('jobQueue', 'view', array('id' => $jobId));
278
-    }
279
-
280
-    protected function requeue()
281
-    {
282
-        if (!WebRequest::wasPosted()) {
283
-            throw new ApplicationLogicException('This page does not support GET methods.');
284
-        }
238
+		$this->redirect('jobQueue', 'view', array('id' => $jobId));
239
+	}
240
+
241
+	protected function cancel()
242
+	{
243
+		if (!WebRequest::wasPosted()) {
244
+			throw new ApplicationLogicException('This page does not support GET methods.');
245
+		}
246
+
247
+		$this->validateCSRFToken();
248
+
249
+		$jobId = WebRequest::postInt('job');
250
+		$database = $this->getDatabase();
251
+
252
+		if ($jobId === null) {
253
+			throw new ApplicationLogicException('No job specified');
254
+		}
255
+
256
+		/** @var JobQueue $job */
257
+		$job = JobQueue::getById($jobId, $database);
258
+
259
+		if ($job === false) {
260
+			throw new ApplicationLogicException('Could not find requested job');
261
+		}
262
+
263
+		if ($job->getStatus() !== JobQueue::STATUS_READY
264
+			&& $job->getStatus() !== JobQueue::STATUS_QUEUED
265
+			&& $job->getStatus() === JobQueue::STATUS_WAITING) {
266
+			throw new ApplicationLogicException('Cannot cancel job not queued for execution');
267
+		}
268
+
269
+		$job->setUpdateVersion(WebRequest::postInt('updateVersion'));
270
+		$job->setStatus(JobQueue::STATUS_CANCELLED);
271
+		$job->setError("Manually cancelled");
272
+		$job->setAcknowledged(null);
273
+		$job->save();
274
+
275
+		Logger::backgroundJobCancelled($this->getDatabase(), $job);
276
+
277
+		$this->redirect('jobQueue', 'view', array('id' => $jobId));
278
+	}
279
+
280
+	protected function requeue()
281
+	{
282
+		if (!WebRequest::wasPosted()) {
283
+			throw new ApplicationLogicException('This page does not support GET methods.');
284
+		}
285 285
 
286
-        $this->validateCSRFToken();
286
+		$this->validateCSRFToken();
287 287
 
288
-        $jobId = WebRequest::postInt('job');
289
-        $database = $this->getDatabase();
290
-
291
-        if ($jobId === null) {
292
-            throw new ApplicationLogicException('No job specified');
293
-        }
294
-
295
-        /** @var JobQueue|false $job */
296
-        $job = JobQueue::getById($jobId, $database);
297
-
298
-        if ($job === false) {
299
-            throw new ApplicationLogicException('Could not find requested job');
300
-        }
301
-
302
-        $job->setStatus(JobQueue::STATUS_QUEUED);
303
-        $job->setUpdateVersion(WebRequest::postInt('updateVersion'));
304
-        $job->setAcknowledged(null);
305
-        $job->setError(null);
306
-        $job->save();
307
-
308
-        /** @var Request $request */
309
-        $request = Request::getById($job->getRequest(), $database);
310
-        $request->setStatus(RequestStatus::JOBQUEUE);
311
-        $request->save();
312
-
313
-        Logger::enqueuedJobQueue($database, $request);
314
-        Logger::backgroundJobRequeued($database, $job);
288
+		$jobId = WebRequest::postInt('job');
289
+		$database = $this->getDatabase();
290
+
291
+		if ($jobId === null) {
292
+			throw new ApplicationLogicException('No job specified');
293
+		}
294
+
295
+		/** @var JobQueue|false $job */
296
+		$job = JobQueue::getById($jobId, $database);
297
+
298
+		if ($job === false) {
299
+			throw new ApplicationLogicException('Could not find requested job');
300
+		}
301
+
302
+		$job->setStatus(JobQueue::STATUS_QUEUED);
303
+		$job->setUpdateVersion(WebRequest::postInt('updateVersion'));
304
+		$job->setAcknowledged(null);
305
+		$job->setError(null);
306
+		$job->save();
307
+
308
+		/** @var Request $request */
309
+		$request = Request::getById($job->getRequest(), $database);
310
+		$request->setStatus(RequestStatus::JOBQUEUE);
311
+		$request->save();
312
+
313
+		Logger::enqueuedJobQueue($database, $request);
314
+		Logger::backgroundJobRequeued($database, $job);
315 315
 
316
-        $this->redirect('jobQueue', 'view', array('id' => $jobId));
317
-    }
318
-
319
-    protected function prepareMaps()
320
-    {
321
-        $taskNameMap = JobQueue::getTaskDescriptions();
322
-
323
-        $statusDecriptionMap = array(
324
-            JobQueue::STATUS_CANCELLED => 'The job was cancelled',
325
-            JobQueue::STATUS_COMPLETE  => 'The job completed successfully',
326
-            JobQueue::STATUS_FAILED    => 'The job encountered an error',
327
-            JobQueue::STATUS_QUEUED    => 'The job is in the queue',
328
-            JobQueue::STATUS_READY     => 'The job is ready to be picked up by the next job runner execution',
329
-            JobQueue::STATUS_RUNNING   => 'The job is being run right now by the job runner',
330
-            JobQueue::STATUS_WAITING   => 'The job has been picked up by a job runner',
331
-            JobQueue::STATUS_HELD      => 'The job has manually held from processing',
332
-        );
333
-        $this->assign('taskNameMap', $taskNameMap);
334
-        $this->assign('statusDescriptionMap', $statusDecriptionMap);
335
-    }
316
+		$this->redirect('jobQueue', 'view', array('id' => $jobId));
317
+	}
318
+
319
+	protected function prepareMaps()
320
+	{
321
+		$taskNameMap = JobQueue::getTaskDescriptions();
322
+
323
+		$statusDecriptionMap = array(
324
+			JobQueue::STATUS_CANCELLED => 'The job was cancelled',
325
+			JobQueue::STATUS_COMPLETE  => 'The job completed successfully',
326
+			JobQueue::STATUS_FAILED    => 'The job encountered an error',
327
+			JobQueue::STATUS_QUEUED    => 'The job is in the queue',
328
+			JobQueue::STATUS_READY     => 'The job is ready to be picked up by the next job runner execution',
329
+			JobQueue::STATUS_RUNNING   => 'The job is being run right now by the job runner',
330
+			JobQueue::STATUS_WAITING   => 'The job has been picked up by a job runner',
331
+			JobQueue::STATUS_HELD      => 'The job has manually held from processing',
332
+		);
333
+		$this->assign('taskNameMap', $taskNameMap);
334
+		$this->assign('statusDescriptionMap', $statusDecriptionMap);
335
+	}
336 336
 }
Please login to merge, or discard this patch.
includes/Pages/Request/PageRequestSubmitted.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -12,17 +12,17 @@
 block discarded – undo
12 12
 
13 13
 class PageRequestSubmitted extends PublicInterfacePageBase
14 14
 {
15
-    /**
16
-     * Main function for this page, when no specific actions are called.
17
-     * @return void
18
-     */
19
-    protected function main()
20
-    {
21
-        // clear any requests for client hints. Should have been done already prior to
22
-        // email confirmation, but this catches the case where email confirmation is
23
-        // disabled.
24
-        $this->headerQueue[] = "Accept-CH:";
15
+	/**
16
+	 * Main function for this page, when no specific actions are called.
17
+	 * @return void
18
+	 */
19
+	protected function main()
20
+	{
21
+		// clear any requests for client hints. Should have been done already prior to
22
+		// email confirmation, but this catches the case where email confirmation is
23
+		// disabled.
24
+		$this->headerQueue[] = "Accept-CH:";
25 25
 
26
-        $this->setTemplate('request/email-confirmed.tpl');
27
-    }
26
+		$this->setTemplate('request/email-confirmed.tpl');
27
+	}
28 28
 }
29 29
\ No newline at end of file
Please login to merge, or discard this patch.