Passed
Branch master (0917e1)
by MusikAnimal
11:12
created

XtoolsController::__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 37
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

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