Failed Conditions
Pull Request — newinternal (#527)
by Simon
17:20 queued 07:22
created
includes/Background/Task/UserCreationTask.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -14,14 +14,14 @@
 block discarded – undo
14 14
 
15 15
 class UserCreationTask extends CreationTaskBase
16 16
 {
17
-    /**
18
-     * @return IMediaWikiClient
19
-     */
20
-    protected function getMediaWikiClient()
21
-    {
22
-        $oauth = new OAuthUserHelper($this->getTriggerUser(), $this->getDatabase(), $this->getOauthProtocolHelper(),
23
-            $this->getSiteConfiguration());
17
+	/**
18
+	 * @return IMediaWikiClient
19
+	 */
20
+	protected function getMediaWikiClient()
21
+	{
22
+		$oauth = new OAuthUserHelper($this->getTriggerUser(), $this->getDatabase(), $this->getOauthProtocolHelper(),
23
+			$this->getSiteConfiguration());
24 24
 
25
-        return $oauth;
26
-    }
25
+		return $oauth;
26
+	}
27 27
 }
28 28
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Background/Task/WelcomeUserTask.php 3 patches
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -20,73 +20,73 @@
 block discarded – undo
20 20
 
21 21
 class WelcomeUserTask extends BackgroundTaskBase
22 22
 {
23
-    public static function enqueue(User $triggerUser, Request $request, PdoDatabase $database)
24
-    {
25
-        $job = new JobQueue();
26
-        $job->setDatabase($database);
27
-        $job->setTask(WelcomeUserTask::class);
28
-        $job->setRequest($request->getId());
29
-        $job->setTriggerUserId($triggerUser->getId());
30
-        $job->save();
31
-    }
32
-
33
-    public function execute()
34
-    {
35
-        $database = $this->getDatabase();
36
-        $request = $this->getRequest();
37
-        $user = $this->getTriggerUser();
38
-
39
-        if ($user->getWelcomeTemplate() === null) {
40
-            $this->markFailed('Welcome template not specified');
41
-
42
-            return;
43
-        }
44
-
45
-        /** @var WelcomeTemplate $template */
46
-        $template = WelcomeTemplate::getById($user->getWelcomeTemplate(), $database);
47
-
48
-        if ($template === false) {
49
-            $this->markFailed('Welcome template missing');
50
-
51
-            return;
52
-        }
53
-
54
-        $oauth = new OAuthUserHelper($user, $database, $this->getOauthProtocolHelper(),
55
-            $this->getSiteConfiguration());
56
-        $mediaWikiHelper = new MediaWikiHelper($oauth, $this->getSiteConfiguration());
57
-
58
-        if ($request->getStatus() !== RequestStatus::CLOSED) {
59
-            $this->markFailed('Request is currently open');
60
-
61
-            return;
62
-        }
63
-
64
-        if (!$mediaWikiHelper->checkAccountExists($request->getName())){
65
-            $this->markFailed('Account does not exist!');
66
-
67
-            return;
68
-        }
69
-
70
-        $this->performWelcome($template, $request, $mediaWikiHelper);
71
-        $this->markComplete();
72
-    }
73
-
74
-    /**
75
-     * Performs the welcome
76
-     *
77
-     * @param WelcomeTemplate $template
78
-     * @param Request         $request
79
-     * @param MediaWikiHelper $mediaWikiHelper
80
-     */
81
-    private function performWelcome(
82
-        WelcomeTemplate $template,
83
-        Request $request,
84
-        MediaWikiHelper $mediaWikiHelper
85
-    ) {
86
-        $templateText = $template->getBotCode();
87
-        $templateText = str_replace('$signature', '~~~~', $templateText);
88
-        $templateText = str_replace('$username', $request->getName(), $templateText);
89
-
90
-        $mediaWikiHelper->addTalkPageMessage($request->getName(), 'Welcome!', 'Welcoming user created through [[WP:ACC]]', $templateText);
91
-    }
23
+	public static function enqueue(User $triggerUser, Request $request, PdoDatabase $database)
24
+	{
25
+		$job = new JobQueue();
26
+		$job->setDatabase($database);
27
+		$job->setTask(WelcomeUserTask::class);
28
+		$job->setRequest($request->getId());
29
+		$job->setTriggerUserId($triggerUser->getId());
30
+		$job->save();
31
+	}
32
+
33
+	public function execute()
34
+	{
35
+		$database = $this->getDatabase();
36
+		$request = $this->getRequest();
37
+		$user = $this->getTriggerUser();
38
+
39
+		if ($user->getWelcomeTemplate() === null) {
40
+			$this->markFailed('Welcome template not specified');
41
+
42
+			return;
43
+		}
44
+
45
+		/** @var WelcomeTemplate $template */
46
+		$template = WelcomeTemplate::getById($user->getWelcomeTemplate(), $database);
47
+
48
+		if ($template === false) {
49
+			$this->markFailed('Welcome template missing');
50
+
51
+			return;
52
+		}
53
+
54
+		$oauth = new OAuthUserHelper($user, $database, $this->getOauthProtocolHelper(),
55
+			$this->getSiteConfiguration());
56
+		$mediaWikiHelper = new MediaWikiHelper($oauth, $this->getSiteConfiguration());
57
+
58
+		if ($request->getStatus() !== RequestStatus::CLOSED) {
59
+			$this->markFailed('Request is currently open');
60
+
61
+			return;
62
+		}
63
+
64
+		if (!$mediaWikiHelper->checkAccountExists($request->getName())){
65
+			$this->markFailed('Account does not exist!');
66
+
67
+			return;
68
+		}
69
+
70
+		$this->performWelcome($template, $request, $mediaWikiHelper);
71
+		$this->markComplete();
72
+	}
73
+
74
+	/**
75
+	 * Performs the welcome
76
+	 *
77
+	 * @param WelcomeTemplate $template
78
+	 * @param Request         $request
79
+	 * @param MediaWikiHelper $mediaWikiHelper
80
+	 */
81
+	private function performWelcome(
82
+		WelcomeTemplate $template,
83
+		Request $request,
84
+		MediaWikiHelper $mediaWikiHelper
85
+	) {
86
+		$templateText = $template->getBotCode();
87
+		$templateText = str_replace('$signature', '~~~~', $templateText);
88
+		$templateText = str_replace('$username', $request->getName(), $templateText);
89
+
90
+		$mediaWikiHelper->addTalkPageMessage($request->getName(), 'Welcome!', 'Welcoming user created through [[WP:ACC]]', $templateText);
91
+	}
92 92
 }
93 93
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
             return;
62 62
         }
63 63
 
