Passed
Push — master ( 3e5dae...8d4e4c )
by Simon
12:37
created
includes/Exceptions/AccessDeniedException.php 1 patch
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -26,93 +26,93 @@
 block discarded – undo
26 26
  */
27 27
 class AccessDeniedException extends ReadableException
28 28
 {
29
-    use NavigationMenuAccessControl;
30
-
31
-    /** @var SecurityManager */
32
-    private $securityManager;
33
-    /** @var DomainAccessManager */
34
-    private $domainAccessManager;
35
-
36
-    /**
37
-     * AccessDeniedException constructor.
38
-     *
39
-     * @param SecurityManager     $securityManager
40
-     * @param DomainAccessManager $domainAccessManager
41
-     */
42
-    public function __construct(SecurityManager $securityManager, DomainAccessManager $domainAccessManager)
43
-    {
44
-        $this->securityManager = $securityManager;
45
-        $this->domainAccessManager = $domainAccessManager;
46
-    }
47
-
48
-    public function getReadableError()
49
-    {
50
-        if (!headers_sent()) {
51
-            header("HTTP/1.1 403 Forbidden");
52
-        }
53
-
54
-        $this->setUpSmarty();
55
-
56
-        // uck. We should still be able to access the database in this situation though.
57
-        $database = PdoDatabase::getDatabaseConnection('acc');
58
-        $currentUser = User::getCurrent($database);
59
-        $this->assign('currentUser', $currentUser);
60
-        $this->assign('currentDomain', Domain::getCurrent($database));
61
-
62
-        if ($this->securityManager !== null) {
63
-            $this->setupNavMenuAccess($currentUser);
64
-        }
65
-
66
-        if ($currentUser->isDeclined()) {
67
-            $this->assign('htmlTitle', 'Account Declined');
68
-            $this->assign('declineReason', $this->getLogEntry('Declined', $currentUser, $database));
69
-
70
-            return $this->fetchTemplate("exception/account-declined.tpl");
71
-        }
72
-
73
-        if ($currentUser->isSuspended()) {
74
-            $this->assign('htmlTitle', 'Account Suspended');
75
-            $this->assign('suspendReason', $this->getLogEntry('Suspended', $currentUser, $database));
76
-
77
-            return $this->fetchTemplate("exception/account-suspended.tpl");
78
-        }
79
-
80
-        if ($currentUser->isNewUser()) {
81
-            $this->assign('htmlTitle', 'Account Pending');
82
-
83
-            return $this->fetchTemplate("exception/account-new.tpl");
84
-        }
85
-
86
-        return $this->fetchTemplate("exception/access-denied.tpl");
87
-    }
88
-
89
-    /**
90
-     * @param string      $action
91
-     * @param User        $user
92
-     * @param PdoDatabase $database
93
-     *
94
-     * @return null|string
95
-     */
96
-    private function getLogEntry($action, User $user, PdoDatabase $database)
97
-    {
98
-        /** @var Log[] $logs */
99
-        $logs = LogSearchHelper::get($database)
100
-            ->byAction($action)
101
-            ->byObjectType('User')
102
-            ->byObjectId($user->getId())
103
-            ->limit(1)
104
-            ->fetch();
105
-
106
-        return $logs[0]->getComment();
107
-    }
108
-
109
-    protected function getSecurityManager(): SecurityManager
110
-    {
111
-        return $this->securityManager;
112
-    }
113
-
114
-    public function getDomainAccessManager(): DomainAccessManager
115
-    {
116
-        return $this->domainAccessManager;
117
-    }
29
+	use NavigationMenuAccessControl;
30
+
31
+	/** @var SecurityManager */
32
+	private $securityManager;
33
+	/** @var DomainAccessManager */
34
+	private $domainAccessManager;
35
+
36
+	/**
37
+	 * AccessDeniedException constructor.
38
+	 *
39
+	 * @param SecurityManager     $securityManager
40
+	 * @param DomainAccessManager $domainAccessManager
41
+	 */
42
+	public function __construct(SecurityManager $securityManager, DomainAccessManager $domainAccessManager)
43
+	{
44
+		$this->securityManager = $securityManager;
45
+		$this->domainAccessManager = $domainAccessManager;
46
+	}
47
+
48
+	public function getReadableError()
49
+	{
50
+		if (!headers_sent()) {
51
+			header("HTTP/1.1 403 Forbidden");
52
+		}
53
+
54
+		$this->setUpSmarty();
55
+
56
+		// uck. We should still be able to access the database in this situation though.
57
+		$database = PdoDatabase::getDatabaseConnection('acc');
58
+		$currentUser = User::getCurrent($database);
59
+		$this->assign('currentUser', $currentUser);
60
+		$this->assign('currentDomain', Domain::getCurrent($database));
61
+
62
+		if ($this->securityManager !== null) {
63
+			$this->setupNavMenuAccess($currentUser);
64
+		}
65
+
66
+		if ($currentUser->isDeclined()) {
67
+			$this->assign('htmlTitle', 'Account Declined');
68
+			$this->assign('declineReason', $this->getLogEntry('Declined', $currentUser, $database));
69
+
70
+			return $this->fetchTemplate("exception/account-declined.tpl");
71
+		}
72
+
73
+		if ($currentUser->isSuspended()) {
74
+			$this->assign('htmlTitle', 'Account Suspended');
75
+			$this->assign('suspendReason', $this->getLogEntry('Suspended', $currentUser, $database));
76
+
77
+			return $this->fetchTemplate("exception/account-suspended.tpl");
78
+		}
79
+
80
+		if ($currentUser->isNewUser()) {
81
+			$this->assign('htmlTitle', 'Account Pending');
82
+
83
+			return $this->fetchTemplate("exception/account-new.tpl");
84
+		}
85
+
86
+		return $this->fetchTemplate("exception/access-denied.tpl");
87
+	}
88
+
89
+	/**
90
+	 * @param string      $action
91
+	 * @param User        $user
92
+	 * @param PdoDatabase $database
93
+	 *
94
+	 * @return null|string
95
+	 */
96
+	private function getLogEntry($action, User $user, PdoDatabase $database)
97
+	{
98
+		/** @var Log[] $logs */
99
+		$logs = LogSearchHelper::get($database)
100
+			->byAction($action)
101
+			->byObjectType('User')
102
+			->byObjectId($user->getId())
103
+			->limit(1)
104
+			->fetch();
105
+
106
+		return $logs[0]->getComment();
107
+	}
108
+
109
+	protected function getSecurityManager(): SecurityManager
110
+	{
111
+		return $this->securityManager;
112
+	}
113
+
114
+	public function getDomainAccessManager(): DomainAccessManager
115
+	{
116
+		return $this->domainAccessManager;
117
+	}
118 118
 }
119 119
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Validation/ValidationError.php 1 patch
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -12,102 +12,102 @@
 block discarded – undo
12 12
 
13 13
 class ValidationError
