Passed
Push — master ( 166648...d6c1bf )
by MusikAnimal
07:19
created

XtoolsController::validateProject()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 8.7414

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 25
ccs 5
cts 15
cp 0.3333
crap 8.7414
rs 9.7998
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 {@see 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::getUTCFromDateParams()
78
     * @var int|null
79
     */
80
    public $maxDays = null;
81
82
    /** @var int|string Namespace parsed from the Request, ID as int or 'all' for all namespaces. */
83
    protected $namespace;
84
85
    /** @var int Pagination offset parsed from the Request. */
86
    protected $offset = 0;
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', [$this->getOptedInPage()->getTitle()]),
0 ignored issues
show
Bug introduced by
It seems like $this->i18n->msg('not-op...dInPage()->getTitle())) 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', [$this->getOptedInPage()->getTitle()]),
Loading history...
203
                '',
204
                $this->params,
205
                true
206
            );
207
        }
208 16
    }
209
210
    /**
211
     * Get the path to the opt-in page for restricted statistics.
212
     * @return Page
213
     */
214
    protected function getOptedInPage(): Page
215
    {
216
        return $this->project
217
            ->getRepository()
218
            ->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

218
            ->/** @scrutinizer ignore-call */ getPage($this->project, $this->project->userOptInPage($this->user));
Loading history...
219
    }
220
221
    /***********
222
     * COOKIES *
223
     ***********/
224
225
    /**
226
     * Load user preferences from the associated cookies.
227
     */
228 16
    private function loadCookies(): void
229
    {
230
        // Not done for subrequests.
231 16
        if ($this->isSubRequest) {
232
            return;
233
        }
234
235 16
        foreach (array_keys($this->cookies) as $name) {
236 16
            $this->cookies[$name] = $this->request->cookies->get($name);
237
        }
238 16
    }
239
240
    /**
241
     * Set cookies on the given Response.
242
     * @param Response $response
243
     */
244
    private function setCookies(Response &$response): void
245
    {
246
        // Not done for subrequests.
247
        if ($this->isSubRequest) {
248
            return;
249
        }
250
251
        foreach ($this->cookies as $name => $value) {
252
            $response->headers->setCookie(
253
                new Cookie($name, $value)
254
            );
255
        }
256
    }
257
258
    /**
259
     * Sets the project, with the domain in $this->cookies['XtoolsProject'] that will
260
     * later get set on the Response headers in self::getFormattedResponse().
261
     * @param Project $project
262
     */
263 12
    private function setProject(Project $project): void
264
    {
265
        // TODO: Remove after deprecated routes are retired.
266 12
        if (false !== strpos((string)$this->request->get('_controller'), 'GlobalContribs')) {
267
            return;
268
        }
269
270 12
        $this->project = $project;
271 12
        $this->cookies['XtoolsProject'] = $project->getDomain();
272 12
    }
273
274
    /****************************
275
     * SETTING CLASS PROPERTIES *
276
     ****************************/
277
278
    /**
279
     * Normalize all common parameters used by the controllers and set class properties.
280
     */
281 6
    private function setProperties(): void
282
    {
283 6
        $this->namespace = $this->params['namespace'] ?? null;
284
285
        // Offset and limit need to be ints.
286 6
        foreach (['offset', 'limit'] as $param) {
287 6
            if (isset($this->params[$param])) {
288 6
                $this->{$param} = (int)$this->params[$param];
289
            }
290
        }
291
292 6
        if (isset($this->params['project'])) {
293 2
            $this->setProject($this->validateProject($this->params['project']));
294 4
        } elseif (null !== $this->cookies['XtoolsProject']) {
295
            // Set from cookie.
296
            $this->setProject(
297
                $this->validateProject($this->cookies['XtoolsProject'])
298
            );
299
        }
300
301 6
        if (isset($this->params['username'])) {
302
            $this->user = $this->validateUser($this->params['username']);
303
        }
304 6
        if (isset($this->params['page'])) {
305
            $this->page = $this->getPageFromNsAndTitle($this->namespace, $this->params['page']);
306
        }
307
308 6
        $this->setDates();
309 6
    }
310
311
    /**
312
     * Set class properties for dates, if such params were passed in.
313
     */
314 6
    private function setDates(): void