64
-        if (!$mediaWikiHelper->checkAccountExists($request->getName())){
64
+        if (!$mediaWikiHelper->checkAccountExists($request->getName())) {
65 65
             $this->markFailed('Account does not exist!');
66 66
 
67 67
             return;
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
             return;
62 62
         }
63 63
 
64
-        if (!$mediaWikiHelper->checkAccountExists($request->getName())){
64
+        if (!$mediaWikiHelper->checkAccountExists($request->getName())) {
65 65
             $this->markFailed('Account does not exist!');
66 66
 
67 67
             return;
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 $oauthProtocolHelper;
191
-        $oauthProtocolHelper = $page->getOAuthProtocolHelper();
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 $oauthProtocolHelper;
191
+		$oauthProtocolHelper = $page->getOAuthProtocolHelper();
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.
includes/ExceptionHandler.php 1 patch
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -13,22 +13,22 @@  discard block
 block discarded – undo
13 13
 
14 14
 class ExceptionHandler
15 15
 {
16
-    /**
17
-     * Global exception handler
18
-     *
19
-     * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
20
-     * Let's build something ourselves, and hope it works.
21
-     *
22
-     * @param $exception
23
-     *
24
-     * @category Security-Critical - has the potential to leak data when exception is thrown.
25
-     */
26
-    public static function exceptionHandler(Exception $exception)
27
-    {
28
-        /** @global $siteConfiguration SiteConfiguration */
29
-        global $siteConfiguration;
30
-
31
-        $errorDocument = <<<HTML
16
+	/**
17
+	 * Global exception handler
18
+	 *
19
+	 * Smarty would be nice to use, but it COULD BE smarty that throws the errors.
20
+	 * Let's build something ourselves, and hope it works.
21
+	 *
22
+	 * @param $exception
23
+	 *
24
+	 * @category Security-Critical - has the potential to leak data when exception is thrown.
25
+	 */
26
+	public static function exceptionHandler(Exception $exception)
27
+	{
28
+		/** @global $siteConfiguration SiteConfiguration */
29
+		global $siteConfiguration;
30
+
31
+		$errorDocument = <<<HTML
32 32
 <!DOCTYPE html>
33 33
 <html lang="en"><head>
34 34
 <meta charset="utf-8">
@@ -49,77 +49,77 @@  discard block
 block discarded – undo
49 49
 </div></body></html>
50 50
 HTML;
51 51
 
52
-        $errorData = self::getExceptionData($exception);
53
-        $errorData['server'] = $_SERVER;
54
-        $errorData['get'] = $_GET;
55
-        $errorData['post'] = $_POST;
56
-
57
-        $state = serialize($errorData);
58
-        $errorId = sha1($state);
59
-
60
-        // Save the error for later analysis
61
-        file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
62
-
63
-        // clear and discard any content that's been saved to the output buffer
64
-        if (ob_get_level() > 0) {
65
-            ob_end_clean();
66
-        }
67
-
68
-        // push error ID into the document.
69
-        $message = str_replace('$1$', $errorId, $errorDocument);
70
-
71
-        if ($siteConfiguration->getDebuggingTraceEnabled()) {
72
-            ob_start();
73
-            var_dump($errorData);
74
-            $textErrorData = ob_get_contents();
75
-            ob_end_clean();
76
-
77
-            $message = str_replace('$2$', $textErrorData, $message);
78
-        }
79
-        else {
80
-            $message = str_replace('$2$', "", $message);
81
-        }
82
-
83
-        // While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
84
-        // This is "only" needed for the tests, but it's a good idea to wrap this anyway.
85
-        if (!headers_sent()) {
86
-            header('HTTP/1.1 500 Internal Server Error');
87
-        }
88
-
89
-        // output the document
90
-        print $message;
91
-    }
92
-
93
-    /**
94
-     * @param int    $errorSeverity The severity level of the exception.
95
-     * @param string $errorMessage  The Exception message to throw.
96
-     * @param string $errorFile     The filename where the exception is thrown.
97
-     * @param int    $errorLine     The line number where the exception is thrown.
98
-     *
99
-     * @throws ErrorException
100
-     */
101
-    public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
102
-    {
103
-        // call into the main exception handler above
104
-        throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
105
-    }
106
-
107
-    /**
108
-     * @param Exception $exception
109
-     *
110
-     * @return null|array
111
-     */
112
-    public static function getExceptionData($exception)
113
-    {
114
-        if ($exception == null) {
115
-            return null;
116
-        }
117
-
118
-        return array(
119
-            'exception' => get_class($exception),
120
-            'message'   => $exception->getMessage(),
121
-            'stack'     => $exception->getTraceAsString(),
122
-            'previous'  => self::getExceptionData($exception->getPrevious()),
123
-        );
124
-    }
52
+		$errorData = self::getExceptionData($exception);
53
+		$errorData['server'] = $_SERVER;
54
+		$errorData['get'] = $_GET;
55
+		$errorData['post'] = $_POST;
56
+
57
+		$state = serialize($errorData);
58
+		$errorId = sha1($state);
59
+
60
+		// Save the error for later analysis
61
+		file_put_contents($siteConfiguration->getErrorLog() . '/' . $errorId . '.log', $state);
62
+
63
+		// clear and discard any content that's been saved to the output buffer
64
+		if (ob_get_level() > 0) {
65
+			ob_end_clean();
66
+		}
67
+
68
+		// push error ID into the document.
69
+		$message = str_replace('$1$', $errorId, $errorDocument);
70
+
71
+		if ($siteConfiguration->getDebuggingTraceEnabled()) {
72
+			ob_start();
73
+			var_dump($errorData);
74
+			$textErrorData = ob_get_contents();
75
+			ob_end_clean();
76
+
77
+			$message = str_replace('$2$', $textErrorData, $message);
78
+		}
79
+		else {
80
+			$message = str_replace('$2$', "", $message);
81
+		}
82
+
83
+		// While we *shouldn't* have sent headers by now due to the output buffering, PHPUnit does weird things.
84
+		// This is "only" needed for the tests, but it's a good idea to wrap this anyway.
85
+		if (!headers_sent()) {
86
+			header('HTTP/1.1 500 Internal Server Error');
87
+		}
88
+
89
+		// output the document
90
+		print $message;
91
+	}
92
+
93
+	/**
94
+	 * @param int    $errorSeverity The severity level of the exception.
95
+	 * @param string $errorMessage  The Exception message to throw.
96
+	 * @param string $errorFile     The filename where the exception is thrown.
97
+	 * @param int    $errorLine     The line number where the exception is thrown.
98
+	 *
99
+	 * @throws ErrorException
100
+	 */
101
+	public static function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine)
102
+	{
103
+		// call into the main exception handler above
104
+		throw new ErrorException($errorMessage, 0, $errorSeverity, $errorFile, $errorLine);
105
+	}
106
+
107
+	/**
108
+	 * @param Exception $exception
109
+	 *
110
+	 * @return null|array
111
+	 */
112
+	public static function getExceptionData($exception)
113
+	{
114
+		if ($exception == null) {
115
+			return null;
116
+		}
117
+
118
+		return array(
119
+			'exception' => get_class($exception),
120
+			'message'   => $exception->getMessage(),
121
+			'stack'     => $exception->getTraceAsString(),
122
+			'previous'  => self::getExceptionData($exception->getPrevious()),
123
+		);
124
+	}
125 125
 }
126 126
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Fragments/NavigationMenuAccessControl.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -25,48 +25,48 @@
 block discarded – undo
25 25
 
26 26
 trait NavigationMenuAccessControl
27 27
 {
28
-    protected abstract function assign($name, $value);
28
+	protected abstract function assign($name, $value);
29 29
 
30
-    /**
31
-     * @return SecurityManager
32
-     */
33
-    protected abstract function getSecurityManager();
30
+	/**
31
+	 * @return SecurityManager
32
+	 */
33
+	protected abstract function getSecurityManager();
34 34
 
35
-    /**
36
-     * @param $currentUser
37
-     */
38
-    protected function setupNavMenuAccess($currentUser)
39
-    {
40
-        $this->assign('nav__canRequests', $this->getSecurityManager()
41
-                ->allows(PageMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
35
+	/**
36
+	 * @param $currentUser
37
+	 */
38
+	protected function setupNavMenuAccess($currentUser)
39
+	{
40
+		$this->assign('nav__canRequests', $this->getSecurityManager()
41
+				->allows(PageMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
42 42
 
43
-        $this->assign('nav__canLogs', $this->getSecurityManager()
44
-                ->allows(PageLog::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
45
-        $this->assign('nav__canUsers', $this->getSecurityManager()
46
-                ->allows(StatsUsers::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
47
-        $this->assign('nav__canSearch', $this->getSecurityManager()
48
-                ->allows(PageSearch::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
49
-        $this->assign('nav__canStats', $this->getSecurityManager()
50
-                ->allows(StatsMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
43
+		$this->assign('nav__canLogs', $this->getSecurityManager()
44
+				->allows(PageLog::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
45
+		$this->assign('nav__canUsers', $this->getSecurityManager()
46
+				->allows(StatsUsers::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
47
+		$this->assign('nav__canSearch', $this->getSecurityManager()
48
+				->allows(PageSearch::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
49
+		$this->assign('nav__canStats', $this->getSecurityManager()
50
+				->allows(StatsMain::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
51 51
 
52
-        $this->assign('nav__canBan', $this->getSecurityManager()
53
-                ->allows(PageBan::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
54
-        $this->assign('nav__canEmailMgmt', $this->getSecurityManager()
55
-                ->allows(PageEmailManagement::class, RoleConfiguration::MAIN,
56
-                    $currentUser) === SecurityManager::ALLOWED);
57
-        $this->assign('nav__canWelcomeMgmt', $this->getSecurityManager()
58
-                ->allows(PageWelcomeTemplateManagement::class, RoleConfiguration::MAIN,
59
-                    $currentUser) === SecurityManager::ALLOWED);
60
-        $this->assign('nav__canSiteNoticeMgmt', $this->getSecurityManager()
61
-                ->allows(PageSiteNotice::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
62
-        $this->assign('nav__canUserMgmt', $this->getSecurityManager()
63
-                ->allows(PageUserManagement::class, RoleConfiguration::MAIN,
64
-                    $currentUser) === SecurityManager::ALLOWED);
65
-        $this->assign('nav__canJobQueue', $this->getSecurityManager()
66
-                ->allows(PageJobQueue::class, RoleConfiguration::MAIN,
67
-                    $currentUser) === SecurityManager::ALLOWED);
52
+		$this->assign('nav__canBan', $this->getSecurityManager()
53
+				->allows(PageBan::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
54
+		$this->assign('nav__canEmailMgmt', $this->getSecurityManager()
55
+				->allows(PageEmailManagement::class, RoleConfiguration::MAIN,
56
+					$currentUser) === SecurityManager::ALLOWED);
57
+		$this->assign('nav__canWelcomeMgmt', $this->getSecurityManager()
58
+				->allows(PageWelcomeTemplateManagement::class, RoleConfiguration::MAIN,
59
+					$currentUser) === SecurityManager::ALLOWED);
60
+		$this->assign('nav__canSiteNoticeMgmt', $this->getSecurityManager()
61
+				->allows(PageSiteNotice::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
62
+		$this->assign('nav__canUserMgmt', $this->getSecurityManager()
63
+				->allows(PageUserManagement::class, RoleConfiguration::MAIN,
64
+					$currentUser) === SecurityManager::ALLOWED);
65
+		$this->assign('nav__canJobQueue', $this->getSecurityManager()
66
+				->allows(PageJobQueue::class, RoleConfiguration::MAIN,
67
+					$currentUser) === SecurityManager::ALLOWED);
68 68
 
69
-        $this->assign('nav__canViewRequest', $this->getSecurityManager()
70
-                ->allows(PageViewRequest::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
71
-    }
69
+		$this->assign('nav__canViewRequest', $this->getSecurityManager()
70
+				->allows(PageViewRequest::class, RoleConfiguration::MAIN, $currentUser) === SecurityManager::ALLOWED);
71
+	}
72 72
 }
73 73
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Fragments/TemplateOutput.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -15,89 +15,89 @@
 block discarded – undo
15 15
 
16 16
 trait TemplateOutput
17 17
 {
18
-    /** @var Smarty */
19
-    private $smarty;
20
-    /** @var string Extra JavaScript to include at the end of the page's execution */
21
-    private $tailScript;
18
+	/** @var Smarty */
19
+	private $smarty;
20
+	/** @var string Extra JavaScript to include at the end of the page's execution */
21
+	private $tailScript;
22 22
 
23
-    /**
24
-     * @return SiteConfiguration
25
-     */
26
-    protected abstract function getSiteConfiguration();
23
+	/**
24
+	 * @return SiteConfiguration
25
+	 */
26
+	protected abstract function getSiteConfiguration();
27 27
 
28
-    /**
29
-     * Include extra JavaScript at the end of the page's execution
30
-     *
31
-     * @param $script string JavaScript to include at the end of the page
32
-     */
33
-    final protected function setTailScript($script)
34
-    {
35
-        $this->tailScript = $script;
36
-    }
28
+	/**
29
+	 * Include extra JavaScript at the end of the page's execution
30
+	 *
31
+	 * @param $script string JavaScript to include at the end of the page
32
+	 */
33
+	final protected function setTailScript($script)
34
+	{
35
+		$this->tailScript = $script;
36
+	}
37 37
 
38
-    /**
39
-     * Assigns a Smarty variable
40
-     *
41
-     * @param  array|string $name  the template variable name(s)
42
-     * @param  mixed        $value the value to assign
43
-     */
44
-    final protected function assign($name, $value)
45
-    {
46
-        $this->smarty->assign($name, $value);
47
-    }
38
+	/**
39
+	 * Assigns a Smarty variable
40
+	 *
41
+	 * @param  array|string $name  the template variable name(s)
42
+	 * @param  mixed        $value the value to assign
43
+	 */
44
+	final protected function assign($name, $value)
45
+	{
46
+		$this->smarty->assign($name, $value);
47
+	}
48 48
 
49
-    /**
50
-     * Sets up the variables used by the main Smarty base template.
51
-     *
52
-     * This list is getting kinda long.
53
-     */
54
-    final protected function setUpSmarty()
55
-    {
56
-        $this->smarty = new Smarty();
57
-        $this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
49
+	/**
50
+	 * Sets up the variables used by the main Smarty base template.
51
+	 *
52
+	 * This list is getting kinda long.
53
+	 */
54
+	final protected function setUpSmarty()
55
+	{
56
+		$this->smarty = new Smarty();
57
+		$this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
58 58
 
59
-        $this->assign('currentUser', User::getCommunity());
60
-        $this->assign('loggedIn', false);
61
-        $this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
62
-        $this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
59
+		$this->assign('currentUser', User::getCommunity());
60
+		$this->assign('loggedIn', false);
61
+		$this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
62
+		$this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
63 63
 
64
-        $this->assign('siteNoticeText', '');
65
-        $this->assign('toolversion', Environment::getToolVersion());
64
+		$this->assign('siteNoticeText', '');
65
+		$this->assign('toolversion', Environment::getToolVersion());
66 66
 
67
-        // default these
68
-        $this->assign('onlineusers', array());
69
-        $this->assign('typeAheadBlock', '');
70
-        $this->assign('extraJs', array());
71
-        $this->assign('extraCss', array());
67
+		// default these
68
+		$this->assign('onlineusers', array());
69
+		$this->assign('typeAheadBlock', '');
70
+		$this->assign('extraJs', array());
71
+		$this->assign('extraCss', array());
72 72
 
73
-        // nav menu access control
74
-        $this->assign('nav__canRequests', false);
75
-        $this->assign('nav__canLogs', false);
76
-        $this->assign('nav__canUsers', false);
77
-        $this->assign('nav__canSearch', false);
78
-        $this->assign('nav__canStats', false);
79
-        $this->assign('nav__canBan', false);
80
-        $this->assign('nav__canEmailMgmt', false);
81
-        $this->assign('nav__canWelcomeMgmt', false);
82
-        $this->assign('nav__canSiteNoticeMgmt', false);
83
-        $this->assign('nav__canUserMgmt', false);
84
-        $this->assign('nav__canViewRequest', false);
85
-        $this->assign('nav__canJobQueue', false);
73
+		// nav menu access control
74
+		$this->assign('nav__canRequests', false);
75
+		$this->assign('nav__canLogs', false);
76
+		$this->assign('nav__canUsers', false);
77
+		$this->assign('nav__canSearch', false);
78
+		$this->assign('nav__canStats', false);
79
+		$this->assign('nav__canBan', false);
80
+		$this->assign('nav__canEmailMgmt', false);
81
+		$this->assign('nav__canWelcomeMgmt', false);
82
+		$this->assign('nav__canSiteNoticeMgmt', false);
83
+		$this->assign('nav__canUserMgmt', false);
84
+		$this->assign('nav__canViewRequest', false);
85
+		$this->assign('nav__canJobQueue', false);
86 86
 
87
-        $this->assign('page', $this);
88
-    }
87
+		$this->assign('page', $this);
88
+	}
89 89
 
90
-    /**
91
-     * Fetches a rendered Smarty template
92
-     *
93
-     * @param $template string Template file path, relative to /templates/
94
-     *
95
-     * @return string Templated HTML
96
-     */
97
-    final protected function fetchTemplate($template)
98
-    {
99
-        $this->assign("tailScript", $this->tailScript);
90
+	/**
91
+	 * Fetches a rendered Smarty template
92
+	 *
93
+	 * @param $template string Template file path, relative to /templates/
94
+	 *
95
+	 * @return string Templated HTML
96
+	 */
97
+	final protected function fetchTemplate($template)
98
+	{
99
+		$this->assign("tailScript", $this->tailScript);
100 100
 
101
-        return $this->smarty->fetch($template);
102
-    }
101
+		return $this->smarty->fetch($template);
102
+	}
103 103
 }
Please login to merge, or discard this patch.
includes/Fragments/RequestData.php 1 patch
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -24,324 +24,324 @@
 block discarded – undo
24 24
 
25 25
 trait RequestData
26 26
 {
27
-    /**
28
-     * @var array Array of IP address classed as 'private' by RFC1918.
29
-     */
30
-    protected static $rfc1918ips = array(
31
-        "10.0.0.0"    => "10.255.255.255",
32
-        "172.16.0.0"  => "172.31.255.255",
33
-        "192.168.0.0" => "192.168.255.255",
34
-        "169.254.0.0" => "169.254.255.255",
35
-        "127.0.0.0"   => "127.255.255.255",
36
-    );
37
-
38
-    /**
39
-     * Gets a request object
40
-     *
41
-     * @param PdoDatabase $database  The database connection
42
-     * @param int         $requestId The ID of the request to retrieve
43
-     *
44
-     * @return Request
45
-     * @throws ApplicationLogicException
46
-     */
47
-    protected function getRequest(PdoDatabase $database, $requestId)
48
-    {
49
-        if ($requestId === null) {
50
-            throw new ApplicationLogicException("No request specified");
51
-        }
52
-
53
-        $request = Request::getById($requestId, $database);
54
-        if ($request === false || !is_a($request, Request::class)) {
55
-            throw new ApplicationLogicException('Could not load the requested request!');
56
-        }
57
-
58
-        return $request;
59
-    }
60
-
61
-    /**
62
-     * Returns a value stating whether the user is allowed to see private data or not
63
-     *
64
-     * @param Request $request
65
-     * @param User    $currentUser
66
-     *
67
-     * @return bool
68
-     * @category Security-Critical
69
-     */
70
-    protected function isAllowedPrivateData(Request $request, User $currentUser)
71
-    {
72
-        // Test the main security barrier for private data access using SecurityManager
73
-        if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
74
-            // Tool admins/check-users can always see private data
75
-            return true;
76
-        }
77
-
78
-        // reserving user is allowed to see the data
79
-        if ($currentUser->getId() === $request->getReserved()
80
-            && $request->getReserved() !== null
81
-            && $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
82
-        ) {
83
-            return true;
84
-        }
85
-
86
-        // user has the reveal hash
87
-        if (WebRequest::getString('hash') === $request->getRevealHash()
88
-            && $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
89
-        ) {
90
-            return true;
91
-        }
92
-
93
-        // nope. Not allowed.
94
-        return false;
95
-    }
96
-
97
-    /**
98
-     * Tests the security barrier for a specified action.
99
-     *
100
-     * Don't use within templates
101
-     *
102
-     * @param string      $action
103
-     *
104
-     * @param User        $user
105
-     * @param null|string $pageName
106
-     *
107
-     * @return bool
108
-     * @category Security-Critical
109
-     */
110
-    abstract protected function barrierTest($action, User $user, $pageName = null);
111
-
112
-    /**
113
-     * Gets the name of the route that has been passed from the request router.
114
-     * @return string
115
-     */
116
-    abstract protected function getRouteName();
117
-
118
-    /** @return SecurityManager */
119
-    abstract protected function getSecurityManager();
120
-
121
-    /**
122
-     * Sets the name of the template this page should display.
123
-     *
124
-     * @param string $name
125
-     */
126
-    abstract protected function setTemplate($name);
127
-
128
-    /** @return IXffTrustProvider */
129
-    abstract protected function getXffTrustProvider();
130
-
131
-    /** @return ILocationProvider */
132
-    abstract protected function getLocationProvider();
133
-
134
-    /** @return IRDnsProvider */
135
-    abstract protected function getRdnsProvider();
136
-
137
-    /**
138
-     * Assigns a Smarty variable
139
-     *
140
-     * @param  array|string $name  the template variable name(s)
141
-     * @param  mixed        $value the value to assign
142
-     */
143
-    abstract protected function assign($name, $value);
144
-
145
-    /**
146
-     * @param int         $requestReservationId
147
-     * @param PdoDatabase $database
148
-     * @param User        $currentUser
149
-     */
150
-    protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
151
-    {
152
-        $requestIsReserved = $requestReservationId !== null;
153
-        $this->assign('requestIsReserved', $requestIsReserved);
154
-        $this->assign('requestIsReservedByMe', false);
155
-
156
-        if ($requestIsReserved) {
157
-            $this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
158
-            $this->assign('requestReservedById', $requestReservationId);
159
-
160
-            if ($requestReservationId === $currentUser->getId()) {
161
-                $this->assign('requestIsReservedByMe', true);
162
-            }
163
-        }
164
-
165
-        $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
166
-    }
167
-
168
-    /**
169
-     * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
170
-     *
171
-     * @param Request           $request
172
-     * @param User              $currentUser
173
-     * @param SiteConfiguration $configuration
174
-     *
175
-     * @param PdoDatabase       $database
176
-     */
177
-    protected function setupPrivateData(
178
-        $request,
179
-        User $currentUser,
180
-        SiteConfiguration $configuration,
181
-        PdoDatabase $database
182
-    ) {
183
-        $xffProvider = $this->getXffTrustProvider();
184
-
185
-        $relatedEmailRequests = RequestSearchHelper::get($database)
186
-            ->byEmailAddress($request->getEmail())
187
-            ->withConfirmedEmail()
188
-            ->excludingPurgedData($configuration)
189
-            ->excludingRequest($request->getId())
190
-            ->fetch();
191
-
192
-        $this->assign('requestEmail', $request->getEmail());
193
-        $emailDomain = explode("@", $request->getEmail())[1];
194
-        $this->assign("emailurl", $emailDomain);
195
-        $this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
196
-        $this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
197
-
198
-        $trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
199
-        $this->assign('requestTrustedIp', $trustedIp);
200
-        $this->assign('requestRealIp', $request->getIp());
201
-        $this->assign('requestForwardedIp', $request->getForwardedIp());
202
-
203
-        $trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
204
-        $this->assign('requestTrustedIpLocation', $trustedIpLocation);
205
-
206
-        $this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
207
-
208
-        $relatedIpRequests = RequestSearchHelper::get($database)
209
-            ->byIp($trustedIp)
210
-            ->withConfirmedEmail()
211
-            ->excludingPurgedData($configuration)
212
-            ->excludingRequest($request->getId())
213
-            ->fetch();
214
-
215
-        $this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
216
-        $this->assign('requestRelatedIpRequests', $relatedIpRequests);
217
-
218
-        $this->assign('showRevealLink', false);
219
-        if ($request->getReserved() === $currentUser->getId() ||
220
-            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
221
-        ) {
222
-            $this->assign('showRevealLink', true);
223
-            $this->assign('revealHash', $request->getRevealHash());
224
-        }
225
-
226
-        $this->setupForwardedIpData($request);
227
-    }
228
-
229
-    /**
230
-     * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
231
-     *
232
-     * @param Request $request
233
-     */
234
-    protected function setupCheckUserData(Request $request)
235
-    {
236
-        $this->assign('requestUserAgent', $request->getUserAgent());
237
-    }
238
-
239
-    /**
240
-     * Sets up the basic data for this request, and adds it to Smarty
241
-     *
242
-     * @param Request           $request
243
-     * @param SiteConfiguration $config
244
-     */
245
-    protected function setupBasicData(Request $request, SiteConfiguration $config)
246
-    {
247
-        $this->assign('requestId', $request->getId());
248
-        $this->assign('updateVersion', $request->getUpdateVersion());
249
-        $this->assign('requestName', $request->getName());
250
-        $this->assign('requestDate', $request->getDate());
251
-        $this->assign('requestStatus', $request->getStatus());
252
-
253
-        $isClosed = !array_key_exists($request->getStatus(), $config->getRequestStates())
254
-            && $request->getStatus() !== RequestStatus::HOSPITAL;
255
-        $this->assign('requestIsClosed', $isClosed);
256
-    }
257
-
258
-    /**
259
-     * Sets up the forwarded IP data for this request and adds it to Smarty
260
-     *
261
-     * @param Request $request
262
-     */
263
-    protected function setupForwardedIpData(Request $request)
264
-    {
265
-        if ($request->getForwardedIp() !== null) {
266
-            $requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
267
-            $proxyIndex = 0;
268
-
269
-            // Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
270
-            // [proxy1], [proxy2], and our actual IP will be [proxy3]
271
-            $proxies = explode(",", $request->getForwardedIp());
272
-            $proxies[] = $request->getIp();
273
-
274
-            // Origin is the supposed "client" IP.
275
-            $origin = $proxies[0];
276
-            $this->assign("forwardedOrigin", $origin);
277
-
278
-            // We step through the servers in reverse order, from closest to furthest
279
-            $proxies = array_reverse($proxies);
280
-
281
-            // By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
282
-            $trust = true;
283
-
284
-            /**
285
-             * @var int    $index     The zero-based index of the proxy.
286
-             * @var string $proxyData The proxy IP address (although possibly not!)
287
-             */
288
-            foreach ($proxies as $index => $proxyData) {
289
-                $proxyAddress = trim($proxyData);
290
-                $requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
291
-
292
-                // get data on this IP.
293
-                $thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
294
-
295
-                $proxyIsInPrivateRange = $this->getXffTrustProvider()
296
-                    ->ipInRange(self::$rfc1918ips, $proxyAddress);
297
-
298
-                if (!$proxyIsInPrivateRange) {
299
-                    $proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
300
-                    $proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
301
-                }
302
-                else {
303
-                    // this is going to fail, so why bother trying?
304
-                    $proxyReverseDns = false;
305
-                    $proxyLocation = false;
306
-                }
307
-
308
-                // current trust chain status BEFORE this link
309
-                $preLinkTrust = $trust;
310
-
311
-                // is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
312
-                $requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
313
-
314
-                // set the trust status of the chain to this point
315
-                $trust = $trust & $thisProxyIsTrusted;
316
-
317
-                // If this is the origin address, and the chain was trusted before this point, then we can trust
318
-                // the origin.
319
-                if ($preLinkTrust && $proxyAddress == $origin) {
320
-                    // if this is the origin, then we are at the last point in the chain.
321
-                    // @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
322
-                    // to see if this is *really* the last in the chain, rather than just the same IP as it.
323
-                    $trust = true;
324
-                }
325
-
326
-                $requestProxyData[$proxyIndex]['trust'] = $trust;
327
-
328
-                $requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
329
-                $requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
330
-                $requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
331
-
332
-                $requestProxyData[$proxyIndex]['location'] = $proxyLocation;
333
-
334
-                if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
335
-                    $requestProxyData[$proxyIndex]['rdns'] = null;
336
-                }
337
-
338
-                $showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
339
-                $requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
340
-
341
-                $proxyIndex++;
342
-            }
343
-
344
-            $this->assign("requestProxyData", $requestProxyData);
345
-        }
346
-    }
27
+	/**
28
+	 * @var array Array of IP address classed as 'private' by RFC1918.
29
+	 */
30
+	protected static $rfc1918ips = array(
31
+		"10.0.0.0"    => "10.255.255.255",
32
+		"172.16.0.0"  => "172.31.255.255",
33
+		"192.168.0.0" => "192.168.255.255",
34
+		"169.254.0.0" => "169.254.255.255",
35
+		"127.0.0.0"   => "127.255.255.255",
36
+	);
37
+
38
+	/**
39
+	 * Gets a request object
40
+	 *
41
+	 * @param PdoDatabase $database  The database connection
42
+	 * @param int         $requestId The ID of the request to retrieve
43
+	 *
44
+	 * @return Request
45
+	 * @throws ApplicationLogicException
46
+	 */
47
+	protected function getRequest(PdoDatabase $database, $requestId)
48
+	{
49
+		if ($requestId === null) {
50
+			throw new ApplicationLogicException("No request specified");
51
+		}
52
+
53
+		$request = Request::getById($requestId, $database);
54
+		if ($request === false || !is_a($request, Request::class)) {
55
+			throw new ApplicationLogicException('Could not load the requested request!');
56
+		}
57
+
58
+		return $request;
59
+	}
60
+
61
+	/**
62
+	 * Returns a value stating whether the user is allowed to see private data or not
63
+	 *
64
+	 * @param Request $request
65
+	 * @param User    $currentUser
66
+	 *
67
+	 * @return bool
68
+	 * @category Security-Critical
69
+	 */
70
+	protected function isAllowedPrivateData(Request $request, User $currentUser)
71
+	{
72
+		// Test the main security barrier for private data access using SecurityManager
73
+		if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
74
+			// Tool admins/check-users can always see private data
75
+			return true;
76
+		}
77
+
78
+		// reserving user is allowed to see the data
79
+		if ($currentUser->getId() === $request->getReserved()
80
+			&& $request->getReserved() !== null
81
+			&& $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
82
+		) {
83
+			return true;
84
+		}
85
+
86
+		// user has the reveal hash
87
+		if (WebRequest::getString('hash') === $request->getRevealHash()
88
+			&& $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
89
+		) {
90
+			return true;
91
+		}
92
+
93
+		// nope. Not allowed.
94
+		return false;
95
+	}
96
+
97
+	/**
98
+	 * Tests the security barrier for a specified action.
99
+	 *
100
+	 * Don't use within templates
101
+	 *
102
+	 * @param string      $action
103
+	 *
104
+	 * @param User        $user
105
+	 * @param null|string $pageName
106
+	 *
107
+	 * @return bool
108
+	 * @category Security-Critical
109
+	 */
110
+	abstract protected function barrierTest($action, User $user, $pageName = null);
111
+
112
+	/**
113
+	 * Gets the name of the route that has been passed from the request router.
114
+	 * @return string
115
+	 */
116
+	abstract protected function getRouteName();
117
+
118
+	/** @return SecurityManager */
119
+	abstract protected function getSecurityManager();
120
+
121
+	/**
122
+	 * Sets the name of the template this page should display.
123
+	 *
124
+	 * @param string $name
125
+	 */
126
+	abstract protected function setTemplate($name);
127
+
128
+	/** @return IXffTrustProvider */
129
+	abstract protected function getXffTrustProvider();
130
+
131
+	/** @return ILocationProvider */
132
+	abstract protected function getLocationProvider();
133
+
134
+	/** @return IRDnsProvider */
135
+	abstract protected function getRdnsProvider();
136
+
137
+	/**
138
+	 * Assigns a Smarty variable
139
+	 *
140
+	 * @param  array|string $name  the template variable name(s)
141
+	 * @param  mixed        $value the value to assign
142
+	 */
143
+	abstract protected function assign($name, $value);
144
+
145
+	/**
146
+	 * @param int         $requestReservationId
147
+	 * @param PdoDatabase $database
148
+	 * @param User        $currentUser
149
+	 */
150
+	protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
151
+	{
152
+		$requestIsReserved = $requestReservationId !== null;
153
+		$this->assign('requestIsReserved', $requestIsReserved);
154
+		$this->assign('requestIsReservedByMe', false);
155
+
156
+		if ($requestIsReserved) {
157
+			$this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
158
+			$this->assign('requestReservedById', $requestReservationId);
159
+
160
+			if ($requestReservationId === $currentUser->getId()) {
161
+				$this->assign('requestIsReservedByMe', true);
162
+			}
163
+		}
164
+
165
+		$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
166
+	}
167
+
168
+	/**
169
+	 * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
170
+	 *
171
+	 * @param Request           $request
172
+	 * @param User              $currentUser
173
+	 * @param SiteConfiguration $configuration
174
+	 *
175
+	 * @param PdoDatabase       $database
176
+	 */
177
+	protected function setupPrivateData(
178
+		$request,
179
+		User $currentUser,
180
+		SiteConfiguration $configuration,
181
+		PdoDatabase $database
182
+	) {
183
+		$xffProvider = $this->getXffTrustProvider();
184
+
185
+		$relatedEmailRequests = RequestSearchHelper::get($database)
186
+			->byEmailAddress($request->getEmail())
187
+			->withConfirmedEmail()
188
+			->excludingPurgedData($configuration)
189
+			->excludingRequest($request->getId())
190
+			->fetch();
191
+
192
+		$this->assign('requestEmail', $request->getEmail());
193
+		$emailDomain = explode("@", $request->getEmail())[1];
194
+		$this->assign("emailurl", $emailDomain);
195
+		$this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
196
+		$this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
197
+
198
+		$trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
199
+		$this->assign('requestTrustedIp', $trustedIp);
200
+		$this->assign('requestRealIp', $request->getIp());
201
+		$this->assign('requestForwardedIp', $request->getForwardedIp());
202
+
203
+		$trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
204
+		$this->assign('requestTrustedIpLocation', $trustedIpLocation);
205
+
206
+		$this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
207
+
208
+		$relatedIpRequests = RequestSearchHelper::get($database)
209
+			->byIp($trustedIp)
210
+			->withConfirmedEmail()
211
+			->excludingPurgedData($configuration)
212
+			->excludingRequest($request->getId())
213
+			->fetch();
214
+
215
+		$this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
216
+		$this->assign('requestRelatedIpRequests', $relatedIpRequests);
217
+
218
+		$this->assign('showRevealLink', false);
219
+		if ($request->getReserved() === $currentUser->getId() ||
220
+			$this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
221
+		) {
222
+			$this->assign('showRevealLink', true);
223
+			$this->assign('revealHash', $request->getRevealHash());
224
+		}
225
+
226
+		$this->setupForwardedIpData($request);
227
+	}
228
+
229
+	/**
230
+	 * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
231
+	 *
232
+	 * @param Request $request
233
+	 */
234
+	protected function setupCheckUserData(Request $request)
235
+	{
236
+		$this->assign('requestUserAgent', $request->getUserAgent());
237
+	}
238
+
239
+	/**
240
+	 * Sets up the basic data for this request, and adds it to Smarty
241
+	 *
242
+	 * @param Request           $request
243
+	 * @param SiteConfiguration $config
244
+	 */
245
+	protected function setupBasicData(Request $request, SiteConfiguration $config)
246
+	{
247
+		$this->assign('requestId', $request->getId());
248
+		$this->assign('updateVersion', $request->getUpdateVersion());
249
+		$this->assign('requestName', $request->getName());
250
+		$this->assign('requestDate', $request->getDate());
251
+		$this->assign('requestStatus', $request->getStatus());
252
+
253
+		$isClosed = !array_key_exists($request->getStatus(), $config->getRequestStates())
254
+			&& $request->getStatus() !== RequestStatus::HOSPITAL;
255
+		$this->assign('requestIsClosed', $isClosed);
256
+	}
257
+
258
+	/**
259
+	 * Sets up the forwarded IP data for this request and adds it to Smarty
260
+	 *
261
+	 * @param Request $request
262
+	 */
263
+	protected function setupForwardedIpData(Request $request)
264
+	{
265
+		if ($request->getForwardedIp() !== null) {
266
+			$requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
267
+			$proxyIndex = 0;
268
+
269
+			// Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
270
+			// [proxy1], [proxy2], and our actual IP will be [proxy3]
271
+			$proxies = explode(",", $request->getForwardedIp());
272
+			$proxies[] = $request->getIp();
273
+
274
+			// Origin is the supposed "client" IP.
275
+			$origin = $proxies[0];
276
+			$this->assign("forwardedOrigin", $origin);
277
+
278
+			// We step through the servers in reverse order, from closest to furthest
279
+			$proxies = array_reverse($proxies);
280
+
281
+			// By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
282
+			$trust = true;
283
+
284
+			/**
285
+			 * @var int    $index     The zero-based index of the proxy.
286
+			 * @var string $proxyData The proxy IP address (although possibly not!)
287
+			 */
288
+			foreach ($proxies as $index => $proxyData) {
289
+				$proxyAddress = trim($proxyData);
290
+				$requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
291
+
292
+				// get data on this IP.
293
+				$thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
294
+
295
+				$proxyIsInPrivateRange = $this->getXffTrustProvider()
296
+					->ipInRange(self::$rfc1918ips, $proxyAddress);
297
+
298
+				if (!$proxyIsInPrivateRange) {
299
+					$proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
300
+					$proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
301
+				}
302
+				else {
303
+					// this is going to fail, so why bother trying?
304
+					$proxyReverseDns = false;
305
+					$proxyLocation = false;
306
+				}
307
+
308
+				// current trust chain status BEFORE this link
309
+				$preLinkTrust = $trust;
310
+
311
+				// is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
312
+				$requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
313
+
314
+				// set the trust status of the chain to this point
315
+				$trust = $trust & $thisProxyIsTrusted;
316
+
317
+				// If this is the origin address, and the chain was trusted before this point, then we can trust
318
+				// the origin.
319
+				if ($preLinkTrust && $proxyAddress == $origin) {
320
+					// if this is the origin, then we are at the last point in the chain.
321
+					// @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
322
+					// to see if this is *really* the last in the chain, rather than just the same IP as it.
323
+					$trust = true;
324
+				}
325
+
326
+				$requestProxyData[$proxyIndex]['trust'] = $trust;
327
+
328
+				$requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
329
+				$requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
330
+				$requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
331
+
332
+				$requestProxyData[$proxyIndex]['location'] = $proxyLocation;
333
+
334
+				if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
335
+					$requestProxyData[$proxyIndex]['rdns'] = null;
336
+				}
337
+
338
+				$showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
339
+				$requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
340
+
341
+				$proxyIndex++;
342
+			}
343
+
344
+			$this->assign("requestProxyData", $requestProxyData);
345
+		}
346
+	}
347 347
 }
Please login to merge, or discard this patch.
includes/Router/OAuthRequestRouter.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -17,9 +17,9 @@
 block discarded – undo
17 17
  */
18 18
 class OAuthRequestRouter extends RequestRouter
19 19
 {
20
-    protected function getRouteFromPath($pathInfo)
21
-    {
22
-        // Hardcode the route for this entry point
23
-        return array(PageOAuthCallback::class, 'authorise');
24
-    }
20
+	protected function getRouteFromPath($pathInfo)
21
+	{
22
+		// Hardcode the route for this entry point
23
+		return array(PageOAuthCallback::class, 'authorise');
24
+	}
25 25
 }
26 26
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Tasks/PagedInternalPageBase.php 3 patches
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -13,97 +13,97 @@
 block discarded – undo
13 13
 
14 14
 abstract class PagedInternalPageBase extends InternalPageBase
15 15
 {
16
-    /** @var SearchHelperBase */
17
-    private $searchHelper;
18
-    private $page;
19
-    private $limit;
20
-
21
-    /**
22
-     * Sets up the pager with the current page, current limit, and total number of records.
23
-     *
24
-     * @param int   $count
25
-     * @param array $formParameters
26
-     */
27
-    protected function setupPageData($count, $formParameters)
28
-    {
29
-        $page = $this->page;
30
-        $limit = $this->limit;
31
-
32
-        // The number of pages on the pager to show. Must be odd
33
-        $pageLimit = 9;
34
-
35
-        $pageData = array(
36
-            // Can the user go to the previous page?
37
-            'canprev'   => $page != 1,
38
-            // Can the user go to the next page?
39
-            'cannext'   => ($page * $limit) < $count,
40
-            // Maximum page number
41
-            'maxpage'   => ceil($count / $limit),
42
-            // Limit to the number of pages to display
43
-            'pagelimit' => $pageLimit,
44
-        );
45
-
46
-        // number of pages either side of the current to show
47
-        $pageMargin = (($pageLimit - 1) / 2);
48
-
49
-        // Calculate the number of pages either side to show - this is for situations like:
50
-        //  [1]  [2] [[3]] [4]  [5]  [6]  [7]  [8]  [9] - where you can't just use the page margin calculated
51
-        $pageData['lowpage'] = max(1, $page - $pageMargin);
52
-        $pageData['hipage'] = min($pageData['maxpage'], $page + $pageMargin);
53
-        $pageCount = ($pageData['hipage'] - $pageData['lowpage']) + 1;
54
-
55
-        if ($pageCount < $pageLimit) {
56
-            if ($pageData['lowpage'] == 1 && $pageData['hipage'] < $pageData['maxpage']) {
57
-                $pageData['hipage'] = min($pageLimit, $pageData['maxpage']);
58
-            }
59
-            elseif ($pageData['lowpage'] > 1 && $pageData['hipage'] == $pageData['maxpage']) {
60
-                $pageData['lowpage'] = max(1, $pageData['maxpage'] - $pageLimit + 1);
61
-            }
62
-        }
63
-
64
-        // Put the range of pages into the page data
65
-        $pageData['pages'] = range($pageData['lowpage'], $pageData['hipage']);
66
-
67
-        $this->assign("pagedata", $pageData);
68
-
69
-        $this->assign("limit", $limit);
70
-        $this->assign("page", $page);
71
-
72
-        $this->setupFormParameters($formParameters);
73
-    }
74
-
75
-    protected function setSearchHelper(SearchHelperBase $searchHelper)
76
-    {
77
-        $this->searchHelper = $searchHelper;
78
-    }
79
-
80
-    protected function setupLimits()
81
-    {
82
-        $limit = WebRequest::getInt('limit');
83
-        if ($limit === null) {
84
-            $limit = 100;
85
-        }
86
-
87
-        $page = WebRequest::getInt('page');
88
-        if ($page === null) {
89
-            $page = 1;
90
-        }
91
-
92
-        $offset = ($page - 1) * $limit;
93
-
94
-        $this->searchHelper->limit($limit, $offset);
95
-
96
-        $this->page = $page;
97
-        $this->limit = $limit;
98
-    }
99
-
100
-    private function setupFormParameters($formParameters)
101
-    {
102
-        $formParameters['limit'] = $this->limit;
103
-        $this->assign('searchParamsUrl', http_build_query($formParameters, '', '&amp;'));
104
-
105
-        foreach ($formParameters as $key => $value)  {
106
-            $this->assign($key, $value);
107
-        }
108
-    }
16
+	/** @var SearchHelperBase */
17
+	private $searchHelper;
18
+	private $page;
19
+	private $limit;
20
+
21
+	/**
22
+	 * Sets up the pager with the current page, current limit, and total number of records.
23
+	 *
24
+	 * @param int   $count
25
+	 * @param array $formParameters
26
+	 */
27
+	protected function setupPageData($count, $formParameters)
28
+	{
29
+		$page = $this->page;
30
+		$limit = $this->limit;
31
+
32
+		// The number of pages on the pager to show. Must be odd
33
+		$pageLimit = 9;
34
+
35
+		$pageData = array(
36
+			// Can the user go to the previous page?
37
+			'canprev'   => $page != 1,
38
+			// Can the user go to the next page?
39
+			'cannext'   => ($page * $limit) < $count,
40
+			// Maximum page number
41
+			'maxpage'   => ceil($count / $limit),
42
+			// Limit to the number of pages to display
43
+			'pagelimit' => $pageLimit,
44
+		);
45
+
46
+		// number of pages either side of the current to show
47
+		$pageMargin = (($pageLimit - 1) / 2);
48
+
49
+		// Calculate the number of pages either side to show - this is for situations like:
50
+		//  [1]  [2] [[3]] [4]  [5]  [6]  [7]  [8]  [9] - where you can't just use the page margin calculated
51
+		$pageData['lowpage'] = max(1, $page - $pageMargin);
52
+		$pageData['hipage'] = min($pageData['maxpage'], $page + $pageMargin);
53
+		$pageCount = ($pageData['hipage'] - $pageData['lowpage']) + 1;
54
+
55
+		if ($pageCount < $pageLimit) {
56
+			if ($pageData['lowpage'] == 1 && $pageData['hipage'] < $pageData['maxpage']) {
57
+				$pageData['hipage'] = min($pageLimit, $pageData['maxpage']);
58
+			}
59
+			elseif ($pageData['lowpage'] > 1 && $pageData['hipage'] == $pageData['maxpage']) {
60
+				$pageData['lowpage'] = max(1, $pageData['maxpage'] - $pageLimit + 1);
61
+			}
62
+		}
63
+
64
+		// Put the range of pages into the page data
65
+		$pageData['pages'] = range($pageData['lowpage'], $pageData['hipage']);
66
+
67
+		$this->assign("pagedata", $pageData);
68
+
69
+		$this->assign("limit", $limit);
70
+		$this->assign("page", $page);
71
+
72
+		$this->setupFormParameters($formParameters);
73
+	}
74
+
75
+	protected function setSearchHelper(SearchHelperBase $searchHelper)
76
+	{
77
+		$this->searchHelper = $searchHelper;
78
+	}
79
+
80
+	protected function setupLimits()
81
+	{
82
+		$limit = WebRequest::getInt('limit');
83
+		if ($limit === null) {
84
+			$limit = 100;
85
+		}
86
+
87
+		$page = WebRequest::getInt('page');
88
+		if ($page === null) {
89
+			$page = 1;
90
+		}
91
+
92
+		$offset = ($page - 1) * $limit;
93
+
94
+		$this->searchHelper->limit($limit, $offset);
95
+
96
+		$this->page = $page;
97
+		$this->limit = $limit;
98
+	}
99
+
100
+	private function setupFormParameters($formParameters)
101
+	{
102
+		$formParameters['limit'] = $this->limit;
103
+		$this->assign('searchParamsUrl', http_build_query($formParameters, '', '&amp;'));
104
+
105
+		foreach ($formParameters as $key => $value)  {
106
+			$this->assign($key, $value);
107
+		}
108
+	}
109 109
 }
110 110
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@
 block discarded – undo
102 102
         $formParameters['limit'] = $this->limit;
103 103
         $this->assign('searchParamsUrl', http_build_query($formParameters, '', '&amp;'));
104 104
 
105
-        foreach ($formParameters as $key => $value)  {
105
+        foreach ($formParameters as $key => $value) {
106 106
             $this->assign($key, $value);
107 107
         }
108 108
     }
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@
 block discarded – undo
102 102
         $formParameters['limit'] = $this->limit;
103 103
         $this->assign('searchParamsUrl', http_build_query($formParameters, '', '&amp;'));
104 104
 
105
-        foreach ($formParameters as $key => $value)  {
105
+        foreach ($formParameters as $key => $value) {
106 106
             $this->assign($key, $value);
107 107
         }
108 108
     }
Please login to merge, or discard this patch.