14 14
 {
15
-    const NAME_EMPTY = "name_empty";
16
-    const NAME_TOO_LONG = "name_too_long";
17
-    const NAME_EXISTS = "name_exists";
18
-    const NAME_EXISTS_SUL = "name_exists_sul";
19
-    const NAME_NUMONLY = "name_numonly";
20
-    const NAME_INVALIDCHAR = "name_invalidchar";
21
-    const NAME_SANITISED = "name_sanitised";
22
-    const NAME_IP = "name_ip";
23
-    const EMAIL_EMPTY = "email_empty";
24
-    const EMAIL_WIKIMEDIA = "email_wikimedia";
25
-    const EMAIL_INVALID = "email_invalid";
26
-    const EMAIL_MISMATCH = "email_mismatch";
27
-    const OPEN_REQUEST_NAME = "open_request_name";
28
-    const BANNED = "banned";
29
-    const BANNED_TOR = "banned_tor";
30
-    /**
31
-     * @var array Error text for the above
32
-     */
33
-    private static $errorText = array(
34
-        self::NAME_EMPTY        => 'You\'ve not chosen a username!',
35
-        self::NAME_TOO_LONG     => 'Your chosen username is too long. Please choose a shorter one.',
36
-        self::NAME_EXISTS       => 'I\'m sorry, but the username you selected is already taken. Please try another. '
37
-            . 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
38
-            . '[[User:example]] would become [[User:Example]].',
39
-        self::NAME_EXISTS_SUL   => 'I\'m sorry, but the username you selected is already taken. Please try another. '
40
-            . 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
41
-            . '[[User:example]] would become [[User:Example]].',
42
-        self::NAME_NUMONLY      => 'The username you chose is invalid: it consists entirely of numbers. Please retry '
43
-            . 'with a valid username.',
44
-        self::NAME_INVALIDCHAR  => 'There appears to be an invalid character in your username. Please note that the '
45
-            . 'following characters are not allowed: <code># @ / &lt; &gt; [ ] | { }</code>',
46
-        self::NAME_SANITISED    => 'Your requested username has been automatically adjusted due to technical '
47
-            . 'restrictions. Underscores have been replaced with spaces, and the first character has been capitalised.',
48
-        self::NAME_IP           => 'The username you chose is invalid: it cannot be an IP address',
49
-        self::EMAIL_EMPTY       => 'You need to supply an email address.',
50
-        self::EMAIL_WIKIMEDIA   => 'Please provide your email address here.',
51
-        self::EMAIL_INVALID     => 'Invalid E-mail address supplied. Please check you entered it correctly.',
52
-        self::EMAIL_MISMATCH    => 'The email addresses you entered do not match. Please try again.',
53
-        self::OPEN_REQUEST_NAME => 'There is already an open request with this name in this system.',
54
-        self::BANNED            => 'Sorry, you are currently banned from requesting accounts using this tool.',
55
-        self::BANNED_TOR        => 'Tor exit nodes are currently banned from using this tool due to excessive abuse. '
56
-            . 'Please note that Tor is also currently banned from editing Wikipedia.',
57
-    );
58
-    /**
59
-     * Summary of $errorCode
60
-     * @var string
61
-     */
62
-    private $errorCode;
63
-    /**
64
-     * Summary of $isError
65
-     * @var bool
66
-     */
67
-    private $isError;
15
+	const NAME_EMPTY = "name_empty";
16
+	const NAME_TOO_LONG = "name_too_long";
17
+	const NAME_EXISTS = "name_exists";
18
+	const NAME_EXISTS_SUL = "name_exists_sul";
19
+	const NAME_NUMONLY = "name_numonly";
20
+	const NAME_INVALIDCHAR = "name_invalidchar";
21
+	const NAME_SANITISED = "name_sanitised";
22
+	const NAME_IP = "name_ip";
23
+	const EMAIL_EMPTY = "email_empty";
24
+	const EMAIL_WIKIMEDIA = "email_wikimedia";
25
+	const EMAIL_INVALID = "email_invalid";
26
+	const EMAIL_MISMATCH = "email_mismatch";
27
+	const OPEN_REQUEST_NAME = "open_request_name";
28
+	const BANNED = "banned";
29
+	const BANNED_TOR = "banned_tor";
30
+	/**
31
+	 * @var array Error text for the above
32
+	 */
33
+	private static $errorText = array(
34
+		self::NAME_EMPTY        => 'You\'ve not chosen a username!',
35
+		self::NAME_TOO_LONG     => 'Your chosen username is too long. Please choose a shorter one.',
36
+		self::NAME_EXISTS       => 'I\'m sorry, but the username you selected is already taken. Please try another. '
37
+			. 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
38
+			. '[[User:example]] would become [[User:Example]].',
39
+		self::NAME_EXISTS_SUL   => 'I\'m sorry, but the username you selected is already taken. Please try another. '
40
+			. 'Please note that Wikipedia automatically capitalizes the first letter of any user name, therefore '
41
+			. '[[User:example]] would become [[User:Example]].',
42
+		self::NAME_NUMONLY      => 'The username you chose is invalid: it consists entirely of numbers. Please retry '
43
+			. 'with a valid username.',
44
+		self::NAME_INVALIDCHAR  => 'There appears to be an invalid character in your username. Please note that the '
45
+			. 'following characters are not allowed: <code># @ / &lt; &gt; [ ] | { }</code>',
46
+		self::NAME_SANITISED    => 'Your requested username has been automatically adjusted due to technical '
47
+			. 'restrictions. Underscores have been replaced with spaces, and the first character has been capitalised.',
48
+		self::NAME_IP           => 'The username you chose is invalid: it cannot be an IP address',
49
+		self::EMAIL_EMPTY       => 'You need to supply an email address.',
50
+		self::EMAIL_WIKIMEDIA   => 'Please provide your email address here.',
51
+		self::EMAIL_INVALID     => 'Invalid E-mail address supplied. Please check you entered it correctly.',
52
+		self::EMAIL_MISMATCH    => 'The email addresses you entered do not match. Please try again.',
53
+		self::OPEN_REQUEST_NAME => 'There is already an open request with this name in this system.',
54
+		self::BANNED            => 'Sorry, you are currently banned from requesting accounts using this tool.',
55
+		self::BANNED_TOR        => 'Tor exit nodes are currently banned from using this tool due to excessive abuse. '
56
+			. 'Please note that Tor is also currently banned from editing Wikipedia.',
57
+	);
58
+	/**
59
+	 * Summary of $errorCode
60
+	 * @var string
61
+	 */
62
+	private $errorCode;
63
+	/**
64
+	 * Summary of $isError
65
+	 * @var bool
66
+	 */
67
+	private $isError;
68 68
 
69
-    /**
70
-     * Summary of __construct
71
-     *
72
-     * @param string $errorCode
73
-     * @param bool   $isError
74
-     */
75
-    public function __construct($errorCode, $isError = true)
76
-    {
77
-        $this->errorCode = $errorCode;
78
-        $this->isError = $isError;
79
-    }
69
+	/**
70
+	 * Summary of __construct
71
+	 *
72
+	 * @param string $errorCode
73
+	 * @param bool   $isError
74
+	 */
75
+	public function __construct($errorCode, $isError = true)
76
+	{
77
+		$this->errorCode = $errorCode;
78
+		$this->isError = $isError;
79
+	}
80 80
 
81
-    /**
82
-     * Summary of getErrorCode
83
-     * @return string
84
-     */
85
-    public function getErrorCode()
86
-    {
87
-        return $this->errorCode;
88
-    }
81
+	/**
82
+	 * Summary of getErrorCode
83
+	 * @return string
84
+	 */
85
+	public function getErrorCode()
86
+	{
87
+		return $this->errorCode;
88
+	}
89 89
 
90
-    /**
91
-     * @return string
92
-     * @throws Exception
93
-     */
94
-    public function getErrorMessage()
95
-    {
96
-        $text = self::$errorText[$this->errorCode];
90
+	/**
91
+	 * @return string
92
+	 * @throws Exception
93
+	 */
94
+	public function getErrorMessage()
95
+	{
96
+		$text = self::$errorText[$this->errorCode];
97 97
 
98
-        if ($text == null) {
99
-            throw new Exception('Unknown validation error');
100
-        }
98
+		if ($text == null) {
99
+			throw new Exception('Unknown validation error');
100
+		}
101 101
 
102
-        return $text;
103
-    }
102
+		return $text;
103
+	}
104 104
 
105
-    /**
106
-     * Summary of isError
107
-     * @return bool
108
-     */
109
-    public function isError()
110
-    {
111
-        return $this->isError;
112
-    }
105
+	/**
106
+	 * Summary of isError
107
+	 * @return bool
108
+	 */
109
+	public function isError()
110
+	{
111
+		return $this->isError;
112
+	}
113 113
 }
Please login to merge, or discard this patch.
includes/Validation/RequestValidationHelper.php 2 patches
Indentation   +422 added lines, -422 removed lines patch added patch discarded remove patch
@@ -31,426 +31,426 @@
 block discarded – undo
31 31
  */
32 32
 class RequestValidationHelper
