Completed
Push — bootstrap4 ( c24853...dc7ca1 )
by Simon
06:16
created
includes/Pages/RequestAction/PageCloseRequest.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -239,11 +239,11 @@
 block discarded – undo
239 239
 
240 240
         $emailSig = $currentUser->getEmailSig();
241 241
         if ($emailSig !== '' || $emailSig !== null) {
242
-            $emailSig = "\n\n" . $emailSig;
242
+            $emailSig = "\n\n".$emailSig;
243 243
         }
244 244
 
245 245
         $subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
246
-        $content = $mailText . $emailSig;
246
+        $content = $mailText.$emailSig;
247 247
 
248 248
         $helper->sendMail($request->getEmail(), $subject, $content, $headers);
249 249
 
Please login to merge, or discard this patch.
Indentation   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -20,242 +20,242 @@
 block discarded – undo
20 20
 
21 21
 class PageCloseRequest extends RequestActionBase
22 22
 {
23
-    protected function main()
24
-    {
25
-        $this->processClose();
26
-    }
27
-
28
-    /**
29
-     * Main function for this page, when no specific actions are called.
30
-     * @throws ApplicationLogicException
31
-     */
32
-    final protected function processClose()
33
-    {
34
-        $this->checkPosted();
35
-        $database = $this->getDatabase();
36
-
37
-        $currentUser = User::getCurrent($database);
38
-        $template = $this->getTemplate($database);
39
-        $request = $this->getRequest($database);
40
-        $request->setUpdateVersion(WebRequest::postInt('updateversion'));
41
-
42
-        if ($request->getStatus() === 'Closed') {
43
-            throw new ApplicationLogicException('Request is already closed');
44
-        }
45
-
46
-        if ($this->confirmEmailAlreadySent($request, $template)) {
47
-            return;
48
-        }
49
-
50
-        if ($this->confirmReserveOverride($request, $template, $currentUser, $database)) {
51
-            return;
52
-        }
53
-
54
-        if ($this->confirmAccountCreated($request, $template)) {
55
-            return;
56
-        }
57
-
58
-        // I think we're good here...
59
-        $request->setStatus('Closed');
60
-        $request->setReserved(null);
61
-
62
-        Logger::closeRequest($database, $request, $template->getId(), null);
63
-
64
-        $request->save();
65
-
66
-        // Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
67
-        // be rolled back.
68
-
69
-        $this->getNotificationHelper()->requestClosed($request, $template->getName());
70
-        SessionAlert::success("Request {$request->getId()} has been closed");
71
-
72
-        $this->sendMail($request, $template->getText(), $currentUser, false);
73
-
74
-        $this->redirect();
75
-    }
76
-
77
-    /**
78
-     * @param PdoDatabase $database
79
-     *
80
-     * @return EmailTemplate
81
-     * @throws ApplicationLogicException
82
-     */
83
-    protected function getTemplate(PdoDatabase $database)
84
-    {
85
-        $templateId = WebRequest::postInt('template');
86
-        if ($templateId === null) {
87
-            throw new ApplicationLogicException('No template specified');
88
-        }
89
-
90
-        /** @var EmailTemplate $template */
91
-        $template = EmailTemplate::getById($templateId, $database);
92
-        if ($template === false || !$template->getActive()) {
93
-            throw new ApplicationLogicException('Invalid or inactive template specified');
94
-        }
95
-
96
-        return $template;
97
-    }
98
-
99
-    /**
100
-     * @param Request       $request
101
-     * @param EmailTemplate $template
102
-     *
103
-     * @return bool
104
-     */
105
-    protected function confirmEmailAlreadySent(Request $request, EmailTemplate $template)
106
-    {
107
-        if ($this->checkEmailAlreadySent($request)) {
108
-            $this->showConfirmation($request, $template, 'close-confirmations/email-sent.tpl');
109
-
110
-            return true;
111
-        }
112
-
113
-        return false;
114
-    }
115
-
116
-    protected function checkEmailAlreadySent(Request $request)
117
-    {
118
-        if ($request->getEmailSent() && !WebRequest::postBoolean('emailSentOverride')) {
119
-            return true;
120
-        }
121
-
122
-        return false;
123
-    }
124
-
125
-    protected function checkReserveOverride(Request $request, User $currentUser)
126
-    {
127
-        $reservationId = $request->getReserved();
128
-
129
-        if ($reservationId !== 0 && $reservationId !== null) {
130
-            if (!WebRequest::postBoolean('reserveOverride')) {
131
-                if ($currentUser->getId() !== $reservationId) {
132
-                    return true;
133
-                }
134
-            }
135
-        }
136
-
137
-        return false;
138
-    }
139
-
140
-    /**
141
-     * @param Request       $request
142
-     * @param EmailTemplate $template
143
-     * @param User          $currentUser
144
-     * @param PdoDatabase   $database
145
-     *
146
-     * @return bool
147
-     */
148
-    protected function confirmReserveOverride(
149
-        Request $request,
150
-        EmailTemplate $template,
151
-        User $currentUser,
152
-        PdoDatabase $database
153
-    ) {
154
-        if ($this->checkReserveOverride($request, $currentUser)) {
155
-            $this->assign('reserveUser', User::getById($request->getReserved(), $database)->getUsername());
156
-            $this->showConfirmation($request, $template, 'close-confirmations/reserve-override.tpl');
157
-
158
-            return true;
159
-        }
160
-
161
-        return false;
162
-    }
163
-
164
-    /**
165
-     * @param Request       $request
166
-     * @param EmailTemplate $template
167
-     *
168
-     * @return bool
169
-     * @throws \Waca\Exceptions\CurlException
170
-     */
171
-    protected function confirmAccountCreated(Request $request, EmailTemplate $template)
172
-    {
173
-        if ($this->checkAccountCreated($request, $template)) {
174
-            $this->showConfirmation($request, $template, 'close-confirmations/account-created.tpl');
175
-
176
-            return true;
177
-        }
178
-
179
-        return false;
180
-    }
181
-
182
-    protected function checkAccountCreated(Request $request, EmailTemplate $template)
183
-    {
184
-        if ($template->getDefaultAction() === EmailTemplate::CREATED && !WebRequest::postBoolean('createOverride')) {
185
-            $parameters = array(
186
-                'action'  => 'query',
187
-                'list'    => 'users',
188
-                'format'  => 'php',
189
-                'ususers' => $request->getName(),
190
-            );
191
-
192
-            $content = $this->getHttpHelper()->get($this->getSiteConfiguration()->getMediawikiWebServiceEndpoint(),
193
-                $parameters);
194
-
195
-            $apiResult = unserialize($content);
196
-            $exists = !isset($apiResult['query']['users']['0']['missing']);
197
-
198
-            if (!$exists) {
199
-                return true;
200
-            }
201
-        }
202
-
203
-        return false;
204
-    }
205
-
206
-    /**
207
-     * @param Request $request
208
-     * @param string  $mailText
209
-     * @param User    $currentUser
210
-     * @param boolean $ccMailingList
211
-     */
212
-    protected function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
213
-    {
214
-        $headers = array(
215
-            'X-ACC-Request' => $request->getId(),
216
-            'X-ACC-UserID'  => $currentUser->getId(),
217
-        );
218
-
219
-        if ($ccMailingList) {
220
-            $headers['Cc'] = '[email protected]';
221
-        }
222
-
223
-        $helper = $this->getEmailHelper();
224
-
225
-        $emailSig = $currentUser->getEmailSig();
226
-        if ($emailSig !== '' || $emailSig !== null) {
227
-            $emailSig = "\n\n" . $emailSig;
228
-        }
229
-
230
-        $subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
231
-        $content = $mailText . $emailSig;
232
-
233
-        $helper->sendMail($request->getEmail(), $subject, $content, $headers);
234
-
235
-        $request->setEmailSent(true);
236
-    }
237
-
238
-    /**
239
-     * @param Request       $request
240
-     * @param EmailTemplate $template
241
-     * @param string        $templateName
242
-     *
243
-     * @throws Exception
244
-     * @return void
245
-     */
246
-    protected function showConfirmation(Request $request, EmailTemplate $template, $templateName)
247
-    {
248
-        $this->assignCSRFToken();
249
-
250
-        $this->assign('request', $request->getId());
251
-        $this->assign('template', $template->getId());
252
-
253
-        $this->assign('updateversion', $request->getUpdateVersion());
254
-
255
-        $this->assign('emailSentOverride', WebRequest::postBoolean('emailSentOverride') ? 'true' : 'false');
256
-        $this->assign('reserveOverride', WebRequest::postBoolean('reserveOverride') ? 'true' : 'false');
257
-        $this->assign('createOverride', WebRequest::postBoolean('createOverride') ? 'true' : 'false');
258
-
259
-        $this->setTemplate($templateName);
260
-    }
23
+	protected function main()
24
+	{
25
+		$this->processClose();
26
+	}
27
+
28
+	/**
29
+	 * Main function for this page, when no specific actions are called.
30
+	 * @throws ApplicationLogicException
31
+	 */
32
+	final protected function processClose()
33
+	{
34
+		$this->checkPosted();
35
+		$database = $this->getDatabase();
36
+
37
+		$currentUser = User::getCurrent($database);
38
+		$template = $this->getTemplate($database);
39
+		$request = $this->getRequest($database);
40
+		$request->setUpdateVersion(WebRequest::postInt('updateversion'));
41
+
42
+		if ($request->getStatus() === 'Closed') {
43
+			throw new ApplicationLogicException('Request is already closed');
44
+		}
45
+
46
+		if ($this->confirmEmailAlreadySent($request, $template)) {
47
+			return;
48
+		}
49
+
50
+		if ($this->confirmReserveOverride($request, $template, $currentUser, $database)) {
51
+			return;
52
+		}
53
+
54
+		if ($this->confirmAccountCreated($request, $template)) {
55
+			return;
56
+		}
57
+
58
+		// I think we're good here...
59
+		$request->setStatus('Closed');
60
+		$request->setReserved(null);
61
+
62
+		Logger::closeRequest($database, $request, $template->getId(), null);
63
+
64
+		$request->save();
65
+
66
+		// Perform the notifications and stuff *after* we've successfully saved, since the save can throw an OLE and
67
+		// be rolled back.
68
+
69
+		$this->getNotificationHelper()->requestClosed($request, $template->getName());
70
+		SessionAlert::success("Request {$request->getId()} has been closed");
71
+
72
+		$this->sendMail($request, $template->getText(), $currentUser, false);
73
+
74
+		$this->redirect();
75
+	}
76
+
77
+	/**
78
+	 * @param PdoDatabase $database
79
+	 *
80
+	 * @return EmailTemplate
81
+	 * @throws ApplicationLogicException
82
+	 */
83
+	protected function getTemplate(PdoDatabase $database)
84
+	{
85
+		$templateId = WebRequest::postInt('template');
86
+		if ($templateId === null) {
87
+			throw new ApplicationLogicException('No template specified');
88
+		}
89
+
90
+		/** @var EmailTemplate $template */
91
+		$template = EmailTemplate::getById($templateId, $database);
92
+		if ($template === false || !$template->getActive()) {
93
+			throw new ApplicationLogicException('Invalid or inactive template specified');
94
+		}
95
+
96
+		return $template;
97
+	}
98
+
99
+	/**
100
+	 * @param Request       $request
101
+	 * @param EmailTemplate $template
102
+	 *
103
+	 * @return bool
104
+	 */
105
+	protected function confirmEmailAlreadySent(Request $request, EmailTemplate $template)
106
+	{
107
+		if ($this->checkEmailAlreadySent($request)) {
108
+			$this->showConfirmation($request, $template, 'close-confirmations/email-sent.tpl');
109
+
110
+			return true;
111
+		}
112
+
113
+		return false;
114
+	}
115
+
116
+	protected function checkEmailAlreadySent(Request $request)
117
+	{
118
+		if ($request->getEmailSent() && !WebRequest::postBoolean('emailSentOverride')) {
119
+			return true;
120
+		}
121
+
122
+		return false;
123
+	}
124
+
125
+	protected function checkReserveOverride(Request $request, User $currentUser)
126
+	{
127
+		$reservationId = $request->getReserved();
128
+
129
+		if ($reservationId !== 0 && $reservationId !== null) {
130
+			if (!WebRequest::postBoolean('reserveOverride')) {
131
+				if ($currentUser->getId() !== $reservationId) {
132
+					return true;
133
+				}
134
+			}
135
+		}
136
+
137
+		return false;
138
+	}
139
+
140
+	/**
141
+	 * @param Request       $request
142
+	 * @param EmailTemplate $template
143
+	 * @param User          $currentUser
144
+	 * @param PdoDatabase   $database
145
+	 *
146
+	 * @return bool
147
+	 */
148
+	protected function confirmReserveOverride(
149
+		Request $request,
150
+		EmailTemplate $template,
151
+		User $currentUser,
152
+		PdoDatabase $database
153
+	) {
154
+		if ($this->checkReserveOverride($request, $currentUser)) {
155
+			$this->assign('reserveUser', User::getById($request->getReserved(), $database)->getUsername());
156
+			$this->showConfirmation($request, $template, 'close-confirmations/reserve-override.tpl');
157
+
158
+			return true;
159
+		}
160
+
161
+		return false;
162
+	}
163
+
164
+	/**
165
+	 * @param Request       $request
166
+	 * @param EmailTemplate $template
167
+	 *
168
+	 * @return bool
169
+	 * @throws \Waca\Exceptions\CurlException
170
+	 */
171
+	protected function confirmAccountCreated(Request $request, EmailTemplate $template)
172
+	{
173
+		if ($this->checkAccountCreated($request, $template)) {
174
+			$this->showConfirmation($request, $template, 'close-confirmations/account-created.tpl');
175
+
176
+			return true;
177
+		}
178
+
179
+		return false;
180
+	}
181
+
182
+	protected function checkAccountCreated(Request $request, EmailTemplate $template)
183
+	{
184
+		if ($template->getDefaultAction() === EmailTemplate::CREATED && !WebRequest::postBoolean('createOverride')) {
185
+			$parameters = array(
186
+				'action'  => 'query',
187
+				'list'    => 'users',
188
+				'format'  => 'php',
189
+				'ususers' => $request->getName(),
190
+			);
191
+
192
+			$content = $this->getHttpHelper()->get($this->getSiteConfiguration()->getMediawikiWebServiceEndpoint(),
193
+				$parameters);
194
+
195
+			$apiResult = unserialize($content);
196
+			$exists = !isset($apiResult['query']['users']['0']['missing']);
197
+
198
+			if (!$exists) {
199
+				return true;
200
+			}
201
+		}
202
+
203
+		return false;
204
+	}
205
+
206
+	/**
207
+	 * @param Request $request
208
+	 * @param string  $mailText
209
+	 * @param User    $currentUser
210
+	 * @param boolean $ccMailingList
211
+	 */
212
+	protected function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
213
+	{
214
+		$headers = array(
215
+			'X-ACC-Request' => $request->getId(),
216
+			'X-ACC-UserID'  => $currentUser->getId(),
217
+		);
218
+
219
+		if ($ccMailingList) {
220
+			$headers['Cc'] = '[email protected]';
221
+		}
222
+
223
+		$helper = $this->getEmailHelper();
224
+
225
+		$emailSig = $currentUser->getEmailSig();
226
+		if ($emailSig !== '' || $emailSig !== null) {
227
+			$emailSig = "\n\n" . $emailSig;
228
+		}
229
+
230
+		$subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
231
+		$content = $mailText . $emailSig;
232
+
233
+		$helper->sendMail($request->getEmail(), $subject, $content, $headers);
234
+
235
+		$request->setEmailSent(true);
236
+	}
237
+
238
+	/**
239
+	 * @param Request       $request
240
+	 * @param EmailTemplate $template
241
+	 * @param string        $templateName
242
+	 *
243
+	 * @throws Exception
244
+	 * @return void
245
+	 */
246
+	protected function showConfirmation(Request $request, EmailTemplate $template, $templateName)
247
+	{
248
+		$this->assignCSRFToken();
249
+
250
+		$this->assign('request', $request->getId());
251
+		$this->assign('template', $template->getId());
252
+
253
+		$this->assign('updateversion', $request->getUpdateVersion());
254
+
255
+		$this->assign('emailSentOverride', WebRequest::postBoolean('emailSentOverride') ? 'true' : 'false');
256
+		$this->assign('reserveOverride', WebRequest::postBoolean('reserveOverride') ? 'true' : 'false');
257
+		$this->assign('createOverride', WebRequest::postBoolean('createOverride') ? 'true' : 'false');
258
+
259
+		$this->setTemplate($templateName);
260
+	}
261 261
 }