315
    {
316 6
        $start = $this->params['start'] ?? false;
317 6
        $end = $this->params['end'] ?? false;
318 6
        if ($start || $end || null !== $this->maxDays) {
319
            [$this->start, $this->end] = $this->getUTCFromDateParams($start, $end);
320
321
            // Set $this->params accordingly too, so that for instance API responses will include it.
322
            $this->params['start'] = is_int($this->start) ? date('Y-m-d', $this->start) : false;
323
            $this->params['end'] = is_int($this->end) ? date('Y-m-d', $this->end) : false;
324
        }
325 6
    }
326
327
    /**
328
     * Construct a fully qualified page title given the namespace and title.
329
     * @param int|string $ns Namespace ID.
330
     * @param string $title Page title.
331
     * @param bool $rawTitle Return only the title (and not a Page).
332
     * @return Page|string
333
     */
334
    protected function getPageFromNsAndTitle($ns, string $title, bool $rawTitle = false)
335
    {
336
        if (0 === (int)$ns) {
337
            return $rawTitle ? $title : $this->validatePage($title);
338
        }
339
340
        // Prepend namespace and strip out duplicates.
341
        $nsName = $this->project->getNamespaces()[$ns] ?? $this->i18n->msg('unknown');
342
        $title = $nsName.':'.preg_replace('/^'.$nsName.':/', '', $title);
343
        return $rawTitle ? $title : $this->validatePage($title);
344
    }
345
346
    /**
347
     * Get a Project instance from the project string, using defaults if the given project string is invalid.
348
     * @return Project
349
     */
350 10
    public function getProjectFromQuery(): Project
351
    {
352
        // Set default project so we can populate the namespace selector on index pages.
353
        // Defaults to project stored in cookie, otherwise project specified in parameters.yml.
354 10
        if (isset($this->params['project'])) {
355 2
            $project = $this->params['project'];
356 8
        } elseif (null !== $this->cookies['XtoolsProject']) {
357
            $project = $this->cookies['XtoolsProject'];
358
        } else {
359 8
            $project = $this->container->getParameter('default_project');
360
        }
361
362 10
        $projectData = ProjectRepository::getProject($project, $this->container);
363
364
        // Revert back to defaults if we've established the given project was invalid.
365 10
        if (!$projectData->exists()) {
366
            $projectData = ProjectRepository::getProject(
367
                $this->container->getParameter('default_project'),
368
                $this->container
369
            );
370
        }
371
372 10
        return $projectData;
373
    }
374
375
    /*************************
376
     * GETTERS / VALIDATIONS *
377
     *************************/
378
379
    /**
380
     * Validate the given project, returning a Project if it is valid or false otherwise.
381
     * @param string $projectQuery Project domain or database name.
382
     * @return Project
383
     * @throws XtoolsHttpException
384
     */
385 2
    public function validateProject(string $projectQuery): Project
386
    {
387
        /** @var Project $project */
388 2
        $project = ProjectRepository::getProject($projectQuery, $this->container);
389
390
        // Check if it is an explicitly allowed project for the current tool.
391 2
        if (isset($this->supportedProjects) && !in_array($project->getDomain(), $this->supportedProjects)) {
392
            $this->throwXtoolsException(
393
                $this->getIndexRoute(),
394
                'error-authorship-unsupported-project',
395
                [$this->params['project']],
396
                'project'
397
            );
398
        }
399
400 2
        if (!$project->exists()) {
401
            $this->throwXtoolsException(
402
                $this->getIndexRoute(),
403
                'invalid-project',
404
                [$this->params['project']],
405
                'project'
406
            );
407
        }
408
409 2
        return $project;
410
    }
411
412
    /**
413
     * Validate the given user, returning a User or Redirect if they don't exist.
414
     * @param string $username
415
     * @return User
416
     * @throws XtoolsHttpException
417
     */
418
    public function validateUser(string $username): User