33 33
 {
34
-    /** @var IBanHelper */
35
-    private $banHelper;
36
-    /** @var PdoDatabase */
37
-    private $database;
38
-    /** @var IAntiSpoofProvider */
39
-    private $antiSpoofProvider;
40
-    /** @var IXffTrustProvider */
41
-    private $xffTrustProvider;
42
-    /** @var HttpHelper */
43
-    private $httpHelper;
44
-    /**
45
-     * @var string
46
-     */
47
-    private $mediawikiApiEndpoint;
48
-    private $titleBlacklistEnabled;
49
-    /**
50
-     * @var TorExitProvider
51
-     */
52
-    private $torExitProvider;
53
-    /**
54
-     * @var SiteConfiguration
55
-     */
56
-    private $siteConfiguration;
57
-
58
-    private $validationRemoteTimeout = 5000;
59
-
60
-    /**
61
-     * Summary of __construct
62
-     *
63
-     * @param IBanHelper         $banHelper
64
-     * @param PdoDatabase        $database
65
-     * @param IAntiSpoofProvider $antiSpoofProvider
66
-     * @param IXffTrustProvider  $xffTrustProvider
67
-     * @param HttpHelper         $httpHelper
68
-     * @param TorExitProvider    $torExitProvider
69
-     * @param SiteConfiguration  $siteConfiguration
70
-     */
71
-    public function __construct(
72
-        IBanHelper $banHelper,
73
-        PdoDatabase $database,
74
-        IAntiSpoofProvider $antiSpoofProvider,
75
-        IXffTrustProvider $xffTrustProvider,
76
-        HttpHelper $httpHelper,
77
-        TorExitProvider $torExitProvider,
78
-        SiteConfiguration $siteConfiguration
79
-    ) {
80
-        $this->banHelper = $banHelper;
81
-        $this->database = $database;
82
-        $this->antiSpoofProvider = $antiSpoofProvider;
83
-        $this->xffTrustProvider = $xffTrustProvider;
84
-        $this->httpHelper = $httpHelper;
85
-
86
-        // FIXME: domains!
87
-        /** @var Domain $domain */
88
-        $domain = Domain::getById(1, $database);
89
-
90
-        $this->mediawikiApiEndpoint = $domain->getWikiApiPath();
91
-        $this->titleBlacklistEnabled = $siteConfiguration->getTitleBlacklistEnabled();
92
-        $this->torExitProvider = $torExitProvider;
93
-        $this->siteConfiguration = $siteConfiguration;
94
-    }
95
-
96
-    /**
97
-     * Summary of validateName
98
-     *
99
-     * @param Request $request
100
-     *
101
-     * @return ValidationError[]
102
-     */
103
-    public function validateName(Request $request)
104
-    {
105
-        $errorList = array();
106
-
107
-        // ERRORS
108
-        // name is empty
109
-        if (trim($request->getName()) == "") {
110
-            $errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
111
-        }
112
-
113
-        // name is too long
114
-        if (mb_strlen(trim($request->getName())) > 500) {
115
-            $errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_TOO_LONG);
116
-        }
117
-
118
-        // username already exists
119
-        if ($this->userExists($request)) {
120
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
121
-        }
122
-
123
-        // username part of SUL account
124
-        if ($this->userSulExists($request)) {
125
-            // using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
126
-            $errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
127
-        }
128
-
129
-        // username is numbers
130
-        if (preg_match("/^[0-9]+$/", $request->getName()) === 1) {
131
-            $errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
132
-        }
133
-
134
-        // username can't contain #@/<>[]|{}
135
-        if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $request->getName()) === 1) {
136
-            $errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
137
-        }
138
-
139
-        // username is an IP
140
-        if (filter_var($request->getName(), FILTER_VALIDATE_IP)) {
141
-            $errorList[ValidationError::NAME_IP] = new ValidationError(ValidationError::NAME_IP);
142
-        }
143
-
144
-        // existing non-closed request for this name
145
-        if ($this->nameRequestExists($request)) {
146
-            $errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
147
-        }
148
-
149
-        return $errorList;
150
-    }
151
-
152
-    /**
153
-     * Summary of validateEmail
154
-     *
155
-     * @param Request $request
156
-     * @param string  $emailConfirmation
157
-     *
158
-     * @return ValidationError[]
159
-     */
160
-    public function validateEmail(Request $request, $emailConfirmation)
161
-    {
162
-        $errorList = array();
163
-
164
-        // ERRORS
165
-
166
-        // email addresses must match
167
-        if ($request->getEmail() != $emailConfirmation) {
168
-            $errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
169
-        }
170
-
171
-        // email address must be validly formed
172
-        if (trim($request->getEmail()) == "") {
173
-            $errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
174
-        }
175
-
176
-        // email address must be validly formed
177
-        if (!filter_var($request->getEmail(), FILTER_VALIDATE_EMAIL)) {
178
-            if (trim($request->getEmail()) != "") {
179
-                $errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
180
-            }
181
-        }
182
-
183
-        // email address can't be wikimedia/wikipedia .com/org
184
-        if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $request->getEmail()) === 1) {
185
-            $errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
186
-        }
187
-
188
-        return $errorList;
189
-    }
190
-
191
-    /**
192
-     * Summary of validateOther
193
-     *
194
-     * @param Request $request
195
-     *
196
-     * @return ValidationError[]
197
-     */
198
-    public function validateOther(Request $request)
199
-    {
200
-        $errorList = array();
201
-
202
-        $trustedIp = $this->xffTrustProvider->getTrustedClientIp($request->getIp(),
203
-            $request->getForwardedIp());
204
-
205
-        // ERRORS
206
-
207
-        // TOR nodes
208
-        if ($this->torExitProvider->isTorExit($trustedIp)) {
209
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
210
-        }
211
-
212
-        // Bans
213
-        if ($this->banHelper->isBlockBanned($request)) {
214
-            $errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
215
-        }
216
-
217
-        return $errorList;
218
-    }
219
-
220
-    public function postSaveValidations(Request $request)
221
-    {
222
-        // Antispoof check
223
-        $this->checkAntiSpoof($request);
224
-
225
-        // Blacklist check
226
-        $this->checkTitleBlacklist($request);
227
-
228
-        // Add comment for form override
229
-        $this->formOverride($request);
230
-
231
-        $bans = $this->banHelper->getBans($request);
232
-
233
-        foreach ($bans as $ban) {
234
-            if ($ban->getAction() == Ban::ACTION_DROP) {
235
-                $request->setStatus(RequestStatus::CLOSED);
236
-                $request->save();
237
-
238
-                Logger::closeRequest($request->getDatabase(), $request, 0, null);
239
-
240
-                $comment = new Comment();
241
-                $comment->setDatabase($this->database);
242
-                $comment->setRequest($request->getId());
243
-                $comment->setVisibility('user');
244
-                $comment->setUser(null);
245
-
246
-                $comment->setComment('Request dropped automatically due to matching rule.');
247
-                $comment->save();
248
-            }
249
-
250
-            if ($ban->getAction() == Ban::ACTION_DEFER) {
251
-                /** @var RequestQueue|false $targetQueue */
252
-                $targetQueue = RequestQueue::getById($ban->getTargetQueue(), $this->database);
253
-
254
-                if ($targetQueue === false ) {
255
-                    $comment = new Comment();
256
-                    $comment->setDatabase($this->database);
257
-                    $comment->setRequest($request->getId());
258
-                    $comment->setVisibility('user');
259
-                    $comment->setUser(null);
260
-
261
-                    $comment->setComment("This request would have been deferred automatically due to a matching rule, but the queue to defer to could not be found.");
262
-                    $comment->save();
263
-                }
264
-                else {
265
-                    $this->deferRequest($request, $targetQueue, 'Request deferred automatically due to matching rule.');
266
-                }
267
-            }
268
-        }
269
-    }
270
-
271
-    private function checkAntiSpoof(Request $request)
272
-    {
273
-        try {
274
-            if (count($this->antiSpoofProvider->getSpoofs($request->getName())) > 0) {
275
-                // If there were spoofs an Admin should handle the request.
276
-                // FIXME: domains!
277
-                $defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_ANTISPOOF);
278
-                $this->deferRequest($request, $defaultQueue,
279
-                    'Request automatically deferred due to AntiSpoof hit');
280
-            }
281
-        }
282
-        catch (Exception $ex) {
283
-            $skippable = [
284
-                'Encountered error while getting result: Contains unassigned character',
285
-                'Encountered error while getting result: Contains incompatible mixed scripts',
286
-                'Encountered error while getting result: Does not contain any letters'
287
-            ];
288
-
289
-            $skip = false;
290
-
291
-            foreach ($skippable as $s) {
292
-                if (strpos($ex->getMessage(), $s) !== false) {
293
-                    $skip = true;
294
-                    break;
295
-                }
296
-            }
297
-
298
-            // Only log to disk if this *isn't* a "skippable" error.
299
-            if (!$skip) {
300
-                ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
301
-            }
302
-        }
303
-    }
304
-
305
-    private function checkTitleBlacklist(Request $request)
306
-    {
307
-        if ($this->titleBlacklistEnabled == 1) {
308
-            try {
309
-                $apiResult = $this->httpHelper->get(
310
-                    $this->mediawikiApiEndpoint,
311
-                    array(
312
-                        'action'       => 'titleblacklist',
313
-                        'tbtitle'      => $request->getName(),
314
-                        'tbaction'     => 'new-account',
315
-                        'tbnooverride' => true,
316
-                        'format'       => 'php',
317
-                    ),
318
-                    [],
319
-                    $this->validationRemoteTimeout
320
-                );
321
-
322
-                $data = unserialize($apiResult);
323
-
324
-                $requestIsOk = $data['titleblacklist']['result'] == "ok";
325
-            }
326
-            catch (CurlException $ex) {
327
-                ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
328
-
329
-                // Don't kill the request, just assume it's fine. Humans can deal with it later.
330
-                return;
331
-            }
332
-
333
-            if (!$requestIsOk) {
334
-                // FIXME: domains!
335
-                $defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_TITLEBLACKLIST);
336
-
337
-                $this->deferRequest($request, $defaultQueue,
338
-                    'Request automatically deferred due to title blacklist hit');
339
-            }
340
-        }
341
-    }
342
-
343
-    private function userExists(Request $request)
344
-    {
345
-        try {
346
-            $userExists = $this->httpHelper->get(
347
-                $this->mediawikiApiEndpoint,
348
-                array(
349
-                    'action'  => 'query',
350
-                    'list'    => 'users',
351
-                    'ususers' => $request->getName(),
352
-                    'format'  => 'php',
353
-                ),
354
-                [],
355
-                $this->validationRemoteTimeout
356
-            );
357
-
358
-            $ue = unserialize($userExists);
359
-            if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
360
-                return true;
361
-            }
362
-        }
363
-        catch (CurlException $ex) {
364
-            ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
365
-
366
-            // Don't kill the request, just assume it's fine. Humans can deal with it later.
367
-            return false;
368
-        }
369
-
370
-        return false;
371
-    }
372
-
373
-    private function userSulExists(Request $request)
374
-    {
375
-        $requestName = $request->getName();
376
-
377
-        try {
378
-            $userExists = $this->httpHelper->get(
379
-                $this->mediawikiApiEndpoint,
380
-                array(
381
-                    'action'  => 'query',
382
-                    'meta'    => 'globaluserinfo',
383
-                    'guiuser' => $requestName,
384
-                    'format'  => 'php',
385
-                ),
386
-                [],
387
-                $this->validationRemoteTimeout
388
-            );
389
-
390
-            $ue = unserialize($userExists);
391
-            if (isset ($ue['query']['globaluserinfo']['id'])) {
392
-                return true;
393
-            }
394
-        }
395
-        catch (CurlException $ex) {
396
-            ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
397
-
398
-            // Don't kill the request, just assume it's fine. Humans can deal with it later.
399
-            return false;
400
-        }
401
-
402
-        return false;
403
-    }
404
-
405
-    /**
406
-     * Checks if a request with this name is currently open
407
-     *
408
-     * @param Request $request
409
-     *
410
-     * @return bool
411
-     */
412
-    private function nameRequestExists(Request $request)
413
-    {
414
-        $query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
415
-        $statement = $this->database->prepare($query);
416
-        $statement->execute(array(':name' => $request->getName()));
417
-
418
-        if (!$statement) {
419
-            return false;
420
-        }
421
-
422
-        return $statement->fetchColumn() > 0;
423
-    }
424
-
425
-    private function deferRequest(Request $request, RequestQueue $targetQueue, $deferComment): void
426
-    {
427
-        $request->setQueue($targetQueue->getId());
428
-        $request->save();
429
-
430
-        $logTarget = $targetQueue->getLogName();
431
-
432
-        Logger::deferRequest($this->database, $request, $logTarget);
433
-
434
-        $comment = new Comment();
435
-        $comment->setDatabase($this->database);
436
-        $comment->setRequest($request->getId());
437
-        $comment->setVisibility('user');
438
-        $comment->setUser(null);
439
-
440
-        $comment->setComment($deferComment);
441
-        $comment->save();
442
-    }
443
-
444
-    private function formOverride(Request $request)
445
-    {
446
-        $form = $request->getOriginFormObject();
447
-        if($form === null || $form->getOverrideQueue() === null) {
448
-            return;
449
-        }
450
-
451
-        /** @var RequestQueue $targetQueue */
452
-        $targetQueue = RequestQueue::getById($form->getOverrideQueue(), $request->getDatabase());
453
-
454
-        $this->deferRequest($request, $targetQueue, 'Request deferred automatically due to request submission through a request form with a default queue set.');
455
-    }
34
+	/** @var IBanHelper */
35
+	private $banHelper;
36
+	/** @var PdoDatabase */
37
+	private $database;
38
+	/** @var IAntiSpoofProvider */
39
+	private $antiSpoofProvider;
40
+	/** @var IXffTrustProvider */
41
+	private $xffTrustProvider;
42
+	/** @var HttpHelper */
43
+	private $httpHelper;
44
+	/**
45
+	 * @var string
46
+	 */
47
+	private $mediawikiApiEndpoint;
48
+	private $titleBlacklistEnabled;
49
+	/**
50
+	 * @var TorExitProvider
51
+	 */
52
+	private $torExitProvider;
53
+	/**
54
+	 * @var SiteConfiguration
55
+	 */
56
+	private $siteConfiguration;
57
+
58
+	private $validationRemoteTimeout = 5000;
59
+
60
+	/**
61
+	 * Summary of __construct
62
+	 *
63
+	 * @param IBanHelper         $banHelper
64
+	 * @param PdoDatabase        $database
65
+	 * @param IAntiSpoofProvider $antiSpoofProvider
66
+	 * @param IXffTrustProvider  $xffTrustProvider
67
+	 * @param HttpHelper         $httpHelper
68
+	 * @param TorExitProvider    $torExitProvider
69
+	 * @param SiteConfiguration  $siteConfiguration
70
+	 */
71
+	public function __construct(
72
+		IBanHelper $banHelper,
73
+		PdoDatabase $database,
74
+		IAntiSpoofProvider $antiSpoofProvider,
75
+		IXffTrustProvider $xffTrustProvider,
76
+		HttpHelper $httpHelper,
77
+		TorExitProvider $torExitProvider,
78
+		SiteConfiguration $siteConfiguration
79
+	) {
80
+		$this->banHelper = $banHelper;
81
+		$this->database = $database;
82
+		$this->antiSpoofProvider = $antiSpoofProvider;
83
+		$this->xffTrustProvider = $xffTrustProvider;
84
+		$this->httpHelper = $httpHelper;
85
+
86
+		// FIXME: domains!
87
+		/** @var Domain $domain */
88
+		$domain = Domain::getById(1, $database);
89
+
90
+		$this->mediawikiApiEndpoint = $domain->getWikiApiPath();
91
+		$this->titleBlacklistEnabled = $siteConfiguration->getTitleBlacklistEnabled();
92
+		$this->torExitProvider = $torExitProvider;
93
+		$this->siteConfiguration = $siteConfiguration;
94
+	}
95
+
96
+	/**
97
+	 * Summary of validateName
98
+	 *
99
+	 * @param Request $request
100
+	 *
101
+	 * @return ValidationError[]
102
+	 */
103
+	public function validateName(Request $request)
104
+	{
105
+		$errorList = array();
106
+
107
+		// ERRORS
108
+		// name is empty
109
+		if (trim($request->getName()) == "") {
110
+			$errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_EMPTY);
111
+		}
112
+
113
+		// name is too long
114
+		if (mb_strlen(trim($request->getName())) > 500) {
115
+			$errorList[ValidationError::NAME_EMPTY] = new ValidationError(ValidationError::NAME_TOO_LONG);
116
+		}
117
+
118
+		// username already exists
119
+		if ($this->userExists($request)) {
120
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS);
121
+		}
122
+
123
+		// username part of SUL account
124
+		if ($this->userSulExists($request)) {
125
+			// using same error slot as name exists - it's the same sort of error, and we probably only want to show one.
126
+			$errorList[ValidationError::NAME_EXISTS] = new ValidationError(ValidationError::NAME_EXISTS_SUL);
127
+		}
128
+
129
+		// username is numbers
130
+		if (preg_match("/^[0-9]+$/", $request->getName()) === 1) {
131
+			$errorList[ValidationError::NAME_NUMONLY] = new ValidationError(ValidationError::NAME_NUMONLY);
132
+		}
133
+
134
+		// username can't contain #@/<>[]|{}
135
+		if (preg_match("/[" . preg_quote("#@/<>[]|{}", "/") . "]/", $request->getName()) === 1) {
136
+			$errorList[ValidationError::NAME_INVALIDCHAR] = new ValidationError(ValidationError::NAME_INVALIDCHAR);
137
+		}
138
+
139
+		// username is an IP
140
+		if (filter_var($request->getName(), FILTER_VALIDATE_IP)) {
141
+			$errorList[ValidationError::NAME_IP] = new ValidationError(ValidationError::NAME_IP);
142
+		}
143
+
144
+		// existing non-closed request for this name
145
+		if ($this->nameRequestExists($request)) {
146
+			$errorList[ValidationError::OPEN_REQUEST_NAME] = new ValidationError(ValidationError::OPEN_REQUEST_NAME);
147
+		}
148
+
149
+		return $errorList;
150
+	}
151
+
152
+	/**
153
+	 * Summary of validateEmail
154
+	 *
155
+	 * @param Request $request
156
+	 * @param string  $emailConfirmation
157
+	 *
158
+	 * @return ValidationError[]
159
+	 */
160
+	public function validateEmail(Request $request, $emailConfirmation)
161
+	{
162
+		$errorList = array();
163
+
164
+		// ERRORS
165
+
166
+		// email addresses must match
167
+		if ($request->getEmail() != $emailConfirmation) {
168
+			$errorList[ValidationError::EMAIL_MISMATCH] = new ValidationError(ValidationError::EMAIL_MISMATCH);
169
+		}
170
+
171
+		// email address must be validly formed
172
+		if (trim($request->getEmail()) == "") {
173
+			$errorList[ValidationError::EMAIL_EMPTY] = new ValidationError(ValidationError::EMAIL_EMPTY);
174
+		}
175
+
176
+		// email address must be validly formed
177
+		if (!filter_var($request->getEmail(), FILTER_VALIDATE_EMAIL)) {
178
+			if (trim($request->getEmail()) != "") {
179
+				$errorList[ValidationError::EMAIL_INVALID] = new ValidationError(ValidationError::EMAIL_INVALID);
180
+			}
181
+		}
182
+
183
+		// email address can't be wikimedia/wikipedia .com/org
184
+		if (preg_match('/.*@.*wiki(m.dia|p.dia)\.(org|com)/i', $request->getEmail()) === 1) {
185
+			$errorList[ValidationError::EMAIL_WIKIMEDIA] = new ValidationError(ValidationError::EMAIL_WIKIMEDIA);
186
+		}
187
+
188
+		return $errorList;
189
+	}
190
+
191
+	/**
192
+	 * Summary of validateOther
193
+	 *
194
+	 * @param Request $request
195
+	 *
196
+	 * @return ValidationError[]
197
+	 */
198
+	public function validateOther(Request $request)
199
+	{
200
+		$errorList = array();
201
+
202
+		$trustedIp = $this->xffTrustProvider->getTrustedClientIp($request->getIp(),
203
+			$request->getForwardedIp());
204
+
205
+		// ERRORS
206
+
207
+		// TOR nodes
208
+		if ($this->torExitProvider->isTorExit($trustedIp)) {
209
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED_TOR);
210
+		}
211
+
212
+		// Bans
213
+		if ($this->banHelper->isBlockBanned($request)) {
214
+			$errorList[ValidationError::BANNED] = new ValidationError(ValidationError::BANNED);
215
+		}
216
+
217
+		return $errorList;
218
+	}
219
+
220
+	public function postSaveValidations(Request $request)
221
+	{
222
+		// Antispoof check
223
+		$this->checkAntiSpoof($request);
224
+
225
+		// Blacklist check
226
+		$this->checkTitleBlacklist($request);
227
+
228
+		// Add comment for form override
229
+		$this->formOverride($request);
230
+
231
+		$bans = $this->banHelper->getBans($request);
232
+
233
+		foreach ($bans as $ban) {
234
+			if ($ban->getAction() == Ban::ACTION_DROP) {
235
+				$request->setStatus(RequestStatus::CLOSED);
236
+				$request->save();
237
+
238
+				Logger::closeRequest($request->getDatabase(), $request, 0, null);
239
+
240
+				$comment = new Comment();
241
+				$comment->setDatabase($this->database);
242
+				$comment->setRequest($request->getId());
243
+				$comment->setVisibility('user');
244
+				$comment->setUser(null);
245
+
246
+				$comment->setComment('Request dropped automatically due to matching rule.');
247
+				$comment->save();
248
+			}
249
+
250
+			if ($ban->getAction() == Ban::ACTION_DEFER) {
251
+				/** @var RequestQueue|false $targetQueue */
252
+				$targetQueue = RequestQueue::getById($ban->getTargetQueue(), $this->database);
253
+
254
+				if ($targetQueue === false ) {
255
+					$comment = new Comment();
256
+					$comment->setDatabase($this->database);
257
+					$comment->setRequest($request->getId());
258
+					$comment->setVisibility('user');
259
+					$comment->setUser(null);
260
+
261
+					$comment->setComment("This request would have been deferred automatically due to a matching rule, but the queue to defer to could not be found.");
262
+					$comment->save();
263
+				}
264
+				else {
265
+					$this->deferRequest($request, $targetQueue, 'Request deferred automatically due to matching rule.');
266
+				}
267
+			}
268
+		}
269
+	}
270
+
271
+	private function checkAntiSpoof(Request $request)
272
+	{
273
+		try {
274
+			if (count($this->antiSpoofProvider->getSpoofs($request->getName())) > 0) {
275
+				// If there were spoofs an Admin should handle the request.
276
+				// FIXME: domains!
277
+				$defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_ANTISPOOF);
278
+				$this->deferRequest($request, $defaultQueue,
279
+					'Request automatically deferred due to AntiSpoof hit');
280
+			}
281
+		}
282
+		catch (Exception $ex) {
283
+			$skippable = [
284
+				'Encountered error while getting result: Contains unassigned character',
285
+				'Encountered error while getting result: Contains incompatible mixed scripts',
286
+				'Encountered error while getting result: Does not contain any letters'
287
+			];
288
+
289
+			$skip = false;
290
+
291
+			foreach ($skippable as $s) {
292
+				if (strpos($ex->getMessage(), $s) !== false) {
293
+					$skip = true;
294
+					break;
295
+				}
296
+			}
297
+
298
+			// Only log to disk if this *isn't* a "skippable" error.
299
+			if (!$skip) {
300
+				ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
301
+			}
302
+		}
303
+	}
304
+
305
+	private function checkTitleBlacklist(Request $request)
306
+	{
307
+		if ($this->titleBlacklistEnabled == 1) {
308
+			try {
309
+				$apiResult = $this->httpHelper->get(
310
+					$this->mediawikiApiEndpoint,
311
+					array(
312
+						'action'       => 'titleblacklist',
313
+						'tbtitle'      => $request->getName(),
314
+						'tbaction'     => 'new-account',
315
+						'tbnooverride' => true,
316
+						'format'       => 'php',
317
+					),
318
+					[],
319
+					$this->validationRemoteTimeout
320
+				);
321
+
322
+				$data = unserialize($apiResult);
323
+
324
+				$requestIsOk = $data['titleblacklist']['result'] == "ok";
325
+			}
326
+			catch (CurlException $ex) {
327
+				ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
328
+
329
+				// Don't kill the request, just assume it's fine. Humans can deal with it later.
330
+				return;
331
+			}
332
+
333
+			if (!$requestIsOk) {
334
+				// FIXME: domains!
335
+				$defaultQueue = RequestQueue::getDefaultQueue($this->database, 1, RequestQueue::DEFAULT_TITLEBLACKLIST);
336
+
337
+				$this->deferRequest($request, $defaultQueue,
338
+					'Request automatically deferred due to title blacklist hit');
339
+			}
340
+		}
341
+	}
342
+
343
+	private function userExists(Request $request)
344
+	{
345
+		try {
346
+			$userExists = $this->httpHelper->get(
347
+				$this->mediawikiApiEndpoint,
348
+				array(
349
+					'action'  => 'query',
350
+					'list'    => 'users',
351
+					'ususers' => $request->getName(),
352
+					'format'  => 'php',
353
+				),
354
+				[],
355
+				$this->validationRemoteTimeout
356
+			);
357
+
358
+			$ue = unserialize($userExists);
359
+			if (!isset ($ue['query']['users']['0']['missing']) && isset ($ue['query']['users']['0']['userid'])) {
360
+				return true;
361
+			}
362
+		}
363
+		catch (CurlException $ex) {
364
+			ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
365
+
366
+			// Don't kill the request, just assume it's fine. Humans can deal with it later.
367
+			return false;
368
+		}
369
+
370
+		return false;
371
+	}
372
+
373
+	private function userSulExists(Request $request)
374
+	{
375
+		$requestName = $request->getName();
376
+
377
+		try {
378
+			$userExists = $this->httpHelper->get(
379
+				$this->mediawikiApiEndpoint,
380
+				array(
381
+					'action'  => 'query',
382
+					'meta'    => 'globaluserinfo',
383
+					'guiuser' => $requestName,
384
+					'format'  => 'php',
385
+				),
386
+				[],
387
+				$this->validationRemoteTimeout
388
+			);
389
+
390
+			$ue = unserialize($userExists);
391
+			if (isset ($ue['query']['globaluserinfo']['id'])) {
392
+				return true;
393
+			}
394
+		}
395
+		catch (CurlException $ex) {
396
+			ExceptionHandler::logExceptionToDisk($ex, $this->siteConfiguration);
397
+
398
+			// Don't kill the request, just assume it's fine. Humans can deal with it later.
399
+			return false;
400
+		}
401
+
402
+		return false;
403
+	}
404
+
405
+	/**
406
+	 * Checks if a request with this name is currently open
407
+	 *
408
+	 * @param Request $request
409
+	 *
410
+	 * @return bool
411
+	 */
412
+	private function nameRequestExists(Request $request)
413
+	{
414
+		$query = "SELECT COUNT(id) FROM request WHERE status != 'Closed' AND name = :name;";
415
+		$statement = $this->database->prepare($query);
416
+		$statement->execute(array(':name' => $request->getName()));
417
+
418
+		if (!$statement) {
419
+			return false;
420
+		}
421
+
422
+		return $statement->fetchColumn() > 0;
423
+	}
424
+
425
+	private function deferRequest(Request $request, RequestQueue $targetQueue, $deferComment): void
426
+	{
427
+		$request->setQueue($targetQueue->getId());
428
+		$request->save();
429
+
430
+		$logTarget = $targetQueue->getLogName();
431
+
432
+		Logger::deferRequest($this->database, $request, $logTarget);
433
+
434
+		$comment = new Comment();
435
+		$comment->setDatabase($this->database);
436
+		$comment->setRequest($request->getId());
437
+		$comment->setVisibility('user');
438
+		$comment->setUser(null);
439
+
440
+		$comment->setComment($deferComment);
441
+		$comment->save();
442
+	}
443
+
444
+	private function formOverride(Request $request)
445
+	{
446
+		$form = $request->getOriginFormObject();
447
+		if($form === null || $form->getOverrideQueue() === null) {
448
+			return;
449
+		}
450
+
451
+		/** @var RequestQueue $targetQueue */
452
+		$targetQueue = RequestQueue::getById($form->getOverrideQueue(), $request->getDatabase());
453
+
454
+		$this->deferRequest($request, $targetQueue, 'Request deferred automatically due to request submission through a request form with a default queue set.');
455
+	}
456 456
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
                 /** @var RequestQueue|false $targetQueue */