Please login to merge, or discard this patch.
includes/Pages/RequestAction/PageComment.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -48,8 +48,8 @@
 block discarded – undo
48 48
         }
49 49
 
50 50
         //Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
51
-        $ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
52
-        $ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
51
+        $ipv4Regex = '/\b'.RegexConstants::IPV4.'\b/';
52
+        $ipv6Regex = '/\b'.RegexConstants::IPV6.'\b/';
53 53
 
54 54
         $overridePolicy = WebRequest::postBoolean('privpol-check-override');
55 55
 
Please login to merge, or discard this patch.
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -15,51 +15,51 @@
 block discarded – undo
15 15
 
16 16
 class PageComment extends RequestActionBase
17 17
 {
18
-    /**
19
-     * Main function for this page, when no specific actions are called.
20
-     * @return void
21
-     */
22
-    protected function main()
23
-    {
24
-        $this->checkPosted();
25
-        $database = $this->getDatabase();
26
-        $request = $this->getRequest($database);
18
+	/**
19
+	 * Main function for this page, when no specific actions are called.
20
+	 * @return void
21
+	 */
22
+	protected function main()
23
+	{
24
+		$this->checkPosted();
25
+		$database = $this->getDatabase();
26
+		$request = $this->getRequest($database);
27 27
 
28
-        $commentText = WebRequest::postString('comment');
29
-        if ($commentText === false || $commentText == '') {
30
-            $this->redirect('viewRequest', null, array('id' => $request->getId()));
28
+		$commentText = WebRequest::postString('comment');
29
+		if ($commentText === false || $commentText == '') {
30
+			$this->redirect('viewRequest', null, array('id' => $request->getId()));
31 31
 
32
-            return;
33
-        }
32
+			return;
33
+		}
34 34
 
35
-        //Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
36
-        $ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
37
-        $ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
35
+		//Look for and detect IPv4/IPv6 addresses in comment text, and warn the commenter.
36
+		$ipv4Regex = '/\b' . RegexConstants::IPV4 . '\b/';
37
+		$ipv6Regex = '/\b' . RegexConstants::IPV6 . '\b/';
38 38
 
39
-        $overridePolicy = WebRequest::postBoolean('privpol-check-override');
39
+		$overridePolicy = WebRequest::postBoolean('privpol-check-override');
40 40
 
41
-        if ((preg_match($ipv4Regex, $commentText) || preg_match($ipv6Regex, $commentText)) && !$overridePolicy) {
42
-            $this->assignCSRFToken();
43
-            $this->assign("request", $request);
44
-            $this->assign("comment", $commentText);
45
-            $this->setTemplate("privpol-warning.tpl");
41
+		if ((preg_match($ipv4Regex, $commentText) || preg_match($ipv6Regex, $commentText)) && !$overridePolicy) {
42
+			$this->assignCSRFToken();
43
+			$this->assign("request", $request);
44
+			$this->assign("comment", $commentText);
45
+			$this->setTemplate("privpol-warning.tpl");
46 46
 
47
-            return;
48
-        }
47
+			return;
48
+		}
49 49
 
50
-        $visibility = WebRequest::postBoolean('adminOnly') ? 'admin' : 'user';
50
+		$visibility = WebRequest::postBoolean('adminOnly') ? 'admin' : 'user';
51 51
 
52
-        $comment = new Comment();
53
-        $comment->setDatabase($database);
52
+		$comment = new Comment();
53
+		$comment->setDatabase($database);
54 54
 
55
-        $comment->setRequest($request->getId());
56
-        $comment->setVisibility($visibility);
57
-        $comment->setUser(User::getCurrent($database)->getId());
58
-        $comment->setComment($commentText);
55
+		$comment->setRequest($request->getId());
56
+		$comment->setVisibility($visibility);
57
+		$comment->setUser(User::getCurrent($database)->getId());
58
+		$comment->setComment($commentText);
59 59
 
60
-        $comment->save();
60
+		$comment->save();
61 61
 
62
-        $this->getNotificationHelper()->commentCreated($comment, $request);
63
-        $this->redirect('viewRequest', null, array('id' => $request->getId()));
64
-    }
62
+		$this->getNotificationHelper()->commentCreated($comment, $request);
63
+		$this->redirect('viewRequest', null, array('id' => $request->getId()));
64
+	}
65 65
 }
