Test Failed
Push — dependabot/composer/newinterna... ( fef629 )
by
unknown
16:20 queued 10:15
created
includes/Pages/RequestAction/PageCreateRequest.php 2 patches
Indentation   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -33,153 +33,153 @@
 block discarded – undo
33 33
  */
34 34
 class PageCreateRequest extends RequestActionBase
35 35
 {
36
-    /**
37
-     * Main function for this page, when no specific actions are called.
38
-     * @return void
39
-     * @throws AccessDeniedException
40
-     * @throws ApplicationLogicException
41
-     */
42
-    protected function main()
43
-    {
44
-        $this->checkPosted();
45
-
46
-        $database = $this->getDatabase();
47
-
48
-        $request = $this->getRequest($database);
49
-        $template = $this->getTemplate($database);
50
-        $creationMode = $this->getCreationMode();
51
-        $user = User::getCurrent($database);
52
-
53
-        $secMgr = $this->getSecurityManager();
54
-        if ($secMgr->allows('RequestCreation', User::CREATION_BOT, $user) !== SecurityManager::ALLOWED
55
-            && $creationMode === 'bot'
56
-        ) {
57
-            throw new AccessDeniedException($secMgr);
58
-        }
59
-        elseif ($secMgr->allows('RequestCreation', User::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
60
-            && $creationMode === 'oauth'
61
-        ) {
62
-            throw new AccessDeniedException($secMgr);
63
-        }
64
-
65
-        if ($request->getEmailSent()) {
66
-            throw new ApplicationLogicException('This requester has already had an email sent to them. Please fall back to manual creation');
67
-        }
68
-
69
-        $request->setStatus(RequestStatus::JOBQUEUE);
70
-        $request->setReserved(null);
71
-        $request->save();
72
-
73
-        Logger::enqueuedJobQueue($database, $request);
74
-
75
-        $creationTaskId = $this->enqueueCreationTask($creationMode, $request, $template, $user, $database);
76
-
77
-        if ($user->getWelcomeTemplate() !== null && !WebRequest::postBoolean('skipAutoWelcome')) {
78
-            $this->enqueueWelcomeTask($request, $creationTaskId, $user, $database);
79
-        }
80
-
81
-        $this->getNotificationHelper()->requestCloseQueued($request, $template->getName());
82
-
83
-        SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
84
-
85
-        $this->redirect();
86
-    }
87
-
88
-    protected function getCreationMode()
89
-    {
90
-        $creationMode = WebRequest::postString('mode');
91
-        if ($creationMode !== 'oauth' && $creationMode !== 'bot') {
92
-            throw new ApplicationLogicException('Unknown creation mode');
93
-        }
94
-
95
-        return $creationMode;
96
-    }
97
-
98
-    /**
99
-     * @param PdoDatabase $database
100
-     *
101
-     * @return EmailTemplate
102
-     * @throws ApplicationLogicException
103
-     */
104
-    protected function getTemplate(PdoDatabase $database)
105
-    {
106
-        $templateId = WebRequest::postInt('template');
107
-        if ($templateId === null) {
108
-            throw new ApplicationLogicException('No template specified');
109
-        }
110
-
111
-        /** @var EmailTemplate $template */
112
-        $template = EmailTemplate::getById($templateId, $database);
113
-        if ($template === false || !$template->getActive()) {
114
-            throw new ApplicationLogicException('Invalid or inactive template specified');
115
-        }
116
-
117
-        if ($template->getDefaultAction() !== EmailTemplate::CREATED) {
118
-            throw new ApplicationLogicException('Specified template is not a creation template!');
119
-        }
120
-
121
-        return $template;
122
-    }
123
-
124
-    /**
125
-     * @param PdoDatabase $database
126
-     *
127
-     * @return Request
128
-     * @throws ApplicationLogicException
129
-     */
130
-    protected function getRequest(PdoDatabase $database)
131
-    {
132
-        $request = parent::getRequest($database);
133
-
134
-        if ($request->getStatus() == RequestStatus::CLOSED) {
135
-            throw new ApplicationLogicException('Request is already closed');
136
-        }
137
-
138
-        return $request;
139
-    }
140
-
141
-    /**
142
-     * @param               $creationMode
143
-     * @param Request       $request
144
-     * @param EmailTemplate $template
145
-     * @param User          $user
146
-     *
147
-     * @param PdoDatabase   $database
148
-     *
149
-     * @return int
150
-     * @throws ApplicationLogicException
151
-     */
152
-    protected function enqueueCreationTask(
153
-        $creationMode,
154
-        Request $request,
155
-        EmailTemplate $template,
156
-        User $user,
157
-        PdoDatabase $database
158
-    ) {
159
-        $creationTaskClass = null;
160
-
161
-        if ($creationMode == "oauth") {
162
-            $creationTaskClass = UserCreationTask::class;
163
-        }
164
-
165
-        if ($creationMode == "bot") {
166
-            $creationTaskClass = BotCreationTask::class;
167
-        }
168
-
169
-        if ($creationTaskClass === null) {
170
-            throw new ApplicationLogicException('Cannot determine creation mode');
171
-        }
172
-
173
-        $creationTask = new JobQueue();
174
-        $creationTask->setTask($creationTaskClass);
175
-        $creationTask->setRequest($request->getId());
176
-        $creationTask->setEmailTemplate($template->getId());
177
-        $creationTask->setTriggerUserId($user->getId());
178
-        $creationTask->setDatabase($database);
179
-        $creationTask->save();
180
-
181
-        $creationTaskId = $creationTask->getId();
182
-
183
-        return $creationTaskId;
184
-    }
36
+	/**
37
+	 * Main function for this page, when no specific actions are called.
38
+	 * @return void
39
+	 * @throws AccessDeniedException
40
+	 * @throws ApplicationLogicException
41
+	 */
42
+	protected function main()
43
+	{
44
+		$this->checkPosted();
45
+
46
+		$database = $this->getDatabase();
47
+
48
+		$request = $this->getRequest($database);
49
+		$template = $this->getTemplate($database);
50
+		$creationMode = $this->getCreationMode();
51
+		$user = User::getCurrent($database);
52
+
53
+		$secMgr = $this->getSecurityManager();
54
+		if ($secMgr->allows('RequestCreation', User::CREATION_BOT, $user) !== SecurityManager::ALLOWED
55
+			&& $creationMode === 'bot'
56
+		) {
57
+			throw new AccessDeniedException($secMgr);
58
+		}
59
+		elseif ($secMgr->allows('RequestCreation', User::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
60
+			&& $creationMode === 'oauth'
61
+		) {
62
+			throw new AccessDeniedException($secMgr);
63
+		}
64
+
65
+		if ($request->getEmailSent()) {
66
+			throw new ApplicationLogicException('This requester has already had an email sent to them. Please fall back to manual creation');
67
+		}
68
+
69
+		$request->setStatus(RequestStatus::JOBQUEUE);
70
+		$request->setReserved(null);
71
+		$request->save();
72
+
73
+		Logger::enqueuedJobQueue($database, $request);
74
+
75
+		$creationTaskId = $this->enqueueCreationTask($creationMode, $request, $template, $user, $database);
76
+
77
+		if ($user->getWelcomeTemplate() !== null && !WebRequest::postBoolean('skipAutoWelcome')) {
78
+			$this->enqueueWelcomeTask($request, $creationTaskId, $user, $database);
79
+		}
80
+
81
+		$this->getNotificationHelper()->requestCloseQueued($request, $template->getName());
82
+
83
+		SessionAlert::success("Request {$request->getId()} has been queued for autocreation");
84
+
85
+		$this->redirect();
86
+	}
87
+
88
+	protected function getCreationMode()
89
+	{
90
+		$creationMode = WebRequest::postString('mode');
91
+		if ($creationMode !== 'oauth' && $creationMode !== 'bot') {
92
+			throw new ApplicationLogicException('Unknown creation mode');
93
+		}
94
+
95
+		return $creationMode;
96
+	}
97
+
98
+	/**
99
+	 * @param PdoDatabase $database
100
+	 *
101
+	 * @return EmailTemplate
102
+	 * @throws ApplicationLogicException
103
+	 */
104
+	protected function getTemplate(PdoDatabase $database)
105
+	{
106
+		$templateId = WebRequest::postInt('template');
107
+		if ($templateId === null) {
108
+			throw new ApplicationLogicException('No template specified');
109
+		}
110
+
111
+		/** @var EmailTemplate $template */
112
+		$template = EmailTemplate::getById($templateId, $database);
113
+		if ($template === false || !$template->getActive()) {
114
+			throw new ApplicationLogicException('Invalid or inactive template specified');
115
+		}
116
+
117
+		if ($template->getDefaultAction() !== EmailTemplate::CREATED) {
118
+			throw new ApplicationLogicException('Specified template is not a creation template!');
119
+		}
120
+
121
+		return $template;
122
+	}
123
+
124
+	/**
125
+	 * @param PdoDatabase $database
126
+	 *
127
+	 * @return Request
128
+	 * @throws ApplicationLogicException
129
+	 */
130
+	protected function getRequest(PdoDatabase $database)
131
+	{
132
+		$request = parent::getRequest($database);
133
+
134
+		if ($request->getStatus() == RequestStatus::CLOSED) {
135
+			throw new ApplicationLogicException('Request is already closed');
136
+		}
137
+
138
+		return $request;
139
+	}
140
+
141
+	/**
142
+	 * @param               $creationMode
143
+	 * @param Request       $request
144
+	 * @param EmailTemplate $template
145
+	 * @param User          $user
146
+	 *
147
+	 * @param PdoDatabase   $database
148
+	 *
149
+	 * @return int
150
+	 * @throws ApplicationLogicException
151
+	 */
152
+	protected function enqueueCreationTask(
153
+		$creationMode,
154
+		Request $request,
155
+		EmailTemplate $template,
156
+		User $user,
157
+		PdoDatabase $database
158
+	) {
159
+		$creationTaskClass = null;
160
+
161
+		if ($creationMode == "oauth") {
162
+			$creationTaskClass = UserCreationTask::class;
163
+		}
164
+
165
+		if ($creationMode == "bot") {
166
+			$creationTaskClass = BotCreationTask::class;
167
+		}
168
+
169
+		if ($creationTaskClass === null) {
170
+			throw new ApplicationLogicException('Cannot determine creation mode');
171
+		}
172
+
173
+		$creationTask = new JobQueue();
174
+		$creationTask->setTask($creationTaskClass);
175
+		$creationTask->setRequest($request->getId());
176
+		$creationTask->setEmailTemplate($template->getId());
177
+		$creationTask->setTriggerUserId($user->getId());
178
+		$creationTask->setDatabase($database);
179
+		$creationTask->save();
180
+
181
+		$creationTaskId = $creationTask->getId();
182
+
183
+		return $creationTaskId;
184
+	}
185 185
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -55,8 +55,7 @@
 block discarded – undo
55 55
             && $creationMode === 'bot'
56 56
         ) {
57 57
             throw new AccessDeniedException($secMgr);
58
-        }
59
-        elseif ($secMgr->allows('RequestCreation', User::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
58
+        } elseif ($secMgr->allows('RequestCreation', User::CREATION_OAUTH, $user) !== SecurityManager::ALLOWED
60 59
             && $creationMode === 'oauth'
61 60
         ) {
62 61
             throw new AccessDeniedException($secMgr);
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageDeferRequest.php 1 patch
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -20,71 +20,71 @@
 block discarded – undo
20 20
 
21 21
 class PageDeferRequest extends RequestActionBase
22 22
 {
23
-    /**
24
-     * Main function for this page, when no specific actions are called.
25
-     * @throws ApplicationLogicException
26
-     */
27
-    protected function main()
28
-    {
29
-        $this->checkPosted();
30
-        $database = $this->getDatabase();
31
-        $request = $this->getRequest($database);
32
-        $currentUser = User::getCurrent($database);
33
-
34
-        $target = WebRequest::postString('target');
35
-        $requestStates = $this->getSiteConfiguration()->getRequestStates();
36
-
37
-        if (!array_key_exists($target, $requestStates)) {
38
-            throw new ApplicationLogicException('Defer target not valid');
39
-        }
40
-
41
-        if ($request->getStatus() == $target) {
42
-            SessionAlert::warning('This request is already in the specified queue.');
43
-            $this->redirect('viewRequest', null, array('id' => $request->getId()));
44
-
45
-            return;
46
-        }
47
-
48
-        $closureDate = $request->getClosureDate();
49
-        $date = new DateTime();
50
-        $date->modify("-7 days");
51
-        $oneweek = $date->format("Y-m-d H:i:s");
52
-
53
-
54
-        if ($request->getStatus() == "Closed" && $closureDate < $oneweek) {
55
-            if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
56
-                throw new ApplicationLogicException(
57
-                    "You are not allowed to re-open a request that has been closed for over a week.");
58
-            }
59
-        }
60
-
61
-        if ($request->getStatus() === RequestStatus::JOBQUEUE) {
62
-            /** @var JobQueue[] $pendingJobs */
63
-            $pendingJobs = JobQueueSearchHelper::get($database)->byRequest($request->getId())->statusIn([
64
-                JobQueue::STATUS_READY,
65
-                JobQueue::STATUS_WAITING,
66
-            ])->fetch();
67
-
68
-            foreach ($pendingJobs as $job) {
69
-                $job->setStatus(JobQueue::STATUS_CANCELLED);
70
-                $job->setError('Cancelled by request deferral');
71
-                $job->save();
72
-            }
73
-        }
74
-
75
-        $request->setReserved(null);
76
-        $request->setStatus($target);
77
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
78
-        $request->save();
79
-
80
-        $deto = $requestStates[$target]['deferto'];
81
-        $detolog = $requestStates[$target]['defertolog'];
82
-
83
-        Logger::deferRequest($database, $request, $detolog);
84
-
85
-        $this->getNotificationHelper()->requestDeferred($request);
86
-        SessionAlert::success("Request {$request->getId()} deferred to {$deto}");
87
-
88
-        $this->redirect();
89
-    }
23
+	/**
24
+	 * Main function for this page, when no specific actions are called.
25
+	 * @throws ApplicationLogicException
26
+	 */
27
+	protected function main()
28
+	{
29
+		$this->checkPosted();
30
+		$database = $this->getDatabase();
31
+		$request = $this->getRequest($database);
32
+		$currentUser = User::getCurrent($database);
33
+
34
+		$target = WebRequest::postString('target');
35
+		$requestStates = $this->getSiteConfiguration()->getRequestStates();
36
+
37
+		if (!array_key_exists($target, $requestStates)) {
38
+			throw new ApplicationLogicException('Defer target not valid');
39
+		}
40
+
41
+		if ($request->getStatus() == $target) {
42
+			SessionAlert::warning('This request is already in the specified queue.');
43
+			$this->redirect('viewRequest', null, array('id' => $request->getId()));
44
+
45
+			return;
46
+		}
47
+
48
+		$closureDate = $request->getClosureDate();
49
+		$date = new DateTime();
50
+		$date->modify("-7 days");
51
+		$oneweek = $date->format("Y-m-d H:i:s");
52
+
53
+
54
+		if ($request->getStatus() == "Closed" && $closureDate < $oneweek) {
55
+			if (!$this->barrierTest('reopenOldRequest', $currentUser, 'RequestData')) {
56
+				throw new ApplicationLogicException(
57
+					"You are not allowed to re-open a request that has been closed for over a week.");
58
+			}
59
+		}
60
+
61
+		if ($request->getStatus() === RequestStatus::JOBQUEUE) {
62
+			/** @var JobQueue[] $pendingJobs */
63
+			$pendingJobs = JobQueueSearchHelper::get($database)->byRequest($request->getId())->statusIn([
64
+				JobQueue::STATUS_READY,
65
+				JobQueue::STATUS_WAITING,
66
+			])->fetch();
67
+
68
+			foreach ($pendingJobs as $job) {
69
+				$job->setStatus(JobQueue::STATUS_CANCELLED);
70
+				$job->setError('Cancelled by request deferral');
71
+				$job->save();
72
+			}
73
+		}
74
+
75
+		$request->setReserved(null);
76
+		$request->setStatus($target);
77
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
78
+		$request->save();
79
+
80
+		$deto = $requestStates[$target]['deferto'];
81
+		$detolog = $requestStates[$target]['defertolog'];
82
+
83
+		Logger::deferRequest($database, $request, $detolog);
84
+
85
+		$this->getNotificationHelper()->requestDeferred($request);
86
+		SessionAlert::success("Request {$request->getId()} deferred to {$deto}");
87
+
88
+		$this->redirect();
89
+	}
90 90
 }
Please login to merge, or discard this patch.
includes/Pages/PageViewRequest.php 3 patches
Indentation   +284 added lines, -284 removed lines patch added patch discarded remove patch
@@ -25,288 +25,288 @@
 block discarded – undo
25 25
 
26 26
 class PageViewRequest extends InternalPageBase
27 27
 {
28
-    use RequestData;
29
-    const STATUS_SYMBOL_OPEN = '&#x2610';
30
-    const STATUS_SYMBOL_ACCEPTED = '&#x2611';
31
-    const STATUS_SYMBOL_REJECTED = '&#x2612';
32
-
33
-    /**
34
-     * Main function for this page, when no specific actions are called.
35
-     * @throws ApplicationLogicException
36
-     */
37
-    protected function main()
38
-    {
39
-        // set up csrf protection
40
-        $this->assignCSRFToken();
41
-
42
-        // get some useful objects
43
-        $database = $this->getDatabase();
44
-        $request = $this->getRequest($database, WebRequest::getInt('id'));
45
-        $config = $this->getSiteConfiguration();
46
-        $currentUser = User::getCurrent($database);
47
-
48
-        // Test we should be able to look at this request
49
-        if ($config->getEmailConfirmationEnabled()) {
50
-            if ($request->getEmailConfirm() !== 'Confirmed') {
51
-                // Not allowed to look at this yet.
52
-                throw new ApplicationLogicException('The email address has not yet been confirmed for this request.');
53
-            }
54
-        }
55
-
56
-        $this->setupBasicData($request, $config);
57
-
58
-        $this->setupUsernameData($request);
59
-
60
-        $this->setupTitle($request);
61
-
62
-        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
63
-        $this->setupGeneralData($database);
64
-
65
-        $this->assign('requestDataCleared', false);
66
-        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
67
-            $this->assign('requestDataCleared', true);
68
-        }
69
-
70
-        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
71
-
72
-        $this->setupCreationTypes($currentUser);
73
-
74
-        $this->setupLogData($request, $database);
75
-
76
-        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
77
-
78
-        $this->assign('showRevealLink', false);
79
-        if ($request->getReserved() === $currentUser->getId() ||
80
-            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
81
-        ) {
82
-            $this->assign('showRevealLink', true);
83
-            $this->assign('revealHash', $request->getRevealHash());
84
-        }
85
-
86
-        if ($allowedPrivateData) {
87
-            $this->setTemplate('view-request/main-with-data.tpl');
88
-            $this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
89
-
90
-            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
91
-            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
92
-
93
-            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
94
-                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
95
-                $this->setupCheckUserData($request);
96
-            }
97
-        }
98
-        else {
99
-            $this->setTemplate('view-request/main.tpl');
100
-        }
101
-    }
102
-
103
-    /**
104
-     * @param Request $request
105
-     */
106
-    protected function setupTitle(Request $request)
107
-    {
108
-        $statusSymbol = self::STATUS_SYMBOL_OPEN;
109
-        if ($request->getStatus() === 'Closed') {
110
-            if ($request->getWasCreated()) {
111
-                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
112
-            }
113
-            else {
114
-                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
115
-            }
116
-        }
117
-
118
-        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
119
-    }
120
-
121
-    /**
122
-     * Sets up data unrelated to the request, such as the email template information
123
-     *
124
-     * @param PdoDatabase $database
125
-     */
126
-    protected function setupGeneralData(PdoDatabase $database)
127
-    {
128
-        $config = $this->getSiteConfiguration();
129
-
130
-        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
131
-
132
-        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
133
-
134
-        $this->assign('requestStates', $config->getRequestStates());
135
-
136
-        /** @var EmailTemplate $createdTemplate */
137
-        $createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
138
-
139
-        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
140
-        $this->assign('createdId', $createdTemplate->getId());
141
-        $this->assign('createdName', $createdTemplate->getName());
142
-
143
-        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
144
-        $this->assign("createReasons", $createReasons);
145
-        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
146
-        $this->assign("declineReasons", $declineReasons);
147
-
148
-        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
149
-        $this->assign("allCreateReasons", $allCreateReasons);
150
-        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
151
-        $this->assign("allDeclineReasons", $allDeclineReasons);
152
-        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
153
-        $this->assign("allOtherReasons", $allOtherReasons);
154
-    }
155
-
156
-    private function setupLogData(Request $request, PdoDatabase $database)
157
-    {
158
-        $currentUser = User::getCurrent($database);
159
-
160
-        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
161
-        $requestLogs = array();
162
-
163
-        if (trim($request->getComment()) !== "") {
164
-            $requestLogs[] = array(
165
-                'type'     => 'comment',
166
-                'security' => 'user',
167
-                'userid'   => null,
168
-                'user'     => $request->getName(),
169
-                'entry'    => null,
170
-                'time'     => $request->getDate(),
171
-                'canedit'  => false,
172
-                'id'       => $request->getId(),
173
-                'comment'  => $request->getComment(),
174
-            );
175
-        }
176
-
177
-        /** @var User[] $nameCache */
178
-        $nameCache = array();
179
-
180
-        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
181
-
182
-        /** @var Log|Comment $entry */
183
-        foreach ($logs as $entry) {
184
-            // both log and comment have a 'user' field
185
-            if (!array_key_exists($entry->getUser(), $nameCache)) {
186
-                $entryUser = User::getById($entry->getUser(), $database);
187
-                $nameCache[$entry->getUser()] = $entryUser;
188
-            }
189
-
190
-            if ($entry instanceof Comment) {
191
-                $requestLogs[] = array(
192
-                    'type'     => 'comment',
193
-                    'security' => $entry->getVisibility(),
194
-                    'user'     => $nameCache[$entry->getUser()]->getUsername(),
195
-                    'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
196
-                    'entry'    => null,
197
-                    'time'     => $entry->getTime(),
198
-                    'canedit'  => ($editableComments || $entry->getUser() == $currentUser->getId()),
199
-                    'id'       => $entry->getId(),
200
-                    'comment'  => $entry->getComment(),
201
-                );
202
-            }
203
-
204
-            if ($entry instanceof Log) {
205
-                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
206
-                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
207
-
208
-                $entryComment = $entry->getComment();
209
-
210
-                if($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest'){
211
-                    $data = unserialize($entry->getComment());
212
-                    /** @var JobQueue $job */
213
-                    $job = JobQueue::getById($data['job'], $database);
214
-                    $requestLogs[] = array(
215
-                        'type'     => 'joblog',
216
-                        'security' => 'user',
217
-                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
218
-                        'user'     => $entryUser->getUsername(),
219
-                        'entry'    => LogHelper::getLogDescription($entry),
220
-                        'time'     => $entry->getTimestamp(),
221
-                        'canedit'  => false,
222
-                        'id'       => $entry->getId(),
223
-                        'jobId'    => $job->getId(),
224
-                        'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
225
-                    );
226
-                } else {
227
-                    $requestLogs[] = array(
228
-                        'type'     => 'log',
229
-                        'security' => 'user',
230
-                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
231
-                        'user'     => $entryUser->getUsername(),
232
-                        'entry'    => LogHelper::getLogDescription($entry),
233
-                        'time'     => $entry->getTimestamp(),
234
-                        'canedit'  => false,
235
-                        'id'       => $entry->getId(),
236
-                        'comment'  => $entryComment,
237
-                    );
238
-                }
239
-            }
240
-        }
241
-
242
-        $this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
243
-
244
-        $this->assign("requestLogs", $requestLogs);
245
-    }
246
-
247
-    /**
248
-     * @param Request $request
249
-     */
250
-    protected function setupUsernameData(Request $request)
251
-    {
252
-        $blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
253
-
254
-        $this->assign('requestIsBlacklisted', $blacklistData !== false);
255
-        $this->assign('requestBlacklist', $blacklistData);
256
-
257
-        try {
258
-            $spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
259
-        }
260
-        catch (Exception $ex) {
261
-            $spoofs = $ex->getMessage();
262
-        }
263
-
264
-        $this->assign("spoofs", $spoofs);
265
-    }
266
-
267
-    private function setupCreationTypes(User $user)
268
-    {
269
-        $this->assign('allowWelcomeSkip', false);
270
-        $this->assign('forceWelcomeSkip', false);
271
-
272
-        $oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
273
-
274
-        if ($user->getWelcomeTemplate() != 0) {
275
-            $this->assign('allowWelcomeSkip', true);
276
-
277
-            if (!$oauth->canWelcome()) {
278
-                $this->assign('forceWelcomeSkip', true);
279
-            }
280
-        }
281
-
282
-        // test credentials
283
-        $canManualCreate = $this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation');
284
-        $canOauthCreate = $this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation');
285
-        $canBotCreate = $this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation');
286
-
287
-        $this->assign('canManualCreate', $canManualCreate);
288
-        $this->assign('canOauthCreate', $canOauthCreate);
289
-        $this->assign('canBotCreate', $canBotCreate);
290
-
291
-        // show/hide the type radio buttons
292
-        $creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
293
-
294
-        if (!$this->barrierTest($user->getCreationMode(), $user, 'RequestCreation')) {
295
-            // user is not allowed to use their default. Force a choice.
296
-            $creationHasChoice = true;
297
-        }
298
-
299
-        $this->assign('creationHasChoice', $creationHasChoice);
300
-
301
-        // determine problems in creation types
302
-        $this->assign('botProblem', false);
303
-        if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
304
-            $this->assign('botProblem', true);
305
-        }
306
-
307
-        $this->assign('oauthProblem', false);
308
-        if ($canOauthCreate && !$oauth->canCreateAccount()) {
309
-            $this->assign('oauthProblem', true);
310
-        }
311
-    }
28
+	use RequestData;
29
+	const STATUS_SYMBOL_OPEN = '&#x2610';
30
+	const STATUS_SYMBOL_ACCEPTED = '&#x2611';
31
+	const STATUS_SYMBOL_REJECTED = '&#x2612';
32
+
33
+	/**
34
+	 * Main function for this page, when no specific actions are called.
35
+	 * @throws ApplicationLogicException
36
+	 */
37
+	protected function main()
38
+	{
39
+		// set up csrf protection
40
+		$this->assignCSRFToken();
41
+
42
+		// get some useful objects
43
+		$database = $this->getDatabase();
44
+		$request = $this->getRequest($database, WebRequest::getInt('id'));
45
+		$config = $this->getSiteConfiguration();
46
+		$currentUser = User::getCurrent($database);
47
+
48
+		// Test we should be able to look at this request
49
+		if ($config->getEmailConfirmationEnabled()) {
50
+			if ($request->getEmailConfirm() !== 'Confirmed') {
51
+				// Not allowed to look at this yet.
52
+				throw new ApplicationLogicException('The email address has not yet been confirmed for this request.');
53
+			}
54
+		}
55
+
56
+		$this->setupBasicData($request, $config);
57
+
58
+		$this->setupUsernameData($request);
59
+
60
+		$this->setupTitle($request);
61
+
62
+		$this->setupReservationDetails($request->getReserved(), $database, $currentUser);
63
+		$this->setupGeneralData($database);
64
+
65
+		$this->assign('requestDataCleared', false);
66
+		if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
67
+			$this->assign('requestDataCleared', true);
68
+		}
69
+
70
+		$allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
71
+
72
+		$this->setupCreationTypes($currentUser);
73
+
74
+		$this->setupLogData($request, $database);
75
+
76
+		$this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
77
+
78
+		$this->assign('showRevealLink', false);
79
+		if ($request->getReserved() === $currentUser->getId() ||
80
+			$this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
81
+		) {
82
+			$this->assign('showRevealLink', true);
83
+			$this->assign('revealHash', $request->getRevealHash());
84
+		}
85
+
86
+		if ($allowedPrivateData) {
87
+			$this->setTemplate('view-request/main-with-data.tpl');
88
+			$this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
89
+
90
+			$this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
91
+			$this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
92
+
93
+			if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
94
+				$this->setTemplate('view-request/main-with-checkuser-data.tpl');
95
+				$this->setupCheckUserData($request);
96
+			}
97
+		}
98
+		else {
99
+			$this->setTemplate('view-request/main.tpl');
100
+		}
101
+	}
102
+
103
+	/**
104
+	 * @param Request $request
105
+	 */
106
+	protected function setupTitle(Request $request)
107
+	{
108
+		$statusSymbol = self::STATUS_SYMBOL_OPEN;
109
+		if ($request->getStatus() === 'Closed') {
110
+			if ($request->getWasCreated()) {
111
+				$statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
112
+			}
113
+			else {
114
+				$statusSymbol = self::STATUS_SYMBOL_REJECTED;
115
+			}
116
+		}
117
+
118
+		$this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
119
+	}
120
+
121
+	/**
122
+	 * Sets up data unrelated to the request, such as the email template information
123
+	 *
124
+	 * @param PdoDatabase $database
125
+	 */
126
+	protected function setupGeneralData(PdoDatabase $database)
127
+	{
128
+		$config = $this->getSiteConfiguration();
129
+
130
+		$this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
131
+
132
+		$this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
133
+
134
+		$this->assign('requestStates', $config->getRequestStates());
135
+
136
+		/** @var EmailTemplate $createdTemplate */
137
+		$createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
138
+
139
+		$this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
140
+		$this->assign('createdId', $createdTemplate->getId());
141
+		$this->assign('createdName', $createdTemplate->getName());
142
+
143
+		$createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
144
+		$this->assign("createReasons", $createReasons);
145
+		$declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
146
+		$this->assign("declineReasons", $declineReasons);
147
+
148
+		$allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
149
+		$this->assign("allCreateReasons", $allCreateReasons);
150
+		$allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
151
+		$this->assign("allDeclineReasons", $allDeclineReasons);
152
+		$allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
153
+		$this->assign("allOtherReasons", $allOtherReasons);
154
+	}
155
+
156
+	private function setupLogData(Request $request, PdoDatabase $database)
157
+	{
158
+		$currentUser = User::getCurrent($database);
159
+
160
+		$logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
161
+		$requestLogs = array();
162
+
163
+		if (trim($request->getComment()) !== "") {
164
+			$requestLogs[] = array(
165
+				'type'     => 'comment',
166
+				'security' => 'user',
167
+				'userid'   => null,
168
+				'user'     => $request->getName(),
169
+				'entry'    => null,
170
+				'time'     => $request->getDate(),
171
+				'canedit'  => false,
172
+				'id'       => $request->getId(),
173
+				'comment'  => $request->getComment(),
174
+			);
175
+		}
176
+
177
+		/** @var User[] $nameCache */
178
+		$nameCache = array();
179
+
180
+		$editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
181
+
182
+		/** @var Log|Comment $entry */
183
+		foreach ($logs as $entry) {
184
+			// both log and comment have a 'user' field
185
+			if (!array_key_exists($entry->getUser(), $nameCache)) {
186
+				$entryUser = User::getById($entry->getUser(), $database);
187
+				$nameCache[$entry->getUser()] = $entryUser;
188
+			}
189
+
190
+			if ($entry instanceof Comment) {
191
+				$requestLogs[] = array(
192
+					'type'     => 'comment',
193
+					'security' => $entry->getVisibility(),
194
+					'user'     => $nameCache[$entry->getUser()]->getUsername(),
195
+					'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
196
+					'entry'    => null,
197
+					'time'     => $entry->getTime(),
198
+					'canedit'  => ($editableComments || $entry->getUser() == $currentUser->getId()),
199
+					'id'       => $entry->getId(),
200
+					'comment'  => $entry->getComment(),
201
+				);
202
+			}
203
+
204
+			if ($entry instanceof Log) {
205
+				$invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
206
+				$entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
207
+
208
+				$entryComment = $entry->getComment();
209
+
210
+				if($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest'){
211
+					$data = unserialize($entry->getComment());
212
+					/** @var JobQueue $job */
213
+					$job = JobQueue::getById($data['job'], $database);
214
+					$requestLogs[] = array(
215
+						'type'     => 'joblog',
216
+						'security' => 'user',
217
+						'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
218
+						'user'     => $entryUser->getUsername(),
219
+						'entry'    => LogHelper::getLogDescription($entry),
220
+						'time'     => $entry->getTimestamp(),
221
+						'canedit'  => false,
222
+						'id'       => $entry->getId(),
223
+						'jobId'    => $job->getId(),
224
+						'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
225
+					);
226
+				} else {
227
+					$requestLogs[] = array(
228
+						'type'     => 'log',
229
+						'security' => 'user',
230
+						'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
231
+						'user'     => $entryUser->getUsername(),
232
+						'entry'    => LogHelper::getLogDescription($entry),
233
+						'time'     => $entry->getTimestamp(),
234
+						'canedit'  => false,
235
+						'id'       => $entry->getId(),
236
+						'comment'  => $entryComment,
237
+					);
238
+				}
239
+			}
240
+		}
241
+
242
+		$this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
243
+
244
+		$this->assign("requestLogs", $requestLogs);
245
+	}
246
+
247
+	/**
248
+	 * @param Request $request
249
+	 */
250
+	protected function setupUsernameData(Request $request)
251
+	{
252
+		$blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
253
+
254
+		$this->assign('requestIsBlacklisted', $blacklistData !== false);
255
+		$this->assign('requestBlacklist', $blacklistData);
256
+
257
+		try {
258
+			$spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
259
+		}
260
+		catch (Exception $ex) {
261
+			$spoofs = $ex->getMessage();
262
+		}
263
+
264
+		$this->assign("spoofs", $spoofs);
265
+	}
266
+
267
+	private function setupCreationTypes(User $user)
268
+	{
269
+		$this->assign('allowWelcomeSkip', false);
270
+		$this->assign('forceWelcomeSkip', false);
271
+
272
+		$oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
273
+
274
+		if ($user->getWelcomeTemplate() != 0) {
275
+			$this->assign('allowWelcomeSkip', true);
276
+
277
+			if (!$oauth->canWelcome()) {
278
+				$this->assign('forceWelcomeSkip', true);
279
+			}
280
+		}
281
+
282
+		// test credentials
283
+		$canManualCreate = $this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation');
284
+		$canOauthCreate = $this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation');
285
+		$canBotCreate = $this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation');
286
+
287
+		$this->assign('canManualCreate', $canManualCreate);
288
+		$this->assign('canOauthCreate', $canOauthCreate);
289
+		$this->assign('canBotCreate', $canBotCreate);
290
+
291
+		// show/hide the type radio buttons
292
+		$creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
293
+
294
+		if (!$this->barrierTest($user->getCreationMode(), $user, 'RequestCreation')) {
295
+			// user is not allowed to use their default. Force a choice.
296
+			$creationHasChoice = true;
297
+		}
298
+
299
+		$this->assign('creationHasChoice', $creationHasChoice);
300
+
301
+		// determine problems in creation types
302
+		$this->assign('botProblem', false);
303
+		if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
304
+			$this->assign('botProblem', true);
305
+		}
306
+
307
+		$this->assign('oauthProblem', false);
308
+		if ($canOauthCreate && !$oauth->canCreateAccount()) {
309
+			$this->assign('oauthProblem', true);
310
+		}
311
+	}
312 312
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -207,7 +207,7 @@
 block discarded – undo