252 252
                 $targetQueue = RequestQueue::getById($ban->getTargetQueue(), $this->database);
253 253
 
254
-                if ($targetQueue === false ) {
254
+                if ($targetQueue === false) {
255 255
                     $comment = new Comment();
256 256
                     $comment->setDatabase($this->database);
257 257
                     $comment->setRequest($request->getId());
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
     private function formOverride(Request $request)
445 445
     {
446 446
         $form = $request->getOriginFormObject();
447
-        if($form === null || $form->getOverrideQueue() === null) {
447
+        if ($form === null || $form->getOverrideQueue() === null) {
448 448
             return;
449 449
         }
450 450
 
Please login to merge, or discard this patch.
includes/WebStart.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -33,206 +33,206 @@
 block discarded – undo
33 33
  */
34 34
 class WebStart extends ApplicationBase
35 35
 {
36
-    /**
37
-     * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
38
-     *                                    routers and hence different URL mappings
39
-     */
40
-    private $requestRouter;
41
-    /**
42
-     * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
43
-     */
44
-    private $isPublic = false;
45
-
46
-    /**
47
-     * WebStart constructor.
48
-     *
49
-     * @param SiteConfiguration $configuration The site configuration
50
-     * @param IRequestRouter    $router        The request router to use
51
-     */
52
-    public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
53
-    {
54
-        parent::__construct($configuration);
55
-
56
-        $this->requestRouter = $router;
57
-    }
58
-
59
-    /**
60
-     * @param ITask             $page
61
-     * @param SiteConfiguration $siteConfiguration
62
-     * @param PdoDatabase       $database
63
-     *
64
-     * @return void
65
-     */
66
-    protected function setupHelpers(
67
-        ITask $page,
68
-        SiteConfiguration $siteConfiguration,
69
-        PdoDatabase $database
70
-    ) {
71
-        parent::setupHelpers($page, $siteConfiguration, $database);
72
-
73
-        if ($page instanceof PageBase) {
74
-            $page->setTokenManager(new TokenManager());
75
-            $page->setCspManager(new ContentSecurityPolicyManager($siteConfiguration));
76
-
77
-            if ($page instanceof InternalPageBase) {
78
-                $page->setTypeAheadHelper(new TypeAheadHelper());
79
-
80
-                $identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration, $database);
81
-                $page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
82
-
83
-                if ($siteConfiguration->getTitleBlacklistEnabled()) {
84
-                    $page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(), $database));
85
-                }
86
-                else {
87
-                    $page->setBlacklistHelper(new FakeBlacklistHelper());
88
-                }
89
-
90
-                $page->setDomainAccessManager(new DomainAccessManager($page->getSecurityManager()));
91
-            }
92
-        }
93
-    }
94
-
95
-    /**
96
-     * Application entry point.
97
-     *
98
-     * Sets up the environment and runs the application, performing any global cleanup operations when done.
99
-     */
100
-    public function run()
101
-    {
102
-        try {
103
-            if ($this->setupEnvironment()) {
104
-                $this->main();
105
-            }
106
-        }
107
-        catch (EnvironmentException $ex) {
108
-            ob_end_clean();
109
-            print Offline::getOfflineMessage($this->isPublic(), $ex->getMessage());
110
-        }
111
-            /** @noinspection PhpRedundantCatchClauseInspection */
112
-        catch (ReadableException $ex) {
113
-            ob_end_clean();
114
-            print $ex->getReadableError();
115
-        }
116
-        finally {
117
-            $this->cleanupEnvironment();
118
-        }
119
-    }
120
-
121
-    /**
122
-     * Environment setup
123
-     *
124
-     * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
125
-     * and shut down prematurely.
126
-     *
127
-     * @return bool
128
-     * @throws EnvironmentException
129
-     */
130
-    protected function setupEnvironment()
131
-    {
132
-        // initialise global exception handler
133
-        set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
134
-        set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
135
-
136
-        // start output buffering if necessary
137
-        if (ob_get_level() === 0) {
138
-            ob_start();
139
-        }
140
-
141
-        // initialise super-global providers
142
-        WebRequest::setGlobalStateProvider(new GlobalStateProvider());
143
-
144
-        if (Offline::isOffline()) {
145
-            print Offline::getOfflineMessage($this->isPublic());
146
-            ob_end_flush();
147
-
148
-            return false;
149
-        }
150
-
151
-        // Call parent setup
152
-        if (!parent::setupEnvironment()) {
153
-            return false;
154
-        }
155
-
156
-        // Start up sessions
157
-        Session::start();
158
-
159
-        // Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
160
-        // get the current user cached.
161
-        // I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
162
-        // session I suppose.
163
-        $this->checkForceLogout();
164
-
165
-        // environment initialised!
166
-        return true;
167
-    }
168
-
169
-    /**
170
-     * Main application logic
171
-     */
172
-    protected function main()
173
-    {
174
-        // Get the right route for the request
175
-        $page = $this->requestRouter->route();
176
-
177
-        $siteConfiguration = $this->getConfiguration();
178
-        $database = PdoDatabase::getDatabaseConnection('acc');
179
-
180
-        $this->setupHelpers($page, $siteConfiguration, $database);
181
-
182
-        // run the route code for the request.
183
-        $page->execute();
184
-    }
185
-
186
-    /**
187
-     * Any cleanup tasks should go here
188
-     *
189
-     * Note that we need to be very careful here, as exceptions may have been thrown and handled.
190
-     * This should *only* be for cleaning up, no logic should go here.
191
-     */
192
-    protected function cleanupEnvironment()
193
-    {
194
-        // Clean up anything we splurged after sending the page.
195
-        if (ob_get_level() > 0) {
196
-            for ($i = ob_get_level(); $i > 0; $i--) {
197
-                ob_end_clean();
198
-            }
199
-        }
200
-    }
201
-
202
-    private function checkForceLogout()
203
-    {
204
-        $database = PdoDatabase::getDatabaseConnection('acc');
205
-
206
-        $sessionUserId = WebRequest::getSessionUserId();
207
-        iF ($sessionUserId === null) {
208
-            return;
209
-        }
210
-
211
-        // Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
212
-        $currentUser = User::getById($sessionUserId, $database);
213
-
214
-        if ($currentUser === false) {
215
-            // Umm... this user has a session cookie with a userId set, but no user exists...
216
-            Session::restart();
217
-
218
-            $currentUser = User::getCurrent($database);
219
-        }
220
-
221
-        if ($currentUser->getForceLogout()) {
222
-            Session::restart();
223
-
224
-            $currentUser->setForceLogout(false);
225
-            $currentUser->save();
226
-        }
227
-    }
228
-
229
-    public function isPublic()
230
-    {
231
-        return $this->isPublic;
232
-    }
233
-
234
-    public function setPublic($isPublic)
235
-    {
236
-        $this->isPublic = $isPublic;
237
-    }
36
+	/**
37
+	 * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
38
+	 *                                    routers and hence different URL mappings
39
+	 */
40
+	private $requestRouter;
41
+	/**
42
+	 * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
43
+	 */
44
+	private $isPublic = false;
45
+
46
+	/**
47
+	 * WebStart constructor.
48
+	 *
49
+	 * @param SiteConfiguration $configuration The site configuration
50
+	 * @param IRequestRouter    $router        The request router to use
51
+	 */
52
+	public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
53
+	{
54
+		parent::__construct($configuration);
55
+
56
+		$this->requestRouter = $router;
57
+	}
58
+
59
+	/**
60
+	 * @param ITask             $page
61
+	 * @param SiteConfiguration $siteConfiguration
62
+	 * @param PdoDatabase       $database
63
+	 *
64
+	 * @return void
65
+	 */
66
+	protected function setupHelpers(
67
+		ITask $page,
68
+		SiteConfiguration $siteConfiguration,
69
+		PdoDatabase $database
70
+	) {
71
+		parent::setupHelpers($page, $siteConfiguration, $database);
72
+
73
+		if ($page instanceof PageBase) {
74
+			$page->setTokenManager(new TokenManager());
75
+			$page->setCspManager(new ContentSecurityPolicyManager($siteConfiguration));
76
+
77
+			if ($page instanceof InternalPageBase) {
78
+				$page->setTypeAheadHelper(new TypeAheadHelper());
79
+
80
+				$identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration, $database);
81
+				$page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
82
+
83
+				if ($siteConfiguration->getTitleBlacklistEnabled()) {
84
+					$page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(), $database));
85
+				}
86
+				else {
87
+					$page->setBlacklistHelper(new FakeBlacklistHelper());
88
+				}
89
+
90
+				$page->setDomainAccessManager(new DomainAccessManager($page->getSecurityManager()));
91
+			}
92
+		}
93
+	}
94
+
95
+	/**
96
+	 * Application entry point.
97
+	 *
98
+	 * Sets up the environment and runs the application, performing any global cleanup operations when done.
99
+	 */
100
+	public function run()
101
+	{
102
+		try {
103
+			if ($this->setupEnvironment()) {
104
+				$this->main();
105
+			}
106
+		}
107
+		catch (EnvironmentException $ex) {
108
+			ob_end_clean();
109
+			print Offline::getOfflineMessage($this->isPublic(), $ex->getMessage());
110
+		}
111
+			/** @noinspection PhpRedundantCatchClauseInspection */
112
+		catch (ReadableException $ex) {
113
+			ob_end_clean();
114
+			print $ex->getReadableError();
115
+		}
116
+		finally {
117
+			$this->cleanupEnvironment();
118
+		}
119
+	}
120
+
121
+	/**
122
+	 * Environment setup
123
+	 *
124
+	 * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
125
+	 * and shut down prematurely.
126
+	 *
127
+	 * @return bool
128
+	 * @throws EnvironmentException
129
+	 */
130
+	protected function setupEnvironment()
131
+	{
132
+		// initialise global exception handler
133
+		set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
134
+		set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
135
+
136
+		// start output buffering if necessary
137
+		if (ob_get_level() === 0) {
138
+			ob_start();
139
+		}
140
+
141
+		// initialise super-global providers
142
+		WebRequest::setGlobalStateProvider(new GlobalStateProvider());
143
+
144
+		if (Offline::isOffline()) {
145
+			print Offline::getOfflineMessage($this->isPublic());
146
+			ob_end_flush();
147
+
148
+			return false;
149
+		}
150
+
151
+		// Call parent setup
152
+		if (!parent::setupEnvironment()) {
153
+			return false;
154
+		}
155
+
156
+		// Start up sessions
157
+		Session::start();
158
+
159
+		// Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
160
+		// get the current user cached.
161
+		// I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
162
+		// session I suppose.
163
+		$this->checkForceLogout();
164
+
165
+		// environment initialised!
166
+		return true;
167
+	}
168
+
169
+	/**
170
+	 * Main application logic
171
+	 */
172
+	protected function main()
173
+	{
174
+		// Get the right route for the request
175
+		$page = $this->requestRouter->route();
176
+
177
+		$siteConfiguration = $this->getConfiguration();
178
+		$database = PdoDatabase::getDatabaseConnection('acc');
179
+
180
+		$this->setupHelpers($page, $siteConfiguration, $database);
181
+
182
+		// run the route code for the request.
183
+		$page->execute();
184
+	}
185
+
186
+	/**
187
+	 * Any cleanup tasks should go here
188
+	 *
189
+	 * Note that we need to be very careful here, as exceptions may have been thrown and handled.
190
+	 * This should *only* be for cleaning up, no logic should go here.
191
+	 */
192
+	protected function cleanupEnvironment()
193
+	{
194
+		// Clean up anything we splurged after sending the page.
195
+		if (ob_get_level() > 0) {
196
+			for ($i = ob_get_level(); $i > 0; $i--) {
197
+				ob_end_clean();
198
+			}
199
+		}
200
+	}
201
+
202
+	private function checkForceLogout()
203
+	{
204
+		$database = PdoDatabase::getDatabaseConnection('acc');
205
+
206
+		$sessionUserId = WebRequest::getSessionUserId();
207
+		iF ($sessionUserId === null) {
208
+			return;
209
+		}
210
+
211
+		// Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
212
+		$currentUser = User::getById($sessionUserId, $database);
213
+
214
+		if ($currentUser === false) {
215
+			// Umm... this user has a session cookie with a userId set, but no user exists...
216
+			Session::restart();
217
+
218
+			$currentUser = User::getCurrent($database);
219
+		}
220
+
221
+		if ($currentUser->getForceLogout()) {
222
+			Session::restart();
223
+
224
+			$currentUser->setForceLogout(false);
225
+			$currentUser->save();
226
+		}
227
+	}
228
+
229
+	public function isPublic()
230
+	{
231
+		return $this->isPublic;
232
+	}
233
+
234
+	public function setPublic($isPublic)
235
+	{
236
+		$this->isPublic = $isPublic;
237
+	}
238 238
 }