Please login to merge, or discard this patch.
includes/Pages/PageViewRequest.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@
 block discarded – undo
100 100
             }
101 101
         }
102 102
 
103
-        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
103
+        $this->setHtmlTitle($statusSymbol.' #'.$request->getId());
104 104
     }
105 105
 
106 106
     /**
Please login to merge, or discard this patch.
Indentation   +211 added lines, -211 removed lines patch added patch discarded remove patch
@@ -24,215 +24,215 @@
 block discarded – undo
24 24
 
25 25
 class PageViewRequest extends InternalPageBase
26 26
 {
27
-    use RequestData;
28
-    const STATUS_SYMBOL_OPEN = '&#x2610';
29
-    const STATUS_SYMBOL_ACCEPTED = '&#x2611';
30
-    const STATUS_SYMBOL_REJECTED = '&#x2612';
31
-
32
-    /**
33
-     * Main function for this page, when no specific actions are called.
34
-     * @throws ApplicationLogicException
35
-     */
36
-    protected function main()
37
-    {
38
-        // set up csrf protection
39
-        $this->assignCSRFToken();
40
-
41
-        // get some useful objects
42
-        $database = $this->getDatabase();
43
-        $request = $this->getRequest($database, WebRequest::getInt('id'));
44
-        $config = $this->getSiteConfiguration();
45
-        $currentUser = User::getCurrent($database);
46
-
47
-        // Test we should be able to look at this request
48
-        if ($config->getEmailConfirmationEnabled()) {
49
-            if ($request->getEmailConfirm() !== 'Confirmed') {
50
-                // Not allowed to look at this yet.
51
-                throw new ApplicationLogicException('The email address has not yet been confirmed for this request.');
52
-            }
53
-        }
54
-
55
-        $this->setupBasicData($request, $config);
56
-
57
-        $this->setupUsernameData($request);
58
-
59
-        $this->setupTitle($request);
60
-
61
-        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
62
-        $this->setupGeneralData($database);
63
-
64
-        $this->assign('requestDataCleared', false);
65
-        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
66
-            $this->assign('requestDataCleared', true);
67
-        }
68
-
69
-        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
70
-
71
-        $this->setupLogData($request, $database);
72
-
73
-        if ($allowedPrivateData) {
74
-            $this->setTemplate('view-request/main-with-data.tpl');
75
-            $this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
76
-
77
-            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
78
-            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
79
-
80
-            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
81
-                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
82
-                $this->setupCheckUserData($request);
83
-            }
84
-        }
85
-        else {
86
-            $this->setTemplate('view-request/main.tpl');
87
-        }
88
-
89
-        $this->addCss('/resources/viewrequest.css');
90
-    }
91
-
92
-    /**
93
-     * @param Request $request
94
-     */
95
-    protected function setupTitle(Request $request)
96
-    {
97
-        $statusSymbol = self::STATUS_SYMBOL_OPEN;
98
-        if ($request->getStatus() === 'Closed') {
99
-            if ($request->getWasCreated()) {
100
-                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
101
-            }
102
-            else {
103
-                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
104
-            }
105
-        }
106
-
107
-        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
108
-    }
109
-
110
-    /**
111
-     * Sets up data unrelated to the request, such as the email template information
112
-     *
113
-     * @param PdoDatabase $database
114
-     */
115
-    protected function setupGeneralData(PdoDatabase $database)
116
-    {
117
-        $config = $this->getSiteConfiguration();
118
-
119
-        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
120
-
121
-        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
122
-
123
-        $this->assign('requestStates', $config->getRequestStates());
124
-
125
-        /** @var EmailTemplate $createdTemplate */
126
-        $createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
127
-
128
-        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
129
-        $this->assign('createdJsQuestion', $createdTemplate->getJsquestion());
130
-        $this->assign('createdId', $createdTemplate->getId());
131
-        $this->assign('createdName', $createdTemplate->getName());
132
-
133
-        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
134
-        $this->assign("createReasons", $createReasons);
135
-        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
136
-        $this->assign("declineReasons", $declineReasons);
137
-
138
-        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
139
-        $this->assign("allCreateReasons", $allCreateReasons);
140
-        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
141
-        $this->assign("allDeclineReasons", $allDeclineReasons);
142
-        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
143
-        $this->assign("allOtherReasons", $allOtherReasons);
144
-
145
-        $this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
146
-            return UserSearchHelper::get($database)->byStatus('Active')->fetchColumn('username');
147
-        });
148
-    }
149
-
150
-    private function setupLogData(Request $request, PdoDatabase $database)
151
-    {
152
-        $currentUser = User::getCurrent($database);
153
-
154
-        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
155
-        $requestLogs = array();
156
-
157
-        if (trim($request->getComment()) !== "") {
158
-            $requestLogs[] = array(
159
-                'type'     => 'comment',
160
-                'security' => 'user',
161
-                'userid'   => null,
162
-                'user'     => $request->getName(),
163
-                'entry'    => null,
164
-                'time'     => $request->getDate(),
165
-                'canedit'  => false,
166
-                'id'       => $request->getId(),
167
-                'comment'  => $request->getComment(),
168
-            );
169
-        }
170
-
171
-        /** @var User[] $nameCache */
172
-        $nameCache = array();
173
-
174
-        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
175
-
176
-        /** @var Log|Comment $entry */
177
-        foreach ($logs as $entry) {
178
-            // both log and comment have a 'user' field
179
-            if (!array_key_exists($entry->getUser(), $nameCache)) {
180
-                $entryUser = User::getById($entry->getUser(), $database);
181
-                $nameCache[$entry->getUser()] = $entryUser;
182
-            }
183
-
184
-            if ($entry instanceof Comment) {
185
-                $requestLogs[] = array(
186
-                    'type'     => 'comment',
187
-                    'security' => $entry->getVisibility(),
188
-                    'user'     => $nameCache[$entry->getUser()]->getUsername(),
189
-                    'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
190
-                    'entry'    => null,
191
-                    'time'     => $entry->getTime(),
192
-                    'canedit'  => ($editableComments || $entry->getUser() == $currentUser->getId()),
193
-                    'id'       => $entry->getId(),
194
-                    'comment'  => $entry->getComment(),
195
-                );
196
-            }
197
-
198
-            if ($entry instanceof Log) {
199
-                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
200
-                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
201
-
202
-                $requestLogs[] = array(
203
-                    'type'     => 'log',
204
-                    'security' => 'user',
205
-                    'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
206
-                    'user'     => $entryUser->getUsername(),
207
-                    'entry'    => LogHelper::getLogDescription($entry),
208
-                    'time'     => $entry->getTimestamp(),
209
-                    'canedit'  => false,
210
-                    'id'       => $entry->getId(),
211
-                    'comment'  => $entry->getComment(),
212
-                );
213
-            }
214
-        }
215
-
216
-        $this->assign("requestLogs", $requestLogs);
217
-    }
218
-
219
-    /**
220
-     * @param Request $request
221
-     */
222
-    protected function setupUsernameData(Request $request)
223
-    {
224
-        $blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
225
-
226
-        $this->assign('requestIsBlacklisted', $blacklistData !== false);
227
-        $this->assign('requestBlacklist', $blacklistData);
228
-
229
-        try {
230
-            $spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
231
-        }
232
-        catch (Exception $ex) {
233
-            $spoofs = $ex->getMessage();
234
-        }
235
-
236
-        $this->assign("spoofs", $spoofs);
237
-    }
27
+	use RequestData;
28
+	const STATUS_SYMBOL_OPEN = '&#x2610';
29
+	const STATUS_SYMBOL_ACCEPTED = '&#x2611';
30
+	const STATUS_SYMBOL_REJECTED = '&#x2612';
31
+
32
+	/**
33
+	 * Main function for this page, when no specific actions are called.
34
+	 * @throws ApplicationLogicException
35
+	 */
36
+	protected function main()
37
+	{
38
+		// set up csrf protection
39
+		$this->assignCSRFToken();
40
+
41
+		// get some useful objects
42
+		$database = $this->getDatabase();
43
+		$request = $this->getRequest($database, WebRequest::getInt('id'));
44
+		$config = $this->getSiteConfiguration();
45
+		$currentUser = User::getCurrent($database);
46
+
47
+		// Test we should be able to look at this request
48
+		if ($config->getEmailConfirmationEnabled()) {
49
+			if ($request->getEmailConfirm() !== 'Confirmed') {
50
+				// Not allowed to look at this yet.
51
+				throw new ApplicationLogicException('The email address has not yet been confirmed for this request.');
52
+			}
53
+		}
54
+
55
+		$this->setupBasicData($request, $config);
56
+
57
+		$this->setupUsernameData($request);
58
+
59
+		$this->setupTitle($request);
60
+
61
+		$this->setupReservationDetails($request->getReserved(), $database, $currentUser);
62
+		$this->setupGeneralData($database);
63
+
64
+		$this->assign('requestDataCleared', false);
65
+		if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
66
+			$this->assign('requestDataCleared', true);
67
+		}
68
+
69
+		$allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
70
+
71
+		$this->setupLogData($request, $database);
72
+
73
+		if ($allowedPrivateData) {
74
+			$this->setTemplate('view-request/main-with-data.tpl');
75
+			$this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
76
+
77
+			$this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
78
+			$this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
79
+
80
+			if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
81
+				$this->setTemplate('view-request/main-with-checkuser-data.tpl');
82
+				$this->setupCheckUserData($request);
83
+			}
84
+		}
85
+		else {
86
+			$this->setTemplate('view-request/main.tpl');
87
+		}
88
+
89
+		$this->addCss('/resources/viewrequest.css');
90
+	}
91
+
92
+	/**
93
+	 * @param Request $request
94
+	 */
95
+	protected function setupTitle(Request $request)
96
+	{
97
+		$statusSymbol = self::STATUS_SYMBOL_OPEN;
98
+		if ($request->getStatus() === 'Closed') {
99
+			if ($request->getWasCreated()) {
100
+				$statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
101
+			}
102
+			else {
103
+				$statusSymbol = self::STATUS_SYMBOL_REJECTED;
104
+			}
105
+		}
106
+
107
+		$this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
108
+	}
109
+
110
+	/**
111
+	 * Sets up data unrelated to the request, such as the email template information
112
+	 *
113
+	 * @param PdoDatabase $database
114
+	 */
115
+	protected function setupGeneralData(PdoDatabase $database)
116
+	{
117
+		$config = $this->getSiteConfiguration();
118
+
119
+		$this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
120
+
121
+		$this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
122
+
123
+		$this->assign('requestStates', $config->getRequestStates());
124
+
125
+		/** @var EmailTemplate $createdTemplate */
126
+		$createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
127
+
128
+		$this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
129
+		$this->assign('createdJsQuestion', $createdTemplate->getJsquestion());
130
+		$this->assign('createdId', $createdTemplate->getId());
131
+		$this->assign('createdName', $createdTemplate->getName());
132
+
133
+		$createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
134
+		$this->assign("createReasons", $createReasons);
135
+		$declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
136
+		$this->assign("declineReasons", $declineReasons);
137
+
138
+		$allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
139
+		$this->assign("allCreateReasons", $allCreateReasons);
140
+		$allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
141
+		$this->assign("allDeclineReasons", $allDeclineReasons);
142
+		$allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
143
+		$this->assign("allOtherReasons", $allOtherReasons);
144
+
145
+		$this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
146
+			return UserSearchHelper::get($database)->byStatus('Active')->fetchColumn('username');
147
+		});
148
+	}
149
+
150
+	private function setupLogData(Request $request, PdoDatabase $database)
151
+	{
152
+		$currentUser = User::getCurrent($database);
153
+
154
+		$logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
155
+		$requestLogs = array();
156
+
157
+		if (trim($request->getComment()) !== "") {
158
+			$requestLogs[] = array(
159
+				'type'     => 'comment',
160
+				'security' => 'user',
161
+				'userid'   => null,
162
+				'user'     => $request->getName(),
163
+				'entry'    => null,
164
+				'time'     => $request->getDate(),
165
+				'canedit'  => false,
166
+				'id'       => $request->getId(),
167
+				'comment'  => $request->getComment(),
168
+			);
169
+		}
170
+
171
+		/** @var User[] $nameCache */
172
+		$nameCache = array();
173
+
174
+		$editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
175
+
176
+		/** @var Log|Comment $entry */
177
+		foreach ($logs as $entry) {
178
+			// both log and comment have a 'user' field
179
+			if (!array_key_exists($entry->getUser(), $nameCache)) {
180
+				$entryUser = User::getById($entry->getUser(), $database);
181
+				$nameCache[$entry->getUser()] = $entryUser;
182
+			}
183
+
184
+			if ($entry instanceof Comment) {
185
+				$requestLogs[] = array(
186
+					'type'     => 'comment',
187
+					'security' => $entry->getVisibility(),
188
+					'user'     => $nameCache[$entry->getUser()]->getUsername(),
189
+					'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
190
+					'entry'    => null,
191
+					'time'     => $entry->getTime(),
192
+					'canedit'  => ($editableComments || $entry->getUser() == $currentUser->getId()),
193
+					'id'       => $entry->getId(),
194
+					'comment'  => $entry->getComment(),
195
+				);
196
+			}
197
+
198
+			if ($entry instanceof Log) {
199
+				$invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
200
+				$entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
201
+
202
+				$requestLogs[] = array(
203
+					'type'     => 'log',
204
+					'security' => 'user',
205
+					'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
206
+					'user'     => $entryUser->getUsername(),
207
+					'entry'    => LogHelper::getLogDescription($entry),
208
+					'time'     => $entry->getTimestamp(),
209
+					'canedit'  => false,
210
+					'id'       => $entry->getId(),
211
+					'comment'  => $entry->getComment(),
212
+				);
213
+			}
214
+		}
215
+
216
+		$this->assign("requestLogs", $requestLogs);
217
+	}
218
+
219
+	/**
220
+	 * @param Request $request
221
+	 */
222
+	protected function setupUsernameData(Request $request)
223
+	{
224
+		$blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
225
+
226
+		$this->assign('requestIsBlacklisted', $blacklistData !== false);
227
+		$this->assign('requestBlacklist', $blacklistData);
228
+
229
+		try {
230
+			$spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
231
+		}
232
+		catch (Exception $ex) {
233
+			$spoofs = $ex->getMessage();
234
+		}
235
+
236
+		$this->assign("spoofs", $spoofs);
237
+	}
238 238
 }