207 207
 
208 208
                 $entryComment = $entry->getComment();
209 209
 
210
-                if($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest'){
210
+                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
211 211
                     $data = unserialize($entry->getComment());
212 212
                     /** @var JobQueue $job */
213 213
                     $job = JobQueue::getById($data['job'], $database);
Please login to merge, or discard this patch.
Braces   +3 added lines, -5 removed lines patch added patch discarded remove patch
@@ -94,8 +94,7 @@  discard block
 block discarded – undo
94 94
                 $this->setTemplate('view-request/main-with-checkuser-data.tpl');
95 95
                 $this->setupCheckUserData($request);
96 96
             }
97
-        }
98
-        else {
97
+        } else {
99 98
             $this->setTemplate('view-request/main.tpl');
100 99
         }
101 100
     }
@@ -109,8 +108,7 @@  discard block
 block discarded – undo
109 108
         if ($request->getStatus() === 'Closed') {
110 109
             if ($request->getWasCreated()) {
111 110
                 $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
112
-            }
113
-            else {
111
+            } else {
114 112
                 $statusSymbol = self::STATUS_SYMBOL_REJECTED;
115 113
             }
116 114
         }
@@ -207,7 +205,7 @@  discard block
 block discarded – undo
207 205
 
208 206
                 $entryComment = $entry->getComment();
