Completed
Push — newinternal-releasecandidate ( 45827b...b95206 )
by Simon
08:27
created

PageBase   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 374
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 43
eloc 116
c 5
b 0
f 0
dl 0
loc 374
rs 8.96

19 Methods

Rating   Name   Duplication   Size   Complexity  
A setupPage() 0 11 1
A addCss() 0 7 2
A setTemplate() 0 7 2
A setHtmlTitle() 0 3 1
A setRoute() 0 9 3
A finalisePage() 0 16 2
B runPage() 0 84 7
A setTokenManager() 0 3 1
A setCspManager() 0 3 1
A addJs() 0 7 2
A validateCSRFToken() 0 4 2
A redirectUrl() 0 8 1
A redirect() 0 27 6
A assignCSRFToken() 0 4 1
A sendResponseHeaders() 0 16 5
A getRouteName() 0 3 1
A getTokenManager() 0 3 1
A getCspManager() 0 3 1
A execute() 0 13 3

How to fix   Complexity   

Complex Class

Complex classes like PageBase often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PageBase, and based on these observations, apply Extract Interface, too.

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 SmartyException;
13
use Waca\DataObjects\SiteNotice;
14
use Waca\DataObjects\User;
15
use Waca\ExceptionHandler;
16
use Waca\Exceptions\ApplicationLogicException;
17
use Waca\Exceptions\OptimisticLockFailedException;
18
use Waca\Fragments\TemplateOutput;
19
use Waca\Security\ContentSecurityPolicyManager;
20
use Waca\Security\TokenManager;
21
use Waca\SessionAlert;
22
use Waca\WebRequest;
23
24
abstract class PageBase extends TaskBase implements IRoutedTask
25
{
26
    use TemplateOutput;
27
    /** @var string Smarty template to display */
28
    protected $template = "base.tpl";
29
    /** @var string HTML title. Currently unused. */
30
    protected $htmlTitle;
31
    /** @var bool Determines if the page is a redirect or not */
32
    protected $isRedirecting = false;
33
    /** @var array Queue of headers to be sent on successful completion */
34
    protected $headerQueue = array();
35
    /** @var string The name of the route to use, as determined by the request router. */
36
    private $routeName = null;
37
    /** @var TokenManager */
38
    protected $tokenManager;
39
    /** @var ContentSecurityPolicyManager */
40
    private $cspManager;
41
    /** @var string[] Extra CSS files to include */
42
    private $extraCss = array();
43
    /** @var string[] Extra JS files to include */
44
    private $extraJs = array();
45
46
    /**
47
     * Sets the route the request will take. Only should be called from the request router or barrier test.
48
     *
49
     * @param string $routeName        The name of the route
50
     * @param bool   $skipCallableTest Don't use this unless you know what you're doing, and what the implications are.
51
     *
52
     * @throws Exception
53
     * @category Security-Critical
54
     */
55
    final public function setRoute($routeName, $skipCallableTest = false)
56
    {
57
        // Test the new route is callable before adopting it.
58
        if (!$skipCallableTest && !is_callable(array($this, $routeName))) {
59
            throw new Exception("Proposed route '$routeName' is not callable.");
60
        }
61
62
        // Adopt the new route
63
        $this->routeName = $routeName;
64
    }
65
66
    /**
67
     * Gets the name of the route that has been passed from the request router.
68
     * @return string
69
     */
70
    final public function getRouteName()
71
    {
72
        return $this->routeName;
73
    }
74
75
    /**
76
     * Performs generic page setup actions
77
     */
78
    final protected function setupPage()
79
    {
80
        $this->setUpSmarty();
81
82
        $siteNoticeText = SiteNotice::get($this->getDatabase());
83
84
        $this->assign('siteNoticeText', $siteNoticeText);
85
86
        $currentUser = User::getCurrent($this->getDatabase());
87
        $this->assign('currentUser', $currentUser);
88
        $this->assign('loggedIn', (!$currentUser->isCommunityUser()));
89
    }
90
91
    /**
92
     * Runs the page logic as routed by the RequestRouter
93
     *
94
     * Only should be called after a security barrier! That means only from execute().
95
     */
96
    final protected function runPage()
97
    {
98
        $database = $this->getDatabase();
99
100
        // initialise a database transaction
101
        if (!$database->beginTransaction()) {
102
            throw new Exception('Failed to start transaction on primary database.');
103
        }
104
105
        try {
106
            // run the page code
107
            $this->{$this->getRouteName()}();
108
109
            $database->commit();
110
        }
111
        catch (ApplicationLogicException $ex) {
112
            // it's an application logic exception, so nothing went seriously wrong with the site. We can use the
113
            // standard templating system for this.
114
115
            // Firstly, let's undo anything that happened to the database.
116
            $database->rollBack();
117
118
            // Reset smarty
119
            $this->setUpSmarty();
120
121
            // Set the template
122
            $this->setTemplate('exception/application-logic.tpl');
123
            $this->assign('message', $ex->getMessage());
124
125
            // Force this back to false
126
            $this->isRedirecting = false;
127
            $this->headerQueue = array();
128
        }
129
        catch (OptimisticLockFailedException $ex) {
130
            // it's an optimistic lock failure exception, so nothing went seriously wrong with the site. We can use the
131
            // standard templating system for this.
132
133
            // Firstly, let's undo anything that happened to the database.
134
            $database->rollBack();
135
136
            // Reset smarty
137
            $this->setUpSmarty();
138
139
            // Set the template
140
            $this->setTemplate('exception/optimistic-lock-failure.tpl');
141
            $this->assign('message', $ex->getMessage());
142
143
            $this->assign('debugTrace', false);
144
145
            if ($this->getSiteConfiguration()->getDebuggingTraceEnabled()) {
146
                ob_start();
147
                var_dump(ExceptionHandler::getExceptionData($ex));
1 ignored issue
show
Security Debugging Code introduced by
var_dump(Waca\ExceptionH...:getExceptionData($ex)) looks like debug code. Are you sure you do not want to remove it?
Loading history...
148
                $textErrorData = ob_get_contents();
149
                ob_end_clean();
150
151
                $this->assign('exceptionData', $textErrorData);
152
                $this->assign('debugTrace', true);
153
            }
154
155
            // Force this back to false
156
            $this->isRedirecting = false;
157
            $this->headerQueue = array();
158
        }
159
        finally {
160
            // Catch any hanging on transactions
161
            if ($database->hasActiveTransaction()) {
162
                $database->rollBack();
163
            }
164
        }
165
166
        // run any finalisation code needed before we send the output to the browser.
167
        $this->finalisePage();
168
169
        // Send the headers
170
        $this->sendResponseHeaders();
171
172
        // Check we have a template to use!
173
        if ($this->template !== null) {
174
            $content = $this->fetchTemplate($this->template);
175
            ob_clean();
176
            print($content);
177
            ob_flush();
178
179
            return;
180
        }
181
    }
182
183
    /**
184
     * Performs final tasks needed before rendering the page.
185
     */
186
    protected function finalisePage()
187
    {
188
        if ($this->isRedirecting) {
189
            $this->template = null;
190
191
            return;
192
        }
193
194
        $this->assign('extraCss', $this->extraCss);
195
        $this->assign('extraJs', $this->extraJs);
196
197
        // If we're actually displaying content, we want to add the session alerts here!
198
        $this->assign('alerts', SessionAlert::getAlerts());
199
        SessionAlert::clearAlerts();
200
201
        $this->assign('htmlTitle', $this->htmlTitle);
202
    }
203
204
    /**
205
     * @return TokenManager
206
     */
207
    public function getTokenManager()
208
    {
209
        return $this->tokenManager;
210
    }
211
212
    /**
213
     * @param TokenManager $tokenManager
214
     */
215
    public function setTokenManager($tokenManager)
216
    {
217
        $this->tokenManager = $tokenManager;
218
    }
219
220
    /**
221
     * @return ContentSecurityPolicyManager
222
     */
223
    public function getCspManager(): ContentSecurityPolicyManager
224
    {
225
        return $this->cspManager;
226
    }
227
228
    /**
229
     * @param ContentSecurityPolicyManager $cspManager
230
     */
231
    public function setCspManager(ContentSecurityPolicyManager $cspManager): void
232
    {
233
        $this->cspManager = $cspManager;
234
    }
235
236
    /**
237
     * Sends the redirect headers to perform a GET at the destination page.
238
     *
239
     * Also nullifies the set template so Smarty does not render it.
240
     *
241
     * @param string      $page   The page to redirect requests to (as used in the UR)
242
     * @param null|string $action The action to use on the page.
243
     * @param null|array  $parameters
244
     * @param null|string $script The script (relative to index.php) to redirect to
245
     */
246
    final protected function redirect($page = '', $action = null, $parameters = null, $script = null)
247
    {
248
        $currentScriptName = WebRequest::scriptName();
249
250
        // Are we changing script?
251
        if ($script === null || substr($currentScriptName, -1 * count($script)) === $script) {
0 ignored issues
show
Bug introduced by
$script of type string is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

251
        if ($script === null || substr($currentScriptName, -1 * count(/** @scrutinizer ignore-type */ $script)) === $script) {
Loading history...
252
            $targetScriptName = $currentScriptName;
253
        }
254
        else {
255
            $targetScriptName = $this->getSiteConfiguration()->getBaseUrl() . '/' . $script;
256
        }
257
258
        $pathInfo = array($targetScriptName);
259
260
        $pathInfo[1] = $page;
261
262
        if ($action !== null) {
263
            $pathInfo[2] = $action;
264
        }
265
266
        $url = implode('/', $pathInfo);
267
268
        if (is_array($parameters) && count($parameters) > 0) {
269
            $url .= '?' . http_build_query($parameters);
270
        }
271
272
        $this->redirectUrl($url);
273
    }
274
275
    /**
276
     * Sends the redirect headers to perform a GET at the new address.
277
     *
278
     * Also nullifies the set template so Smarty does not render it.
279
     *
280
     * @param string $path URL to redirect to
281
     */
282
    final protected function redirectUrl($path)
283
    {
284
        // 303 See Other = re-request at new address with a GET.
285
        $this->headerQueue[] = 'HTTP/1.1 303 See Other';
286
        $this->headerQueue[] = "Location: $path";
287
288
        $this->setTemplate(null);
289
        $this->isRedirecting = true;
290
    }
291
292
    /**
293
     * Sets the name of the template this page should display.
294
     *
295
     * @param string $name
296
     *
297
     * @throws Exception
298
     */
299
    final protected function setTemplate($name)
300
    {
301
        if ($this->isRedirecting) {
302
            throw new Exception('This page has been set as a redirect, no template can be displayed!');
303
        }
304
305
        $this->template = $name;
306
    }
307
308
    /**
309
     * Adds an extra CSS file to to the page
310
     *
311
     * @param string $path The path (relative to the application root) of the file
312
     */
313
    final protected function addCss($path) {
314
        if(in_array($path, $this->extraCss)){
315
            // nothing to do
316
            return;
317
        }
318
319
        $this->extraCss[] = $path;
320
    }
321
322
    /**
323
     * Adds an extra JS file to to the page
324
     *
325
     * @param string $path The path (relative to the application root) of the file
326
     */
327
    final protected function addJs($path){
328
        if(in_array($path, $this->extraJs)){
329
            // nothing to do
330
            return;
331
        }
332
333
        $this->extraJs[] = $path;
334
    }
335
336
    /**
337
     * Main function for this page, when no specific actions are called.
338
     * @return void
339
     */
340
    abstract protected function main();
341
342
    /**
343
     * Takes a smarty template string and sets the HTML title to that value
344
     *
345
     * @param string $title
346
     *
347
     * @throws SmartyException
348
     */
349
    final protected function setHtmlTitle($title)
350
    {
351
        $this->htmlTitle = $this->smarty->fetch('string:' . $title);
352
    }
353
354
    public function execute()
355
    {
356
        if ($this->getRouteName() === null) {
0 ignored issues
show
introduced by
The condition $this->getRouteName() === null is always false.
Loading history...
357
            throw new Exception('Request is unrouted.');
358
        }
359
360
        if ($this->getSiteConfiguration() === null) {
361
            throw new Exception('Page has no configuration!');
362
        }
363
364
        $this->setupPage();
365
366
        $this->runPage();
367
    }
368
369
    public function assignCSRFToken()
370
    {
371
        $token = $this->tokenManager->getNewToken();
372
        $this->assign('csrfTokenData', $token->getTokenData());
373
    }
374
375
    public function validateCSRFToken()
376
    {
377
        if (!$this->tokenManager->validateToken(WebRequest::postString('csrfTokenData'))) {
378
            throw new ApplicationLogicException('Form token is not valid, please reload and try again');
379
        }
380
    }
381
382
    protected function sendResponseHeaders()
383
    {
384
        if (headers_sent()) {
385
            throw new ApplicationLogicException('Headers have already been sent! This is likely a bug in the application.');
386
        }
387
388
        // send the CSP headers now
389
        header($this->getCspManager()->getHeader());
390
391
        foreach ($this->headerQueue as $item) {
392
            if (mb_strpos($item, "\r") !== false || mb_strpos($item, "\n") !== false) {
393
                // Oops. We're not allowed to do this.
394
                throw new Exception('Unable to split header');
395
            }
396
397
            header($item);
398
        }
399
    }
400
}
401