Please login to merge, or discard this patch.
includes/IrcColourCode.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -10,27 +10,27 @@
 block discarded – undo
10 10
 
11 11
 class IrcColourCode
12 12
 {
13
-    const BOLD = "\x02";
14
-    const ITALIC = "\x09";
15
-    const STRIKE = "\x13";
16
-    const UNDERLINE = "\x15";
17
-    const UNDERLINE2 = "\x1f";
18
-    const REVERSE = "\x16";
19
-    const RESET = "\x0f";
20
-    const WHITE = "\x0300";
21
-    const BLACK = "\x0301";
22
-    const DARK_BLUE = "\x0302";
23
-    const DARK_GREEN = "\x0303";
24
-    const RED = "\x0304";
25
-    const DARK_RED = "\x0305";
26
-    const DARK_VIOLET = "\x0306";
27
-    const ORANGE = "\x0307";
28
-    const YELLOW = "\x0308";
29
-    const LIGHT_GREEN = "\x0309";
30
-    const CYAN = "\x0310";
31
-    const LIGHT_CYAN = "\x0311";
32
-    const BLUE = "\x0312";
33
-    const VIOLET = "\x0313";
34
-    const DARK_GREY = "\x0314";
35
-    const LIGHT_GREY = "\x0315";
13
+	const BOLD = "\x02";
14
+	const ITALIC = "\x09";
15
+	const STRIKE = "\x13";
16
+	const UNDERLINE = "\x15";
17
+	const UNDERLINE2 = "\x1f";
18
+	const REVERSE = "\x16";
19
+	const RESET = "\x0f";
20
+	const WHITE = "\x0300";
21
+	const BLACK = "\x0301";
22
+	const DARK_BLUE = "\x0302";
23
+	const DARK_GREEN = "\x0303";
24
+	const RED = "\x0304";
25
+	const DARK_RED = "\x0305";
26
+	const DARK_VIOLET = "\x0306";
27
+	const ORANGE = "\x0307";
28
+	const YELLOW = "\x0308";
29
+	const LIGHT_GREEN = "\x0309";
30
+	const CYAN = "\x0310";
31
+	const LIGHT_CYAN = "\x0311";
32
+	const BLUE = "\x0312";
33
+	const VIOLET = "\x0313";
34
+	const DARK_GREY = "\x0314";
35
+	const LIGHT_GREY = "\x0315";
36 36
 }