209 207
 
210
-                if($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest'){
208
+                if($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
211 209
                     $data = unserialize($entry->getComment());
212 210
                     /** @var JobQueue $job */
213 211
                     $job = JobQueue::getById($data['job'], $database);
Please login to merge, or discard this patch.
includes/Pages/Page404.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -12,21 +12,21 @@
 block discarded – undo
12 12
 
13 13
 class Page404 extends InternalPageBase
14 14
 {
15
-    /**
16
-     * Main function for this page, when no actions are called.
17
-     */
18
-    protected function main()
19
-    {
20
-        if (!headers_sent()) {
21
-            header("HTTP/1.1 404 Not Found");
22
-        }
15
+	/**
16
+	 * Main function for this page, when no actions are called.
17
+	 */
18
+	protected function main()
19
+	{
20
+		if (!headers_sent()) {
21
+			header("HTTP/1.1 404 Not Found");
22
+		}
23 23
 
24
-        $this->skipAlerts();
25
-        $this->setTemplate("404.tpl");
26
-    }
24
+		$this->skipAlerts();
25
+		$this->setTemplate("404.tpl");
26
+	}
27 27
 
28
-    protected function isProtectedPage()
29
-    {
30
-        return false;
31
-    }
28
+	protected function isProtectedPage()
29
+	{
30
+		return false;
31
+	}
32 32
 }
Please login to merge, or discard this patch.
includes/Pages/PageUserManagement.php 3 patches
Indentation   +561 added lines, -561 removed lines patch added patch discarded remove patch
@@ -24,565 +24,565 @@
 block discarded – undo
24 24
  */
25 25
 class PageUserManagement extends InternalPageBase
26 26
 {
27
-    /** @var string */
28
-    private $adminMailingList = '[email protected]';
29
-
30
-    /**
31
-     * Main function for this page, when no specific actions are called.
32
-     */
33
-    protected function main()
34
-    {
35
-        $this->setHtmlTitle('User Management');
36
-
37
-        $database = $this->getDatabase();
38
-        $currentUser = User::getCurrent($database);
39
-
40
-        $userSearchRequest = WebRequest::getString('usersearch');
41
-        if ($userSearchRequest !== null) {
42
-            $searchedUser = User::getByUsername($userSearchRequest, $database);
43
-            if($searchedUser !== false) {
44
-                $this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
45
-                return;
46
-            }
47
-        }
48
-
49
-        // A bit hacky, but it's better than my last solution of creating an object for each user and passing that to
50
-        // the template. I still don't have a particularly good way of handling this.
51
-        OAuthUserHelper::prepareTokenCountStatement($database);
52
-
53
-        if (WebRequest::getBoolean("showAll")) {
54
-            $this->assign("showAll", true);
55
-
56
-            $suspendedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch();
57
-            $this->assign("suspendedUsers", $suspendedUsers);
58
-
59
-            $declinedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch();
60
-            $this->assign("declinedUsers", $declinedUsers);
61
-
62
-            UserSearchHelper::get($database)->getRoleMap($roleMap);
63
-        }
64
-        else {
65
-            $this->assign("showAll", false);
66
-            $this->assign("suspendedUsers", array());
67
-            $this->assign("declinedUsers", array());
68
-
69
-            UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
70
-        }
71
-
72
-        $newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
73
-        $normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
74
-        $adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
75
-        $checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
76
-        $toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
77
-        $this->assign('newUsers', $newUsers);
78
-        $this->assign('normalUsers', $normalUsers);
79
-        $this->assign('adminUsers', $adminUsers);
80
-        $this->assign('checkUsers', $checkUsers);
81
-        $this->assign('toolRoots', $toolRoots);
82
-
83
-        $this->assign('roles', $roleMap);
84
-
85
-        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
86
-
87
-        $this->assign('canApprove', $this->barrierTest('approve', $currentUser));
88
-        $this->assign('canDecline', $this->barrierTest('decline', $currentUser));
89
-        $this->assign('canRename', $this->barrierTest('rename', $currentUser));
90
-        $this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
91
-        $this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
92
-        $this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
93
-
94
-        $this->setTemplate("usermanagement/main.tpl");
95
-    }
96
-
97
-    #region Access control
98
-
99
-    /**
100
-     * Action target for editing the roles assigned to a user
101
-     */
102
-    protected function editRoles()
103
-    {
104
-        $this->setHtmlTitle('User Management');
105
-        $database = $this->getDatabase();
106
-        $userId = WebRequest::getInt('user');
107
-
108
-        /** @var User $user */
109
-        $user = User::getById($userId, $database);
110
-
111
-        if ($user === false) {
112
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
113
-        }
114
-
115
-        $roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database));
116
-
117
-        // Dual-mode action
118
-        if (WebRequest::wasPosted()) {
119
-            $this->validateCSRFToken();
120
-
121
-            $reason = WebRequest::postString('reason');
122
-            if ($reason === false || trim($reason) === '') {
123
-                throw new ApplicationLogicException('No reason specified for roles change');
124
-            }
125
-
126
-            /** @var UserRole[] $delete */
127
-            $delete = array();
128
-            /** @var string[] $delete */
129
-            $add = array();
130
-
131
-            foreach ($roleData as $name => $r) {
132
-                if ($r['allowEdit'] !== 1) {
133
-                    // not allowed, to touch this, so ignore it
134
-                    continue;
135
-                }
136
-
137
-                $newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
138
-                if ($newValue !== $r['active']) {
139
-                    if ($newValue === 0) {
140
-                        $delete[] = $r['object'];
141
-                    }
142
-
143
-                    if ($newValue === 1) {
144
-                        $add[] = $name;
145
-                    }
146
-                }
147
-            }
148
-
149
-            // Check there's something to do
150
-            if ((count($add) + count($delete)) === 0) {
151
-                $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
152
-                SessionAlert::warning('No changes made to roles.');
153
-
154
-                return;
155
-            }
156
-
157
-            $removed = array();
158
-
159
-            /** @var UserRole $d */
160
-            foreach ($delete as $d) {
161
-                $removed[] = $d->getRole();
162
-                $d->delete();
163
-            }
164
-
165
-            foreach ($add as $x) {
166
-                $a = new UserRole();
167
-                $a->setUser($user->getId());
168
-                $a->setRole($x);
169
-                $a->setDatabase($database);
170
-                $a->save();
171
-            }
172
-
173
-            Logger::userRolesEdited($database, $user, $reason, $add, $removed);
174
-
175
-            // dummy save for optimistic locking. If this fails, the entire txn will roll back.
176
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
177
-            $user->save();
178
-
179
-            $this->getNotificationHelper()->userRolesEdited($user, $reason);
180
-            SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
181
-
182
-            $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
183
-
184
-            return;
185
-        }
186
-        else {
187
-            $this->assignCSRFToken();
188
-            $this->setTemplate('usermanagement/roleedit.tpl');
189
-            $this->assign('user', $user);
190
-            $this->assign('roleData', $roleData);
191
-        }
192
-    }
193
-
194
-    /**
195
-     * Action target for suspending users
196
-     *
197
-     * @throws ApplicationLogicException
198
-     */
199
-    protected function suspend()
200
-    {
201
-        $this->setHtmlTitle('User Management');
202
-
203
-        $database = $this->getDatabase();
204
-
205
-        $userId = WebRequest::getInt('user');
206
-
207
-        /** @var User $user */
208
-        $user = User::getById($userId, $database);
209
-
210
-        if ($user === false) {
211
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
212
-        }
213
-
214
-        if ($user->isSuspended()) {
215
-            throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
216
-        }
217
-
218
-        // Dual-mode action
219
-        if (WebRequest::wasPosted()) {
220
-            $this->validateCSRFToken();
221
-            $reason = WebRequest::postString('reason');
222
-
223
-            if ($reason === null || trim($reason) === "") {
224
-                throw new ApplicationLogicException('No reason provided');
225
-            }
226
-
227
-            $user->setStatus(User::STATUS_SUSPENDED);
228
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
229
-            $user->save();
230
-            Logger::suspendedUser($database, $user, $reason);
231
-
232
-            $this->getNotificationHelper()->userSuspended($user, $reason);
233
-            SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
234
-
235
-            // send email
236
-            $this->sendStatusChangeEmail(
237
-                'Your WP:ACC account has been suspended',
238
-                'usermanagement/emails/suspended.tpl',
239
-                $reason,
240
-                $user,
241
-                User::getCurrent($database)->getUsername()
242
-            );
243
-
244
-            $this->redirect('userManagement');
245
-
246
-            return;
247
-        }
248
-        else {
249
-            $this->assignCSRFToken();
250
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
251
-            $this->assign('user', $user);
252
-            $this->assign('status', 'Suspended');
253
-            $this->assign("showReason", true);
254
-
255
-            if (WebRequest::getString('preload')) {
256
-                $this->assign('preload', WebRequest::getString('preload'));
257
-            }
258
-        }
259
-    }
260
-
261
-    /**
262
-     * Entry point for the decline action
263
-     *
264
-     * @throws ApplicationLogicException
265
-     */
266
-    protected function decline()
267
-    {
268
-        $this->setHtmlTitle('User Management');
269
-
270
-        $database = $this->getDatabase();
271
-
272
-        $userId = WebRequest::getInt('user');
273
-        $user = User::getById($userId, $database);
274
-
275
-        if ($user === false) {
276
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
277
-        }
278
-
279
-        if (!$user->isNewUser()) {
280
-            throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
281
-        }
282
-
283
-        // Dual-mode action
284
-        if (WebRequest::wasPosted()) {
285
-            $this->validateCSRFToken();
286
-            $reason = WebRequest::postString('reason');
287
-
288
-            if ($reason === null || trim($reason) === "") {
289
-                throw new ApplicationLogicException('No reason provided');
290
-            }
291
-
292
-            $user->setStatus(User::STATUS_DECLINED);
293
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
294
-            $user->save();
295
-            Logger::declinedUser($database, $user, $reason);
296
-
297
-            $this->getNotificationHelper()->userDeclined($user, $reason);
298
-            SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
299
-
300
-            // send email
301
-            $this->sendStatusChangeEmail(
302
-                'Your WP:ACC account has been declined',
303
-                'usermanagement/emails/declined.tpl',
304
-                $reason,
305
-                $user,
306
-                User::getCurrent($database)->getUsername()
307
-            );
308
-
309
-            $this->redirect('userManagement');
310
-
311
-            return;
312
-        }
313
-        else {
314
-            $this->assignCSRFToken();
315
-            $this->setTemplate('usermanagement/changelevel-reason.tpl');
316
-            $this->assign('user', $user);
317
-            $this->assign('status', 'Declined');
318
-            $this->assign("showReason", true);
319
-        }
320
-    }
321
-
322
-    /**
323
-     * Entry point for the approve action
324
-     *
325
-     * @throws ApplicationLogicException
326
-     */
327
-    protected function approve()
328
-    {
329
-        $this->setHtmlTitle('User Management');
330
-
331
-        $database = $this->getDatabase();
332
-
333
-        $userId = WebRequest::getInt('user');
334
-        $user = User::getById($userId, $database);
335
-
336
-        if ($user === false) {
337
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
338
-        }
339
-
340
-        if ($user->isActive()) {
341
-            throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
342
-        }
343
-
344
-        // Dual-mode action
345
-        if (WebRequest::wasPosted()) {
346
-            $this->validateCSRFToken();
347
-            $user->setStatus(User::STATUS_ACTIVE);
348
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
349
-            $user->save();
350
-            Logger::approvedUser($database, $user);
351
-
352
-            $this->getNotificationHelper()->userApproved($user);
353
-            SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
354
-
355
-            // send email
356
-            $this->sendStatusChangeEmail(
357
-                'Your WP:ACC account has been approved',
358
-                'usermanagement/emails/approved.tpl',
359
-                null,
360
-                $user,
361
-                User::getCurrent($database)->getUsername()
362
-            );
363
-
364
-            $this->redirect("userManagement");
365
-
366
-            return;
367
-        }
368
-        else {
369
-            $this->assignCSRFToken();
370
-            $this->setTemplate("usermanagement/changelevel-reason.tpl");
371
-            $this->assign("user", $user);
372
-            $this->assign("status", "Active");
373
-            $this->assign("showReason", false);
374
-        }
375
-    }
376
-
377
-    #endregion
378
-
379
-    #region Renaming / Editing
380
-
381
-    /**
382
-     * Entry point for the rename action
383
-     *
384
-     * @throws ApplicationLogicException
385
-     */
386
-    protected function rename()
387
-    {
388
-        $this->setHtmlTitle('User Management');
389
-
390
-        $database = $this->getDatabase();
391
-
392
-        $userId = WebRequest::getInt('user');
393
-        $user = User::getById($userId, $database);
394
-
395
-        if ($user === false) {
396
-            throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
397
-        }
398
-
399
-        // Dual-mode action
400
-        if (WebRequest::wasPosted()) {
401
-            $this->validateCSRFToken();
402
-            $newUsername = WebRequest::postString('newname');
403
-
404
-            if ($newUsername === null || trim($newUsername) === "") {
405
-                throw new ApplicationLogicException('The new username cannot be empty');
406
-            }
407
-
408
-            if (User::getByUsername($newUsername, $database) != false) {
409
-                throw new ApplicationLogicException('The new username already exists');
410
-            }
411
-
412
-            $oldUsername = $user->getUsername();
413
-            $user->setUsername($newUsername);
414
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
415
-
416
-            $user->save();
417
-
418
-            $logEntryData = serialize(array(
419
-                'old' => $oldUsername,
420
-                'new' => $newUsername,
421
-            ));
422
-
423
-            Logger::renamedUser($database, $user, $logEntryData);
424
-
425
-            SessionAlert::quick("Changed User "
426
-                . htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
427
-                . " name to "
428
-                . htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
429
-
430
-            $this->getNotificationHelper()->userRenamed($user, $oldUsername);
431
-
432
-            // send an email to the user.
433
-            $this->assign('targetUsername', $user->getUsername());
434
-            $this->assign('toolAdmin', User::getCurrent($database)->getUsername());
435
-            $this->assign('oldUsername', $oldUsername);
436
-            $this->assign('mailingList', $this->adminMailingList);
437
-
438
-            $this->getEmailHelper()->sendMail(
439
-                $user->getEmail(),
440
-                'Your username on WP:ACC has been changed',
441
-                $this->fetchTemplate('usermanagement/emails/renamed.tpl'),
442
-                array('Reply-To' => $this->adminMailingList)
443
-            );
444
-
445
-            $this->redirect("userManagement");
446
-
447
-            return;
448
-        }
449
-        else {
450
-            $this->assignCSRFToken();
451
-            $this->setTemplate('usermanagement/renameuser.tpl');
452
-            $this->assign('user', $user);
453
-        }
454
-    }
455
-
456
-    /**
457
-     * Entry point for the edit action
458
-     *
459
-     * @throws ApplicationLogicException
460
-     */
461
-    protected function editUser()
462
-    {
463
-        $this->setHtmlTitle('User Management');
464
-
465
-        $database = $this->getDatabase();
466
-
467
-        $userId = WebRequest::getInt('user');
468
-        $user = User::getById($userId, $database);
469
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
470
-
471
-        if ($user === false) {
472
-            throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
473
-        }
474
-
475
-        // Dual-mode action
476
-        if (WebRequest::wasPosted()) {
477
-            $this->validateCSRFToken();
478
-            $newEmail = WebRequest::postEmail('user_email');
479
-            $newOnWikiName = WebRequest::postString('user_onwikiname');
480
-
481
-            if ($newEmail === null) {
482
-                throw new ApplicationLogicException('Invalid email address');
483
-            }
484
-
485
-            if (!($oauth->isFullyLinked() || $oauth->isPartiallyLinked())) {
486
-                if (trim($newOnWikiName) == "") {
487
-                    throw new ApplicationLogicException('New on-wiki username cannot be blank');
488
-                }
489
-
490
-                $user->setOnWikiName($newOnWikiName);
491
-                $user->setWelcomeSig(WebRequest::postString('sig'));
492
-            }
493
-
494
-            $user->setEmail($newEmail);
495
-            $user->setCreationMode(WebRequest::postInt('creationmode'));
496
-
497
-            $user->setUpdateVersion(WebRequest::postInt('updateversion'));
498
-
499
-            $user->save();
500
-
501
-            Logger::userPreferencesChange($database, $user);
502
-            $this->getNotificationHelper()->userPrefChange($user);
503
-            SessionAlert::quick('Changes to user\'s preferences have been saved');
504
-
505
-            $this->redirect("userManagement");
506
-
507
-            return;
508
-        }
509
-        else {
510
-            $this->assignCSRFToken();
511
-            $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
512
-                $this->getSiteConfiguration());
513
-            $this->setTemplate('usermanagement/edituser.tpl');
514
-            $this->assign('user', $user);
515
-            $this->assign('oauth', $oauth);
516
-
517
-            $this->assign('canManualCreate',
518
-                $this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation'));
519
-            $this->assign('canOauthCreate',
520
-                $this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation'));
521
-            $this->assign('canBotCreate',
522
-                $this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation'));
523
-        }
524
-    }
525
-
526
-    #endregion
527
-
528
-    /**
529
-     * Sends a status change email to the user.
530
-     *
531
-     * @param string      $subject           The subject of the email
532
-     * @param string      $template          The smarty template to use
533
-     * @param string|null $reason            The reason for performing the status change
534
-     * @param User        $user              The user affected
535
-     * @param string      $toolAdminUsername The tool admin's username who is making the edit
536
-     */
537
-    private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
538
-    {
539
-        $this->assign('targetUsername', $user->getUsername());
540
-        $this->assign('toolAdmin', $toolAdminUsername);
541
-        $this->assign('actionReason', $reason);
542
-        $this->assign('mailingList', $this->adminMailingList);
543
-
544
-        $this->getEmailHelper()->sendMail(
545
-            $user->getEmail(),
546
-            $subject,
547
-            $this->fetchTemplate($template),
548
-            array('Reply-To' => $this->adminMailingList)
549
-        );
550
-    }
551
-
552
-    /**
553
-     * @param UserRole[] $activeRoles
554
-     *
555
-     * @return array
556
-     */
557
-    private function getRoleData($activeRoles)
558
-    {
559
-        $availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
560
-
561
-        $currentUser = User::getCurrent($this->getDatabase());
562
-        $this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
563
-
564
-        $initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
565
-
566
-        $roleData = array();
567
-        foreach ($availableRoles as $role => $data) {
568
-            $intersection = array_intersect($data['editableBy'], $userRoles);
569
-
570
-            $roleData[$role] = $initialValue;
571
-            $roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
572
-            $roleData[$role]['description'] = $data['description'];
573
-        }
574
-
575
-        foreach ($activeRoles as $role) {
576
-            if (!isset($roleData[$role->getRole()])) {
577
-                // This value is no longer available in the configuration, allow changing (aka removing) it.
578
-                $roleData[$role->getRole()] = $initialValue;
579
-                $roleData[$role->getRole()]['allowEdit'] = 1;
580
-            }
581
-
582
-            $roleData[$role->getRole()]['object'] = $role;
583
-            $roleData[$role->getRole()]['active'] = 1;
584
-        }
585
-
586
-        return $roleData;
587
-    }
27
+	/** @var string */
28
+	private $adminMailingList = '[email protected]';
29
+
30
+	/**
31
+	 * Main function for this page, when no specific actions are called.
32
+	 */
33
+	protected function main()
34
+	{
35
+		$this->setHtmlTitle('User Management');
36
+
37
+		$database = $this->getDatabase();
38
+		$currentUser = User::getCurrent($database);
39
+
40
+		$userSearchRequest = WebRequest::getString('usersearch');
41
+		if ($userSearchRequest !== null) {
42
+			$searchedUser = User::getByUsername($userSearchRequest, $database);
43
+			if($searchedUser !== false) {
44
+				$this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
45
+				return;
46
+			}
47
+		}
48
+
49
+		// A bit hacky, but it's better than my last solution of creating an object for each user and passing that to
50
+		// the template. I still don't have a particularly good way of handling this.
51
+		OAuthUserHelper::prepareTokenCountStatement($database);
52
+
53
+		if (WebRequest::getBoolean("showAll")) {
54
+			$this->assign("showAll", true);
55
+
56
+			$suspendedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_SUSPENDED)->fetch();
57
+			$this->assign("suspendedUsers", $suspendedUsers);
58
+
59
+			$declinedUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_DECLINED)->fetch();
60
+			$this->assign("declinedUsers", $declinedUsers);
61
+
62
+			UserSearchHelper::get($database)->getRoleMap($roleMap);
63
+		}
64
+		else {
65
+			$this->assign("showAll", false);
66
+			$this->assign("suspendedUsers", array());
67
+			$this->assign("declinedUsers", array());
68
+
69
+			UserSearchHelper::get($database)->statusIn(array('New', 'Active'))->getRoleMap($roleMap);
70
+		}
71
+
72
+		$newUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_NEW)->fetch();
73
+		$normalUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('user')->fetch();
74
+		$adminUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('admin')->fetch();
75
+		$checkUsers = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('checkuser')->fetch();
76
+		$toolRoots = UserSearchHelper::get($database)->byStatus(User::STATUS_ACTIVE)->byRole('toolRoot')->fetch();
77
+		$this->assign('newUsers', $newUsers);
78
+		$this->assign('normalUsers', $normalUsers);
79
+		$this->assign('adminUsers', $adminUsers);
80
+		$this->assign('checkUsers', $checkUsers);
81
+		$this->assign('toolRoots', $toolRoots);
82
+
83
+		$this->assign('roles', $roleMap);
84
+
85
+		$this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
86
+
87
+		$this->assign('canApprove', $this->barrierTest('approve', $currentUser));
88
+		$this->assign('canDecline', $this->barrierTest('decline', $currentUser));
89
+		$this->assign('canRename', $this->barrierTest('rename', $currentUser));
90
+		$this->assign('canEditUser', $this->barrierTest('editUser', $currentUser));
91
+		$this->assign('canSuspend', $this->barrierTest('suspend', $currentUser));
92
+		$this->assign('canEditRoles', $this->barrierTest('editRoles', $currentUser));
93
+
94
+		$this->setTemplate("usermanagement/main.tpl");
95
+	}
96
+
97
+	#region Access control
98
+
99
+	/**
100
+	 * Action target for editing the roles assigned to a user
101
+	 */
102
+	protected function editRoles()
103
+	{
104
+		$this->setHtmlTitle('User Management');
105
+		$database = $this->getDatabase();
106
+		$userId = WebRequest::getInt('user');
107
+
108
+		/** @var User $user */
109
+		$user = User::getById($userId, $database);
110
+
111
+		if ($user === false) {
112
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
113
+		}
114
+
115
+		$roleData = $this->getRoleData(UserRole::getForUser($user->getId(), $database));
116
+
117
+		// Dual-mode action
118
+		if (WebRequest::wasPosted()) {
119
+			$this->validateCSRFToken();
120
+
121
+			$reason = WebRequest::postString('reason');
122
+			if ($reason === false || trim($reason) === '') {
123
+				throw new ApplicationLogicException('No reason specified for roles change');
124
+			}
125
+
126
+			/** @var UserRole[] $delete */
127
+			$delete = array();
128
+			/** @var string[] $delete */
129
+			$add = array();
130
+
131
+			foreach ($roleData as $name => $r) {
132
+				if ($r['allowEdit'] !== 1) {
133
+					// not allowed, to touch this, so ignore it
134
+					continue;
135
+				}
136
+
137
+				$newValue = WebRequest::postBoolean('role-' . $name) ? 1 : 0;
138
+				if ($newValue !== $r['active']) {
139
+					if ($newValue === 0) {
140
+						$delete[] = $r['object'];
141
+					}
142
+
143
+					if ($newValue === 1) {
144
+						$add[] = $name;
145
+					}
146
+				}
147
+			}
148
+
149
+			// Check there's something to do
150
+			if ((count($add) + count($delete)) === 0) {
151
+				$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
152
+				SessionAlert::warning('No changes made to roles.');
153
+
154
+				return;
155
+			}
156
+
157
+			$removed = array();
158
+
159
+			/** @var UserRole $d */
160
+			foreach ($delete as $d) {
161
+				$removed[] = $d->getRole();
162
+				$d->delete();
163
+			}
164
+
165
+			foreach ($add as $x) {
166
+				$a = new UserRole();
167
+				$a->setUser($user->getId());
168
+				$a->setRole($x);
169
+				$a->setDatabase($database);
170
+				$a->save();
171
+			}
172
+
173
+			Logger::userRolesEdited($database, $user, $reason, $add, $removed);
174
+
175
+			// dummy save for optimistic locking. If this fails, the entire txn will roll back.
176
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
177
+			$user->save();
178
+
179
+			$this->getNotificationHelper()->userRolesEdited($user, $reason);
180
+			SessionAlert::quick('Roles changed for user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
181
+
182
+			$this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
183
+
184
+			return;
185
+		}
186
+		else {
187
+			$this->assignCSRFToken();
188
+			$this->setTemplate('usermanagement/roleedit.tpl');
189
+			$this->assign('user', $user);
190
+			$this->assign('roleData', $roleData);
191
+		}
192
+	}
193
+
194
+	/**
195
+	 * Action target for suspending users
196
+	 *
197
+	 * @throws ApplicationLogicException
198
+	 */
199
+	protected function suspend()
200
+	{
201
+		$this->setHtmlTitle('User Management');
202
+
203
+		$database = $this->getDatabase();
204
+
205
+		$userId = WebRequest::getInt('user');
206
+
207
+		/** @var User $user */
208
+		$user = User::getById($userId, $database);
209
+
210
+		if ($user === false) {
211
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend could not be found.');
212
+		}
213
+
214
+		if ($user->isSuspended()) {
215
+			throw new ApplicationLogicException('Sorry, the user you are trying to suspend is already suspended.');
216
+		}
217
+
218
+		// Dual-mode action
219
+		if (WebRequest::wasPosted()) {
220
+			$this->validateCSRFToken();
221
+			$reason = WebRequest::postString('reason');
222
+
223
+			if ($reason === null || trim($reason) === "") {
224
+				throw new ApplicationLogicException('No reason provided');
225
+			}
226
+
227
+			$user->setStatus(User::STATUS_SUSPENDED);
228
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
229
+			$user->save();
230
+			Logger::suspendedUser($database, $user, $reason);
231
+
232
+			$this->getNotificationHelper()->userSuspended($user, $reason);
233
+			SessionAlert::quick('Suspended user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
234
+
235
+			// send email
236
+			$this->sendStatusChangeEmail(
237
+				'Your WP:ACC account has been suspended',
238
+				'usermanagement/emails/suspended.tpl',
239
+				$reason,
240
+				$user,
241
+				User::getCurrent($database)->getUsername()
242
+			);
243
+
244
+			$this->redirect('userManagement');
245
+
246
+			return;
247
+		}
248
+		else {
249
+			$this->assignCSRFToken();
250
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
251
+			$this->assign('user', $user);
252
+			$this->assign('status', 'Suspended');
253
+			$this->assign("showReason", true);
254
+
255
+			if (WebRequest::getString('preload')) {
256
+				$this->assign('preload', WebRequest::getString('preload'));
257
+			}
258
+		}
259
+	}
260
+
261
+	/**
262
+	 * Entry point for the decline action
263
+	 *
264
+	 * @throws ApplicationLogicException
265
+	 */
266
+	protected function decline()
267
+	{
268
+		$this->setHtmlTitle('User Management');
269
+
270
+		$database = $this->getDatabase();
271
+
272
+		$userId = WebRequest::getInt('user');
273
+		$user = User::getById($userId, $database);
274
+
275
+		if ($user === false) {
276
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline could not be found.');
277
+		}
278
+
279
+		if (!$user->isNewUser()) {
280
+			throw new ApplicationLogicException('Sorry, the user you are trying to decline is not new.');
281
+		}
282
+
283
+		// Dual-mode action
284
+		if (WebRequest::wasPosted()) {
285
+			$this->validateCSRFToken();
286
+			$reason = WebRequest::postString('reason');
287
+
288
+			if ($reason === null || trim($reason) === "") {
289
+				throw new ApplicationLogicException('No reason provided');
290
+			}
291
+
292
+			$user->setStatus(User::STATUS_DECLINED);
293
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
294
+			$user->save();
295
+			Logger::declinedUser($database, $user, $reason);
296
+
297
+			$this->getNotificationHelper()->userDeclined($user, $reason);
298
+			SessionAlert::quick('Declined user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
299
+
300
+			// send email
301
+			$this->sendStatusChangeEmail(
302
+				'Your WP:ACC account has been declined',
303
+				'usermanagement/emails/declined.tpl',
304
+				$reason,
305
+				$user,
306
+				User::getCurrent($database)->getUsername()
307
+			);
308
+
309
+			$this->redirect('userManagement');
310
+
311
+			return;
312
+		}
313
+		else {
314
+			$this->assignCSRFToken();
315
+			$this->setTemplate('usermanagement/changelevel-reason.tpl');
316
+			$this->assign('user', $user);
317
+			$this->assign('status', 'Declined');
318
+			$this->assign("showReason", true);
319
+		}
320
+	}
321
+
322
+	/**
323
+	 * Entry point for the approve action
324
+	 *
325
+	 * @throws ApplicationLogicException
326
+	 */
327
+	protected function approve()
328
+	{
329
+		$this->setHtmlTitle('User Management');
330
+
331
+		$database = $this->getDatabase();
332
+
333
+		$userId = WebRequest::getInt('user');
334
+		$user = User::getById($userId, $database);
335
+
336
+		if ($user === false) {
337
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve could not be found.');
338
+		}
339
+
340
+		if ($user->isActive()) {
341
+			throw new ApplicationLogicException('Sorry, the user you are trying to approve is already an active user.');
342
+		}
343
+
344
+		// Dual-mode action
345
+		if (WebRequest::wasPosted()) {
346
+			$this->validateCSRFToken();
347
+			$user->setStatus(User::STATUS_ACTIVE);
348
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
349
+			$user->save();
350
+			Logger::approvedUser($database, $user);
351
+
352
+			$this->getNotificationHelper()->userApproved($user);
353
+			SessionAlert::quick('Approved user ' . htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8'));
354
+
355
+			// send email
356
+			$this->sendStatusChangeEmail(
357
+				'Your WP:ACC account has been approved',
358
+				'usermanagement/emails/approved.tpl',
359
+				null,
360
+				$user,
361
+				User::getCurrent($database)->getUsername()
362
+			);
363
+
364
+			$this->redirect("userManagement");
365
+
366
+			return;
367
+		}
368
+		else {
369
+			$this->assignCSRFToken();
370
+			$this->setTemplate("usermanagement/changelevel-reason.tpl");
371
+			$this->assign("user", $user);
372
+			$this->assign("status", "Active");
373
+			$this->assign("showReason", false);
374
+		}
375
+	}
376
+
377
+	#endregion
378
+
379
+	#region Renaming / Editing
380
+
381
+	/**
382
+	 * Entry point for the rename action
383
+	 *
384
+	 * @throws ApplicationLogicException
385
+	 */
386
+	protected function rename()
387
+	{
388
+		$this->setHtmlTitle('User Management');
389
+
390
+		$database = $this->getDatabase();
391
+
392
+		$userId = WebRequest::getInt('user');
393
+		$user = User::getById($userId, $database);
394
+
395
+		if ($user === false) {
396
+			throw new ApplicationLogicException('Sorry, the user you are trying to rename could not be found.');
397
+		}
398
+
399
+		// Dual-mode action
400
+		if (WebRequest::wasPosted()) {
401
+			$this->validateCSRFToken();
402
+			$newUsername = WebRequest::postString('newname');
403
+
404
+			if ($newUsername === null || trim($newUsername) === "") {
405
+				throw new ApplicationLogicException('The new username cannot be empty');
406
+			}
407
+
408
+			if (User::getByUsername($newUsername, $database) != false) {
409
+				throw new ApplicationLogicException('The new username already exists');
410
+			}
411
+
412
+			$oldUsername = $user->getUsername();
413
+			$user->setUsername($newUsername);
414
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
415
+
416
+			$user->save();
417
+
418
+			$logEntryData = serialize(array(
419
+				'old' => $oldUsername,
420
+				'new' => $newUsername,
421
+			));
422
+
423
+			Logger::renamedUser($database, $user, $logEntryData);
424
+
425
+			SessionAlert::quick("Changed User "
426
+				. htmlentities($oldUsername, ENT_COMPAT, 'UTF-8')
427
+				. " name to "
428
+				. htmlentities($newUsername, ENT_COMPAT, 'UTF-8'));
429
+
430
+			$this->getNotificationHelper()->userRenamed($user, $oldUsername);
431
+
432
+			// send an email to the user.
433
+			$this->assign('targetUsername', $user->getUsername());
434
+			$this->assign('toolAdmin', User::getCurrent($database)->getUsername());
435
+			$this->assign('oldUsername', $oldUsername);
436
+			$this->assign('mailingList', $this->adminMailingList);
437
+
438
+			$this->getEmailHelper()->sendMail(
439
+				$user->getEmail(),
440
+				'Your username on WP:ACC has been changed',
441
+				$this->fetchTemplate('usermanagement/emails/renamed.tpl'),
442
+				array('Reply-To' => $this->adminMailingList)
443
+			);
444
+
445
+			$this->redirect("userManagement");
446
+
447
+			return;
448
+		}
449
+		else {
450
+			$this->assignCSRFToken();
451
+			$this->setTemplate('usermanagement/renameuser.tpl');
452
+			$this->assign('user', $user);
453
+		}
454
+	}
455
+
456
+	/**
457
+	 * Entry point for the edit action
458
+	 *
459
+	 * @throws ApplicationLogicException
460
+	 */
461
+	protected function editUser()
462
+	{
463
+		$this->setHtmlTitle('User Management');
464
+
465
+		$database = $this->getDatabase();
466
+
467
+		$userId = WebRequest::getInt('user');
468
+		$user = User::getById($userId, $database);
469
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
470
+
471
+		if ($user === false) {
472
+			throw new ApplicationLogicException('Sorry, the user you are trying to edit could not be found.');
473
+		}
474
+
475
+		// Dual-mode action
476
+		if (WebRequest::wasPosted()) {
477
+			$this->validateCSRFToken();
478
+			$newEmail = WebRequest::postEmail('user_email');
479
+			$newOnWikiName = WebRequest::postString('user_onwikiname');
480
+
481
+			if ($newEmail === null) {
482
+				throw new ApplicationLogicException('Invalid email address');
483
+			}
484
+
485
+			if (!($oauth->isFullyLinked() || $oauth->isPartiallyLinked())) {
486
+				if (trim($newOnWikiName) == "") {
487
+					throw new ApplicationLogicException('New on-wiki username cannot be blank');
488
+				}
489
+
490
+				$user->setOnWikiName($newOnWikiName);
491
+				$user->setWelcomeSig(WebRequest::postString('sig'));
492
+			}
493
+
494
+			$user->setEmail($newEmail);
495
+			$user->setCreationMode(WebRequest::postInt('creationmode'));
496
+
497
+			$user->setUpdateVersion(WebRequest::postInt('updateversion'));
498
+
499
+			$user->save();
500
+
501
+			Logger::userPreferencesChange($database, $user);
502
+			$this->getNotificationHelper()->userPrefChange($user);
503
+			SessionAlert::quick('Changes to user\'s preferences have been saved');
504
+
505
+			$this->redirect("userManagement");
506
+
507
+			return;
508
+		}
509
+		else {
510
+			$this->assignCSRFToken();
511
+			$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
512
+				$this->getSiteConfiguration());
513
+			$this->setTemplate('usermanagement/edituser.tpl');
514
+			$this->assign('user', $user);
515
+			$this->assign('oauth', $oauth);
516
+
517
+			$this->assign('canManualCreate',
518
+				$this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation'));
519
+			$this->assign('canOauthCreate',
520
+				$this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation'));
521
+			$this->assign('canBotCreate',
522
+				$this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation'));
523
+		}
524
+	}
525
+
526
+	#endregion
527
+
528
+	/**
529
+	 * Sends a status change email to the user.
530
+	 *
531
+	 * @param string      $subject           The subject of the email
532
+	 * @param string      $template          The smarty template to use
533
+	 * @param string|null $reason            The reason for performing the status change
534
+	 * @param User        $user              The user affected
535
+	 * @param string      $toolAdminUsername The tool admin's username who is making the edit
536
+	 */
537
+	private function sendStatusChangeEmail($subject, $template, $reason, $user, $toolAdminUsername)
538
+	{
539
+		$this->assign('targetUsername', $user->getUsername());
540
+		$this->assign('toolAdmin', $toolAdminUsername);
541
+		$this->assign('actionReason', $reason);
542
+		$this->assign('mailingList', $this->adminMailingList);
543
+
544
+		$this->getEmailHelper()->sendMail(
545
+			$user->getEmail(),
546
+			$subject,
547
+			$this->fetchTemplate($template),
548
+			array('Reply-To' => $this->adminMailingList)
549
+		);
550
+	}
551
+
552
+	/**
553
+	 * @param UserRole[] $activeRoles
554
+	 *
555
+	 * @return array
556
+	 */
557
+	private function getRoleData($activeRoles)
558
+	{
559
+		$availableRoles = $this->getSecurityManager()->getRoleConfiguration()->getAvailableRoles();
560
+
561
+		$currentUser = User::getCurrent($this->getDatabase());
562
+		$this->getSecurityManager()->getActiveRoles($currentUser, $userRoles, $inactiveRoles);
563
+
564
+		$initialValue = array('active' => 0, 'allowEdit' => 0, 'description' => '???', 'object' => null);
565
+
566
+		$roleData = array();
567
+		foreach ($availableRoles as $role => $data) {
568
+			$intersection = array_intersect($data['editableBy'], $userRoles);
569
+
570
+			$roleData[$role] = $initialValue;
571
+			$roleData[$role]['allowEdit'] = count($intersection) > 0 ? 1 : 0;
572
+			$roleData[$role]['description'] = $data['description'];
573
+		}
574
+
575
+		foreach ($activeRoles as $role) {
576
+			if (!isset($roleData[$role->getRole()])) {
577
+				// This value is no longer available in the configuration, allow changing (aka removing) it.
578
+				$roleData[$role->getRole()] = $initialValue;
579
+				$roleData[$role->getRole()]['allowEdit'] = 1;
580
+			}
581
+
582
+			$roleData[$role->getRole()]['object'] = $role;
583
+			$roleData[$role->getRole()]['active'] = 1;
584
+		}
585
+
586
+		return $roleData;
587
+	}
588 588
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@
 block discarded – undo
40 40
         $userSearchRequest = WebRequest::getString('usersearch');
41 41
         if ($userSearchRequest !== null) {
42 42
             $searchedUser = User::getByUsername($userSearchRequest, $database);
43
-            if($searchedUser !== false) {
43
+            if ($searchedUser !== false) {
44 44
                 $this->redirect('statistics/users', 'detail', ['user' => $searchedUser->getId()]);
45 45
                 return;
46 46
             }
Please login to merge, or discard this patch.
Braces   +7 added lines, -14 removed lines patch added patch discarded remove patch
@@ -60,8 +60,7 @@  discard block
 block discarded – undo
60 60
             $this->assign("declinedUsers", $declinedUsers);
61 61
 
62 62
             UserSearchHelper::get($database)->getRoleMap($roleMap);
63
-        }
64
-        else {
63
+        } else {
65 64
             $this->assign("showAll", false);
66 65
             $this->assign("suspendedUsers", array());
67 66
             $this->assign("declinedUsers", array());
@@ -182,8 +181,7 @@  discard block
 block discarded – undo
182 181
             $this->redirect('statistics/users', 'detail', array('user' => $user->getId()));
183 182
 
184 183
             return;
185
-        }
186
-        else {
184
+        } else {
187 185
             $this->assignCSRFToken();
188 186
             $this->setTemplate('usermanagement/roleedit.tpl');
189 187
             $this->assign('user', $user);
@@ -244,8 +242,7 @@  discard block
 block discarded – undo
244 242
             $this->redirect('userManagement');
245 243
 
246 244
             return;
247
-        }
248
-        else {
245
+        } else {
249 246
             $this->assignCSRFToken();
250 247
             $this->setTemplate('usermanagement/changelevel-reason.tpl');
251 248
             $this->assign('user', $user);
@@ -309,8 +306,7 @@  discard block
 block discarded – undo
309 306
             $this->redirect('userManagement');
310 307
 
311 308
             return;
312
-        }
313
-        else {
309
+        } else {
314 310
             $this->assignCSRFToken();
315 311
             $this->setTemplate('usermanagement/changelevel-reason.tpl');
316 312
             $this->assign('user', $user);
@@ -364,8 +360,7 @@  discard block
 block discarded – undo
364 360
             $this->redirect("userManagement");
365 361
 
366 362
             return;
367
-        }
368
-        else {
363
+        } else {
369 364
             $this->assignCSRFToken();
370 365
             $this->setTemplate("usermanagement/changelevel-reason.tpl");
371 366
             $this->assign("user", $user);
@@ -445,8 +440,7 @@  discard block
 block discarded – undo
445 440
             $this->redirect("userManagement");
446 441
 
447 442
             return;
448
-        }
449
-        else {
443
+        } else {
450 444
             $this->assignCSRFToken();
451 445
             $this->setTemplate('usermanagement/renameuser.tpl');
452 446
             $this->assign('user', $user);
@@ -505,8 +499,7 @@  discard block
 block discarded – undo
505 499
             $this->redirect("userManagement");
506 500
 
507 501
             return;
508
-        }
509
-        else {
502
+        } else {
510 503
             $this->assignCSRFToken();
511 504
             $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
512 505
                 $this->getSiteConfiguration());
Please login to merge, or discard this patch.
includes/Pages/PageXffDemo.php 2 patches
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -13,136 +13,136 @@
 block discarded – undo
13 13
 
14 14
 class PageXffDemo extends InternalPageBase
15 15
 {
16
-    use RequestData;
17
-
18
-    /**
19
-     * @inheritDoc
20
-     */
21
-    protected function main()
22
-    {
23
-        $this->setTemplate('xffdemo.tpl');
24
-
25
-        // requestHasForwardedIp == false
26
-        // requestProxyData
27
-        // requestRealIp == proxy
28
-        // requestForwardedIp == xff header
29
-        // forwardedOrigin  == top of the chain, assuming xff is trusted
30
-
31
-
32
-        $this->assign('demo2', [
33
-            [
34
-                'trust' => true,
35
-                'trustedlink' => true,
36
-                'ip' => '172.16.0.164',
37
-                'routable' => false,
38
-
39
-            ],[
40
-                'trust' => true,
41
-                'ip' => '198.51.100.123',
42
-                'routable' => true,
43
-                'rdns' => 'trustedproxy.example.com',
44
-
45
-            ],[
46
-                'trust' => true,
47
-                'ip' => '192.0.2.1',
48
-                'routable' => true,
49
-                'rdns' => 'client.users.example.org',
50
-                'location' => [
51
-                    'cityName' => 'San Francisco',
52
-                    'regionName' => 'California',
53
-                    'countryName' => 'United States'
54
-                ],
55
-                'showlinks' => true
56
-            ]
57
-        ]);
58
-
59
-        $this->assign('demo3', [
60
-            [
61
-                'trust' => true,
62
-                'trustedlink' => true,
63
-                'ip' => '172.16.0.164',
64
-                'routable' => false,
65
-
66
-            ],[
67
-                'trust' => false,
68
-                'ip' => '198.51.100.234',
69
-                'routable' => true,
70
-                'rdns' => 'sketchyproxy.example.com',
71
-                'showlinks' => true
72
-
73
-            ],[
74
-                'trust' => false,
75
-                'ip' => '192.0.2.1',
76
-                'routable' => true,
77
-                'rdns' => 'client.users.example.org',
78
-                'location' => [
79
-                    'cityName' => 'San Francisco',
80
-                    'regionName' => 'California',
81
-                    'countryName' => 'United States'
82
-                ],
83
-                'showlinks' => true
84
-            ]
85
-        ]);
86
-
87
-        $this->assign('demo4', [
88
-            [
89
-                'trust' => true,
90
-                'trustedlink' => true,
91
-                'ip' => '172.16.0.164',
92
-                'routable' => false,
93
-
94
-            ],[
95
-                'trust' => true,
96
-                'ip' => '198.51.100.123',
97
-                'routable' => true,
98
-                'rdns' => 'trustedproxy.example.com',
99
-            ],[
100
-                'trust' => false,
101
-                'ip' => '198.51.100.234',
102
-                'routable' => true,
103
-                'rdns' => 'sketchyproxy.example.com',
104
-                'showlinks' => true
105
-            ], [
106
-                'trust' => false,
107
-                'trustedlink' => true,
108
-                'ip' => '198.51.100.124',
109
-                'routable' => true,
110
-                'rdns' => 'trustedproxy2.example.com',
111
-                'showlinks' => true
112
-            ],[
113
-                'trust' => false,
114
-                'ip' => '192.0.2.1',
115
-                'routable' => true,
116
-                'rdns' => 'client.users.example.org',
117
-                'location' => [
118
-                    'cityName' => 'San Francisco',
119
-                    'regionName' => 'California',
120
-                    'countryName' => 'United States'
121
-                ],
122
-                'showlinks' => true
123
-            ]
124
-        ]);
125
-
126
-        $this->assign('demo1', [
127
-            [
128
-                'trust' => true,
129
-                'trustedlink' => true,
130
-                'ip' => '172.16.0.164',
131
-                'routable' => false,
132
-
133
-            ], [
134
-                'trust' => true,
135
-                'trustedlink' => true,
136
-                'ip' => '192.0.2.1',
137
-                'routable' => true,
138
-                'rdns' => 'client.users.example.org',
139
-                'location' => [
140
-                    'cityName' => 'San Francisco',
141
-                    'regionName' => 'California',
142
-                    'countryName' => 'United States'
143
-                ],
144
-                'showlinks' => true
145
-            ]
146
-        ]);
147
-    }
16
+	use RequestData;
17
+
18
+	/**
19
+	 * @inheritDoc
20
+	 */
21
+	protected function main()
22
+	{
23
+		$this->setTemplate('xffdemo.tpl');
24
+
25
+		// requestHasForwardedIp == false
26
+		// requestProxyData
27
+		// requestRealIp == proxy
28
+		// requestForwardedIp == xff header
29
+		// forwardedOrigin  == top of the chain, assuming xff is trusted
30
+
31
+
32
+		$this->assign('demo2', [
33
+			[
34
+				'trust' => true,
35
+				'trustedlink' => true,
36
+				'ip' => '172.16.0.164',
37
+				'routable' => false,
38
+
39
+			],[
40
+				'trust' => true,
41
+				'ip' => '198.51.100.123',
42
+				'routable' => true,
43
+				'rdns' => 'trustedproxy.example.com',
44
+
45
+			],[
46
+				'trust' => true,
47
+				'ip' => '192.0.2.1',
48
+				'routable' => true,
49
+				'rdns' => 'client.users.example.org',
50
+				'location' => [
51
+					'cityName' => 'San Francisco',
52
+					'regionName' => 'California',
53
+					'countryName' => 'United States'
54
+				],
55
+				'showlinks' => true
56
+			]
57
+		]);
58
+
59
+		$this->assign('demo3', [
60
+			[
61
+				'trust' => true,
62
+				'trustedlink' => true,
63
+				'ip' => '172.16.0.164',
64
+				'routable' => false,
65
+
66
+			],[
67
+				'trust' => false,
68
+				'ip' => '198.51.100.234',
69
+				'routable' => true,
70
+				'rdns' => 'sketchyproxy.example.com',
71
+				'showlinks' => true
72
+
73
+			],[
74
+				'trust' => false,
75
+				'ip' => '192.0.2.1',
76
+				'routable' => true,
77
+				'rdns' => 'client.users.example.org',
78
+				'location' => [
79
+					'cityName' => 'San Francisco',
80
+					'regionName' => 'California',
81
+					'countryName' => 'United States'
82
+				],
83
+				'showlinks' => true
84
+			]
85
+		]);
86
+
87
+		$this->assign('demo4', [
88
+			[
89
+				'trust' => true,
90
+				'trustedlink' => true,
91
+				'ip' => '172.16.0.164',
92
+				'routable' => false,
93
+
94
+			],[
95
+				'trust' => true,
96
+				'ip' => '198.51.100.123',
97
+				'routable' => true,
98
+				'rdns' => 'trustedproxy.example.com',
99
+			],[
100
+				'trust' => false,
101
+				'ip' => '198.51.100.234',
102
+				'routable' => true,
103
+				'rdns' => 'sketchyproxy.example.com',
104
+				'showlinks' => true
105
+			], [
106
+				'trust' => false,
107
+				'trustedlink' => true,
108
+				'ip' => '198.51.100.124',
109
+				'routable' => true,
110
+				'rdns' => 'trustedproxy2.example.com',
111
+				'showlinks' => true
112
+			],[
113
+				'trust' => false,
114
+				'ip' => '192.0.2.1',
115
+				'routable' => true,
116
+				'rdns' => 'client.users.example.org',
117
+				'location' => [
118
+					'cityName' => 'San Francisco',
119
+					'regionName' => 'California',
120
+					'countryName' => 'United States'
121
+				],
122
+				'showlinks' => true
123
+			]
124
+		]);
125
+
126
+		$this->assign('demo1', [
127
+			[
128
+				'trust' => true,
129
+				'trustedlink' => true,
130
+				'ip' => '172.16.0.164',
131
+				'routable' => false,
132
+
133
+			], [
134
+				'trust' => true,
135
+				'trustedlink' => true,
136
+				'ip' => '192.0.2.1',
137
+				'routable' => true,
138
+				'rdns' => 'client.users.example.org',
139
+				'location' => [
140
+					'cityName' => 'San Francisco',
141
+					'regionName' => 'California',
142
+					'countryName' => 'United States'
143
+				],
144
+				'showlinks' => true
145
+			]
146
+		]);
147
+	}
148 148
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -36,13 +36,13 @@  discard block
 block discarded – undo
36 36
                 'ip' => '172.16.0.164',
37 37
                 'routable' => false,
38 38
 
39
-            ],[
39
+            ], [
40 40
                 'trust' => true,
41 41
                 'ip' => '198.51.100.123',
42 42
                 'routable' => true,
43 43
                 'rdns' => 'trustedproxy.example.com',
44 44
 
45
-            ],[
45
+            ], [
46 46
                 'trust' => true,
47 47
                 'ip' => '192.0.2.1',
48 48
                 'routable' => true,
@@ -63,14 +63,14 @@  discard block
 block discarded – undo
63 63
                 'ip' => '172.16.0.164',
64 64
                 'routable' => false,
65 65
 
66
-            ],[
66
+            ], [
67 67
                 'trust' => false,
68 68
                 'ip' => '198.51.100.234',
69 69
                 'routable' => true,
70 70
                 'rdns' => 'sketchyproxy.example.com',
71 71
                 'showlinks' => true
72 72
 
73
-            ],[
73
+            ], [
74 74
                 'trust' => false,
75 75
                 'ip' => '192.0.2.1',
76 76
                 'routable' => true,
@@ -91,12 +91,12 @@  discard block
 block discarded – undo
91 91
                 'ip' => '172.16.0.164',
92 92
                 'routable' => false,
93 93
 
94
-            ],[
94
+            ], [
95 95
                 'trust' => true,
96 96
                 'ip' => '198.51.100.123',
97 97
                 'routable' => true,
98 98
                 'rdns' => 'trustedproxy.example.com',
99
-            ],[
99
+            ], [
100 100
                 'trust' => false,
101 101
                 'ip' => '198.51.100.234',
102 102
                 'routable' => true,
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
                 'routable' => true,
110 110
                 'rdns' => 'trustedproxy2.example.com',
111 111
                 'showlinks' => true
112
-            ],[
112
+            ], [
113 113
                 'trust' => false,
114 114
                 'ip' => '192.0.2.1',
115 115
                 'routable' => true,
Please login to merge, or discard this patch.
includes/Pages/PageBan.php 2 patches
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -21,308 +21,308 @@
 block discarded – undo
21 21
 
22 22
 class PageBan extends InternalPageBase
23 23
 {
24
-    /**
25
-     * Main function for this page, when no specific actions are called.
26
-     */
27
-    protected function main()
28
-    {
29
-        $this->assignCSRFToken();
30
-
31
-        $this->setHtmlTitle('Bans');
32
-
33
-        $bans = Ban::getActiveBans(null, $this->getDatabase());
34
-
35
-        $userIds = array_map(
36
-            function(Ban $entry) {
37
-                return $entry->getUser();
38
-            },
39
-            $bans);
40
-        $userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
41
-
42
-        $user = User::getCurrent($this->getDatabase());
43
-        $this->assign('canSet', $this->barrierTest('set', $user));
44
-        $this->assign('canRemove', $this->barrierTest('remove', $user));
45
-
46
-        $this->assign('usernames', $userList);
47
-        $this->assign('activebans', $bans);
48
-        $this->setTemplate('bans/banlist.tpl');
49
-    }
50
-
51
-    /**
52
-     * Entry point for the ban set action
53
-     */
54
-    protected function set()
55
-    {
56
-        $this->setHtmlTitle('Bans');
57
-
58
-        // dual-mode action
59
-        if (WebRequest::wasPosted()) {
60
-            try {
61
-                $this->handlePostMethodForSetBan();
62
-            }
63
-            catch (ApplicationLogicException $ex) {
64
-                SessionAlert::error($ex->getMessage());
65
-                $this->redirect("bans", "set");
66
-            }
67
-        }
68
-        else {
69
-            $this->handleGetMethodForSetBan();
70
-        }
71
-    }
72
-
73
-    /**
74
-     * Entry point for the ban remove action
75
-     */
76
-    protected function remove()
77
-    {
78
-        $this->setHtmlTitle('Bans');
79
-
80
-        $ban = $this->getBanForUnban();
81
-
82
-        // dual mode
83
-        if (WebRequest::wasPosted()) {
84
-            $this->validateCSRFToken();
85
-            $unbanReason = WebRequest::postString('unbanreason');
86
-
87
-            if ($unbanReason === null || trim($unbanReason) === "") {
88
-                SessionAlert::error('No unban reason specified');
89
-                $this->redirect("bans", "remove", array('id' => $ban->getId()));
90
-            }
91
-
92
-            // set optimistic locking from delete form page load
93
-            $updateVersion = WebRequest::postInt('updateversion');
94
-            $ban->setUpdateVersion($updateVersion);
95
-
96
-            $database = $this->getDatabase();
97
-            $ban->setActive(false);
98
-            $ban->save();
99
-
100
-            Logger::unbanned($database, $ban, $unbanReason);
101
-
102
-            SessionAlert::quick('Disabled ban.');
103
-            $this->getNotificationHelper()->unbanned($ban, $unbanReason);
104
-
105
-            $this->redirect('bans');
106
-        }
107
-        else {
108
-            $this->assignCSRFToken();
109
-            $this->assign('ban', $ban);
110
-            $this->setTemplate('bans/unban.tpl');
111
-        }
112
-    }
113
-
114
-    /**
115
-     * @throws ApplicationLogicException
116
-     */
117
-    private function getBanDuration()
118
-    {
119
-        $duration = WebRequest::postString('duration');
120
-        if ($duration === "other") {
121
-            $duration = strtotime(WebRequest::postString('otherduration'));
122
-
123
-            if (!$duration) {
124
-                throw new ApplicationLogicException('Invalid ban time');
125
-            }
126
-            elseif (time() > $duration) {
127
-                throw new ApplicationLogicException('Ban time has already expired!');
128
-            }
129
-
130
-            return $duration;
131
-        }
132
-        elseif ($duration === "-1") {
133
-            return null;
134
-        }
135
-        else {
136
-            $duration = WebRequest::postInt('duration') + time();
137
-
138
-            return $duration;
139
-        }
140
-    }
141
-
142
-    /**
143
-     * @param string $type
144
-     * @param string $target
145
-     *
146
-     * @throws ApplicationLogicException
147
-     */
148
-    private function validateBanType($type, $target)
149
-    {
150
-        switch ($type) {
151
-            case 'IP':
152
-                $this->validateIpBan($target);
153
-
154
-                return;
155
-            case 'Name':
156
-                // No validation needed here.
157
-                return;
158
-            case 'EMail':
159
-                $this->validateEmailBanTarget($target);
160
-
161
-                return;
162
-            default:
163
-                throw new ApplicationLogicException("Unknown ban type");
164
-        }
165
-    }
166
-
167
-    /**
168
-     * Handles the POST method on the set action
169
-     *
170
-     * @throws ApplicationLogicException
171
-     * @throws Exception
172
-     */
173
-    private function handlePostMethodForSetBan()
174
-    {
175
-        $this->validateCSRFToken();
176
-        $reason = WebRequest::postString('banreason');
177
-        $target = WebRequest::postString('target');
178
-
179
-        // Checks whether there is a reason entered for ban.
180
-        if ($reason === null || trim($reason) === "") {
181
-            throw new ApplicationLogicException('You must specify a ban reason');
182
-        }
183
-
184
-        // Checks whether there is a target entered to ban.
185
-        if ($target === null || trim($target) === "") {
186
-            throw new ApplicationLogicException('You must specify a target to be banned');
187
-        }
188
-
189
-        // Validate ban duration
190
-        $duration = $this->getBanDuration();
191
-
192
-        // Validate ban type & target for that type
193
-        $type = WebRequest::postString('type');
194
-        $this->validateBanType($type, $target);
195
-
196
-        $database = $this->getDatabase();
197
-
198
-        if (count(Ban::getActiveBans($target, $database)) > 0) {
199
-            throw new ApplicationLogicException('This target is already banned!');
200
-        }
201
-
202
-        $ban = new Ban();
203
-        $ban->setDatabase($database);
204
-        $ban->setActive(true);
205
-        $ban->setType($type);
206
-        $ban->setTarget($target);
207
-        $ban->setUser(User::getCurrent($database)->getId());
208
-        $ban->setReason($reason);
209
-        $ban->setDuration($duration);
210
-
211
-        $ban->save();
212
-
213
-        Logger::banned($database, $ban, $reason);
214
-
215
-        $this->getNotificationHelper()->banned($ban);
216
-        SessionAlert::quick('Ban has been set.');
217
-
218
-        $this->redirect('bans');
219
-    }
220
-
221
-    /**
222
-     * Handles the GET method on the set action
223
-     */
224
-    protected function handleGetMethodForSetBan()
225
-    {
226
-        $this->setTemplate('bans/banform.tpl');
227
-        $this->assignCSRFToken();
228
-
229
-        $banType = WebRequest::getString('type');
230
-        $banTarget = WebRequest::getInt('request');
231
-
232
-        $database = $this->getDatabase();
233
-
234
-        // if the parameters are null, skip loading a request.
235
-        if ($banType === null
236
-            || !in_array($banType, array('IP', 'Name', 'EMail'))
237
-            || $banTarget === null
238
-            || $banTarget === 0
239
-        ) {
240
-            $this->assign('bantarget', '');
241
-            $this->assign('bantype', '');
242
-
243
-            return;
244
-        }
245
-
246
-        // Set the ban type, which the user has indicated.
247
-        $this->assign('bantype', $banType);
248
-
249
-        // Attempt to resolve the correct target
250
-        /** @var Request $request */
251
-        $request = Request::getById($banTarget, $database);
252
-        if ($request === false) {
253
-            $this->assign('bantarget', '');
254
-
255
-            return;
256
-        }
257
-
258
-        $realTarget = '';
259
-        switch ($banType) {
260
-            case 'EMail':
261
-                $realTarget = $request->getEmail();
262
-                break;
263
-            case 'IP':
264
-                $xffProvider = $this->getXffTrustProvider();
265
-                $realTarget = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
266
-                break;
267
-            case 'Name':
268
-                $realTarget = $request->getName();
269
-                break;
270
-        }
271
-
272
-        $this->assign('bantarget', $realTarget);
273
-    }
274
-
275
-    /**
276
-     * Validates an IP ban target
277
-     *
278
-     * @param string $target
279
-     *
280
-     * @throws ApplicationLogicException
281
-     */
282
-    private function validateIpBan($target)
283
-    {
284
-        $squidIpList = $this->getSiteConfiguration()->getSquidList();
285
-
286
-        if (filter_var($target, FILTER_VALIDATE_IP) === false) {
287
-            throw new ApplicationLogicException('Invalid target - IP address expected.');
288
-        }
289
-
290
-        if (in_array($target, $squidIpList)) {
291
-            throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
292
-        }
293
-    }
294
-
295
-    /**
296
-     * Validates an email address as a ban target
297
-     *
298
-     * @param string $target
299
-     *
300
-     * @throws ApplicationLogicException
301
-     */
302
-    private function validateEmailBanTarget($target)
303
-    {
304
-        if (filter_var($target, FILTER_VALIDATE_EMAIL) !== $target) {
305
-            throw new ApplicationLogicException('Invalid target - email address expected.');
306
-        }
307
-    }
308
-
309
-    /**
310
-     * @return Ban
311
-     * @throws ApplicationLogicException
312
-     */
313
-    private function getBanForUnban()
314
-    {
315
-        $banId = WebRequest::getInt('id');
316
-        if ($banId === null || $banId === 0) {
317
-            throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
318
-        }
319
-
320
-        $ban = Ban::getActiveId($banId, $this->getDatabase());
321
-
322
-        if ($ban === false) {
323
-            throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
324
-        }
325
-
326
-        return $ban;
327
-    }
24
+	/**
25
+	 * Main function for this page, when no specific actions are called.
26
+	 */
27
+	protected function main()
28
+	{
29
+		$this->assignCSRFToken();
30
+
31
+		$this->setHtmlTitle('Bans');
32
+
33
+		$bans = Ban::getActiveBans(null, $this->getDatabase());
34
+
35
+		$userIds = array_map(
36
+			function(Ban $entry) {
37
+				return $entry->getUser();
38
+			},
39
+			$bans);
40
+		$userList = UserSearchHelper::get($this->getDatabase())->inIds($userIds)->fetchMap('username');
41
+
42
+		$user = User::getCurrent($this->getDatabase());
43
+		$this->assign('canSet', $this->barrierTest('set', $user));
44
+		$this->assign('canRemove', $this->barrierTest('remove', $user));
45
+
46
+		$this->assign('usernames', $userList);
47
+		$this->assign('activebans', $bans);
48
+		$this->setTemplate('bans/banlist.tpl');
49
+	}
50
+
51
+	/**
52
+	 * Entry point for the ban set action
53
+	 */
54
+	protected function set()
55
+	{
56
+		$this->setHtmlTitle('Bans');
57
+
58
+		// dual-mode action
59
+		if (WebRequest::wasPosted()) {
60
+			try {
61
+				$this->handlePostMethodForSetBan();
62
+			}
63
+			catch (ApplicationLogicException $ex) {
64
+				SessionAlert::error($ex->getMessage());
65
+				$this->redirect("bans", "set");
66
+			}
67
+		}
68
+		else {
69
+			$this->handleGetMethodForSetBan();
70
+		}
71
+	}
72
+
73
+	/**
74
+	 * Entry point for the ban remove action
75
+	 */
76
+	protected function remove()
77
+	{
78
+		$this->setHtmlTitle('Bans');
79
+
80
+		$ban = $this->getBanForUnban();
81
+
82
+		// dual mode
83
+		if (WebRequest::wasPosted()) {
84
+			$this->validateCSRFToken();
85
+			$unbanReason = WebRequest::postString('unbanreason');
86
+
87
+			if ($unbanReason === null || trim($unbanReason) === "") {
88
+				SessionAlert::error('No unban reason specified');
89
+				$this->redirect("bans", "remove", array('id' => $ban->getId()));
90
+			}
91
+
92
+			// set optimistic locking from delete form page load
93
+			$updateVersion = WebRequest::postInt('updateversion');
94
+			$ban->setUpdateVersion($updateVersion);
95
+
96
+			$database = $this->getDatabase();
97
+			$ban->setActive(false);
98
+			$ban->save();
99
+
100
+			Logger::unbanned($database, $ban, $unbanReason);
101
+
102
+			SessionAlert::quick('Disabled ban.');
103
+			$this->getNotificationHelper()->unbanned($ban, $unbanReason);
104
+
105
+			$this->redirect('bans');
106
+		}
107
+		else {
108
+			$this->assignCSRFToken();
109
+			$this->assign('ban', $ban);
110
+			$this->setTemplate('bans/unban.tpl');
111
+		}
112
+	}
113
+
114
+	/**
115
+	 * @throws ApplicationLogicException
116
+	 */
117
+	private function getBanDuration()
118
+	{
119
+		$duration = WebRequest::postString('duration');
120
+		if ($duration === "other") {
121
+			$duration = strtotime(WebRequest::postString('otherduration'));
122
+
123
+			if (!$duration) {
124
+				throw new ApplicationLogicException('Invalid ban time');
125
+			}
126
+			elseif (time() > $duration) {
127
+				throw new ApplicationLogicException('Ban time has already expired!');
128
+			}
129
+
130
+			return $duration;
131
+		}
132
+		elseif ($duration === "-1") {
133
+			return null;
134
+		}
135
+		else {
136
+			$duration = WebRequest::postInt('duration') + time();
137
+
138
+			return $duration;
139
+		}
140
+	}
141
+
142
+	/**
143
+	 * @param string $type
144
+	 * @param string $target
145
+	 *
146
+	 * @throws ApplicationLogicException
147
+	 */
148
+	private function validateBanType($type, $target)
149
+	{
150
+		switch ($type) {
151
+			case 'IP':
152
+				$this->validateIpBan($target);
153
+
154
+				return;
155
+			case 'Name':
156
+				// No validation needed here.
157
+				return;
158
+			case 'EMail':
159
+				$this->validateEmailBanTarget($target);
160
+
161
+				return;
162
+			default:
163
+				throw new ApplicationLogicException("Unknown ban type");
164
+		}
165
+	}
166
+
167
+	/**
168
+	 * Handles the POST method on the set action
169
+	 *
170
+	 * @throws ApplicationLogicException
171
+	 * @throws Exception
172
+	 */
173
+	private function handlePostMethodForSetBan()
174
+	{
175
+		$this->validateCSRFToken();
176
+		$reason = WebRequest::postString('banreason');
177
+		$target = WebRequest::postString('target');
178
+
179
+		// Checks whether there is a reason entered for ban.
180
+		if ($reason === null || trim($reason) === "") {
181
+			throw new ApplicationLogicException('You must specify a ban reason');
182
+		}
183
+
184
+		// Checks whether there is a target entered to ban.
185
+		if ($target === null || trim($target) === "") {
186
+			throw new ApplicationLogicException('You must specify a target to be banned');
187
+		}
188
+
189
+		// Validate ban duration
190
+		$duration = $this->getBanDuration();
191
+
192
+		// Validate ban type & target for that type
193
+		$type = WebRequest::postString('type');
194
+		$this->validateBanType($type, $target);
195
+
196
+		$database = $this->getDatabase();
197
+
198
+		if (count(Ban::getActiveBans($target, $database)) > 0) {
199
+			throw new ApplicationLogicException('This target is already banned!');
200
+		}
201
+
202
+		$ban = new Ban();
203
+		$ban->setDatabase($database);
204
+		$ban->setActive(true);
205
+		$ban->setType($type);
206
+		$ban->setTarget($target);
207
+		$ban->setUser(User::getCurrent($database)->getId());
208
+		$ban->setReason($reason);
209
+		$ban->setDuration($duration);
210
+
211
+		$ban->save();
212
+
213
+		Logger::banned($database, $ban, $reason);
214
+
215
+		$this->getNotificationHelper()->banned($ban);
216
+		SessionAlert::quick('Ban has been set.');
217
+
218
+		$this->redirect('bans');
219
+	}
220
+
221
+	/**
222
+	 * Handles the GET method on the set action
223
+	 */
224
+	protected function handleGetMethodForSetBan()
225
+	{
226
+		$this->setTemplate('bans/banform.tpl');
227
+		$this->assignCSRFToken();
228
+
229
+		$banType = WebRequest::getString('type');
230
+		$banTarget = WebRequest::getInt('request');
231
+
232
+		$database = $this->getDatabase();
233
+
234
+		// if the parameters are null, skip loading a request.
235
+		if ($banType === null
236
+			|| !in_array($banType, array('IP', 'Name', 'EMail'))
237
+			|| $banTarget === null
238
+			|| $banTarget === 0
239
+		) {
240
+			$this->assign('bantarget', '');
241
+			$this->assign('bantype', '');
242
+
243
+			return;
244
+		}
245
+
246
+		// Set the ban type, which the user has indicated.
247
+		$this->assign('bantype', $banType);
248
+
249
+		// Attempt to resolve the correct target
250
+		/** @var Request $request */
251
+		$request = Request::getById($banTarget, $database);
252
+		if ($request === false) {
253
+			$this->assign('bantarget', '');
254
+
255
+			return;
256
+		}
257
+
258
+		$realTarget = '';
259
+		switch ($banType) {
260
+			case 'EMail':
261
+				$realTarget = $request->getEmail();
262
+				break;
263
+			case 'IP':
264
+				$xffProvider = $this->getXffTrustProvider();
265
+				$realTarget = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
266
+				break;
267
+			case 'Name':
268
+				$realTarget = $request->getName();
269
+				break;
270
+		}
271
+
272
+		$this->assign('bantarget', $realTarget);
273
+	}
274
+
275
+	/**
276
+	 * Validates an IP ban target
277
+	 *
278
+	 * @param string $target
279
+	 *
280
+	 * @throws ApplicationLogicException
281
+	 */
282
+	private function validateIpBan($target)
283
+	{
284
+		$squidIpList = $this->getSiteConfiguration()->getSquidList();
285
+
286
+		if (filter_var($target, FILTER_VALIDATE_IP) === false) {
287
+			throw new ApplicationLogicException('Invalid target - IP address expected.');
288
+		}
289
+
290
+		if (in_array($target, $squidIpList)) {
291
+			throw new ApplicationLogicException("This IP address is on the protected list of proxies, and cannot be banned.");
292
+		}
293
+	}
294
+
295
+	/**
296
+	 * Validates an email address as a ban target
297
+	 *
298
+	 * @param string $target
299
+	 *
300
+	 * @throws ApplicationLogicException
301
+	 */
302
+	private function validateEmailBanTarget($target)
303
+	{
304
+		if (filter_var($target, FILTER_VALIDATE_EMAIL) !== $target) {
305
+			throw new ApplicationLogicException('Invalid target - email address expected.');
306
+		}
307
+	}
308
+
309
+	/**
310
+	 * @return Ban
311
+	 * @throws ApplicationLogicException
312
+	 */
313
+	private function getBanForUnban()
314
+	{
315
+		$banId = WebRequest::getInt('id');
316
+		if ($banId === null || $banId === 0) {
317
+			throw new ApplicationLogicException("The ban ID appears to be missing. This is probably a bug.");
318
+		}
319
+
320
+		$ban = Ban::getActiveId($banId, $this->getDatabase());
321
+
322
+		if ($ban === false) {
323
+			throw new ApplicationLogicException("The specified ban is not currently active, or doesn't exist.");
324
+		}
325
+
326
+		return $ban;
327
+	}
328 328
 }
Please login to merge, or discard this patch.
Braces   +7 added lines, -11 removed lines patch added patch discarded remove patch
@@ -33,7 +33,8 @@  discard block
 block discarded – undo
33 33
         $bans = Ban::getActiveBans(null, $this->getDatabase());
34 34
 
35 35
         $userIds = array_map(
36
-            function(Ban $entry) {
36
+            function(Ban $entry)
37
+            {
37 38
                 return $entry->getUser();
38 39
             },
39 40
             $bans);
@@ -64,8 +65,7 @@  discard block
 block discarded – undo
64 65
                 SessionAlert::error($ex->getMessage());
65 66
                 $this->redirect("bans", "set");
66 67
             }
67
-        }
68
-        else {
68
+        } else {
69 69
             $this->handleGetMethodForSetBan();
70 70
         }
71 71
     }
@@ -103,8 +103,7 @@  discard block
 block discarded – undo
103 103
             $this->getNotificationHelper()->unbanned($ban, $unbanReason);
104 104
 
105 105
             $this->redirect('bans');
106
-        }
107
-        else {
106
+        } else {
108 107
             $this->assignCSRFToken();
109 108
             $this->assign('ban', $ban);
110 109
             $this->setTemplate('bans/unban.tpl');
@@ -122,17 +121,14 @@  discard block
 block discarded – undo
122 121
 
123 122
             if (!$duration) {
124 123
                 throw new ApplicationLogicException('Invalid ban time');
125
-            }
126
-            elseif (time() > $duration) {
124
+            } elseif (time() > $duration) {
127 125
                 throw new ApplicationLogicException('Ban time has already expired!');
128 126
             }
129 127
 
130 128
             return $duration;
131
-        }
132
-        elseif ($duration === "-1") {
129
+        } elseif ($duration === "-1") {
133 130
             return null;
134
-        }
135
-        else {
131
+        } else {
136 132
             $duration = WebRequest::postInt('duration') + time();
137 133
 
138 134
             return $duration;
Please login to merge, or discard this patch.
includes/Pages/PageSearch.php 2 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -18,143 +18,143 @@
 block discarded – undo
18 18
 
19 19
 class PageSearch extends InternalPageBase
20 20
 {
21
-    use RequestListData;
22
-
23
-    /**
24
-     * Main function for this page, when no specific actions are called.
25
-     */
26
-    protected function main()
27
-    {
28
-        $this->setHtmlTitle('Search');
29
-
30
-        // Dual-mode page
31
-        if (WebRequest::wasPosted()) {
32
-            $searchType = WebRequest::postString('type');
33
-            $searchTerm = WebRequest::postString('term');
34
-
35
-            $validationError = "";
36
-            if (!$this->validateSearchParameters($searchType, $searchTerm, $validationError)) {
37
-                SessionAlert::error($validationError, "Search error");
38
-                $this->redirect("search");
39
-
40
-                return;
41
-            }
42
-
43
-            $results = array();
44
-
45
-            switch ($searchType) {
46
-                case 'name':
47
-                    $results = $this->getNameSearchResults($searchTerm);
48
-                    break;
49
-                case 'email':
50
-                    $results = $this->getEmailSearchResults($searchTerm);
51
-                    break;
52
-                case 'ip':
53
-                    $results = $this->getIpSearchResults($searchTerm);
54
-                    break;
55
-            }
56
-
57
-            // deal with results
58
-            $this->assign('requests', $this->prepareRequestData($results));
59
-            $this->assign('resultCount', count($results));
60
-            $this->assign('term', $searchTerm);
61
-            $this->assign('target', $searchType);
62
-
63
-            $this->assignCSRFToken();
64
-            $this->setTemplate('search/searchResult.tpl');
65
-        }
66
-        else {
67
-            $this->assignCSRFToken();
68
-            $this->setTemplate('search/searchForm.tpl');
69
-        }
70
-    }
71
-
72
-    /**
73
-     * Gets search results by name
74
-     *
75
-     * @param string $searchTerm
76
-     *
77
-     * @return Request[]
78
-     */
79
-    private function getNameSearchResults($searchTerm)
80
-    {
81
-        $padded = '%' . $searchTerm . '%';
82
-
83
-        /** @var Request[] $requests */
84
-        $requests = RequestSearchHelper::get($this->getDatabase())
85
-            ->byName($padded)
86
-            ->fetch();
87
-
88
-        return $requests;
89
-    }
90
-
91
-    /**
92
-     * Gets search results by email
93
-     *
94
-     * @param string $searchTerm
95
-     *
96
-     * @return Request[]
97
-     * @throws ApplicationLogicException
98
-     */
99
-    private function getEmailSearchResults($searchTerm)
100
-    {
101
-        if ($searchTerm === "@") {
102
-            throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
103
-        }
104
-
105
-        $padded = '%' . $searchTerm . '%';
106
-
107
-        /** @var Request[] $requests */
108
-        $requests = RequestSearchHelper::get($this->getDatabase())
109
-            ->byEmailAddress($padded)
110
-            ->excludingPurgedData($this->getSiteConfiguration())
111
-            ->fetch();
112
-
113
-        return $requests;
114
-    }
115
-
116
-    /**
117
-     * Gets search results by IP address or XFF IP address
118
-     *
119
-     * @param string $searchTerm
120
-     *
121
-     * @return Request[]
122
-     */
123
-    private function getIpSearchResults($searchTerm)
124
-    {
125
-        /** @var Request[] $requests */
126
-        $requests = RequestSearchHelper::get($this->getDatabase())
127
-            ->byIp($searchTerm)
128
-            ->excludingPurgedData($this->getSiteConfiguration())
129
-            ->fetch();
130
-
131
-        return $requests;
132
-    }
133
-
134
-    /**
135
-     * @param string $searchType
136
-     * @param string $searchTerm
137
-     *
138
-     * @param string $errorMessage
139
-     *
140
-     * @return bool true if parameters are valid
141
-     */
142
-    protected function validateSearchParameters($searchType, $searchTerm, &$errorMessage)
143
-    {
144
-        if (!in_array($searchType, array('name', 'email', 'ip'))) {
145
-            $errorMessage = 'Unknown search type';
146
-
147
-            return false;
148
-        }
149
-
150
-        if ($searchTerm === '%' || $searchTerm === '' || $searchTerm === null) {
151
-            $errorMessage = 'No search term specified entered';
152
-
153
-            return false;
154
-        }
155
-
156
-        $errorMessage = "";
157
-
158
-        return true;
159
-    }
21
+	use RequestListData;
22
+
23
+	/**
24
+	 * Main function for this page, when no specific actions are called.
25
+	 */
26
+	protected function main()
27
+	{
28
+		$this->setHtmlTitle('Search');
29
+
30
+		// Dual-mode page
31
+		if (WebRequest::wasPosted()) {
32
+			$searchType = WebRequest::postString('type');
33
+			$searchTerm = WebRequest::postString('term');
34
+
35
+			$validationError = "";
36
+			if (!$this->validateSearchParameters($searchType, $searchTerm, $validationError)) {
37
+				SessionAlert::error($validationError, "Search error");
38
+				$this->redirect("search");
39
+
40
+				return;
41
+			}
42
+
43
+			$results = array();
44
+
45
+			switch ($searchType) {
46
+				case 'name':
47
+					$results = $this->getNameSearchResults($searchTerm);
48
+					break;
49
+				case 'email':
50
+					$results = $this->getEmailSearchResults($searchTerm);
51
+					break;
52
+				case 'ip':
53
+					$results = $this->getIpSearchResults($searchTerm);
54
+					break;
55
+			}
56
+
57
+			// deal with results
58
+			$this->assign('requests', $this->prepareRequestData($results));
59
+			$this->assign('resultCount', count($results));
60
+			$this->assign('term', $searchTerm);
61
+			$this->assign('target', $searchType);
62
+
63
+			$this->assignCSRFToken();
64
+			$this->setTemplate('search/searchResult.tpl');
65
+		}
66
+		else {
67
+			$this->assignCSRFToken();
68
+			$this->setTemplate('search/searchForm.tpl');
69
+		}
70
+	}
71
+
72
+	/**
73
+	 * Gets search results by name
74
+	 *
75
+	 * @param string $searchTerm
76
+	 *
77
+	 * @return Request[]
78
+	 */
79
+	private function getNameSearchResults($searchTerm)
80
+	{
81
+		$padded = '%' . $searchTerm . '%';
82
+
83
+		/** @var Request[] $requests */
84
+		$requests = RequestSearchHelper::get($this->getDatabase())
85
+			->byName($padded)
86
+			->fetch();
87
+
88
+		return $requests;
89
+	}
90
+
91
+	/**
92
+	 * Gets search results by email
93
+	 *
94
+	 * @param string $searchTerm
95
+	 *
96
+	 * @return Request[]
97
+	 * @throws ApplicationLogicException
98
+	 */
99
+	private function getEmailSearchResults($searchTerm)
100
+	{
101
+		if ($searchTerm === "@") {
102
+			throw new ApplicationLogicException('The search term "@" is not valid for email address searches!');
103
+		}
104
+
105
+		$padded = '%' . $searchTerm . '%';
106
+
107
+		/** @var Request[] $requests */
108
+		$requests = RequestSearchHelper::get($this->getDatabase())
109
+			->byEmailAddress($padded)
110
+			->excludingPurgedData($this->getSiteConfiguration())
111
+			->fetch();
112
+
113
+		return $requests;
114
+	}
115
+
116
+	/**
117
+	 * Gets search results by IP address or XFF IP address
118
+	 *
119
+	 * @param string $searchTerm
120
+	 *
121
+	 * @return Request[]
122
+	 */
123
+	private function getIpSearchResults($searchTerm)
124
+	{
125
+		/** @var Request[] $requests */
126
+		$requests = RequestSearchHelper::get($this->getDatabase())
127
+			->byIp($searchTerm)
128
+			->excludingPurgedData($this->getSiteConfiguration())
129
+			->fetch();
130
+
131
+		return $requests;
132
+	}
133
+
134
+	/**
135
+	 * @param string $searchType
136
+	 * @param string $searchTerm
137
+	 *
138
+	 * @param string $errorMessage
139
+	 *
140
+	 * @return bool true if parameters are valid
141
+	 */
142
+	protected function validateSearchParameters($searchType, $searchTerm, &$errorMessage)
143
+	{
144
+		if (!in_array($searchType, array('name', 'email', 'ip'))) {
145
+			$errorMessage = 'Unknown search type';
146
+
147
+			return false;
148
+		}
149
+
150
+		if ($searchTerm === '%' || $searchTerm === '' || $searchTerm === null) {
151
+			$errorMessage = 'No search term specified entered';
152
+
153
+			return false;
154
+		}
155
+
156
+		$errorMessage = "";
157
+
158
+		return true;
159
+	}
160 160
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -62,8 +62,7 @@
 block discarded – undo
62 62
 
63 63
             $this->assignCSRFToken();
64 64
             $this->setTemplate('search/searchResult.tpl');
65
-        }
66
-        else {
65
+        } else {
67 66
             $this->assignCSRFToken();
68 67
             $this->setTemplate('search/searchForm.tpl');
69 68
         }
Please login to merge, or discard this patch.
includes/Pages/PageMain.php 2 patches
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -20,54 +20,54 @@  discard block
 block discarded – undo
20 20
 
21 21
 class PageMain extends InternalPageBase
22 22
 {
23
-    use RequestListData;
24
-
25
-    /**
26
-     * Main function for this page, when no actions are called.
27
-     */
28
-    protected function main()
29
-    {
30
-        $this->assignCSRFToken();
31
-
32
-        $config = $this->getSiteConfiguration();
33
-        $database = $this->getDatabase();
34
-        $currentUser = User::getCurrent($database);
35
-
36
-        // general template configuration
37
-        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
38
-        $this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
39
-
40
-        $seeAllRequests = $this->barrierTest('seeAllRequests', $currentUser, PageViewRequest::class);
41
-
42
-        // Fetch request data
43
-        $requestSectionData = array();
44
-        if ($seeAllRequests) {
45
-            $this->setupStatusSections($database, $config, $requestSectionData);
46
-            $this->setupHospitalQueue($database, $config, $requestSectionData);
47
-            $this->setupJobQueue($database, $config, $requestSectionData);
48
-        }
49
-        $this->setupLastFiveClosedData($database, $seeAllRequests);
50
-
51
-        // Assign data to template
52
-        $this->assign('requestSectionData', $requestSectionData);
53
-
54
-        $this->setTemplate('mainpage/mainpage.tpl');
55
-    }
56
-
57
-    /**
58
-     * @param PdoDatabase $database
59
-     * @param bool        $seeAllRequests
60
-     *
61
-     * @internal param User $currentUser
62
-     */
63
-    private function setupLastFiveClosedData(PdoDatabase $database, $seeAllRequests)
64
-    {
65
-        $this->assign('showLastFive', $seeAllRequests);
66
-        if (!$seeAllRequests) {
67
-            return;
68
-        }
69
-
70
-        $query = <<<SQL
23
+	use RequestListData;
24
+
25
+	/**
26
+	 * Main function for this page, when no actions are called.
27
+	 */
28
+	protected function main()
29
+	{
30
+		$this->assignCSRFToken();
31
+
32
+		$config = $this->getSiteConfiguration();
33
+		$database = $this->getDatabase();
34
+		$currentUser = User::getCurrent($database);
35
+
36
+		// general template configuration
37
+		$this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
38
+		$this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
39
+
40
+		$seeAllRequests = $this->barrierTest('seeAllRequests', $currentUser, PageViewRequest::class);
41
+
42
+		// Fetch request data
43
+		$requestSectionData = array();
44
+		if ($seeAllRequests) {
45
+			$this->setupStatusSections($database, $config, $requestSectionData);
46
+			$this->setupHospitalQueue($database, $config, $requestSectionData);
47
+			$this->setupJobQueue($database, $config, $requestSectionData);
48
+		}
49
+		$this->setupLastFiveClosedData($database, $seeAllRequests);
50
+
51
+		// Assign data to template
52
+		$this->assign('requestSectionData', $requestSectionData);
53
+
54
+		$this->setTemplate('mainpage/mainpage.tpl');
55
+	}
56
+
57
+	/**
58
+	 * @param PdoDatabase $database
59
+	 * @param bool        $seeAllRequests
60
+	 *
61
+	 * @internal param User $currentUser
62
+	 */
63
+	private function setupLastFiveClosedData(PdoDatabase $database, $seeAllRequests)
64
+	{
65
+		$this->assign('showLastFive', $seeAllRequests);
66
+		if (!$seeAllRequests) {
67
+			return;
68
+		}
69
+
70
+		$query = <<<SQL
71 71
 		SELECT request.id, request.name, request.updateversion
72 72
 		FROM request /* PageMain::main() */
73 73
 		JOIN log ON log.objectid = request.id AND log.objecttype = 'Request'
@@ -76,113 +76,113 @@  discard block
 block discarded – undo
76 76
 		LIMIT 5;
77 77
 SQL;
78 78
 
79
-        $statement = $database->prepare($query);
80
-        $statement->execute();
81
-
82
-        $last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
83
-
84
-        $this->assign('lastFive', $last5result);
85
-    }
86
-
87
-    /**
88
-     * @param PdoDatabase       $database
89
-     * @param SiteConfiguration $config
90
-     * @param                   $requestSectionData
91
-     */
92
-    private function setupHospitalQueue(
93
-        PdoDatabase $database,
94
-        SiteConfiguration $config,
95
-        &$requestSectionData
96
-    ) {
97
-        $search = RequestSearchHelper::get($database)
98
-            ->limit($config->getMiserModeLimit())
99
-            ->excludingStatus('Closed')
100
-            ->isHospitalised();
101
-
102
-        if ($config->getEmailConfirmationEnabled()) {
103
-            $search->withConfirmedEmail();
104
-        }
105
-
106
-        /** @var Request[] $results */
107
-        $results = $search->getRecordCount($requestCount)->fetch();
108
-
109
-        if($requestCount > 0) {
110
-            $requestSectionData['Hospital - Requests failed auto-creation'] = array(
111
-                'requests' => $this->prepareRequestData($results),
112
-                'total'    => $requestCount,
113
-                'api'      => 'hospital',
114
-                'type'     => 'hospital',
115
-                'special'  => 'Job Queue',
116
-                'help'     => 'This queue lists all the requests which have been attempted to be created in the background, but for which this has failed for one reason or another. Check the job queue to find the error. Requests here may need to be created manually, or it may be possible to re-queue the request for auto-creation by the tool, or it may have been created already. Use your own technical discretion here.',
117
-                'showAll'  => false
118
-            );
119
-        }
120
-    }
121
-
122
-    /**
123
-     * @param PdoDatabase       $database
124
-     * @param SiteConfiguration $config
125
-     * @param                   $requestSectionData
126
-     */
127
-    private function setupJobQueue(
128
-        PdoDatabase $database,
129
-        SiteConfiguration $config,
130
-        &$requestSectionData
131
-    ) {
132
-        $search = RequestSearchHelper::get($database)
133
-            ->limit($config->getMiserModeLimit())
134
-            ->byStatus(RequestStatus::JOBQUEUE);
135
-
136
-        if ($config->getEmailConfirmationEnabled()) {
137
-            $search->withConfirmedEmail();
138
-        }
139
-
140
-        /** @var Request[] $results */
141
-        $results = $search->getRecordCount($requestCount)->fetch();
142
-
143
-        if($requestCount > 0) {
144
-            $requestSectionData['Requests queued in the Job Queue'] = array(
145
-                'requests' => $this->prepareRequestData($results),
146
-                'total'    => $requestCount,
147
-                'api'      => 'JobQueue',
148
-                'type'     => 'JobQueue',
149
-                'special'  => 'Job Queue',
150
-                'help'     => 'This section lists all the requests which are currently waiting to be created by the tool. Requests should automatically disappear from here within a few minutes.',
151
-                'showAll'  => false
152
-            );
153
-        }
154
-    }
155
-
156
-    /**
157
-     * @param PdoDatabase       $database
158
-     * @param SiteConfiguration $config
159
-     * @param                   $requestSectionData
160
-     */
161
-    private function setupStatusSections(
162
-        PdoDatabase $database,
163
-        SiteConfiguration $config,
164
-        &$requestSectionData
165
-    ) {
166
-        $search = RequestSearchHelper::get($database)->limit($config->getMiserModeLimit())->notHospitalised();
167
-
168
-        if ($config->getEmailConfirmationEnabled()) {
169
-            $search->withConfirmedEmail();
170
-        }
171
-
172
-        $allRequestStates = $config->getRequestStates();
173
-        $requestsByStatus = $search->fetchByStatus(array_keys($allRequestStates));
174
-
175
-        foreach ($allRequestStates as $requestState => $requestStateConfig) {
176
-
177
-            $requestSectionData[$requestStateConfig['header']] = array(
178
-                'requests' => $this->prepareRequestData($requestsByStatus[$requestState]['data']),
179
-                'total'    => $requestsByStatus[$requestState]['count'],
180
-                'api'      => $requestStateConfig['api'],
181
-                'type'     => $requestState,
182
-                'special'  => null,
183
-                'help'     => $requestStateConfig['queuehelp'],
184
-                'showAll'  => true
185
-            );
186
-        }
187
-    }
79
+		$statement = $database->prepare($query);
80
+		$statement->execute();
81
+
82
+		$last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
83
+
84
+		$this->assign('lastFive', $last5result);
85
+	}
86
+
87
+	/**
88
+	 * @param PdoDatabase       $database
89
+	 * @param SiteConfiguration $config
90
+	 * @param                   $requestSectionData
91
+	 */
92
+	private function setupHospitalQueue(
93
+		PdoDatabase $database,
94
+		SiteConfiguration $config,
95
+		&$requestSectionData
96
+	) {
97
+		$search = RequestSearchHelper::get($database)
98
+			->limit($config->getMiserModeLimit())
99
+			->excludingStatus('Closed')
100
+			->isHospitalised();
101
+
102
+		if ($config->getEmailConfirmationEnabled()) {
103
+			$search->withConfirmedEmail();
104
+		}
105
+
106
+		/** @var Request[] $results */
107
+		$results = $search->getRecordCount($requestCount)->fetch();
108
+
109
+		if($requestCount > 0) {
110
+			$requestSectionData['Hospital - Requests failed auto-creation'] = array(
111
+				'requests' => $this->prepareRequestData($results),
112
+				'total'    => $requestCount,
113
+				'api'      => 'hospital',
114
+				'type'     => 'hospital',
115
+				'special'  => 'Job Queue',
116
+				'help'     => 'This queue lists all the requests which have been attempted to be created in the background, but for which this has failed for one reason or another. Check the job queue to find the error. Requests here may need to be created manually, or it may be possible to re-queue the request for auto-creation by the tool, or it may have been created already. Use your own technical discretion here.',
117
+				'showAll'  => false
118
+			);
119
+		}
120
+	}
121
+
122
+	/**
123
+	 * @param PdoDatabase       $database
124
+	 * @param SiteConfiguration $config
125
+	 * @param                   $requestSectionData
126
+	 */
127
+	private function setupJobQueue(
128
+		PdoDatabase $database,
129
+		SiteConfiguration $config,
130
+		&$requestSectionData
131
+	) {
132
+		$search = RequestSearchHelper::get($database)
133
+			->limit($config->getMiserModeLimit())
134
+			->byStatus(RequestStatus::JOBQUEUE);
135
+
136
+		if ($config->getEmailConfirmationEnabled()) {
137
+			$search->withConfirmedEmail();
138
+		}
139
+
140
+		/** @var Request[] $results */
141
+		$results = $search->getRecordCount($requestCount)->fetch();
142
+
143
+		if($requestCount > 0) {
144
+			$requestSectionData['Requests queued in the Job Queue'] = array(
145
+				'requests' => $this->prepareRequestData($results),
146
+				'total'    => $requestCount,
147
+				'api'      => 'JobQueue',
148
+				'type'     => 'JobQueue',
149
+				'special'  => 'Job Queue',
150
+				'help'     => 'This section lists all the requests which are currently waiting to be created by the tool. Requests should automatically disappear from here within a few minutes.',
151
+				'showAll'  => false
152
+			);
153
+		}
154
+	}
155
+
156
+	/**
157
+	 * @param PdoDatabase       $database
158
+	 * @param SiteConfiguration $config
159
+	 * @param                   $requestSectionData
160
+	 */
161
+	private function setupStatusSections(
162
+		PdoDatabase $database,
163
+		SiteConfiguration $config,
164
+		&$requestSectionData
165
+	) {
166
+		$search = RequestSearchHelper::get($database)->limit($config->getMiserModeLimit())->notHospitalised();
167
+
168
+		if ($config->getEmailConfirmationEnabled()) {
169
+			$search->withConfirmedEmail();
170
+		}
171
+
172
+		$allRequestStates = $config->getRequestStates();
173
+		$requestsByStatus = $search->fetchByStatus(array_keys($allRequestStates));
174
+
175
+		foreach ($allRequestStates as $requestState => $requestStateConfig) {
176
+
177
+			$requestSectionData[$requestStateConfig['header']] = array(
178
+				'requests' => $this->prepareRequestData($requestsByStatus[$requestState]['data']),
179
+				'total'    => $requestsByStatus[$requestState]['count'],
180
+				'api'      => $requestStateConfig['api'],
181
+				'type'     => $requestState,
182
+				'special'  => null,
183
+				'help'     => $requestStateConfig['queuehelp'],
184
+				'showAll'  => true
185
+			);
186
+		}
187
+	}
188 188
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
         /** @var Request[] $results */
107 107
         $results = $search->getRecordCount($requestCount)->fetch();
108 108
 
109
-        if($requestCount > 0) {
109
+        if ($requestCount > 0) {
110 110
             $requestSectionData['Hospital - Requests failed auto-creation'] = array(
111 111
                 'requests' => $this->prepareRequestData($results),
112 112
                 'total'    => $requestCount,
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
         /** @var Request[] $results */
141 141
         $results = $search->getRecordCount($requestCount)->fetch();
142 142
 
143
-        if($requestCount > 0) {
143
+        if ($requestCount > 0) {
144 144
             $requestSectionData['Requests queued in the Job Queue'] = array(
145 145
                 'requests' => $this->prepareRequestData($results),
146 146
                 'total'    => $requestCount,
Please login to merge, or discard this patch.