Completed
Branch newinternal (cdd491)
by Simon
04:39
created

PageBase   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 290
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 5.56%

Importance

Changes 13
Bugs 1 Features 1
Metric Value
c 13
b 1
f 1
dl 0
loc 290
rs 9.3999
ccs 6
cts 108
cp 0.0556
wmc 33
lcom 1
cbo 11

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setRoute() 0 10 3
A getRouteName() 0 4 1
A setupPage() 0 12 1
B runPage() 0 74 6
A finalisePage() 0 14 2
A getTokenManager() 0 4 1
A setTokenManager() 0 4 1
A redirect() 0 18 4
A redirectUrl() 0 9 1
A setTemplate() 0 8 2
main() 0 1 ?
A setHtmlTitle() 0 4 1
A execute() 0 14 3
A assignCSRFToken() 0 5 1
A validateCSRFToken() 0 6 2
A sendResponseHeaders() 0 11 4
1
<?php
2
/******************************************************************************
3
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Tasks;
10
11
use Exception;
12
use Waca\DataObjects\SiteNotice;
13
use Waca\DataObjects\User;
14
use Waca\Exceptions\ApplicationLogicException;
15
use Waca\Exceptions\OptimisticLockFailedException;
16
use Waca\Fragments\TemplateOutput;
17
use Waca\Security\TokenManager;
18
use Waca\SessionAlert;
19
use Waca\WebRequest;
20
21
abstract class PageBase extends TaskBase implements IRoutedTask
22
{
23
	use TemplateOutput;
24
	/** @var string Smarty template to display */
25
	protected $template = "base.tpl";
26
	/** @var string HTML title. Currently unused. */
27
	protected $htmlTitle;
28
	/** @var bool Determines if the page is a redirect or not */
29
	protected $isRedirecting = false;
30
	/** @var array Queue of headers to be sent on successful completion */
31
	protected $headerQueue = array();
32
	/** @var string The name of the route to use, as determined by the request router. */
33
	private $routeName = null;
34
	/** @var TokenManager */
35
	protected $tokenManager;
36
37
	/**
38
	 * Sets the route the request will take. Only should be called from the request router or barrier test.
39
	 *
40
	 * @param string $routeName        The name of the route
41
	 * @param bool   $skipCallableTest Don't use this unless you know what you're doing, and what the implications are.
42
	 *
43
	 * @throws Exception
44
	 * @category Security-Critical
45
	 */
46 5
	final public function setRoute($routeName, $skipCallableTest = false)
47
	{
48
		// Test the new route is callable before adopting it.
49 5
		if (!$skipCallableTest && !is_callable(array($this, $routeName))) {
50
			throw new Exception("Proposed route '$routeName' is not callable.");
51
		}
52
53
		// Adopt the new route
54 5
		$this->routeName = $routeName;
55 5
	}
56
57
	/**
58
	 * Gets the name of the route that has been passed from the request router.
59
	 * @return string
60
	 */
61 5
	final public function getRouteName()
62
	{
63 5
		return $this->routeName;
64
	}
65
66
	/**
67
	 * Performs generic page setup actions
68
	 */
69
	final protected function setupPage()
70
	{
71
		$this->setUpSmarty();
72
73
		$siteNoticeText = SiteNotice::get($this->getDatabase());
74
75
		$this->assign('siteNoticeText', $siteNoticeText);
76
77
		$currentUser = User::getCurrent($this->getDatabase());
78
		$this->assign('currentUser', $currentUser);
79
		$this->assign('loggedIn', (!$currentUser->isCommunityUser()));
80
	}
81
82
	/**
83
	 * Runs the page logic as routed by the RequestRouter
84
	 *
85
	 * Only should be called after a security barrier! That means only from execute().
86
	 */
87
	final protected function runPage()
88
	{
89
		$database = $this->getDatabase();
90
91
		// initialise a database transaction
92
		if (!$database->beginTransaction()) {
93
			throw new Exception('Failed to start transaction on primary database.');
94
		}
95
96
		try {
97
			// run the page code
98
			$this->{$this->getRouteName()}();
99
100
			$database->commit();
101
		}
102
		catch (ApplicationLogicException $ex) {
103
			// it's an application logic exception, so nothing went seriously wrong with the site. We can use the
104
			// standard templating system for this.
105
106
			// Firstly, let's undo anything that happened to the database.
107
			$database->rollBack();
108
109
			// Reset smarty
110
			$this->setUpSmarty();
111
112
			// Set the template
113
			$this->setTemplate('exception/application-logic.tpl');
114
			$this->assign('message', $ex->getMessage());
115
116
			// Force this back to false
117
			$this->isRedirecting = false;
118
			$this->headerQueue = array();
119
		}
120
		catch (OptimisticLockFailedException $ex) {
121
			// it's an optimistic lock failure exception, so nothing went seriously wrong with the site. We can use the
122
			// standard templating system for this.
123
124
			// Firstly, let's undo anything that happened to the database.
125
			$database->rollBack();
126
127
			// Reset smarty
128
			$this->setUpSmarty();
129
130
			// Set the template
131
			$this->setTemplate('exception/optimistic-lock-failure.tpl');
132
			$this->assign('message', $ex->getMessage());
133
134
			// Force this back to false
135
			$this->isRedirecting = false;
136
			$this->headerQueue = array();
137
		}
138
		finally {
139
			// Catch any hanging on transactions
140
			if ($database->hasActiveTransaction()) {
141
				$database->rollBack();
142
			}
143
		}
144
145
		// run any finalisation code needed before we send the output to the browser.
146
		$this->finalisePage();
147
148
		// Send the headers
149
		$this->sendResponseHeaders();
150
151
		// Check we have a template to use!
152
		if ($this->template !== null) {
153
			$content = $this->fetchTemplate($this->template);
154
			ob_clean();
155
			print($content);
156
			ob_flush();
157
158
			return;
159
		}
160
	}
