Completed
Push — newinternal ( 65a0f5...5b021c )
by Simon
08:29
created
includes/Pages/RequestAction/PageCloseRequest.php 1 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/WebStart.php 1 patch
Indentation   +220 added lines, -220 removed lines patch added patch discarded remove patch
@@ -30,224 +30,224 @@
 block discarded – undo
30 30
  */
31 31
 class WebStart extends ApplicationBase
32 32
 {
33
-    /**
34
-     * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
35
-     *                                    routers and hence different URL mappings
36
-     */
37
-    private $requestRouter;
38
-    /**
39
-     * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
40
-     */
41
-    private $isPublic = false;
42
-
43
-    /**
44
-     * WebStart constructor.
45
-     *
46
-     * @param SiteConfiguration $configuration The site configuration
47
-     * @param IRequestRouter    $router        The request router to use
48
-     */
49
-    public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
50
-    {
51
-        parent::__construct($configuration);
52
-
53
-        $this->requestRouter = $router;
54
-    }
55
-
56
-    /**
57
-     * @param ITask             $page
58
-     * @param SiteConfiguration $siteConfiguration
59
-     * @param PdoDatabase       $database
60
-     * @param PdoDatabase       $notificationsDatabase
61
-     *
62
-     * @return void
63
-     */
64
-    protected function setupHelpers(
65
-        ITask $page,
66
-        SiteConfiguration $siteConfiguration,
67
-        PdoDatabase $database,
68
-        PdoDatabase $notificationsDatabase = null
69
-    ) {
70
-        parent::setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
71
-
72
-        if ($page instanceof PageBase) {
73
-            $page->setTokenManager(new TokenManager());
74
-
75
-            if ($page instanceof InternalPageBase) {
76
-                $page->setTypeAheadHelper(new TypeAheadHelper());
77
-
78
-                $identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration,
79
-                    $database);
80
-                $page->setIdentificationVerifier($identificationVerifier);
81
-
82
-                $page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
83
-
84
-                if ($siteConfiguration->getTitleBlacklistEnabled()) {
85
-                    $page->setBlacklistHelper(new FakeBlacklistHelper());
86
-                }
87
-                else {
88
-                    $page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(),
89
-                        $siteConfiguration->getMediawikiWebServiceEndpoint()));
90
-                }
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
-        catch (ReadableException $ex) {
112
-            ob_end_clean();
113
-            print $ex->getReadableError();
114
-        }
115
-        finally {
116
-            $this->cleanupEnvironment();
117
-        }
118
-    }
119
-
120
-    /**
121
-     * Environment setup
122
-     *
123
-     * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
124
-     * and shut down prematurely.
125
-     *
126
-     * @return bool
127
-     * @throws EnvironmentException
128
-     */
129
-    protected function setupEnvironment()
130
-    {
131
-        // initialise global exception handler
132
-        set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
133
-        set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
134
-
135
-        // start output buffering if necessary
136
-        if (ob_get_level() === 0) {
137
-            ob_start();
138
-        }
139
-
140
-        // initialise super-global providers
141
-        WebRequest::setGlobalStateProvider(new GlobalStateProvider());
142
-
143
-        if (Offline::isOffline()) {
144
-            print Offline::getOfflineMessage($this->isPublic());
145
-            ob_end_flush();
146
-
147
-            return false;
148
-        }
149
-
150
-        // Call parent setup
151
-        if (!parent::setupEnvironment()) {
152
-            return false;
153
-        }
154
-
155
-        // Start up sessions
156
-        Session::start();
157
-
158
-        // Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
159
-        // get the current user cached.
160
-        // I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
161
-        // session I suppose.
162
-        $this->checkForceLogout();
163
-
164
-        // environment initialised!
165
-        return true;
166
-    }
167
-
168
-    /**
169
-     * Main application logic
170
-     */
171
-    protected function main()
172
-    {
173
-        // Get the right route for the request
174
-        $page = $this->requestRouter->route();
175
-
176
-        $siteConfiguration = $this->getConfiguration();
177
-        $database = PdoDatabase::getDatabaseConnection('acc');
178
-
179
-        if ($siteConfiguration->getIrcNotificationsEnabled()) {
180
-            $notificationsDatabase = PdoDatabase::getDatabaseConnection('notifications');
181
-        }
182
-        else {
183
-            // @todo federated table here?
184
-            $notificationsDatabase = $database;
185
-        }
186
-
187
-        $this->setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
188
-
189
-        /* @todo Remove this global statement! It's here for User.php, which does far more than it should. */
190
-        global $oauthHelper;
191
-        $oauthHelper = $page->getOAuthHelper();
192
-
193
-        /* @todo Remove this global statement! It's here for Request.php, which does far more than it should. */
194
-        global $globalXffTrustProvider;
195
-        $globalXffTrustProvider = $page->getXffTrustProvider();
196
-
197
-        // run the route code for the request.
198
-        $page->execute();
199
-    }
200
-
201
-    /**
202
-     * Any cleanup tasks should go here
203
-     *
204
-     * Note that we need to be very careful here, as exceptions may have been thrown and handled.
205
-     * This should *only* be for cleaning up, no logic should go here.
206
-     */
207
-    protected function cleanupEnvironment()
208
-    {
209
-        // Clean up anything we splurged after sending the page.
210
-        if (ob_get_level() > 0) {
211
-            for ($i = ob_get_level(); $i > 0; $i--) {
212
-                ob_end_clean();
213
-            }
214
-        }
215
-    }
216
-
217
-    private function checkForceLogout()
218
-    {
219
-        $database = PdoDatabase::getDatabaseConnection('acc');
220
-
221
-        $sessionUserId = WebRequest::getSessionUserId();
222
-        iF ($sessionUserId === null) {
223
-            return;
224
-        }
225
-
226
-        // Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
227
-        $currentUser = User::getById($sessionUserId, $database);
228
-
229
-        if ($currentUser === false) {
230
-            // Umm... this user has a session cookie with a userId set, but no user exists...
231
-            Session::restart();
232
-
233
-            $currentUser = User::getCurrent($database);
234
-        }
235
-
236
-        if ($currentUser->getForceLogout()) {
237
-            Session::restart();
238
-
239
-            $currentUser->setForceLogout(false);
240
-            $currentUser->save();
241
-        }
242
-    }
243
-
244
-    public function isPublic()
245
-    {
246
-        return $this->isPublic;
247
-    }
248
-
249
-    public function setPublic($isPublic)
250
-    {
251
-        $this->isPublic = $isPublic;
252
-    }
33
+	/**
34
+	 * @var IRequestRouter $requestRouter The request router to use. Note that different entry points have different
35
+	 *                                    routers and hence different URL mappings
36
+	 */
37
+	private $requestRouter;
38
+	/**
39
+	 * @var bool $isPublic Determines whether to use public interface objects or internal interface objects
40
+	 */
41
+	private $isPublic = false;
42
+
43
+	/**
44
+	 * WebStart constructor.
45
+	 *
46
+	 * @param SiteConfiguration $configuration The site configuration
47
+	 * @param IRequestRouter    $router        The request router to use
48
+	 */
49
+	public function __construct(SiteConfiguration $configuration, IRequestRouter $router)
50
+	{
51
+		parent::__construct($configuration);
52
+
53
+		$this->requestRouter = $router;
54
+	}
55
+
56
+	/**
57
+	 * @param ITask             $page
58
+	 * @param SiteConfiguration $siteConfiguration
59
+	 * @param PdoDatabase       $database
60
+	 * @param PdoDatabase       $notificationsDatabase
61
+	 *
62
+	 * @return void
63
+	 */
64
+	protected function setupHelpers(
65
+		ITask $page,
66
+		SiteConfiguration $siteConfiguration,
67
+		PdoDatabase $database,
68
+		PdoDatabase $notificationsDatabase = null
69
+	) {
70
+		parent::setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
71
+
72
+		if ($page instanceof PageBase) {
73
+			$page->setTokenManager(new TokenManager());
74
+
75
+			if ($page instanceof InternalPageBase) {
76
+				$page->setTypeAheadHelper(new TypeAheadHelper());
77
+
78
+				$identificationVerifier = new IdentificationVerifier($page->getHttpHelper(), $siteConfiguration,
79
+					$database);
80
+				$page->setIdentificationVerifier($identificationVerifier);
81
+
82
+				$page->setSecurityManager(new SecurityManager($identificationVerifier, new RoleConfiguration()));
83
+
84
+				if ($siteConfiguration->getTitleBlacklistEnabled()) {
85
+					$page->setBlacklistHelper(new FakeBlacklistHelper());
86
+				}
87
+				else {
88
+					$page->setBlacklistHelper(new BlacklistHelper($page->getHttpHelper(),
89
+						$siteConfiguration->getMediawikiWebServiceEndpoint()));
90
+				}
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
+		catch (ReadableException $ex) {
112
+			ob_end_clean();
113
+			print $ex->getReadableError();
114
+		}
115
+		finally {
116
+			$this->cleanupEnvironment();
117
+		}
118
+	}
119
+
120
+	/**
121
+	 * Environment setup
122
+	 *
123
+	 * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
124
+	 * and shut down prematurely.
125
+	 *
126
+	 * @return bool
127
+	 * @throws EnvironmentException
128
+	 */
129
+	protected function setupEnvironment()
130
+	{
131
+		// initialise global exception handler
132
+		set_exception_handler(array(ExceptionHandler::class, 'exceptionHandler'));
133
+		set_error_handler(array(ExceptionHandler::class, 'errorHandler'), E_RECOVERABLE_ERROR);
134
+
135
+		// start output buffering if necessary
136
+		if (ob_get_level() === 0) {
137
+			ob_start();
138
+		}
139
+
140
+		// initialise super-global providers
141
+		WebRequest::setGlobalStateProvider(new GlobalStateProvider());
142
+
143
+		if (Offline::isOffline()) {
144
+			print Offline::getOfflineMessage($this->isPublic());
145
+			ob_end_flush();
146
+
147
+			return false;
148
+		}
149
+
150
+		// Call parent setup
151
+		if (!parent::setupEnvironment()) {
152
+			return false;
153
+		}
154
+
155
+		// Start up sessions
156
+		Session::start();
157
+
158
+		// Check the user is allowed to be logged in still. This must be before we call any user-loading functions and
159
+		// get the current user cached.
160
+		// I'm not sure if this function call being here is particularly a good thing, but it's part of starting up a
161
+		// session I suppose.
162
+		$this->checkForceLogout();
163
+
164
+		// environment initialised!
165
+		return true;
166
+	}
167
+
168
+	/**
169
+	 * Main application logic
170
+	 */
171
+	protected function main()
172
+	{
173
+		// Get the right route for the request
174
+		$page = $this->requestRouter->route();
175
+
176
+		$siteConfiguration = $this->getConfiguration();
177
+		$database = PdoDatabase::getDatabaseConnection('acc');
178
+
179
+		if ($siteConfiguration->getIrcNotificationsEnabled()) {
180
+			$notificationsDatabase = PdoDatabase::getDatabaseConnection('notifications');
181
+		}
182
+		else {
183
+			// @todo federated table here?
184
+			$notificationsDatabase = $database;
185
+		}
186
+
187
+		$this->setupHelpers($page, $siteConfiguration, $database, $notificationsDatabase);
188
+
189
+		/* @todo Remove this global statement! It's here for User.php, which does far more than it should. */
190
+		global $oauthHelper;
191
+		$oauthHelper = $page->getOAuthHelper();
192
+
193
+		/* @todo Remove this global statement! It's here for Request.php, which does far more than it should. */
194
+		global $globalXffTrustProvider;
195
+		$globalXffTrustProvider = $page->getXffTrustProvider();
196
+
197
+		// run the route code for the request.
198
+		$page->execute();
199
+	}
200
+
201
+	/**
202
+	 * Any cleanup tasks should go here
203
+	 *
204
+	 * Note that we need to be very careful here, as exceptions may have been thrown and handled.
205
+	 * This should *only* be for cleaning up, no logic should go here.
206
+	 */
207
+	protected function cleanupEnvironment()
208
+	{
209
+		// Clean up anything we splurged after sending the page.
210
+		if (ob_get_level() > 0) {
211
+			for ($i = ob_get_level(); $i > 0; $i--) {
212
+				ob_end_clean();
213
+			}
214
+		}
215
+	}
216
+
217
+	private function checkForceLogout()
218
+	{
219
+		$database = PdoDatabase::getDatabaseConnection('acc');
220
+
221
+		$sessionUserId = WebRequest::getSessionUserId();
222
+		iF ($sessionUserId === null) {
223
+			return;
224
+		}
225
+
226
+		// Note, User::getCurrent() caches it's result, which we *really* don't want to trigger.
227
+		$currentUser = User::getById($sessionUserId, $database);
228
+
229
+		if ($currentUser === false) {
230
+			// Umm... this user has a session cookie with a userId set, but no user exists...
231
+			Session::restart();
232
+
233
+			$currentUser = User::getCurrent($database);
234
+		}
235
+
236
+		if ($currentUser->getForceLogout()) {
237
+			Session::restart();
238
+
239
+			$currentUser->setForceLogout(false);
240
+			$currentUser->save();
241
+		}
242
+	}
243
+
244
+	public function isPublic()
245
+	{
246
+		return $this->isPublic;
247
+	}
248
+
249
+	public function setPublic($isPublic)
250
+	{
251
+		$this->isPublic = $isPublic;
252
+	}
253 253
 }
Please login to merge, or discard this patch.