Please login to merge, or discard this patch.
includes/ApplicationBase.php 1 patch
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -24,146 +24,146 @@
 block discarded – undo
24 24
 
25 25
 abstract class ApplicationBase
26 26
 {
27
-    private $configuration;
28
-
29
-    public function __construct(SiteConfiguration $configuration)
30
-    {
31
-        $this->configuration = $configuration;
32
-    }
33
-
34
-    /**
35
-     * Application entry point.
36
-     *
37
-     * Sets up the environment and runs the application, performing any global cleanup operations when done.
38
-     */
39
-    public function run()
40
-    {
41
-        try {
42
-            if ($this->setupEnvironment()) {
43
-                $this->main();
44
-            }
45
-        }
46
-        catch (Exception $ex) {
47
-            print $ex->getMessage();
48
-        }
49
-        finally {
50
-            $this->cleanupEnvironment();
51
-        }
52
-    }
53
-
54
-    /**
55
-     * Environment setup
56
-     *
57
-     * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
58
-     * and shut down prematurely.
59
-     *
60
-     * @return bool
61
-     * @throws EnvironmentException
62
-     */
63
-    protected function setupEnvironment()
64
-    {
65
-        $this->setupDatabase();
66
-
67
-        return true;
68
-    }
69
-
70
-    /**
71
-     * @return PdoDatabase
72
-     * @throws EnvironmentException
73
-     * @throws Exception
74
-     */
75
-    protected function setupDatabase()
76
-    {
77
-        // check the schema version
78
-        $database = PdoDatabase::getDatabaseConnection('acc');
79
-
80
-        $actualVersion = (int)$database->query('SELECT version FROM schemaversion')->fetchColumn();
81
-        if ($actualVersion !== $this->getConfiguration()->getSchemaVersion()) {
82
-            throw new EnvironmentException('Database schema is wrong version! Please either update configuration or database.');
83
-        }
84
-
85
-        return $database;
86
-    }
87
-
88
-    /**
89
-     * @return SiteConfiguration
90
-     */
91
-    public function getConfiguration()
92
-    {
93
-        return $this->configuration;
94
-    }
95
-
96
-    /**
97
-     * Main application logic
98
-     * @return void
99
-     */
100
-    abstract protected function main();
101
-
102
-    /**
103
-     * Any cleanup tasks should go here
104
-     *
105
-     * Note that we need to be very careful here, as exceptions may have been thrown and handled.
106
-     * This should *only* be for cleaning up, no logic should go here.
107
-     *
108
-     * @return void
109
-     */
110
-    abstract protected function cleanupEnvironment();
111
-
112
-    /**
113
-     * @param ITask             $page
114
-     * @param SiteConfiguration $siteConfiguration
115
-     * @param PdoDatabase       $database
116
-     *
117
-     * @return void
118
-     */
119
-    protected function setupHelpers(
120
-        ITask $page,
121
-        SiteConfiguration $siteConfiguration,
122
-        PdoDatabase $database
123
-    ) {
124
-        $page->setSiteConfiguration($siteConfiguration);
125
-
126
-        // setup the global database object
127
-        $page->setDatabase($database);
128
-
129
-        // set up helpers and inject them into the page.
130
-        $httpHelper = new HttpHelper($siteConfiguration);
131
-
132
-        $page->setEmailHelper(
133
-            new EmailHelper($siteConfiguration->getEmailSender(), $siteConfiguration->getIrcNotificationsInstance())
134
-        );
135
-
136
-        $page->setHttpHelper($httpHelper);
137
-
138
-        if ($siteConfiguration->getLocationProviderApiKey() === null) {
139
-            $page->setLocationProvider(new FakeLocationProvider());
140
-        }
141
-        else {
142
-            $page->setLocationProvider(
143
-                new IpLocationProvider(
144
-                    $database,
145
-                    $siteConfiguration->getLocationProviderApiKey(),
146
-                    $httpHelper
147
-                ));
148
-        }
149
-
150
-        $page->setXffTrustProvider(new XffTrustProvider($siteConfiguration->getSquidList(), $database));
151
-
152
-        $page->setRdnsProvider(new CachedRDnsLookupProvider($database));
153
-
154
-        $page->setAntiSpoofProvider(new CachedApiAntispoofProvider($database, $httpHelper));
155
-
156
-        $page->setOAuthProtocolHelper(new OAuthProtocolHelper(
157
-            $siteConfiguration->getOAuthConsumerToken(),
158
-            $siteConfiguration->getOAuthConsumerSecret(),
159
-            $database,
160
-            $siteConfiguration->getUserAgent()
161
-        ));
162
-
163
-        $page->setNotificationHelper(new IrcNotificationHelper(
164
-            $siteConfiguration,
165
-            $database));
166
-
167
-        $page->setTorExitProvider(new TorExitProvider($database));
168
-    }
27
+	private $configuration;
28
+
29
+	public function __construct(SiteConfiguration $configuration)
30
+	{
31
+		$this->configuration = $configuration;
32
+	}
33
+
34
+	/**
35
+	 * Application entry point.
36
+	 *
37
+	 * Sets up the environment and runs the application, performing any global cleanup operations when done.
38
+	 */
39
+	public function run()
40
+	{
41
+		try {
42
+			if ($this->setupEnvironment()) {
43
+				$this->main();
44
+			}
45
+		}
46
+		catch (Exception $ex) {
47
+			print $ex->getMessage();
48
+		}
49
+		finally {
50
+			$this->cleanupEnvironment();
51
+		}
52
+	}
53
+
54
+	/**
55
+	 * Environment setup
56
+	 *
57
+	 * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
58
+	 * and shut down prematurely.
59
+	 *
60
+	 * @return bool
61
+	 * @throws EnvironmentException
62
+	 */
63
+	protected function setupEnvironment()
64
+	{
65
+		$this->setupDatabase();
66
+
67
+		return true;
68
+	}
69
+
70
+	/**
71
+	 * @return PdoDatabase
72
+	 * @throws EnvironmentException
73
+	 * @throws Exception
74
+	 */
75
+	protected function setupDatabase()
76
+	{
77
+		// check the schema version
78
+		$database = PdoDatabase::getDatabaseConnection('acc');
79
+
80
+		$actualVersion = (int)$database->query('SELECT version FROM schemaversion')->fetchColumn();
81
+		if ($actualVersion !== $this->getConfiguration()->getSchemaVersion()) {
82
+			throw new EnvironmentException('Database schema is wrong version! Please either update configuration or database.');
83
+		}
84
+
85
+		return $database;
86
+	}
87
+
88
+	/**
89
+	 * @return SiteConfiguration
90
+	 */
91
+	public function getConfiguration()
92
+	{
93
+		return $this->configuration;
94
+	}
95
+
96
+	/**
97
+	 * Main application logic
98
+	 * @return void
99
+	 */
100
+	abstract protected function main();
101
+
102
+	/**
103
+	 * Any cleanup tasks should go here
104
+	 *
105
+	 * Note that we need to be very careful here, as exceptions may have been thrown and handled.
106
+	 * This should *only* be for cleaning up, no logic should go here.
107
+	 *
108
+	 * @return void
109
+	 */
110
+	abstract protected function cleanupEnvironment();
111
+
112
+	/**
113
+	 * @param ITask             $page
114
+	 * @param SiteConfiguration $siteConfiguration
115
+	 * @param PdoDatabase       $database
116
+	 *
117
+	 * @return void
118
+	 */
119
+	protected function setupHelpers(
120
+		ITask $page,
121
+		SiteConfiguration $siteConfiguration,
122
+		PdoDatabase $database
123
+	) {
124
+		$page->setSiteConfiguration($siteConfiguration);
125
+
126
+		// setup the global database object
127
+		$page->setDatabase($database);
128
+
129
+		// set up helpers and inject them into the page.
130
+		$httpHelper = new HttpHelper($siteConfiguration);
131
+
132
+		$page->setEmailHelper(
133
+			new EmailHelper($siteConfiguration->getEmailSender(), $siteConfiguration->getIrcNotificationsInstance())
134
+		);
135
+
136
+		$page->setHttpHelper($httpHelper);
137
+
138
+		if ($siteConfiguration->getLocationProviderApiKey() === null) {
139
+			$page->setLocationProvider(new FakeLocationProvider());
140
+		}
141
+		else {
142
+			$page->setLocationProvider(
143
+				new IpLocationProvider(
144
+					$database,
145
+					$siteConfiguration->getLocationProviderApiKey(),
146
+					$httpHelper
147
+				));
148
+		}
149
+
150
+		$page->setXffTrustProvider(new XffTrustProvider($siteConfiguration->getSquidList(), $database));
151
+
152
+		$page->setRdnsProvider(new CachedRDnsLookupProvider($database));
153
+
154
+		$page->setAntiSpoofProvider(new CachedApiAntispoofProvider($database, $httpHelper));
155
+
156
+		$page->setOAuthProtocolHelper(new OAuthProtocolHelper(
157
+			$siteConfiguration->getOAuthConsumerToken(),
158
+			$siteConfiguration->getOAuthConsumerSecret(),
159
+			$database,
160
+			$siteConfiguration->getUserAgent()
161
+		));
162
+
163
+		$page->setNotificationHelper(new IrcNotificationHelper(
164
+			$siteConfiguration,
165
+			$database));
166
+
167
+		$page->setTorExitProvider(new TorExitProvider($database));
168
+	}
169 169
 }