419
    {
420
        $user = UserRepository::getUser($username, $this->container);
421
422
        // Allow querying for any IP, currently with no edit count limitation...
423
        // Once T188677 is resolved IPs will be affected by the EXPLAIN results.
424
        if ($user->isAnon()) {
425
            return $user;
426
        }
427
428
        $originalParams = $this->params;
429
430
        // Don't continue if the user doesn't exist.
431
        if ($this->project && !$user->existsOnProject($this->project)) {
432
            $this->throwXtoolsException($this->getIndexRoute(), 'user-not-found', [], 'username');
433
        }
434
435
        // Reject users with a crazy high edit count.
436
        if (isset($this->tooHighEditCountAction) &&
437
            !in_array($this->controllerAction, $this->tooHighEditCountActionBlacklist) &&
438
            $user->hasTooManyEdits($this->project)
439
        ) {
440
            /** TODO: Somehow get this to use self::throwXtoolsException */
441
442
            // If redirecting to a different controller, show an informative message accordingly.
443
            if ($this->tooHighEditCountAction !== $this->getIndexRoute()) {
444
                // FIXME: This is currently only done for Edit Counter, redirecting to Simple Edit Counter,
445
                //   so this bit is hardcoded. We need to instead give the i18n key of the route.
446
                $redirMsg = $this->i18n->msg('too-many-edits-redir', [
447
                    $this->i18n->msg('tool-simpleeditcounter'),
448
                ]);
449
                $msg = $this->i18n->msg('too-many-edits', [
450
                    $this->i18n->numberFormat($user->maxEdits()),
451
                ]).'. '.$redirMsg;
452
                $this->addFlashMessage('danger', $msg);
453
            } else {
454
                $this->addFlashMessage('danger', 'too-many-edits', [
455
                    $this->i18n->numberFormat($user->maxEdits()),
456
                ]);
457
458
                // Redirecting back to index, so remove username (otherwise we'd get a redirect loop).
459
                unset($this->params['username']);
460
            }
461
462
            // Clear flash bag for API responses, since they get intercepted in ExceptionListener
463
            // and would otherwise be shown in subsequent requests.
464
            if ($this->isApi) {
465
                $this->get('session')->getFlashBag()->clear();
466
            }
467
468
            throw new XtoolsHttpException(
469
                'User has made too many edits! Maximum '.$user->maxEdits(),
470
                $this->generateUrl($this->tooHighEditCountAction, $this->params),
471
                $originalParams,
472
                $this->isApi
473
            );
474
        }
475
476
        return $user;
477
    }
478
479
    /**
480
     * Get a Page instance from the given page title, and validate that it exists.
481
     * @param string $pageTitle
482
     * @return Page
483
     * @throws XtoolsHttpException
484
     */
485
    public function validatePage(string $pageTitle): Page
486
    {
487
        $page = new Page($this->project, $pageTitle);
488
        $pageRepo = new PageRepository();
489
        $pageRepo->setContainer($this->container);
490
        $page->setRepository($pageRepo);
491
492
        if (!$page->exists()) {
493
            $this->throwXtoolsException(
494
                $this->getIndexRoute(),
495
                'no-result',
496
                [$this->params['page'] ?? null],
497
                'page'
498
            );
499
        }
500
501
        return $page;
502
    }
503
504
    /**
505
     * Throw an XtoolsHttpException, which the given error message and redirects to specified action.
506
     * @param string $redirectAction Name of action to redirect to.
507
     * @param string $message i18n key of error message. Shown in API responses.
508
     *   If no message with this key exists, $message is shown as-is.
509
     * @param array $messageParams
510
     * @param string $invalidParam This will be removed from $this->params. Omit if you don't want this to happen.
511
     * @throws XtoolsHttpException
512
     */
513
    public function throwXtoolsException(
514
        string $redirectAction,
515
        string $message,
516
        array $messageParams = [],
517
        ?string $invalidParam = null
518
    ): void {
519
        $this->addFlashMessage('danger', $message, $messageParams);
520
        $originalParams = $this->params;
521
522
        // Remove invalid parameter if it was given.
523
        if (is_string($invalidParam)) {
524
            unset($this->params[$invalidParam]);
525
        }
526
527
        // We sometimes are redirecting to the index page, so also remove project (otherwise we'd get a redirect loop).
528
        /**
529
         * FIXME: Index pages should have a 'nosubmit' parameter to prevent submission.
530
         * Then we don't even need to remove $invalidParam.
531
         * Better, we should show the error on the results page, with no results.
532
         */
533
        unset($this->params['project']);
534
535
        // Throw exception which will redirect to $redirectAction.
536
        throw new XtoolsHttpException(
537
            $this->i18n->msgIfExists($message, $messageParams),
538
            $this->generateUrl($redirectAction, $this->params),
539
            $originalParams,
540
            $this->isApi
541
        );
542
    }
543
544
    /**
545
     * Get the first error message stored in the session's FlashBag.
546
     * @return string
547
     */
548
    public function getFlashMessage(): string
