Passed
Push — master ( f5769e...cca843 )
by MusikAnimal
10:28
created

XtoolsController   F

Complexity

Total Complexity 101

Size/Duplication

Total Lines 879
Duplicated Lines 0 %

Test Coverage

Coverage 50.19%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 326
c 1
b 0
f 0
dl 0
loc 879
rs 2
ccs 129
cts 257
cp 0.5019
wmc 101

25 Methods

Rating   Name   Duplication   Size   Complexity  
A checkIfAjax() 0 6 4
A __construct() 0 37 4
B convertLegacyParams() 0 40 7
A checkRestrictedApiEndpoint() 0 15 4
A setCookies() 0 10 3
A loadCookies() 0 9 3
A getOptedInPage() 0 5 1
A setProject() 0 9 2
A validateProject() 0 25 4
A getProjectFromQuery() 0 23 4
B validateUser() 0 59 9
A recordApiUsage() 0 23 2
A validatePage() 0 17 2
A getFormattedApiResponse() 0 33 4
A parseQueryParams() 0 12 2
A addFlashMessage() 0 5 2
A getParams() 0 45 5
A getFormattedResponse() 0 49 4
A setDates() 0 10 6
C getUnixFromDateParams() 0 48 13
A getPageFromNsAndTitle() 0 10 4
B setProperties() 0 33 7
A getFilenameForRequest() 0 4 1
A getFlashMessage() 0 13 2
A throwXtoolsException() 0 28 2

How to fix   Complexity   

Complex Class

Complex classes like XtoolsController 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 XtoolsController, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * This file contains the abstract XtoolsController, which all other controllers will extend.
4
 */
5
6
declare(strict_types=1);
7
8
namespace AppBundle\Controller;
9
10
use AppBundle\Exception\XtoolsHttpException;
11
use AppBundle\Helper\I18nHelper;
12
use AppBundle\Model\Page;
13
use AppBundle\Model\Project;
14
use AppBundle\Model\User;
15
use AppBundle\Repository\PageRepository;
16
use AppBundle\Repository\ProjectRepository;
17
use AppBundle\Repository\UserRepository;
18
use DateTime;
19
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21
use Symfony\Component\HttpFoundation\Cookie;
22
use Symfony\Component\HttpFoundation\JsonResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\RequestStack;
25
use Symfony\Component\HttpFoundation\Response;
26
use Symfony\Component\HttpKernel\Exception\HttpException;
27
28
/**
29
 * XtoolsController supplies a variety of methods around parsing and validating parameters, and initializing
30
 * Project/User instances. These are used in other controllers in the AppBundle\Controller namespace.
31
 * @abstract
32
 */
33
abstract class XtoolsController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated: since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead. ( Ignorable by Annotation )

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