Please login to merge, or discard this patch.
includes/Helpers/RequestQueueHelper.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -15,71 +15,71 @@
 block discarded – undo
15 15
 
16 16
 class RequestQueueHelper
17 17
 {
18
-    /**
19
-     * @param RequestQueue $queue
20
-     * @param bool         $enabled
21
-     * @param bool         $default
22
-     * @param bool         $antiSpoof
23
-     * @param bool         $titleBlacklist
24
-     */
25
-    public function configureDefaults(
26
-        RequestQueue $queue,
27
-        bool $enabled,
28
-        bool $default,
29
-        bool $antiSpoof,
30
-        bool $titleBlacklist,
31
-        bool $isTarget
32
-    ) {
33
-        // always allow enabling a queue
34
-        if ($enabled) {
35
-            $queue->setEnabled($enabled);
36
-        }
18
+	/**
19
+	 * @param RequestQueue $queue
20
+	 * @param bool         $enabled
21
+	 * @param bool         $default
22
+	 * @param bool         $antiSpoof
23
+	 * @param bool         $titleBlacklist
24
+	 */
25
+	public function configureDefaults(
26
+		RequestQueue $queue,
27
+		bool $enabled,
28
+		bool $default,
29
+		bool $antiSpoof,
30
+		bool $titleBlacklist,
31
+		bool $isTarget
32
+	) {
33
+		// always allow enabling a queue
34
+		if ($enabled) {
35
+			$queue->setEnabled($enabled);
36
+		}
37 37
 
38
-        // only allow other enable-flag changes if we're not a default
39
-        if (!($queue->isDefault() || $queue->isDefaultAntispoof() || $queue->isDefaultTitleBlacklist() || $isTarget)) {
40
-            $queue->setEnabled($enabled);
41
-        }
38
+		// only allow other enable-flag changes if we're not a default
39
+		if (!($queue->isDefault() || $queue->isDefaultAntispoof() || $queue->isDefaultTitleBlacklist() || $isTarget)) {
40
+			$queue->setEnabled($enabled);
41
+		}
42 42
 
43
-        // only allow enabling the default flags, and only when we're enabled.
44
-        $queue->setDefault(($queue->isDefault() || $default) && $queue->isEnabled());
45
-        $queue->setDefaultAntispoof(($queue->isDefaultAntispoof() || $antiSpoof) && $queue->isEnabled());
46
-        $queue->setDefaultTitleBlacklist(($queue->isDefaultTitleBlacklist() || $titleBlacklist) && $queue->isEnabled());
47
-    }
43
+		// only allow enabling the default flags, and only when we're enabled.
44
+		$queue->setDefault(($queue->isDefault() || $default) && $queue->isEnabled());
45
+		$queue->setDefaultAntispoof(($queue->isDefaultAntispoof() || $antiSpoof) && $queue->isEnabled());
46
+		$queue->setDefaultTitleBlacklist(($queue->isDefaultTitleBlacklist() || $titleBlacklist) && $queue->isEnabled());
47
+	}
48 48
 
49
-    /**
50
-     * @param RequestQueue $queue
51
-     * @param PdoDatabase  $database
52
-     *
53
-     * @return bool
54
-     */
55
-    public function isEmailTemplateTarget(RequestQueue $queue, PdoDatabase $database): bool
56
-    {
57
-        $isTarget = false;
58
-        /** @var EmailTemplate[] $deferralTemplates */
59
-        $deferralTemplates = EmailTemplate::getAllActiveTemplates('defer', $database);
60
-        foreach ($deferralTemplates as $t) {
61
-            if ($t->getQueue() === $queue->getId()) {
62
-                $isTarget = true;
63
-                break;
64
-            }
65
-        }
49
+	/**
50
+	 * @param RequestQueue $queue
51
+	 * @param PdoDatabase  $database
52
+	 *
53
+	 * @return bool
54
+	 */
55
+	public function isEmailTemplateTarget(RequestQueue $queue, PdoDatabase $database): bool
56
+	{
57
+		$isTarget = false;
58
+		/** @var EmailTemplate[] $deferralTemplates */
59
+		$deferralTemplates = EmailTemplate::getAllActiveTemplates('defer', $database);
60
+		foreach ($deferralTemplates as $t) {
61
+			if ($t->getQueue() === $queue->getId()) {
62
+				$isTarget = true;
63
+				break;
64
+			}
65
+		}
66 66
 
67
-        return $isTarget;
68
-    }
67
+		return $isTarget;
68
+	}
69 69
 
70
-    public function isRequestFormTarget(RequestQueue $queue, PdoDatabase $database): bool
71
-    {
72
-        $isTarget = false;
73
-        $forms = RequestForm::getAllForms($database, 1); // FIXME: domains
74
-        foreach ($forms as $t) {
75
-            if ($t->isEnabled()) {
76
-                if ($t->getOverrideQueue() === $queue->getId()) {
77
-                    $isTarget = true;
78
-                    break;
79
-                }
80
-            }
81
-        }
70
+	public function isRequestFormTarget(RequestQueue $queue, PdoDatabase $database): bool
71
+	{
72
+		$isTarget = false;
73
+		$forms = RequestForm::getAllForms($database, 1); // FIXME: domains
74
+		foreach ($forms as $t) {
75
+			if ($t->isEnabled()) {
76
+				if ($t->getOverrideQueue() === $queue->getId()) {
77
+					$isTarget = true;
78
+					break;
79
+				}
80
+			}
81
+		}
82 82
 
83
-        return $isTarget;
84
-    }
83
+		return $isTarget;
84
+	}
85 85
 }