Please login to merge, or discard this patch.
includes/Exceptions/ReadableException.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -21,22 +21,22 @@
 block discarded – undo
21 21
  */
22 22
 abstract class ReadableException extends Exception
23 23
 {
24
-    use TemplateOutput;
24
+	use TemplateOutput;
25 25
 
26
-    /**
27
-     * Returns a readable HTML error message that's displayable to the user using templates.
28
-     * @return string
29
-     */
30
-    abstract public function getReadableError();
26
+	/**
27
+	 * Returns a readable HTML error message that's displayable to the user using templates.
28
+	 * @return string
29
+	 */
30
+	abstract public function getReadableError();
31 31
 
32
-    /**
33
-     * @return SiteConfiguration
34
-     */
35
-    protected function getSiteConfiguration()
36
-    {
37
-        // Uck. However, we have encountered an exception.
38
-        global $siteConfiguration;
32
+	/**
33
+	 * @return SiteConfiguration
34
+	 */
35
+	protected function getSiteConfiguration()
36
+	{
37
+		// Uck. However, we have encountered an exception.
38
+		global $siteConfiguration;
39 39
 
40
-        return $siteConfiguration;
41
-    }
40
+		return $siteConfiguration;
41
+	}
42 42
 }
43 43
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Exceptions/EnvironmentException.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -21,13 +21,13 @@
 block discarded – undo
21 21
  */
22 22
 class EnvironmentException extends Exception
23 23
 {
24
-    /**
25
-     * EnvironmentException constructor.
26
-     *
27
-     * @param string $friendlyMessage
28
-     */
29
-    public function __construct($friendlyMessage)
30
-    {
31
-        parent::__construct($friendlyMessage);
32
-    }
24
+	/**
25
+	 * EnvironmentException constructor.
26
+	 *
27
+	 * @param string $friendlyMessage
28
+	 */
29
+	public function __construct($friendlyMessage)
30
+	{
31
+		parent::__construct($friendlyMessage);
32
+	}
33 33
 }
34 34
\ No newline at end of file
Please login to merge, or discard this patch.
includes/PdoDatabase.php 2 patches
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -15,112 +15,112 @@
 block discarded – undo
15 15
 
16 16
 class PdoDatabase extends PDO
17 17
 {
18
-    /**
19
-     * @var PdoDatabase[]
20
-     */
21
-    private static $connections = array();
22
-    /**
23
-     * @var bool True if a transaction is active
24
-     */
25
-    protected $hasActiveTransaction = false;
26
-
27
-    /**
28
-     * Unless you're doing low-level work, this is not the function you want.
29
-     *
30
-     * @param string $connectionName
31
-     *
32
-     * @return PdoDatabase
33
-     * @throws Exception
34
-     */
35
-    public static function getDatabaseConnection($connectionName)
36
-    {
37
-        if (!isset(self::$connections[$connectionName])) {
38
-            global $cDatabaseConfig;
39
-
40
-            if (!array_key_exists($connectionName, $cDatabaseConfig)) {
41
-                throw new Exception("Database configuration not found for alias $connectionName");
42
-            }
43
-
44
-            try {
45
-                $databaseObject = new PdoDatabase(
46
-                    $cDatabaseConfig[$connectionName]["dsrcname"],
47
-                    $cDatabaseConfig[$connectionName]["username"],
48
-                    $cDatabaseConfig[$connectionName]["password"]
49
-                );
50
-            }
51
-            catch (PDOException $ex) {
52
-                // wrap around any potential stack traces which may include passwords
53
-                throw new EnvironmentException("Error connecting to database '$connectionName': " . $ex->getMessage());
54
-            }
55
-
56
-            $databaseObject->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
57
-
58
-            // emulating prepared statements gives a performance boost on MySQL.
59
-            //
60
-            // however, our version of PDO doesn't seem to understand parameter types when emulating
61
-            // the prepared statements, so we're forced to turn this off for now.
62
-            // -- stw 2014-02-11
63
-            $databaseObject->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
64
-
65
-            self::$connections[$connectionName] = $databaseObject;
66
-        }
67
-
68
-        return self::$connections[$connectionName];
69
-    }
70
-
71
-    /**
72
-     * Determines if this connection has a transaction in progress or not
73
-     * @return boolean true if there is a transaction in progress.
74
-     */
75
-    public function hasActiveTransaction()
76
-    {
77
-        return $this->hasActiveTransaction;
78
-    }
79
-
80
-    /**
81
-     * Summary of beginTransaction
82
-     * @return bool
83
-     */
84
-    public function beginTransaction()
85
-    {
86
-        // Override the pre-existing method, which doesn't stop you from
87
-        // starting transactions within transactions - which doesn't work and
88
-        // will throw an exception. This eliminates the need to catch exceptions
89
-        // all over the rest of the code
90
-        if ($this->hasActiveTransaction) {
91
-            return false;
92
-        }
93
-        else {
94
-            // set the transaction isolation level for every transaction.
95
-            $this->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;");
96
-
97
-            // start a new transaction, and return whether or not the start was
98
-            // successful
99
-            $this->hasActiveTransaction = parent::beginTransaction();
100
-
101
-            return $this->hasActiveTransaction;
102
-        }
103
-    }
104
-
105
-    /**
106
-     * Commits the active transaction
107
-     */
108
-    public function commit()
109
-    {
110
-        if ($this->hasActiveTransaction) {
111
-            parent::commit();
112
-            $this->hasActiveTransaction = false;
113
-        }
114
-    }
115
-
116
-    /**
117
-     * Rolls back a transaction
118
-     */
119
-    public function rollBack()
120
-    {
121
-        if ($this->hasActiveTransaction) {
122
-            parent::rollback();
123
-            $this->hasActiveTransaction = false;
124
-        }
125
-    }
18
+	/**
19
+	 * @var PdoDatabase[]
20
+	 */
21
+	private static $connections = array();
22
+	/**
23
+	 * @var bool True if a transaction is active
24
+	 */
25
+	protected $hasActiveTransaction = false;
26
+
27
+	/**
28
+	 * Unless you're doing low-level work, this is not the function you want.
29
+	 *
30
+	 * @param string $connectionName
31
+	 *
32
+	 * @return PdoDatabase
33
+	 * @throws Exception
34
+	 */
35
+	public static function getDatabaseConnection($connectionName)
36
+	{
37
+		if (!isset(self::$connections[$connectionName])) {
38
+			global $cDatabaseConfig;
39
+
40
+			if (!array_key_exists($connectionName, $cDatabaseConfig)) {
41
+				throw new Exception("Database configuration not found for alias $connectionName");
42
+			}
43
+
44
+			try {
45
+				$databaseObject = new PdoDatabase(
46
+					$cDatabaseConfig[$connectionName]["dsrcname"],
47
+					$cDatabaseConfig[$connectionName]["username"],
48
+					$cDatabaseConfig[$connectionName]["password"]
49
+				);
50
+			}
51
+			catch (PDOException $ex) {
52
+				// wrap around any potential stack traces which may include passwords
53
+				throw new EnvironmentException("Error connecting to database '$connectionName': " . $ex->getMessage());
54
+			}
55
+
56
+			$databaseObject->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
57
+
58
+			// emulating prepared statements gives a performance boost on MySQL.
59
+			//
60
+			// however, our version of PDO doesn't seem to understand parameter types when emulating
61
+			// the prepared statements, so we're forced to turn this off for now.
62
+			// -- stw 2014-02-11
63
+			$databaseObject->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
64
+
65
+			self::$connections[$connectionName] = $databaseObject;
66
+		}
67
+
68
+		return self::$connections[$connectionName];
69
+	}
70
+
71
+	/**
72
+	 * Determines if this connection has a transaction in progress or not
73
+	 * @return boolean true if there is a transaction in progress.
74
+	 */
75
+	public function hasActiveTransaction()
76
+	{
77
+		return $this->hasActiveTransaction;
78
+	}
79
+
80
+	/**
81
+	 * Summary of beginTransaction
82
+	 * @return bool
83
+	 */
84
+	public function beginTransaction()
85
+	{
86
+		// Override the pre-existing method, which doesn't stop you from
87
+		// starting transactions within transactions - which doesn't work and
88
+		// will throw an exception. This eliminates the need to catch exceptions
89
+		// all over the rest of the code
90
+		if ($this->hasActiveTransaction) {
91
+			return false;
92
+		}
93
+		else {
94
+			// set the transaction isolation level for every transaction.
95
+			$this->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;");
96
+
97
+			// start a new transaction, and return whether or not the start was
98
+			// successful
99
+			$this->hasActiveTransaction = parent::beginTransaction();
100
+
101
+			return $this->hasActiveTransaction;
102
+		}
103
+	}
104
+
105
+	/**
106
+	 * Commits the active transaction
107
+	 */
108
+	public function commit()
109
+	{
110
+		if ($this->hasActiveTransaction) {
111
+			parent::commit();
112
+			$this->hasActiveTransaction = false;
113
+		}
114
+	}
115
+
116
+	/**
117
+	 * Rolls back a transaction
118
+	 */
119
+	public function rollBack()
120
+	{
121
+		if ($this->hasActiveTransaction) {
122
+			parent::rollback();
123
+			$this->hasActiveTransaction = false;
124
+		}
125
+	}
126 126
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@
 block discarded – undo
50 50
             }