33
abstract class XtoolsController extends /** @scrutinizer ignore-deprecated */ Controller
Loading history...
34
{
35
    /** @var I18nHelper i18n helper. */
36
    protected $i18n;
37
38
    /** @var Request The request object. */
39
    protected $request;
40
41
    /** @var string Name of the action within the child controller that is being executed. */
42
    protected $controllerAction;
43
44
    /** @var array Hash of params parsed from the Request. */
45
    protected $params;
46
47
    /** @var bool Whether this is a request to an API action. */
48
    protected $isApi;
49
50
    /** @var Project Relevant Project parsed from the Request. */
51
    protected $project;
52
53
    /** @var User Relevant User parsed from the Request. */
54
    protected $user;
55
56
    /** @var Page Relevant Page parsed from the Request. */
57
    protected $page;
58
59
    /** @var int|false Start date parsed from the Request. */
60
    protected $start = false;
61
62
    /** @var int|false End date parsed from the Request. */
63
    protected $end = false;
64
65
    /**
66
     * Default days from current day, to use as the start date if none was provided.
67
     * If this is null and $maxDays is non-null, the latter will be used as the default.
68
     * Is public visibility evil here? I don't think so.
69
     * @var int|null
70
     */
71
    public $defaultDays = null;
72
73
    /**
74
     * Maximum number of days allowed for the given date range.
75
     * Set this in the controller's constructor to enforce the given date range to be within this range.
76
     * This will be used as the default date span unless $defaultDays is defined.
77
     * @see XtoolsController::getUnixFromDateParams()
78
     * @var int|null
79
     */
80
    public $maxDays = null;
81
82
    /** @var int|string|null Namespace parsed from the Request, ID as int or 'all' for all namespaces. */
83
    protected $namespace;
84
85
    /** @var int|false Unix timestamp. Pagination offset that substitutes for $end. */
86
    protected $offset = false;
87
88
    /** @var int Number of results to return. */
89
    protected $limit;
90
91
    /** @var bool Is the current request a subrequest? */
92
    protected $isSubRequest;
93
94
    /**
95
     * Stores user preferences such default project.
96
     * This may get altered from the Request and updated in the Response.
97
     * @var array
98
     */
99
    protected $cookies = [
100
        'XtoolsProject' => null,
101
    ];
102
103
    /**
104
     * This activates the 'too high edit count' functionality. This property represents the
105
     * action that should be redirected to if the user has too high of an edit count.
106
     * @var string
107
     */
108
    protected $tooHighEditCountAction;
109
110
    /** @var array Actions that are exempt from edit count limitations. */
111
    protected $tooHighEditCountActionBlacklist = [];
112
113
    /**
114
     * Actions that require the target user to opt in to the restricted statistics.
115
     * @see https://xtools.readthedocs.io/en/stable/opt-in.html
116
     * @var string[]
117
     */
118
    protected $restrictedActions = [];
119
120
    /**
121
     * XtoolsController::validateProject() will ensure the given project matches one of these domains,
122
     * instead of any valid project.
123
     * @var string[]
124
     */
125
    protected $supportedProjects;
126
127
    /**
128
     * Require the tool's index route (initial form) be defined here. This should also
129
     * be the name of the associated model, if present.
130
     * @return string
131
     */
132
    abstract protected function getIndexRoute(): string;
133
134
    /**
135
     * XtoolsController constructor.
136
     * @param RequestStack $requestStack
137
     * @param ContainerInterface $container
138
     * @param I18nHelper $i18n
139
     */
140 16
    public function __construct(RequestStack $requestStack, ContainerInterface $container, I18nHelper $i18n)
141
    {
142 16
        $this->request = $requestStack->getCurrentRequest();
143 16
        $this->container = $container;
144 16
        $this->i18n = $i18n;
145 16
        $this->params = $this->parseQueryParams();
146
147
        // Parse out the name of the controller and action.
148 16
        $pattern = "#::([a-zA-Z]*)Action#";
149 16
        $matches = [];
150
        // The blank string here only happens in the unit tests, where the request may not be made to an action.
151 16
        preg_match($pattern, $this->request->get('_controller') ?? '', $matches);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

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

151
        preg_match($pattern, $this->request->/** @scrutinizer ignore-call */ get('_controller') ?? '', $matches);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
152 16
        $this->controllerAction = $matches[1] ?? '';
153
154
        // Whether the action is an API action.
155 16
        $this->isApi = 'Api' === substr($this->controllerAction, -3) || 'recordUsage' === $this->controllerAction;
156
157
        // Whether we're making a subrequest (the view makes a request to another action).
158 16
        $this->isSubRequest = $this->request->get('htmlonly')
159 16
            || null !== $this->get('request_stack')->getParentRequest();
160
161
        // Disallow AJAX (unless it's an API or subrequest).
162 16
        $this->checkIfAjax();
163
164
        // Load user options from cookies.
165 16
        $this->loadCookies();
166
167
        // Set the class-level properties based on params.
168 16
        if (false !== strpos(strtolower($this->controllerAction), 'index')) {
169
            // Index pages should only set the project, and no other class properties.
170 10
            $this->setProject($this->getProjectFromQuery());
171
        } else {
172 6
            $this->setProperties(); // Includes the project.
173
        }
174
175
        // Check if the request is to a restricted API endpoint, where the target user has to opt-in to statistics.
176 16
        $this->checkRestrictedApiEndpoint();
177 16
    }
178
179
    /**
180
     * Check if the request is AJAX, and disallow it unless they're using the API or if it's a subrequest.
181
     */
182 16
    private function checkIfAjax(): void
183
    {
184 16
        if ($this->request->isXmlHttpRequest() && !$this->isApi && !$this->isSubRequest) {
185
            throw new HttpException(
186
                403,
187
                $this->i18n->msg('error-automation', ['https://xtools.readthedocs.io/en/stable/api/'])
188
            );
189
        }
190 16
    }
191
192
    /**
193
     * Check if the request is to a restricted API endpoint, and throw an exception if the target user hasn't opted-in.
194
     * @throws XtoolsHttpException
195
     */
196 16
    private function checkRestrictedApiEndpoint(): void
197
    {
198 16
        $restrictedAction = in_array($this->controllerAction, $this->restrictedActions);
199
200 16
        if ($this->isApi && $restrictedAction && !$this->project->userHasOptedIn($this->user)) {
201
            throw new XtoolsHttpException(
202
                $this->i18n->msg('not-opted-in', [
0 ignored issues
show
Bug introduced by
It seems like $this->i18n->msg('not-op...'not-opted-in-login'))) can also be of type null; however, parameter $message of AppBundle\Exception\Xtoo...xception::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

202
                /** @scrutinizer ignore-type */ $this->i18n->msg('not-opted-in', [
Loading history...
203
                    $this->getOptedInPage()->getTitle(),
204
                    $this->i18n->msg('not-opted-in-link').' <https://xtools.readthedocs.io/en/stable/opt-in.html>',
205
                    $this->i18n->msg('not-opted-in-login'),
206
                ]),
207
                '',
208
                $this->params,
209
                true,
210
                Response::HTTP_UNAUTHORIZED
211
            );
212
        }
213 16
    }
214
215
    /**
216
     * Get the path to the opt-in page for restricted statistics.
217
     * @return Page
218
     */
219
    protected function getOptedInPage(): Page
220
    {
221
        return $this->project
222
            ->getRepository()
223
            ->getPage($this->project, $this->project->userOptInPage($this->user));
0 ignored issues
show
Bug introduced by
The method getPage() does not exist on AppBundle\Repository\Repository. It seems like you code against a sub-type of AppBundle\Repository\Repository such as AppBundle\Repository\ProjectRepository. ( Ignorable by Annotation )

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

223
            ->/** @scrutinizer ignore-call */ getPage($this->project, $this->project->userOptInPage($this->user));
Loading history...
224
    }
225
226
    /***********
227
     * COOKIES *
228
     ***********/
229
230
    /**
231
     * Load user preferences from the associated cookies.
232
     */
233 16
    private function loadCookies(): void
234
    {
235
        // Not done for subrequests.
236 16
        if ($this->isSubRequest) {
237
            return;
238
        }
239
240 16
        foreach (array_keys($this->cookies) as $name) {
241 16
            $this->cookies[$name] = $this->request->cookies->get($name);
242
        }
243 16
    }
244
245
    /**
246
     * Set cookies on the given Response.
247
     * @param Response $response
248
     */
249
    private function setCookies(Response &$response): void
250
    {
251
        // Not done for subrequests.
252
        if ($this->isSubRequest) {
253
            return;
254
        }
255
256
        foreach ($this->cookies as $name => $value) {
257
            $response->headers->setCookie(
258
                Cookie::create($name, $value)
259
            );
260
        }
261
    }
262
263
    /**
264
     * Sets the project, with the domain in $this->cookies['XtoolsProject'] that will
265
     * later get set on the Response headers in self::getFormattedResponse().
266
     * @param Project $project
267
     */
268 12
    private function setProject(Project $project): void
269
    {
270
        // TODO: Remove after deprecated routes are retired.
271 12
        if (false !== strpos((string)$this->request->get('_controller'), 'GlobalContribs')) {
272
            return;
273
        }
274
275 12
        $this->project = $project;
276 12
        $this->cookies['XtoolsProject'] = $project->getDomain();
277 12
    }
278
279
    /****************************
280
     * SETTING CLASS PROPERTIES *
281
     ****************************/
282
283
    /**
284
     * Normalize all common parameters used by the controllers and set class properties.
285
     */
286 6
    private function setProperties(): void
287
    {
288 6
        $this->namespace = $this->params['namespace'] ?? null;
289
290
        // Offset is given as ISO timestamp and is stored as a UNIX timestamp (or false).
291 6
        if (isset($this->params['offset'])) {
292
            $this->offset = strtotime($this->params['offset']);
293
        }
294
295
        // Limit need to be an int.
296 6
        if (isset($this->params['limit'])) {
297
            // Normalize.
298
            $this->params['limit'] = max(0, (int)$this->params['limit']);
299
            $this->limit = $this->params['limit'];
300
        }
301
302 6
        if (isset($this->params['project'])) {
303 2
            $this->setProject($this->validateProject($this->params['project']));
304 4
        } elseif (null !== $this->cookies['XtoolsProject']) {
305
            // Set from cookie.
306
            $this->setProject(
307
                $this->validateProject($this->cookies['XtoolsProject'])
308
            );
309
        }
310
311 6
        if (isset($this->params['username'])) {
312
            $this->user = $this->validateUser($this->params['username']);
313
        }
314 6
        if (isset($this->params['page'])) {
315
            $this->page = $this->getPageFromNsAndTitle($this->namespace, $this->params['page']);
316
        }
317
318 6
        $this->setDates();
319 6
    }
320
321
    /**
322
     * Set class properties for dates, if such params were passed in.
323
     */
324 6
    private function setDates(): void
325
    {
326 6
        $start = $this->params['start'] ?? false;
327 6
        $end = $this->params['end'] ?? false;
328 6
        if ($start || $end || null !== $this->maxDays) {
329
            [$this->start, $this->end] = $this->getUnixFromDateParams($start, $end);
330
331
            // Set $this->params accordingly too, so that for instance API responses will include it.
332
            $this->params['start'] = is_int($this->start) ? date('Y-m-d', $this->start) : false;
333
            $this->params['end'] = is_int($this->end) ? date('Y-m-d', $this->end) : false;
334
        }
335 6
    }
336
337
    /**
338
     * Construct a fully qualified page title given the namespace and title.
339
     * @param int|string $ns Namespace ID.
340
     * @param string $title Page title.
341
     * @param bool $rawTitle Return only the title (and not a Page).
342
     * @return Page|string
343
     */
344
    protected function getPageFromNsAndTitle($ns, string $title, bool $rawTitle = false)
345
    {
346
        if (0 === (int)$ns) {
347
            return $rawTitle ? $title : $this->validatePage($title);
348
        }
349
350
        // Prepend namespace and strip out duplicates.
351
        $nsName = $this->project->getNamespaces()[$ns] ?? $this->i18n->msg('unknown');
352
        $title = $nsName.':'.preg_replace('/^'.$nsName.':/', '', $title);
353
        return $rawTitle ? $title : $this->validatePage($title);
354
    }
355
356
    /**
357
     * Get a Project instance from the project string, using defaults if the given project string is invalid.
358
     * @return Project
359
     */
360 10
    public function getProjectFromQuery(): Project
361
    {
362
        // Set default project so we can populate the namespace selector on index pages.
363
        // Defaults to project stored in cookie, otherwise project specified in parameters.yml.
364 10
        if (isset($this->params['project'])) {
365 2
            $project = $this->params['project'];
366 8
        } elseif (null !== $this->cookies['XtoolsProject']) {
367
            $project = $this->cookies['XtoolsProject'];
368
        } else {
369 8
            $project = $this->container->getParameter('default_project');
370
        }
371
372 10
        $projectData = ProjectRepository::getProject($project, $this->container);
373
374
        // Revert back to defaults if we've established the given project was invalid.
375 10
        if (!$projectData->exists()) {
376
            $projectData = ProjectRepository::getProject(
377
                $this->container->getParameter('default_project'),
378
                $this->container
379
            );
380
        }
381
382 10
        return $projectData;
383
    }
384
385
    /*************************
386
     * GETTERS / VALIDATIONS *
387
     *************************/
388
389
    /**
390
     * Validate the given project, returning a Project if it is valid or false otherwise.
391
     * @param string $projectQuery Project domain or database name.
392
     * @return Project
393
     * @throws XtoolsHttpException
394
     */
395 2
    public function validateProject(string $projectQuery): Project
396
    {
397
        /** @var Project $project */
398 2
        $project = ProjectRepository::getProject($projectQuery, $this->container);
399
400
        // Check if it is an explicitly allowed project for the current tool.
401 2
        if (isset($this->supportedProjects) && !in_array($project->getDomain(), $this->supportedProjects)) {
402
            $this->throwXtoolsException(
403
                $this->getIndexRoute(),
404
                'error-authorship-unsupported-project',
405
                [$this->params['project']],
406
                'project'
407
            );
408
        }
409
410 2
        if (!$project->exists()) {
411
            $this->throwXtoolsException(
412
                $this->getIndexRoute(),
413
                'invalid-project',
414
                [$this->params['project']],
415
                'project'
416
            );
417
        }
418
419 2
        return $project;
420
    }
421
422
    /**
423
     * Validate the given user, returning a User or Redirect if they don't exist.
424
     * @param string $username
425
     * @return User
426
     * @throws XtoolsHttpException
427
     */
428
    public function validateUser(string $username): User
429
    {
430
        $user = UserRepository::getUser($username, $this->container);
431
432
        // Allow querying for any IP, currently with no edit count limitation...
433
        // Once T188677 is resolved IPs will be affected by the EXPLAIN results.
434
        if ($user->isAnon()) {
435
            return $user;
436
        }
437
438
        $originalParams = $this->params;
439
440
        // Don't continue if the user doesn't exist.
441
        if ($this->project && !$user->existsOnProject($this->project)) {
442
            $this->throwXtoolsException($this->getIndexRoute(), 'user-not-found', [], 'username');
443
        }
444
445
        // Reject users with a crazy high edit count.
446
        if (isset($this->tooHighEditCountAction) &&
447
            !in_array($this->controllerAction, $this->tooHighEditCountActionBlacklist) &&
448
            $user->hasTooManyEdits($this->project)
449
        ) {
450
            /** TODO: Somehow get this to use self::throwXtoolsException */
451
452
            // If redirecting to a different controller, show an informative message accordingly.
453
            if ($this->tooHighEditCountAction !== $this->getIndexRoute()) {
454
                // FIXME: This is currently only done for Edit Counter, redirecting to Simple Edit Counter,
455
                //   so this bit is hardcoded. We need to instead give the i18n key of the route.
456
                $redirMsg = $this->i18n->msg('too-many-edits-redir', [
457
                    $this->i18n->msg('tool-simpleeditcounter'),
458
                ]);
459
                $msg = $this->i18n->msg('too-many-edits', [
460
                    $this->i18n->numberFormat($user->maxEdits()),
461
                ]).'. '.$redirMsg;
462
                $this->addFlashMessage('danger', $msg);
463
            } else {
464
                $this->addFlashMessage('danger', 'too-many-edits', [
465
                    $this->i18n->numberFormat($user->maxEdits()),
466
                ]);
467
468
                // Redirecting back to index, so remove username (otherwise we'd get a redirect loop).
469
                unset($this->params['username']);
470
            }
471
472
            // Clear flash bag for API responses, since they get intercepted in ExceptionListener
473
            // and would otherwise be shown in subsequent requests.
474
            if ($this->isApi) {
475
                $this->get('session')->getFlashBag()->clear();
476
            }
477
478
            throw new XtoolsHttpException(
479
                'User has made too many edits! Maximum '.$user->maxEdits(),
480
                $this->generateUrl($this->tooHighEditCountAction, $this->params),
481
                $originalParams,
482
                $this->isApi
483
            );
484
        }
485
486
        return $user;
487
    }
488
489
    /**
490
     * Get a Page instance from the given page title, and validate that it exists.
491
     * @param string $pageTitle
492
     * @return Page
493
     * @throws XtoolsHttpException
494
     */
495
    public function validatePage(string $pageTitle): Page
496
    {
497
        $page = new Page($this->project, $pageTitle);
498
        $pageRepo = new PageRepository();
499
        $pageRepo->setContainer($this->container);
500
        $page->setRepository($pageRepo);
501
502
        if (!$page->exists()) {
503
            $this->throwXtoolsException(
504
                $this->getIndexRoute(),
505
                'no-result',
506
                [$this->params['page'] ?? null],
507
                'page'
508
            );
509
        }
510
511
        return $page;
512
    }
513
514
    /**
515
     * Throw an XtoolsHttpException, which the given error message and redirects to specified action.
516
     * @param string $redirectAction Name of action to redirect to.
517
     * @param string $message i18n key of error message. Shown in API responses.
518
     *   If no message with this key exists, $message is shown as-is.
519
     * @param array $messageParams
520
     * @param string $invalidParam This will be removed from $this->params. Omit if you don't want this to happen.
521
     * @throws XtoolsHttpException
522
     */
523
    public function throwXtoolsException(
524
        string $redirectAction,
525
        string $message,
526
        array $messageParams = [],
527
        ?string $invalidParam = null
528
    ): void {
529
        $this->addFlashMessage('danger', $message, $messageParams);
530
        $originalParams = $this->params;
531
532
        // Remove invalid parameter if it was given.
533
        if (is_string($invalidParam)) {
534
            unset($this->params[$invalidParam]);
535
        }
536
537
        // We sometimes are redirecting to the index page, so also remove project (otherwise we'd get a redirect loop).
538
        /**
539
         * FIXME: Index pages should have a 'nosubmit' parameter to prevent submission.
540
         * Then we don't even need to remove $invalidParam.
541
         * Better, we should show the error on the results page, with no results.
542
         */
543
        unset($this->params['project']);
544
545
        // Throw exception which will redirect to $redirectAction.
546
        throw new XtoolsHttpException(
547
            $this->i18n->msgIfExists($message, $messageParams),
548
            $this->generateUrl($redirectAction, $this->params),
549
            $originalParams,
550
            $this->isApi
551
        );
552
    }
553
554
    /**
555
     * Get the first error message stored in the session's FlashBag.
556
     * @return string
557
     */
558
    public function getFlashMessage(): string
559
    {
560
        $key = $this->get('session')->getFlashBag()->get('danger')[0];
561
        $param = null;
562
563
        if (is_array($key)) {
564
            [$key, $param] = $key;
565
        }
566
567
        return $this->render('message.twig', [
568
            'key' => $key,
569
            'params' => [$param],
570
        ])->getContent();
571
    }
572
573
    /******************
574
     * PARSING PARAMS *
575
     ******************/
576
577
    /**
578
     * Get all standardized parameters from the Request, either via URL query string or routing.
579
     * @return string[]
580
     */
581 16
    public function getParams(): array
582
    {
583
        $paramsToCheck = [
584 16
            'project',
585
            'username',
586
            'namespace',
587
            'page',
588
            'categories',
589
            'group',
590
            'redirects',
591
            'deleted',
592
            'start',
593
            'end',
594
            'offset',
595
            'limit',
596
            'format',
597
            'tool',
598
            'tools',
599
            'q',
600
601
            // Legacy parameters.
602
            'user',
603
            'name',
604
            'article',
605
            'wiki',
606
            'wikifam',
607
            'lang',
608
            'wikilang',
609
            'begin',
610
        ];
611
612
        /** @var string[] $params Each parameter that was detected along with its value. */
613 16
        $params = [];
614
615 16
        foreach ($paramsToCheck as $param) {
616
            // Pull in either from URL query string or route.
617 16
            $value = $this->request->query->get($param) ?: $this->request->get($param);
618
619
            // Only store if value is given ('namespace' or 'username' could be '0').
620 16
            if (null !== $value && '' !== $value) {
621 16
                $params[$param] = rawurldecode((string)$value);
622
            }
623
        }
624
625 16
        return $params;
626
    }
627
628
    /**
629
     * Parse out common parameters from the request. These include the 'project', 'username', 'namespace' and 'page',
630
     * along with their legacy counterparts (e.g. 'lang' and 'wiki').
631
     * @return string[] Normalized parameters (no legacy params).
632
     */
633 16
    public function parseQueryParams(): array
634
    {
635
        /** @var string[] $params Each parameter and value that was detected. */
636 16
        $params = $this->getParams();
637
638
        // Covert any legacy parameters, if present.
639 16
        $params = $this->convertLegacyParams($params);
640
641
        // Remove blank values.
642
        return array_filter($params, function ($param) {
643
            // 'namespace' or 'username' could be '0'.
644 4
            return null !== $param && '' !== $param;
645 16
        });
646
    }
647
648
    /**
649
     * Get Unix timestamps from given start and end string parameters. This also makes $start $maxDays before
650
     * $end if not present, and makes $end the current time if not present.
651
     * The date range will not exceed $this->maxDays days, if this public class property is set.
652
     * @param int|string|false $start Unix timestamp or string accepted by strtotime.
653
     * @param int|string|false $end Unix timestamp or string accepted by strtotime.
654
     * @return int[] Start and end date as UTC timestamps.
655
     */
656 1
    public function getUnixFromDateParams($start, $end): array
657
    {
658 1
        $today = strtotime('today midnight');
659
660
        // start time should not be in the future.
661 1
        $startTime = min(
662 1
            is_int($start) ? $start : strtotime((string)$start),
663 1
            $today
664
        );
665
666
        // end time defaults to now, and will not be in the future.
667 1
        $endTime = min(
668 1
            (is_int($end) ? $end : strtotime((string)$end)) ?: $today,
669 1
            $today
670
        );
671
672
        // Default to $this->defaultDays or $this->maxDays before end time if start is not present.
673 1
        $daysOffset = $this->defaultDays ?? $this->maxDays;
674 1
        if (false === $startTime && is_int($daysOffset)) {
675 1
            $startTime = strtotime("-$daysOffset days", $endTime);
676
        }
677
678
        // Default to $this->defaultDays or $this->maxDays after start time if end is not present.
679 1
        if (false === $end && is_int($daysOffset)) {
680
            $endTime = min(
681
                strtotime("+$daysOffset days", $startTime),
682
                $today
683
            );
684
        }
685
686
        // Reverse if start date is after end date.
687 1
        if ($startTime > $endTime && false !== $startTime && false !== $end) {
688 1
            $newEndTime = $startTime;
689 1
            $startTime = $endTime;
690 1
            $endTime = $newEndTime;
691
        }
692
693
        // Finally, don't let the date range exceed $this->maxDays.
694 1
        $startObj = DateTime::createFromFormat('U', (string)$startTime);
695 1
        $endObj = DateTime::createFromFormat('U', (string)$endTime);
696 1
        if (is_int($this->maxDays) && $startObj->diff($endObj)->days > $this->maxDays) {
697
            // Show warnings that the date range was truncated.
698 1
            $this->addFlashMessage('warning', 'date-range-too-wide', [$this->maxDays]);
699
700 1
            $startTime = strtotime("-$this->maxDays days", $endTime);
701
        }
702
703 1
        return [$startTime, $endTime];
704
    }
705
706
    /**
707
     * Given the params hash, normalize any legacy parameters to their modern equivalent.
708
     * @param string[] $params
709
     * @return string[]
710
     */
711 16
    private function convertLegacyParams(array $params): array
712
    {
713
        $paramMap = [
714 16
            'user' => 'username',
715
            'name' => 'username',
716
            'article' => 'page',
717
            'begin' => 'start',
718
719
            // Copy super legacy project params to legacy so we can concatenate below.
720
            'wikifam' => 'wiki',
721
            'wikilang' => 'lang',
722
        ];
723
724
        // Copy legacy parameters to modern equivalent.
725 16
        foreach ($paramMap as $legacy => $modern) {
726 16
            if (isset($params[$legacy])) {
727
                $params[$modern] = $params[$legacy];
728 16
                unset($params[$legacy]);
729
            }
730
        }
731
732
        // Separate parameters for language and wiki.
733 16
        if (isset($params['wiki']) && isset($params['lang'])) {
734
            // 'wikifam' will be like '.wikipedia.org', vs just 'wikipedia',
735
            // so we must remove leading periods and trailing .org's.
736
            $params['project'] = rtrim(ltrim($params['wiki'], '.'), '.org').'.org';
737
738
            /** @var string[] $languagelessProjects Projects for which there is no specific language association. */
739
            $languagelessProjects = $this->container->getParameter('languageless_wikis');
740
741
            // Prepend language if applicable.
742
            if (isset($params['lang']) && !in_array($params['wiki'], $languagelessProjects)) {
743
                $params['project'] = $params['lang'].'.'.$params['project'];
744
            }
745
746
            unset($params['wiki']);
747
            unset($params['lang']);
748
        }
749
750 16
        return $params;
751
    }
752
753
    /************************
754
     * FORMATTING RESPONSES *
755
     ************************/
756
757
    /**
758
     * Get the rendered template for the requested format. This method also updates the cookies.
759
     * @param string $templatePath Path to template without format,
760
     *   such as '/editCounter/latest_global'.
761
     * @param array $ret Data that should be passed to the view.
762
     * @return Response
763
     * @codeCoverageIgnore
764
     */
765
    public function getFormattedResponse(string $templatePath, array $ret): Response
766
    {
767
        $format = $this->request->query->get('format', 'html');
768
        if ('' == $format) {
769
            // The default above doesn't work when the 'format' parameter is blank.
770
            $format = 'html';
771
        }
772
773
        // Merge in common default parameters, giving $ret (from the caller) the priority.
774
        $ret = array_merge([
775
            'project' => $this->project,
776
            'user' => $this->user,
777
            'page' => $this->page,
778
            'namespace' => $this->namespace,
779
            'start' => $this->start,
780
            'end' => $this->end,
781
        ], $ret);
782
783
        $formatMap = [
784
            'wikitext' => 'text/plain',
785
            'csv' => 'text/csv',
786
            'tsv' => 'text/tab-separated-values',
787
            'json' => 'application/json',
788
        ];
789
790
        $response = new Response();
791
792
        // Set cookies. Note this must be done before rendering the view, as the view may invoke subrequests.
793
        $this->setCookies($response);
794
795
        // If requested format does not exist, assume HTML.
796
        if (false === $this->get('twig')->getLoader()->exists("$templatePath.$format.twig")) {
797
            $format = 'html';
798
        }
799
800
        $response = $this->render("$templatePath.$format.twig", $ret, $response);
801
802
        $contentType = $formatMap[$format] ?? 'text/html';
803
        $response->headers->set('Content-Type', $contentType);
804
805
        if (in_array($format, ['csv', 'tsv'])) {
806
            $filename = $this->getFilenameForRequest();
807
            $response->headers->set(
808
                'Content-Disposition',
809
                "attachment; filename=\"{$filename}.$format\""
810
            );
811
        }
812
813
        return $response;
814
    }
815
816
    /**
817
     * Returns given filename from the current Request, with problematic characters filtered out.
818
     * @return string
819
     */
820
    private function getFilenameForRequest(): string
821
    {
822
        $filename = trim($this->request->getPathInfo(), '/');
823
        return trim(preg_replace('/[-\/\\:;*?|<>%#"]+/', '-', $filename));
824
    }
825
826
    /**
827
     * Return a JsonResponse object pre-supplied with the requested params.
828
     * @param array $data
829
     * @return JsonResponse
830
     */
831 2
    public function getFormattedApiResponse(array $data): JsonResponse
832
    {
833 2
        $response = new JsonResponse();
834 2
        $response->setEncodingOptions(JSON_NUMERIC_CHECK);
835 2
        $response->setStatusCode(Response::HTTP_OK);
836
837 2
        $elapsedTime = round(
838 2
            microtime(true) - $this->request->server->get('REQUEST_TIME_FLOAT'),
839 2
            3
840
        );
841
842
        // Any pipe-separated values should be returned as an array.
843 2
        foreach ($this->params as $param => $value) {
844 2
            if (is_string($value) && false !== strpos($value, '|')) {
845 2
                $this->params[$param] = explode('|', $value);
846
            }
847
        }
848
849 2
        $ret = array_merge($this->params, [
850
            // In some controllers, $this->params['project'] may be overridden with a Project object.
851 2
            'project' => $this->project->getDomain(),
852 2
        ], $data, ['elapsed_time' => $elapsedTime]);
853
854
        // Merge in flash messages, putting them at the top.
855 2
        $flashes = $this->get('session')->getFlashBag()->peekAll();
856 2
        $ret = array_merge($flashes, $ret);
857
858
        // Flashes now can be cleared after merging into the response.
859 2
        $this->get('session')->getFlashBag()->clear();
860
861 2
        $response->setData($ret);
862
863 2
        return $response;
864
    }
865
866
    /*********
867
     * OTHER *
868
     *********/
869
870
    /**
871
     * Record usage of an API endpoint.
872
     * @param string $endpoint
873
     * @codeCoverageIgnore
874
     */
875
    public function recordApiUsage(string $endpoint): void
876
    {
877
        /** @var \Doctrine\DBAL\Connection $conn */
878
        $conn = $this->container->get('doctrine')
879
            ->getManager('default')
880
            ->getConnection();
881
        $date =  date('Y-m-d');
882
883
        // Increment count in timeline
884
        $existsSql = "SELECT 1 FROM usage_api_timeline
885
                      WHERE date = '$date'
886
                      AND endpoint = '$endpoint'";
887
888
        if (0 === count($conn->query($existsSql)->fetchAll())) {
889
            $createSql = "INSERT INTO usage_api_timeline
890
                          VALUES(NULL, '$date', '$endpoint', 1)";
891
            $conn->query($createSql);
892
        } else {
893
            $updateSql = "UPDATE usage_api_timeline
894
                          SET count = count + 1
895
                          WHERE endpoint = '$endpoint'
896
                          AND date = '$date'";
897
            $conn->query($updateSql);
898
        }
899
    }
900
901
    /**
902
     * Add a flash message.
903
     * @param string $type
904
     * @param string $key i18n key or raw message.
905
     * @param array $vars
906
     */
907 1
    public function addFlashMessage(string $type, string $key, array $vars = []): void
908
    {
909 1
        $this->addFlash(
910 1
            $type,
911 1
            $this->i18n->msgExists($key, $vars) ? $this->i18n->msg($key, $vars) : $key
912
        );
913 1
    }
914
}
915