86 86
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/RequestEmailHelper.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -15,54 +15,54 @@
 block discarded – undo
15 15
 
16 16
 class RequestEmailHelper
17 17
 {
18
-    /**
19
-     * @var IEmailHelper
20
-     */
21
-    private $emailHelper;
18
+	/**
19
+	 * @var IEmailHelper
20
+	 */
21
+	private $emailHelper;
22 22
 
23
-    /**
24
-     * RequestEmailHelper constructor.
25
-     *
26
-     * @param IEmailHelper $emailHelper
27
-     */
28
-    public function __construct(IEmailHelper $emailHelper)
29
-    {
30
-        $this->emailHelper = $emailHelper;
31
-    }
23
+	/**
24
+	 * RequestEmailHelper constructor.
25
+	 *
26
+	 * @param IEmailHelper $emailHelper
27
+	 */
28
+	public function __construct(IEmailHelper $emailHelper)
29
+	{
30
+		$this->emailHelper = $emailHelper;
31
+	}
32 32
 
33
-    /**
34
-     * @param Request $request
35
-     * @param string  $mailText
36
-     * @param User    $currentUser
37
-     * @param boolean $ccMailingList
38
-     */
39
-    public function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
40
-    {
41
-        $headers = array(
42
-            'X-ACC-Request' => $request->getId(),
43
-            'X-ACC-UserID'  => $currentUser->getId(),
44
-        );
33
+	/**
34
+	 * @param Request $request
35
+	 * @param string  $mailText
36
+	 * @param User    $currentUser
37
+	 * @param boolean $ccMailingList
38
+	 */
39
+	public function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
40
+	{
41
+		$headers = array(
42
+			'X-ACC-Request' => $request->getId(),
43
+			'X-ACC-UserID'  => $currentUser->getId(),
44
+		);
45 45
 
46
-        // FIXME: domains!
47
-        /** @var Domain $domain */
48
-        $domain = Domain::getById(1, $request->getDatabase());
46
+		// FIXME: domains!
47
+		/** @var Domain $domain */
48
+		$domain = Domain::getById(1, $request->getDatabase());
49 49
 
50
-        if ($ccMailingList) {
51
-            $headers['Cc'] = $domain->getEmailReplyAddress();
52
-        }
50
+		if ($ccMailingList) {
51
+			$headers['Cc'] = $domain->getEmailReplyAddress();
52
+		}
53 53
 
54
-        $helper = $this->emailHelper;
54
+		$helper = $this->emailHelper;
55 55
 
56
-        $emailSig = $currentUser->getEmailSig();
57
-        if ($emailSig !== '' || $emailSig !== null) {
58
-            $emailSig = "\n\n" . $emailSig;
59
-        }
56
+		$emailSig = $currentUser->getEmailSig();
57
+		if ($emailSig !== '' || $emailSig !== null) {
58
+			$emailSig = "\n\n" . $emailSig;
59
+		}
60 60
 
61
-        $subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
62
-        $content = $mailText . $emailSig;
61
+		$subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
62
+		$content = $mailText . $emailSig;
63 63
 
64
-        $helper->sendMail($domain->getEmailReplyAddress(), $request->getEmail(), $subject, $content, $headers);
64
+		$helper->sendMail($domain->getEmailReplyAddress(), $request->getEmail(), $subject, $content, $headers);
65 65
 
66
-        $request->setEmailSent(true);
67
-    }
66
+		$request->setEmailSent(true);
67
+	}
68 68
 }