51 51
             catch (PDOException $ex) {
52 52
                 // wrap around any potential stack traces which may include passwords
53
-                throw new EnvironmentException("Error connecting to database '$connectionName': " . $ex->getMessage());
53
+                throw new EnvironmentException("Error connecting to database '$connectionName': ".$ex->getMessage());
54 54
             }
55 55
 
56 56
             $databaseObject->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Please login to merge, or discard this patch.
includes/ExceptionHandler.php 2 patches
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -13,22 +13,22 @@  discard block
 block discarded – undo
13 13
 
14 14
 class ExceptionHandler
15 15
 {
16
-    /**
17
-     * Global exception handler
18
-     *
19
-     * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
20
-     * Let's build something ourselves, and hope it works.
21
-     *
22
-     * @param $exception
23
-     *
24
-     * @category Security-Critical - has the potential to leak data when exception is thrown.
25
-     */
26
-    public static function exceptionHandler(Exception $exception)
27
-    {
28
-        /** @global $siteConfiguration SiteConfiguration */
29
-        global $siteConfiguration;
30
-
31
-        $errorDocument = <<<HTML
16
+	/**
17
+	 * Global exception handler
18
+	 *
19
+	 * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
20
+	 * Let's build something ourselves, and hope it works.
21
+	 *
22
+	 * @param $exception
23
+	 *
24
+	 * @category Security-Critical - has the potential to leak data when exception is thrown.
25
+	 */
26
+	public static function exceptionHandler(Exception $exception)
27
+	{
28
+		/** @global $siteConfiguration SiteConfiguration */
29
+		global $siteConfiguration;
30
+
31
+		$errorDocument = <<<HTML
32 32
 <!DOCTYPE html>
33 33
 <html lang="en"><head>
34 34
 <meta charset="utf-8">
@@ -49,77 +49,77 @@  discard block
 block discarded – undo
49 49
 </div></body></html>
50 50
 HTML;
51 51
 
52
-        $errorData = self::getExceptionData($exception);
53
-        $errorData['server'] = $_SERVER;
54
-        $errorData['get'] = $_GET;
55
-        $errorData['post'] = $_POST;
56
-
57
-        $state = serialize($errorData);
58
-        $errorId = sha1($state);
59
-
60
-        // Save the error for later analysis
61
-        file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
62
-
63
-        // clear and discard any content that's been saved to the output buffer
64
-        if (ob_get_level() > 0) {
65
-            ob_end_clean();
66
-        }
67
-
68
-        // push error ID into the document.
69
-        $message = str_replace('$1$', $errorId, $errorDocument);
70
-
71
-        if ($siteConfiguration->getDebuggingTraceEnabled()) {
72
-            ob_start();
73
-            var_dump($errorData);
74
-            $textErrorData = ob_get_contents();
75
-            ob_end_clean();
76
-
77
-            $message = str_replace('$2$', $textErrorData, $message);
78
-        }
79
-        else {
80
-            $message = str_replace('$2$', "", $message);
81
-        }
82
-
83
-        // While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
84
-        // This is "only" needed for the tests, but it's a good idea to wrap this anyway.
85
-        if (!headers_sent()) {
86
-            header('HTTP/1.1 500 Internal Server Error');
87
-        }
88
-
89
-        // output the document
90
-        print $message;
91
-    }
92
-
93
-    /**
94
-     * @param int    $errorSeverity The severity level of the exception.
95
-     * @param string $errorMessage  The Exception message to throw.
96
-     * @param string $errorFile     The filename where the exception is thrown.
97
-     * @param int    $errorLine     The line number where the exception is thrown.
98
-     *
99
-     * @throws ErrorException
100
-     */
101
-    public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
102
-    {
103
-        // call into the main exception handler above
104
-        throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
105
-    }
106
-
107
-    /**
108
-     * @param Exception $exception
109
-     *
110
-     * @return null|array
111
-     */
112
-    private static function getExceptionData($exception)
113
-    {
114
-        if ($exception == null) {
115
-            return null;
116
-        }
117
-
118
-        return array(
119
-            'exception' => get_class($exception),
120
-            'message'   => $exception->getMessage(),
121
-            'stack'     => $exception->getTraceAsString(),
122
-            'previous'  => self::getExceptionData($exception->getPrevious()),
123
-        );
124
-    }
52
+		$errorData = self::getExceptionData($exception);
53
+		$errorData['server'] = $_SERVER;
54
+		$errorData['get'] = $_GET;
55
+		$errorData['post'] = $_POST;
56
+
57
+		$state = serialize($errorData);
58
+		$errorId = sha1($state);
59
+
60
+		// Save the error for later analysis
61
+		file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
62
+
63
+		// clear and discard any content that's been saved to the output buffer
64
+		if (ob_get_level() > 0) {
65
+			ob_end_clean();
66
+		}
67
+
68
+		// push error ID into the document.
69
+		$message = str_replace('$1$', $errorId, $errorDocument);
70
+
71
+		if ($siteConfiguration->getDebuggingTraceEnabled()) {
72
+			ob_start();
73
+			var_dump($errorData);
74
+			$textErrorData = ob_get_contents();
75
+			ob_end_clean();
76
+
77
+			$message = str_replace('$2$', $textErrorData, $message);
78
+		}
79
+		else {
80
+			$message = str_replace('$2$', "", $message);
81
+		}
82
+
83
+		// While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
84
+		// This is "only" needed for the tests, but it's a good idea to wrap this anyway.
85
+		if (!headers_sent()) {
86
+			header('HTTP/1.1 500 Internal Server Error');
87
+		}
88
+
89
+		// output the document
90
+		print $message;
91
+	}
92
+
93
+	/**
94
+	 * @param int    $errorSeverity The severity level of the exception.
95
+	 * @param string $errorMessage  The Exception message to throw.
96
+	 * @param string $errorFile     The filename where the exception is thrown.
97
+	 * @param int    $errorLine     The line number where the exception is thrown.
98
+	 *
99
+	 * @throws ErrorException
100
+	 */
101
+	public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
102
+	{
103
+		// call into the main exception handler above
104
+		throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
105
+	}
106
+
107
+	/**
108
+	 * @param Exception $exception
109
+	 *
110
+	 * @return null|array
111
+	 */
112
+	private static function getExceptionData($exception)
113
+	{
114
+		if ($exception == null) {
115
+			return null;
116
+		}
117
+
118
+		return array(
119
+			'exception' => get_class($exception),
120
+			'message'   => $exception->getMessage(),
121
+			'stack'     => $exception->getTraceAsString(),
122
+			'previous'  => self::getExceptionData($exception->getPrevious()),
123
+		);
124
+	}
125 125
 }
126 126
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@
 block discarded – undo
58 58
         $errorId = sha1($state);
59 59
 
60 60
         // Save the error for later analysis
61
-        file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
61
+        file_put_contents($siteConfiguration->getErrorLog().'/'.$errorId.'.log', $state);
62 62
 
63 63
         // clear and discard any content that's been saved to the output buffer
