Passed
Push — master ( 2e558b...522171 )
by MusikAnimal
11:17
created

XtoolsController::getUTCFromDateParams()   C

Complexity

Conditions 13
Paths 16

Size

Total Lines 48
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 13.292

Importance

Changes 0
Metric Value
cc 13
eloc 24
nc 16
nop 2
dl 0
loc 48
ccs 22
cts 25
cp 0.88
crap 13.292
rs 6.6166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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