549
    {
550
        $key = $this->get('session')->getFlashBag()->get('danger')[0];
551
        $param = null;
552
553
        if (is_array($key)) {
554
            [$key, $param] = $key;
555
        }
556
557
        return $this->render('message.twig', [
558
            'key' => $key,
559
            'params' => [$param],
560
        ])->getContent();
561
    }
562
563
    /******************
564
     * PARSING PARAMS *
565
     ******************/
566
567
    /**
568
     * Get all standardized parameters from the Request, either via URL query string or routing.
569
     * @return string[]
570
     */
571 16
    public function getParams(): array
572
    {
573
        $paramsToCheck = [
574 16
            'project',
575
            'username',
576
            'namespace',
577
            'page',
578
            'categories',
579
            'group',
580
            'redirects',
581
            'deleted',
582
            'start',
583
            'end',
584
            'offset',
585
            'limit',
586
            'format',
587
            'tool',
588
            'q',
589
590
            // Legacy parameters.
591
            'user',
592
            'name',
593
            'article',
594
            'wiki',
595
            'wikifam',
596
            'lang',
597
            'wikilang',
598
            'begin',
599
        ];
600
601
        /** @var string[] $params Each parameter that was detected along with its value. */
602 16
        $params = [];
603
604 16
        foreach ($paramsToCheck as $param) {
605
            // Pull in either from URL query string or route.
606 16
            $value = $this->request->query->get($param) ?: $this->request->get($param);
607
608
            // Only store if value is given ('namespace' or 'username' could be '0').
609 16
            if (null !== $value && '' !== $value) {
610 16
                $params[$param] = rawurldecode((string)$value);
611
            }
612
        }
613
614 16
        return $params;
615
    }
616
617
    /**
618
     * Parse out common parameters from the request. These include the 'project', 'username', 'namespace' and 'page',
619
     * along with their legacy counterparts (e.g. 'lang' and 'wiki').
620
     * @return string[] Normalized parameters (no legacy params).
621
     */
622 16
    public function parseQueryParams(): array
623
    {
624
        /** @var string[] $params Each parameter and value that was detected. */
625 16
        $params = $this->getParams();
626
627
        // Covert any legacy parameters, if present.
628 16
        $params = $this->convertLegacyParams($params);
629
630
        // Remove blank values.
631 16
        return array_filter($params, function ($param) {
632
            // 'namespace' or 'username' could be '0'.
633 4
            return null !== $param && '' !== $param;
634 16
        });
635
    }
636
637
    /**
638
     * Get UTC timestamps from given start and end string parameters. This also makes $start $maxDays before
639
     * $end if not present, and makes $end the current time if not present.
640
     * The date range will not exceed $this->maxDays days, if this public class property is set.
641
     * @param int|string|false $start Unix timestamp or string accepted by strtotime.
642
     * @param int|string|false $end Unix timestamp or string accepted by strtotime.
643
     * @return int[] Start and end date as UTC timestamps.
644
     */
645 1
    public function getUTCFromDateParams($start, $end): array