161
162
	/**
163
	 * Performs final tasks needed before rendering the page.
164
	 */
165
	protected function finalisePage()
166
	{
167
		if ($this->isRedirecting) {
168
			$this->template = null;
169
170
			return;
171
		}
172
173
		// If we're actually displaying content, we want to add the session alerts here!
174
		$this->assign('alerts', SessionAlert::getAlerts());
175
		SessionAlert::clearAlerts();
176
177
		$this->assign('htmlTitle', $this->htmlTitle);
178
	}
179
180
	/**
181
	 * @return TokenManager
182
	 */
183
	public function getTokenManager()
184
	{
185
		return $this->tokenManager;
186
	}
187
188
	/**
189
	 * @param TokenManager $tokenManager
190
	 */
191
	public function setTokenManager($tokenManager)
192
	{
193
		$this->tokenManager = $tokenManager;
194
	}
195
196
	/**
197
	 * Sends the redirect headers to perform a GET at the destination page.
198
	 *
199
	 * Also nullifies the set template so Smarty does not render it.
200
	 *
201
	 * @param string      $page   The page to redirect requests to (as used in the UR)
202
	 * @param null|string $action The action to use on the page.
203
	 * @param null|array  $parameters
204
	 */
205
	final protected function redirect($page = '', $action = null, $parameters = null)
206
	{
207
		$pathInfo = array(WebRequest::scriptName());
208
209
		$pathInfo[1] = $page;
210
211
		if ($action !== null) {
212
			$pathInfo[2] = $action;
213
		}
214
215
		$url = implode('/', $pathInfo);
216
217
		if (is_array($parameters) && count($parameters) > 0) {
218
			$url .= '?' . http_build_query($parameters);
219
		}
220
221
		$this->redirectUrl($url);
222
	}
223
224
	/**
225
	 * Sends the redirect headers to perform a GET at the new address.
226
	 *
227
	 * Also nullifies the set template so Smarty does not render it.
228
	 *
229
	 * @param string $path URL to redirect to
230
	 */
231
	final protected function redirectUrl($path)
232
	{
233
		// 303 See Other = re-request at new address with a GET.
234
		$this->headerQueue[] = 'HTTP/1.1 303 See Other';
235
		$this->headerQueue[] = "Location: $path";
236
237
		$this->setTemplate(null);
238
		$this->isRedirecting = true;
239
	}
240
241
	/**
242
	 * Sets the name of the template this page should display.
243
	 *
244
	 * @param string $name
245
	 *
246
	 * @throws Exception
247
	 */
248
	final protected function setTemplate($name)
249
	{
250
		if ($this->isRedirecting) {
251
			throw new Exception('This page has been set as a redirect, no template can be displayed!');
252
		}
253
254
		$this->template = $name;
255
	}
256
257
	/**
258
	 * Main function for this page, when no specific actions are called.
259
	 * @return void
260
	 */
261
	abstract protected function main();
262
263
	/**
264
	 * @param string $title
265
	 */
266
	final protected function setHtmlTitle($title)
267
	{
268
		$this->htmlTitle = $title;
269
	}
270
271
	public function execute()
272
	{
273
		if ($this->getRouteName() === null) {
274
			throw new Exception('Request is unrouted.');
275
		}
276
277
		if ($this->getSiteConfiguration() === null) {
278
			throw new Exception('Page has no configuration!');
279
		}
280
281
		$this->setupPage();
282
283
		$this->runPage();
284
	}
285
286
	public function assignCSRFToken()
287
	{
288
		$token = $this->tokenManager->getNewToken();
289
		$this->assign('csrfTokenData', $token->getTokenData());
290
	}
291
292
	public function validateCSRFToken()
293
	{
294
		if (!$this->tokenManager->validateToken(WebRequest::postString('csrfTokenData'))) {
295
			throw new ApplicationLogicException('Form token is not valid, please reload and try again');
296
		}
297
	}
298
299
	protected function sendResponseHeaders()
300
	{
301
		foreach ($this->headerQueue as $item) {
302
			if (mb_strpos($item, "\r") !== false || mb_strpos($item, "\n") !== false) {
303
				// Oops. We're not allowed to do this.
304
				throw new Exception('Unable to split header');
305
			}
306
307
			header($item);
308
		}
309
	}
310
}