64 64
         if (ob_get_level() > 0) {
Please login to merge, or discard this patch.
includes/Validation/RequestValidationHelper.php 2 patches
Indentation   +284 added lines, -284 removed lines patch added patch discarded remove patch
@@ -22,288 +22,288 @@
 block discarded – undo
22 22
  */
23 23
 class RequestValidationHelper
24 24
 {
25
-    /** @var IBanHelper */
26
-    private $banHelper;
27
-    /** @var Request */
28
-    private $request;
29
-    private $emailConfirmation;
30
-    /** @var PdoDatabase */
31
-    private $database;
32
-    /** @var IAntiSpoofProvider */
33
-    private $antiSpoofProvider;
34
-    /** @var IXffTrustProvider */
35
-    private $xffTrustProvider;
36
-    /** @var HttpHelper */
37
-    private $httpHelper;
38
-    /**
39
-     * @var string
40
-     */
41
-    private $mediawikiApiEndpoint;
42
-    private $titleBlacklistEnabled;
43
-    /**
44
-     * @var TorExitProvider
45
-     */
46
-    private $torExitProvider;
47
-
48
-    /**
49
-     * Summary of __construct
50
-     *
51
-     * @param IBanHelper         $banHelper
52
-     * @param Request            $request
53
-     * @param string             $emailConfirmation
54
-     * @param PdoDatabase        $database
55
-     * @param IAntiSpoofProvider $antiSpoofProvider
56
-     * @param IXffTrustProvider  $xffTrustProvider
57
-     * @param HttpHelper         $httpHelper
58
-     * @param string             $mediawikiApiEndpoint
59
-     * @param boolean            $titleBlacklistEnabled
60
-     * @param TorExitProvider    $torExitProvider
61
-     */
62
-    public function __construct(
63
-        IBanHelper $banHelper,
64
-        Request $request,
65
-        $emailConfirmation,
66
-        PdoDatabase $database,
67
-        IAntiSpoofProvider $antiSpoofProvider,
68
-        IXffTrustProvider $xffTrustProvider,
69
-        HttpHelper $httpHelper,
70
-        $mediawikiApiEndpoint,
71
-        $titleBlacklistEnabled,
72
-        TorExitProvider $torExitProvider
73
-    ) {
74
-        $this->banHelper = $banHelper;
75
-        $this->request = $request;
76
-        $this->emailConfirmation = $emailConfirmation;
77
-        $this->database = $database;
78
-        $this->antiSpoofProvider = $antiSpoofProvider;
79
-        $this->xffTrustProvider = $xffTrustProvider;
80
-        $this->httpHelper = $httpHelper;
81
-        $this->mediawikiApiEndpoint = $mediawikiApiEndpoint;
82
-        $this->titleBlacklistEnabled = $titleBlacklistEnabled;
83
-        $this->torExitProvider = $torExitProvider;
84
-    }
85
-
86
-    /**
87
-     * Summary of validateName
88
-     * @return ValidationError[]
89
-     */
90
-    public function validateName()
91
-    {
92
-        $errorList = array();
93
-
94
-        // ERRORS
95
-        // name is empty
96
-        if (trim($this->request->getName()) == "") {
97
-            $errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
98
-        }
99
-
100
-        // name is banned
101
-        $ban = $this->banHelper->nameIsBanned($this->request->getName());
102
-        if ($ban != false) {
103
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
104
-        }
105
-
106
-        // username already exists
107
-        if ($this->userExists()) {
108
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
109
-        }
110
-
111
-        // username part of SUL account
112
-        if ($this->userSulExists()) {
113
-            // using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
114
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
115
-        }
116
-
117
-        // username is numbers
118
-        if (preg_match("/^[0-9]+$/", $this->request->getName()) === 1) {
119
-            $errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
120
-        }
121
-
122
-        // username can't contain #@/<>[]|{}
123
-        if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $this->request->getName()) === 1) {
124
-            $errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
125
-        }
126
-
127
-        // existing non-closed request for this name
128
-        if ($this->nameRequestExists()) {
129
-            $errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
130
-        }
131
-
132
-        return $errorList;
133
-    }
134
-
135
-    /**
136
-     * Summary of validateEmail
137
-     * @return ValidationError[]
138
-     */
139
-    public function validateEmail()
140
-    {
141
-        $errorList = array();
142
-
143
-        // ERRORS
144
-
145
-        // Email is banned
146
-        $ban = $this->banHelper->emailIsBanned($this->request->getEmail());
147
-        if ($ban != false) {
148
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
149
-        }
150
-
151
-        // email addresses must match
152
-        if ($this->request->getEmail() != $this->emailConfirmation) {
153
-            $errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
154
-        }
155
-
156
-        // email address must be validly formed
157
-        if (trim($this->request->getEmail()) == "") {
158
-            $errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
159
-        }
160
-
161
-        // email address must be validly formed
162
-        if (!filter_var($this->request->getEmail(), FILTER_VALIDATE_EMAIL)) {
163
-            if (trim($this->request->getEmail()) != "") {
164
-                $errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
165
-            }
166
-        }
167
-
168
-        // email address can't be wikimedia/wikipedia .com/org
169
-        if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $this->request->getEmail()) === 1) {
170
-            $errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
171
-        }
172
-
173
-        // WARNINGS
174
-
175
-        return $errorList;
176
-    }
177
-
178
-    /**
179
-     * Summary of validateOther
180
-     * @return ValidationError[]
181
-     */
182
-    public function validateOther()
183
-    {
184
-        $errorList = array();
185
-
186
-        $trustedIp = $this->xffTrustProvider->getTrustedClientIp($this->request->getIp(),
187
-            $this->request->getForwardedIp());
188
-
189
-        // ERRORS
190
-
191
-        // TOR nodes
192
-        if ($this->torExitProvider->isTorExit($trustedIp)) {
193
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
194
-        }
195
-
196
-        // IP banned
197
-        $ban = $this->banHelper->ipIsBanned($trustedIp);
198
-        if ($ban != false) {
199
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
200
-        }
201
-
202
-        // WARNINGS
203
-
204
-        // Antispoof check
205
-        $this->checkAntiSpoof();
206
-
207
-        // Blacklist check
208
-        $this->checkTitleBlacklist();
209
-
210
-        return $errorList;
211
-    }
212
-
213
-    private function checkAntiSpoof()
214
-    {
215
-        try {
216
-            if (count($this->antiSpoofProvider->getSpoofs($this->request->getName())) > 0) {
217
-                // If there were spoofs an Admin should handle the request.
218
-                $this->request->setStatus("Flagged users");
219
-            }
220
-        }
221
-        catch (Exception $ex) {
222
-            // logme
223
-        }
224
-    }
225
-
226
-    private function checkTitleBlacklist()
227
-    {
228
-        if ($this->titleBlacklistEnabled == 1) {
229
-            $apiResult = $this->httpHelper->get(
230
-                $this->mediawikiApiEndpoint,
231
-                array(
232
-                    'action'       => 'titleblacklist',
233
-                    'tbtitle'      => $this->request->getName(),
234
-                    'tbaction'     => 'new-account',
235
-                    'tbnooverride' => true,
236
-                    'format'       => 'php',
237
-                )
238
-            );
239
-
240
-            $data = unserialize($apiResult);
241
-
242
-            $requestIsOk = $data['titleblacklist']['result'] == "ok";
243
-
244
-            if (!$requestIsOk) {
245
-                $this->request->setStatus("Flagged users");
246
-            }
247
-        }
248
-    }
249
-
250
-    private function userExists()
251
-    {
252
-        $userExists = $this->httpHelper->get(
253
-            $this->mediawikiApiEndpoint,
254
-            array(
255
-                'action'  => 'query',
256
-                'list'    => 'users',
257
-                'ususers' => $this->request->getName(),
258
-                'format'  => 'php',
259
-            )
260
-        );
261
-
262
-        $ue = unserialize($userExists);
263
-        if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
264
-            return true;
265
-        }
266
-
267
-        return false;
268
-    }
269
-
270
-    private function userSulExists()
271
-    {
272
-        $requestName = $this->request->getName();
273
-
274
-        $userExists = $this->httpHelper->get(
275
-            $this->mediawikiApiEndpoint,
276
-            array(
277
-                'action'  => 'query',
278
-                'meta'    => 'globaluserinfo',
279
-                'guiuser' => $requestName,
280
-                'format'  => 'php',
281
-            )
282
-        );
283
-
284
-        $ue = unserialize($userExists);
285
-        if (isset ($ue['query']['globaluserinfo']['id'])) {
286
-            return true;
287
-        }
288
-
289
-        return false;
290
-    }
291
-
292
-    /**
293
-     * Checks if a request with this name is currently open
294
-     *
295
-     * @return bool
296
-     */
297
-    private function nameRequestExists()
298
-    {
299
-        $query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
300
-        $statement = $this->database->prepare($query);
301
-        $statement->execute(array(':name' => $this->request->getName()));
302
-
303
-        if (!$statement) {
304
-            return false;
305
-        }
306
-
307
-        return $statement->fetchColumn() > 0;
308
-    }
25
+	/** @var IBanHelper */
26
+	private $banHelper;
27
+	/** @var Request */
28
+	private $request;
29
+	private $emailConfirmation;
30
+	/** @var PdoDatabase */
31
+	private $database;
32
+	/** @var IAntiSpoofProvider */
33
+	private $antiSpoofProvider;
34
+	/** @var IXffTrustProvider */
35
+	private $xffTrustProvider;
36
+	/** @var HttpHelper */
37
+	private $httpHelper;
38
+	/**
39
+	 * @var string
40
+	 */
41
+	private $mediawikiApiEndpoint;
42
+	private $titleBlacklistEnabled;
43
+	/**
44
+	 * @var TorExitProvider
45
+	 */
46
+	private $torExitProvider;
47
+
48
+	/**
49
+	 * Summary of __construct
50
+	 *
51
+	 * @param IBanHelper         $banHelper
52
+	 * @param Request            $request
53
+	 * @param string             $emailConfirmation
54
+	 * @param PdoDatabase        $database
55
+	 * @param IAntiSpoofProvider $antiSpoofProvider
56
+	 * @param IXffTrustProvider  $xffTrustProvider
57
+	 * @param HttpHelper         $httpHelper
58
+	 * @param string             $mediawikiApiEndpoint
59
+	 * @param boolean            $titleBlacklistEnabled
60
+	 * @param TorExitProvider    $torExitProvider
61
+	 */
62
+	public function __construct(
63
+		IBanHelper $banHelper,
64
+		Request $request,
65
+		$emailConfirmation,
66
+		PdoDatabase $database,
67
+		IAntiSpoofProvider $antiSpoofProvider,
68
+		IXffTrustProvider $xffTrustProvider,
69
+		HttpHelper $httpHelper,
70
+		$mediawikiApiEndpoint,
71
+		$titleBlacklistEnabled,
72
+		TorExitProvider $torExitProvider
73
+	) {
74
+		$this->banHelper = $banHelper;
75
+		$this->request = $request;
76
+		$this->emailConfirmation = $emailConfirmation;
77
+		$this->database = $database;
78
+		$this->antiSpoofProvider = $antiSpoofProvider;
79
+		$this->xffTrustProvider = $xffTrustProvider;
80
+		$this->httpHelper = $httpHelper;
81
+		$this->mediawikiApiEndpoint = $mediawikiApiEndpoint;
82
+		$this->titleBlacklistEnabled = $titleBlacklistEnabled;
83
+		$this->torExitProvider = $torExitProvider;
84
+	}
85
+
86
+	/**
87
+	 * Summary of validateName
88
+	 * @return ValidationError[]
89
+	 */
90
+	public function validateName()
91
+	{
92
+		$errorList = array();
93
+
94
+		// ERRORS
95
+		// name is empty
96
+		if (trim($this->request->getName()) == "") {
97
+			$errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
98
+		}
99
+
100
+		// name is banned
101
+		$ban = $this->banHelper->nameIsBanned($this->request->getName());
102
+		if ($ban != false) {
103
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
104
+		}
105
+
106
+		// username already exists
107
+		if ($this->userExists()) {
108
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
109
+		}
110
+
111
+		// username part of SUL account
112
+		if ($this->userSulExists()) {
113
+			// using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
114
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
115
+		}
116
+
117
+		// username is numbers
118
+		if (preg_match("/^[0-9]+$/", $this->request->getName()) === 1) {
119
+			$errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
120
+		}
121
+
122
+		// username can't contain #@/<>[]|{}
123
+		if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $this->request->getName()) === 1) {
124
+			$errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
125
+		}
126
+
127
+		// existing non-closed request for this name
128
+		if ($this->nameRequestExists()) {
129
+			$errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
130
+		}
131
+
132
+		return $errorList;
133
+	}
134
+
135
+	/**
136
+	 * Summary of validateEmail
137
+	 * @return ValidationError[]
138
+	 */
139
+	public function validateEmail()
140
+	{
141
+		$errorList = array();
142
+
143
+		// ERRORS
144
+
145
+		// Email is banned
146
+		$ban = $this->banHelper->emailIsBanned($this->request->getEmail());
147
+		if ($ban != false) {
148
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
149
+		}
150
+
151
+		// email addresses must match
152
+		if ($this->request->getEmail() != $this->emailConfirmation) {
153
+			$errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
154
+		}
155
+
156
+		// email address must be validly formed
157
+		if (trim($this->request->getEmail()) == "") {
158
+			$errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
159
+		}
160
+
161
+		// email address must be validly formed
162
+		if (!filter_var($this->request->getEmail(), FILTER_VALIDATE_EMAIL)) {
163
+			if (trim($this->request->getEmail()) != "") {
164
+				$errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
165
+			}
166
+		}
167
+
168
+		// email address can't be wikimedia/wikipedia .com/org
169
+		if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $this->request->getEmail()) === 1) {
170
+			$errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
171
+		}
172
+
173
+		// WARNINGS
174
+
175
+		return $errorList;
176
+	}
177
+
178
+	/**
179
+	 * Summary of validateOther
180
+	 * @return ValidationError[]
181
+	 */
182
+	public function validateOther()
183
+	{
184
+		$errorList = array();
185
+
186
+		$trustedIp = $this->xffTrustProvider->getTrustedClientIp($this->request->getIp(),
187
+			$this->request->getForwardedIp());
188
+
189
+		// ERRORS
190
+
191
+		// TOR nodes
192
+		if ($this->torExitProvider->isTorExit($trustedIp)) {
193
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
194
+		}
195
+
196
+		// IP banned
197
+		$ban = $this->banHelper->ipIsBanned($trustedIp);
198
+		if ($ban != false) {
199
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
200
+		}
201
+
202
+		// WARNINGS
203
+
204
+		// Antispoof check
205
+		$this->checkAntiSpoof();
206
+
207
+		// Blacklist check
208
+		$this->checkTitleBlacklist();
209
+
210
+		return $errorList;
211
+	}
212
+
213
+	private function checkAntiSpoof()
214
+	{
215
+		try {
216
+			if (count($this->antiSpoofProvider->getSpoofs($this->request->getName())) > 0) {
217
+				// If there were spoofs an Admin should handle the request.
218
+				$this->request->setStatus("Flagged users");
219
+			}
220
+		}
221
+		catch (Exception $ex) {
222
+			// logme
223
+		}
224
+	}
225
+
226
+	private function checkTitleBlacklist()
227
+	{
228
+		if ($this->titleBlacklistEnabled == 1) {
229
+			$apiResult = $this->httpHelper->get(
230
+				$this->mediawikiApiEndpoint,
231
+				array(
232
+					'action'       => 'titleblacklist',
233
+					'tbtitle'      => $this->request->getName(),
234
+					'tbaction'     => 'new-account',
235
+					'tbnooverride' => true,
236
+					'format'       => 'php',
237
+				)
238
+			);
239
+
240
+			$data = unserialize($apiResult);
241
+
242
+			$requestIsOk = $data['titleblacklist']['result'] == "ok";
243
+
244
+			if (!$requestIsOk) {
245
+				$this->request->setStatus("Flagged users");
246
+			}
247
+		}
248
+	}
249
+
250
+	private function userExists()
251
+	{
252
+		$userExists = $this->httpHelper->get(
253
+			$this->mediawikiApiEndpoint,
254
+			array(
255
+				'action'  => 'query',
256
+				'list'    => 'users',
257
+				'ususers' => $this->request->getName(),
258
+				'format'  => 'php',
259
+			)
260
+		);
261
+
262
+		$ue = unserialize($userExists);
263
+		if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
264
+			return true;
265
+		}
266
+
267
+		return false;
268
+	}
269
+
270
+	private function userSulExists()
271
+	{
272
+		$requestName = $this->request->getName();
273
+
274
+		$userExists = $this->httpHelper->get(
275
+			$this->mediawikiApiEndpoint,
276
+			array(
277
+				'action'  => 'query',
278
+				'meta'    => 'globaluserinfo',
279
+				'guiuser' => $requestName,
280
+				'format'  => 'php',
281
+			)
282
+		);
283
+
284
+		$ue = unserialize($userExists);
285
+		if (isset ($ue['query']['globaluserinfo']['id'])) {
286
+			return true;
287
+		}
288
+
289
+		return false;
290
+	}
291
+
292
+	/**
293
+	 * Checks if a request with this name is currently open
294
+	 *
295
+	 * @return bool
296
+	 */
297
+	private function nameRequestExists()
298
+	{
299
+		$query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
300
+		$statement = $this->database->prepare($query);
301
+		$statement->execute(array(':name' => $this->request->getName()));
302
+
303
+		if (!$statement) {
304
+			return false;
305
+		}
306
+
307
+		return $statement->fetchColumn() > 0;
308
+	}
309 309
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@
 block discarded – undo
120 120
         }
121 121
 
122 122
         // username can't contain #@/<>[]|{}
123
-        if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $this->request->getName()) === 1) {
123
+        if (preg_match("/[".preg_quote("#@/<>[]|{}", "/")."]/", $this->request->getName()) === 1) {
124 124
             $errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
125 125
         }
126 126
 
Please login to merge, or discard this patch.