646
    {
647 1
        $today = strtotime('today midnight');
648
649
        // start time should not be in the future.
650 1
        $startTime = min(
651 1
            is_int($start) ? $start : strtotime((string)$start),
652 1
            $today
653
        );
654
655
        // end time defaults to now, and will not be in the future.
656 1
        $endTime = min(
657 1
            (is_int($end) ? $end : strtotime((string)$end)) ?: $today,
658 1
            $today
659
        );
660
661
        // Default to $this->defaultDays or $this->maxDays before end time if start is not present.
662 1
        $daysOffset = $this->defaultDays ?? $this->maxDays;
663 1
        if (false === $startTime && is_int($daysOffset)) {
664 1
            $startTime = strtotime("-$daysOffset days", $endTime);
665
        }
666
667
        // Default to $this->defaultDays or $this->maxDays after start time if end is not present.
668 1
        if (false === $end && is_int($daysOffset)) {
669
            $endTime = min(
670
                strtotime("+$daysOffset days", $startTime),
671
                $today
672
            );
673
        }
674
675
        // Reverse if start date is after end date.
676 1
        if ($startTime > $endTime && false !== $startTime && false !== $end) {
677 1
            $newEndTime = $startTime;
678 1
            $startTime = $endTime;
679 1
            $endTime = $newEndTime;
680
        }
681
682
        // Finally, don't let the date range exceed $this->maxDays.
683 1
        $startObj = DateTime::createFromFormat('U', (string)$startTime);
684 1
        $endObj = DateTime::createFromFormat('U', (string)$endTime);
685 1
        if (is_int($this->maxDays) && $startObj->diff($endObj)->days > $this->maxDays) {
0 ignored issues
show
Bug introduced by
It seems like $endObj can also be of type false; however, parameter $datetime2 of DateTime::diff() does only seem to accept DateTimeInterface, 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

685
        if (is_int($this->maxDays) && $startObj->diff(/** @scrutinizer ignore-type */ $endObj)->days > $this->maxDays) {
Loading history...
686
            // Show warnings that the date range was truncated.
687 1
            $this->addFlashMessage('warning', 'date-range-too-wide', [$this->maxDays]);
688
689 1
            $startTime = strtotime("-$this->maxDays days", $endTime);
690
        }
691
692 1
        return [$startTime, $endTime];
693
    }
694
695
    /**
696
     * Given the params hash, normalize any legacy parameters to their modern equivalent.
697
     * @param string[] $params
698
     * @return string[]
699
     */
700 16
    private function convertLegacyParams(array $params): array
701
    {
702
        $paramMap = [
703 16
            'user' => 'username',
704
            'name' => 'username',
705
            'article' => 'page',
706
            'begin' => 'start',
707
708
            // Copy super legacy project params to legacy so we can concatenate below.
709
            'wikifam' => 'wiki',
710
            'wikilang' => 'lang',
711
        ];
712
713
        // Copy legacy parameters to modern equivalent.
714 16
        foreach ($paramMap as $legacy => $modern) {
715 16
            if (isset($params[$legacy])) {
716
                $params[$modern] = $params[$legacy];
717 16
                unset($params[$legacy]);
718
            }
719
        }
720
721
        // Separate parameters for language and wiki.
722 16
        if (isset($params['wiki']) && isset($params['lang'])) {
723
            // 'wikifam' will be like '.wikipedia.org', vs just 'wikipedia',
724
            // so we must remove leading periods and trailing .org's.
725
            $params['project'] = rtrim(ltrim($params['wiki'], '.'), '.org').'.org';
726
727
            /** @var string[] $languagelessProjects Projects for which there is no specific language association. */
728
            $languagelessProjects = $this->container->getParameter('languageless_wikis');
729
730
            // Prepend language if applicable.
731
            if (isset($params['lang']) && !in_array($params['wiki'], $languagelessProjects)) {
732
                $params['project'] = $params['lang'].'.'.$params['project'];
733
            }
734
735
            unset($params['wiki']);
736
            unset($params['lang']);
737
        }
738
739 16
        return $params;
740
    }
741
742
    /************************
743
     * FORMATTING RESPONSES *
744
     ************************/
745
746
    /**
747
     * Get the rendered template for the requested format. This method also updates the cookies.
748
     * @param string $templatePath Path to template without format,
749
     *   such as '/editCounter/latest_global'.
750
     * @param array $ret Data that should be passed to the view.
751
     * @return Response
752
     * @codeCoverageIgnore
753
     */
754
    public function getFormattedResponse(string $templatePath, array $ret): Response
755
    {
756
        $format = $this->request->query->get('format', 'html');
757
        if ('' == $format) {
758
            // The default above doesn't work when the 'format' parameter is blank.
759
            $format = 'html';
760
        }
761
762
        // Merge in common default parameters, giving $ret (from the caller) the priority.
763
        $ret = array_merge([
764
            'project' => $this->project,
765
            'user' => $this->user,
766
            'page' => $this->page,
767
        ], $ret);
768
769
        $formatMap = [
770
            'wikitext' => 'text/plain',
771
            'csv' => 'text/csv',
772
            'tsv' => 'text/tab-separated-values',
773
            'json' => 'application/json',
774
        ];
775
776
        $response = new Response();
777
778
        // Set cookies. Note this must be done before rendering the view, as the view may invoke subrequests.
779
        $this->setCookies($response);
780
781
        // If requested format does not exist, assume HTML.
782
        if (false === $this->get('twig')->getLoader()->exists("$templatePath.$format.twig")) {
783
            $format = 'html';
784
        }
785
786
        $response = $this->render("$templatePath.$format.twig", $ret, $response);
787
788
        $contentType = $formatMap[$format] ?? 'text/html';
789
        $response->headers->set('Content-Type', $contentType);
790
791
        if (in_array($format, ['csv', 'tsv'])) {
792
            $filename = $this->getFilenameForRequest();
793
            $response->headers->set(
794
                'Content-Disposition',
795
                "attachment; filename=\"{$filename}.$format\""
796
            );
797
        }
798
799
        return $response;
800
    }
801
802
    /**
803
     * Returns given filename from the current Request, with problematic characters filtered out.
804
     * @return string
805
     */
806
    private function getFilenameForRequest(): string
807
    {
808
        $filename = trim($this->request->getPathInfo(), '/');
809
        return trim(preg_replace('/[-\/\\:;*?|<>%#"]+/', '-', $filename));
810
    }
811
812
    /**
813
     * Return a JsonResponse object pre-supplied with the requested params.
814
     * @param array $data
815
     * @return JsonResponse
816
     */
817 2
    public function getFormattedApiResponse(array $data): JsonResponse
818
    {
819 2
        $response = new JsonResponse();
820 2
        $response->setEncodingOptions(JSON_NUMERIC_CHECK);
821 2
        $response->setStatusCode(Response::HTTP_OK);
822
823 2
        $elapsedTime = round(
824 2
            microtime(true) - $this->request->server->get('REQUEST_TIME_FLOAT'),
825 2
            3
826
        );
827
828
        // Any pipe-separated values should be returned as an array.
829 2
        foreach ($this->params as $param => $value) {
830 2
            if (is_string($value) && false !== strpos($value, '|')) {
831 2
                $this->params[$param] = explode('|', $value);
832
            }
833
        }
834
835 2
        $ret = array_merge($this->params, [
836
            // In some controllers, $this->params['project'] may be overridden with a Project object.
837 2
            'project' => $this->project->getDomain(),
838 2
        ], $data, ['elapsed_time' => $elapsedTime]);
839
840
        // Merge in flash messages, putting them at the top.
841 2
        $flashes = $this->get('session')->getFlashBag()->peekAll();
842 2
        $ret = array_merge($flashes, $ret);
843
844
        // Flashes now can be cleared after merging into the response.
845 2
        $this->get('session')->getFlashBag()->clear();
846
847 2
        $response->setData($ret);
848
849 2
        return $response;
850
    }
851
852
    /*********
853
     * OTHER *
854
     *********/
855
856
    /**
857
     * Record usage of an API endpoint.
858
     * @param string $endpoint
859
     * @codeCoverageIgnore
860
     */
861
    public function recordApiUsage(string $endpoint): void
862
    {
863
        /** @var \Doctrine\DBAL\Connection $conn */
864
        $conn = $this->container->get('doctrine')
865
            ->getManager('default')
866
            ->getConnection();
867
        $date =  date('Y-m-d');
868
869
        // Increment count in timeline
870
        $existsSql = "SELECT 1 FROM usage_api_timeline
871
                      WHERE date = '$date'
872
                      AND endpoint = '$endpoint'";
873
874
        if (0 === count($conn->query($existsSql)->fetchAll())) {
875
            $createSql = "INSERT INTO usage_api_timeline
876
                          VALUES(NULL, '$date', '$endpoint', 1)";
877
            $conn->query($createSql);
878
        } else {
879
            $updateSql = "UPDATE usage_api_timeline
880
                          SET count = count + 1
881
                          WHERE endpoint = '$endpoint'
882
                          AND date = '$date'";
883
            $conn->query($updateSql);
884
        }
885
    }
886
887
    /**
888
     * Add a flash message.
889
     * @param string $type
890
     * @param string $key i18n key or raw message.
891
     * @param array $vars
892
     */
893 1
    public function addFlashMessage(string $type, string $key, array $vars = []): void
894
    {
895 1
        $this->addFlash(
896 1
            $type,
897 1
            $this->i18n->msgExists($key, $vars) ? $this->i18n->msg($key, $vars) : $key
0 ignored issues
show
Bug introduced by
It seems like $this->i18n->msgExists($...msg($key, $vars) : $key can also be of type null; however, parameter $message of Symfony\Bundle\Framework...\Controller::addFlash() 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

897
            /** @scrutinizer ignore-type */ $this->i18n->msgExists($key, $vars) ? $this->i18n->msg($key, $vars) : $key
Loading history...
898
        );
899 1
    }
900
}
901