Please login to merge, or discard this patch.
includes/Helpers/BotMediaWikiClient.php 1 patch
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -17,136 +17,136 @@
 block discarded – undo
17 17
 
18 18
 class BotMediaWikiClient implements IMediaWikiClient
19 19
 {
20
-    /**
21
-     * @var HttpHelper
22
-     */
23
-    private $httpHelper;
24
-    /** @var string */
25
-    private $mediawikiWebServiceEndpoint;
26
-    /** @var string */
27
-    private $creationBotUsername;
28
-    /** @var string */
29
-    private $creationBotPassword;
30
-    /** @var bool */
31
-    private $knownLoggedIn = false;
32
-
33
-    /**
34
-     * BotMediaWikiClient constructor.
35
-     *
36
-     * @param SiteConfiguration        $siteConfiguration
37
-     * @param Domain $domain
38
-     */
39
-    public function __construct(SiteConfiguration $siteConfiguration, Domain $domain)
40
-    {
41
-        $this->mediawikiWebServiceEndpoint = $domain->getWikiApiPath();
42
-
43
-        $this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
44
-        $this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
45
-
46
-        $this->httpHelper = new HttpHelper(
47
-            $siteConfiguration,
48
-            $siteConfiguration->getCurlCookieJar()
49
-        );
50
-    }
51
-
52
-    public function doApiCall($apiParams, $method = 'GET')
53
-    {
54
-        $this->ensureLoggedIn();
55
-        $apiParams['assert'] = 'user';
56
-
57
-        return $this->callApi($apiParams, $method);
58
-    }
59
-
60
-    private function ensureLoggedIn()
61
-    {
62
-        if ($this->knownLoggedIn) {
63
-            return;
64
-        }
65
-
66
-        $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
67
-        if (isset($userinfoResult->query->userinfo->anon)) {
68
-            // not logged in.
69
-            $this->logIn();
70
-
71
-            // retest
72
-            $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
73
-            if (isset($userinfoResult->query->userinfo->anon)) {
74
-                throw new MediaWikiApiException('Unable to log in.');
75
-            }
76
-            else {
77
-                $this->knownLoggedIn = true;
78
-            }
79
-        }
80
-        else {
81
-            $this->knownLoggedIn = true;
82
-        }
83
-    }
84
-
85
-    /**
86
-     * @param $apiParams
87
-     * @param $method
88
-     *
89
-     * @return mixed
90
-     * @throws ApplicationLogicException
91
-     * @throws CurlException
92
-     */
93
-    private function callApi($apiParams, $method)
94
-    {
95
-        $apiParams['format'] = 'json';
96
-
97
-        if ($method == 'GET') {
98
-            $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
99
-        }
100
-        elseif ($method == 'POST') {
101
-            $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
102
-        }
103
-        else {
104
-            throw new ApplicationLogicException('Unsupported HTTP Method');
105
-        }
106
-
107
-        if ($data === false) {
108
-            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
109
-        }
110
-
111
-        $result = json_decode($data);
112
-
113
-        return $result;
114
-    }
115
-
116
-    private function logIn()
117
-    {
118
-        // get token
119
-        $tokenParams = array(
120
-            'action' => 'query',
121
-            'meta'   => 'tokens',
122
-            'type'   => 'login',
123
-        );
124
-
125
-        $response = $this->callApi($tokenParams, 'POST');
126
-
127
-        if (isset($response->error)) {
128
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
129
-        }
130
-
131
-        $token = $response->query->tokens->logintoken;
132
-
133
-        if ($token === null) {
134
-            throw new MediaWikiApiException('Edit token could not be acquired');
135
-        }
136
-
137
-        $params = array(
138
-            'action' => 'login',
139
-            'lgname' => $this->creationBotUsername,
140
-            'lgpassword' => $this->creationBotPassword,
141
-            'lgtoken' => $token,
142
-        );
143
-
144
-        $loginResponse = $this->callApi($params, 'POST');
145
-
146
-        if ($loginResponse->login->result == 'Success') {
147
-            return;
148
-        }
149
-
150
-        throw new ApplicationLogicException(json_encode($loginResponse));
151
-    }
20
+	/**
21
+	 * @var HttpHelper
22
+	 */
23
+	private $httpHelper;
24
+	/** @var string */
25
+	private $mediawikiWebServiceEndpoint;
26
+	/** @var string */
27
+	private $creationBotUsername;
28
+	/** @var string */
29
+	private $creationBotPassword;
30
+	/** @var bool */
31
+	private $knownLoggedIn = false;
32
+
33
+	/**
34
+	 * BotMediaWikiClient constructor.
35
+	 *
36
+	 * @param SiteConfiguration        $siteConfiguration
37
+	 * @param Domain $domain
38
+	 */
39
+	public function __construct(SiteConfiguration $siteConfiguration, Domain $domain)
40
+	{
41
+		$this->mediawikiWebServiceEndpoint = $domain->getWikiApiPath();
42
+
43
+		$this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
44
+		$this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
45
+
46
+		$this->httpHelper = new HttpHelper(
47
+			$siteConfiguration,
48
+			$siteConfiguration->getCurlCookieJar()
49
+		);
50
+	}
51
+
52
+	public function doApiCall($apiParams, $method = 'GET')
53
+	{
54
+		$this->ensureLoggedIn();
55
+		$apiParams['assert'] = 'user';
56
+
57
+		return $this->callApi($apiParams, $method);
58
+	}
59
+
60
+	private function ensureLoggedIn()
61
+	{
62
+		if ($this->knownLoggedIn) {
63
+			return;
64
+		}
65
+
66
+		$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
67
+		if (isset($userinfoResult->query->userinfo->anon)) {
68
+			// not logged in.
69
+			$this->logIn();
70
+
71
+			// retest
72
+			$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
73
+			if (isset($userinfoResult->query->userinfo->anon)) {
74
+				throw new MediaWikiApiException('Unable to log in.');
75
+			}
76
+			else {
77
+				$this->knownLoggedIn = true;
78
+			}
79
+		}
80
+		else {
81
+			$this->knownLoggedIn = true;
82
+		}
83
+	}
84
+
85
+	/**
86
+	 * @param $apiParams
87
+	 * @param $method
88
+	 *
89
+	 * @return mixed
90
+	 * @throws ApplicationLogicException
91
+	 * @throws CurlException
92
+	 */
93
+	private function callApi($apiParams, $method)
94
+	{
95
+		$apiParams['format'] = 'json';
96
+
97
+		if ($method == 'GET') {
98
+			$data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
99
+		}
100
+		elseif ($method == 'POST') {
101
+			$data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
102
+		}
103
+		else {
104
+			throw new ApplicationLogicException('Unsupported HTTP Method');
105
+		}
106
+
107
+		if ($data === false) {
108
+			throw new CurlException('Curl error: ' . $this->httpHelper->getError());
109
+		}
110
+
111
+		$result = json_decode($data);
112
+
113
+		return $result;
114
+	}
115
+
116
+	private function logIn()
117
+	{
118
+		// get token
119
+		$tokenParams = array(
120
+			'action' => 'query',
121
+			'meta'   => 'tokens',
122
+			'type'   => 'login',
123
+		);
124
+
125
+		$response = $this->callApi($tokenParams, 'POST');
126
+
127
+		if (isset($response->error)) {
128
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
129
+		}
130
+
131
+		$token = $response->query->tokens->logintoken;
132
+
133
+		if ($token === null) {
134
+			throw new MediaWikiApiException('Edit token could not be acquired');
135
+		}
136
+
137
+		$params = array(
138
+			'action' => 'login',
139
+			'lgname' => $this->creationBotUsername,
140
+			'lgpassword' => $this->creationBotPassword,
141
+			'lgtoken' => $token,
142
+		);
143
+
144
+		$loginResponse = $this->callApi($params, 'POST');
145
+
146
+		if ($loginResponse->login->result == 'Success') {
147
+			return;
148
+		}
149
+
150
+		throw new ApplicationLogicException(json_encode($loginResponse));
151
+	}
152 152
 }
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IEmailHelper.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -17,16 +17,16 @@
 block discarded – undo
17 17
  */
18 18
 interface IEmailHelper
19 19
 {
20
-    /**
21
-     * Sends an email to the specified email address.
22
-     *
23
-     * @param string $replyAddress
24
-     * @param string $to
25
-     * @param string $subject
26
-     * @param string $content
27
-     * @param array  $headers Extra headers to include
28
-     *
29
-     * @return void
30
-     */
31
-    public function sendMail(?string $replyAddress, $to, $subject, $content, $headers = array());
20
+	/**
21
+	 * Sends an email to the specified email address.
22
+	 *
23
+	 * @param string $replyAddress
24
+	 * @param string $to
25
+	 * @param string $subject
26
+	 * @param string $content
27
+	 * @param array  $headers Extra headers to include
28
+	 *
29
+	 * @return void
30
+	 */
31
+	public function sendMail(?string $replyAddress, $to, $subject, $content, $headers = array());
32 32
 }
33 33
\ No newline at end of file
Please login to merge, or discard this patch.