Total Complexity | 117 |
Total Lines | 980 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like XtoolsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use XtoolsController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
34 | abstract class XtoolsController extends AbstractController |
||
35 | { |
||
36 | /** DEPENDENCIES */ |
||
37 | |||
38 | protected CacheItemPoolInterface $cache; |
||
39 | protected Client $guzzle; |
||
40 | protected I18nHelper $i18n; |
||
41 | protected ProjectRepository $projectRepo; |
||
42 | protected UserRepository $userRepo; |
||
43 | protected PageRepository $pageRepo; |
||
44 | |||
45 | /** OTHER CLASS PROPERTIES */ |
||
46 | |||
47 | /** @var Request The request object. */ |
||
48 | protected Request $request; |
||
49 | |||
50 | /** @var string Name of the action within the child controller that is being executed. */ |
||
51 | protected string $controllerAction; |
||
52 | |||
53 | /** @var array Hash of params parsed from the Request. */ |
||
54 | protected array $params; |
||
55 | |||
56 | /** @var bool Whether this is a request to an API action. */ |
||
57 | protected bool $isApi; |
||
58 | |||
59 | /** @var Project Relevant Project parsed from the Request. */ |
||
60 | protected Project $project; |
||
61 | |||
62 | /** @var User|null Relevant User parsed from the Request. */ |
||
63 | protected ?User $user = null; |
||
64 | |||
65 | /** @var Page|null Relevant Page parsed from the Request. */ |
||
66 | protected ?Page $page = null; |
||
67 | |||
68 | /** @var int|false Start date parsed from the Request. */ |
||
69 | protected $start = false; |
||
70 | |||
71 | /** @var int|false End date parsed from the Request. */ |
||
72 | protected $end = false; |
||
73 | |||
74 | /** @var int|string|null Namespace parsed from the Request, ID as int or 'all' for all namespaces. */ |
||
75 | protected $namespace; |
||
76 | |||
77 | /** @var int|false Unix timestamp. Pagination offset that substitutes for $end. */ |
||
78 | protected $offset = false; |
||
79 | |||
80 | /** @var int Number of results to return. */ |
||
81 | protected int $limit = 50; |
||
82 | |||
83 | /** @var bool Is the current request a subrequest? */ |
||
84 | protected bool $isSubRequest; |
||
85 | |||
86 | /** |
||
87 | * Stores user preferences such default project. |
||
88 | * This may get altered from the Request and updated in the Response. |
||
89 | * @var array |
||
90 | */ |
||
91 | protected array $cookies = [ |
||
92 | 'XtoolsProject' => null, |
||
93 | ]; |
||
94 | |||
95 | /** OVERRIDABLE METHODS */ |
||
96 | |||
97 | /** |
||
98 | * Require the tool's index route (initial form) be defined here. This should also |
||
99 | * be the name of the associated model, if present. |
||
100 | * @return string |
||
101 | */ |
||
102 | abstract protected function getIndexRoute(): string; |
||
103 | |||
104 | /** |
||
105 | * Override this to activate the 'too high edit count' functionality. The return value |
||
106 | * should represent the route name that we should be redirected to if the requested user |
||
107 | * has too high of an edit count. |
||
108 | * @return string|null Name of route to redirect to. |
||
109 | */ |
||
110 | protected function tooHighEditCountRoute(): ?string |
||
111 | { |
||
112 | return null; |
||
113 | } |
||
114 | |||
115 | /** |
||
116 | * Override this to specify which actions |
||
117 | * @return string[] |
||
118 | */ |
||
119 | protected function tooHighEditCountActionAllowlist(): array |
||
120 | { |
||
121 | return []; |
||
122 | } |
||
123 | |||
124 | /** |
||
125 | * Override to restrict a tool's access to only the specified projects, instead of any valid project. |
||
126 | * @return string[] Domain or DB names. |
||
127 | */ |
||
128 | protected function supportedProjects(): array |
||
129 | { |
||
130 | return []; |
||
131 | } |
||
132 | |||
133 | /** |
||
134 | * Override this to set which API actions for the controller require the |
||
135 | * target user to opt in to the restricted statistics. |
||
136 | * @see https://www.mediawiki.org/wiki/XTools/Edit_Counter#restricted_stats |
||
137 | * @return array |
||
138 | */ |
||
139 | protected function restrictedApiActions(): array |
||
140 | { |
||
141 | return []; |
||
142 | } |
||
143 | |||
144 | /** |
||
145 | * Override to set the maximum number of days allowed for the given date range. |
||
146 | * This will be used as the default date span unless $this->defaultDays() is overridden. |
||
147 | * @see XtoolsController::getUnixFromDateParams() |
||
148 | * @return int|null |
||
149 | */ |
||
150 | public function maxDays(): ?int |
||
151 | { |
||
152 | return null; |
||
153 | } |
||
154 | |||
155 | /** |
||
156 | * Override to set default days from current day, to use as the start date if none was provided. |
||
157 | * If this is null and $this->maxDays() is non-null, the latter will be used as the default. |
||
158 | * @return int|null |
||
159 | */ |
||
160 | protected function defaultDays(): ?int |
||
161 | { |
||
162 | return null; |
||
163 | } |
||
164 | |||
165 | /** |
||
166 | * Override to set the maximum number of results to show per page, default 5000. |
||
167 | * @return int |
||
168 | */ |
||
169 | protected function maxLimit(): int |
||
170 | { |
||
171 | return 5000; |
||
172 | } |
||
173 | |||
174 | /** |
||
175 | * XtoolsController constructor. |
||
176 | * @param RequestStack $requestStack |
||
177 | * @param ContainerInterface $container |
||
178 | * @param CacheItemPoolInterface $cache |
||
179 | * @param Client $guzzle |
||
180 | * @param I18nHelper $i18n |
||
181 | * @param ProjectRepository $projectRepo |
||
182 | * @param UserRepository $userRepo |
||
183 | * @param PageRepository $pageRepo |
||
184 | */ |
||
185 | public function __construct( |
||
186 | RequestStack $requestStack, |
||
187 | ContainerInterface $container, |
||
188 | CacheItemPoolInterface $cache, |
||
189 | Client $guzzle, |
||
190 | I18nHelper $i18n, |
||
191 | ProjectRepository $projectRepo, |
||
192 | UserRepository $userRepo, |
||
193 | PageRepository $pageRepo |
||
194 | ) { |
||
195 | $this->request = $requestStack->getCurrentRequest(); |
||
196 | $this->container = $container; |
||
197 | $this->cache = $cache; |
||
198 | $this->guzzle = $guzzle; |
||
199 | $this->i18n = $i18n; |
||
200 | $this->projectRepo = $projectRepo; |
||
201 | $this->userRepo = $userRepo; |
||
202 | $this->pageRepo = $pageRepo; |
||
203 | $this->params = $this->parseQueryParams(); |
||
204 | |||
205 | // Parse out the name of the controller and action. |
||
206 | $pattern = "#::([a-zA-Z]*)Action#"; |
||
207 | $matches = []; |
||
208 | // The blank string here only happens in the unit tests, where the request may not be made to an action. |
||
209 | preg_match($pattern, $this->request->get('_controller') ?? '', $matches); |
||
210 | $this->controllerAction = $matches[1] ?? ''; |
||
211 | |||
212 | // Whether the action is an API action. |
||
213 | $this->isApi = 'Api' === substr($this->controllerAction, -3) || 'recordUsage' === $this->controllerAction; |
||
214 | |||
215 | // Whether we're making a subrequest (the view makes a request to another action). |
||
216 | $this->isSubRequest = $this->request->get('htmlonly') |
||
217 | || null !== $this->get('request_stack')->getParentRequest(); |
||
218 | |||
219 | // Disallow AJAX (unless it's an API or subrequest). |
||
220 | $this->checkIfAjax(); |
||
221 | |||
222 | // Load user options from cookies. |
||
223 | $this->loadCookies(); |
||
224 | |||
225 | // Set the class-level properties based on params. |
||
226 | if (false !== strpos(strtolower($this->controllerAction), 'index')) { |
||
227 | // Index pages should only set the project, and no other class properties. |
||
228 | $this->setProject($this->getProjectFromQuery()); |
||
229 | |||
230 | // ...except for transforming IP ranges. Because Symfony routes are separated by slashes, we need a way to |
||
231 | // indicate a CIDR range because otherwise i.e. the path /sc/enwiki/192.168.0.0/24 could be interpreted as |
||
232 | // the Simple Edit Counter for 192.168.0.0 in the namespace with ID 24. So we prefix ranges with 'ipr-'. |
||
233 | // Further IP range handling logic is in the User class, i.e. see User::__construct, User::isIpRange. |
||
234 | if (isset($this->params['username']) && IPUtils::isValidRange($this->params['username'])) { |
||
235 | $this->params['username'] = 'ipr-'.$this->params['username']; |
||
236 | } |
||
237 | } else { |
||
238 | $this->setProperties(); // Includes the project. |
||
239 | } |
||
240 | |||
241 | // Check if the request is to a restricted API endpoint, where the target user has to opt-in to statistics. |
||
242 | $this->checkRestrictedApiEndpoint(); |
||
243 | } |
||
244 | |||
245 | /** |
||
246 | * Check if the request is AJAX, and disallow it unless they're using the API or if it's a subrequest. |
||
247 | */ |
||
248 | private function checkIfAjax(): void |
||
249 | { |
||
250 | if ($this->request->isXmlHttpRequest() && !$this->isApi && !$this->isSubRequest) { |
||
251 | throw new HttpException( |
||
252 | 403, |
||
253 | $this->i18n->msg('error-automation', ['https://www.mediawiki.org/Special:MyLanguage/XTools/API']) |
||
254 | ); |
||
255 | } |
||
256 | } |
||
257 | |||
258 | /** |
||
259 | * Check if the request is to a restricted API endpoint, and throw an exception if the target user hasn't opted-in. |
||
260 | * @throws XtoolsHttpException |
||
261 | */ |
||
262 | private function checkRestrictedApiEndpoint(): void |
||
263 | { |
||
264 | $restrictedAction = in_array($this->controllerAction, $this->restrictedApiActions()); |
||
265 | |||
266 | if ($this->isApi && $restrictedAction && !$this->project->userHasOptedIn($this->user)) { |
||
|
|||
267 | throw new XtoolsHttpException( |
||
268 | $this->i18n->msg('not-opted-in', [ |
||
269 | $this->getOptedInPage()->getTitle(), |
||
270 | $this->i18n->msg('not-opted-in-link') . |
||
271 | ' <https://www.mediawiki.org/wiki/Special:MyLanguage/XTools/Edit_Counter#restricted_stats>', |
||
272 | $this->i18n->msg('not-opted-in-login'), |
||
273 | ]), |
||
274 | '', |
||
275 | $this->params, |
||
276 | true, |
||
277 | Response::HTTP_UNAUTHORIZED |
||
278 | ); |
||
279 | } |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * Get the path to the opt-in page for restricted statistics. |
||
284 | * @return Page |
||
285 | */ |
||
286 | protected function getOptedInPage(): Page |
||
287 | { |
||
288 | return new Page($this->pageRepo, $this->project, $this->project->userOptInPage($this->user)); |
||
289 | } |
||
290 | |||
291 | /*********** |
||
292 | * COOKIES * |
||
293 | ***********/ |
||
294 | |||
295 | /** |
||
296 | * Load user preferences from the associated cookies. |
||
297 | */ |
||
298 | private function loadCookies(): void |
||
299 | { |
||
300 | // Not done for subrequests. |
||
301 | if ($this->isSubRequest) { |
||
302 | return; |
||
303 | } |
||
304 | |||
305 | foreach (array_keys($this->cookies) as $name) { |
||
306 | $this->cookies[$name] = $this->request->cookies->get($name); |
||
307 | } |
||
308 | } |
||
309 | |||
310 | /** |
||
311 | * Set cookies on the given Response. |
||
312 | * @param Response $response |
||
313 | */ |
||
314 | private function setCookies(Response $response): void |
||
315 | { |
||
316 | // Not done for subrequests. |
||
317 | if ($this->isSubRequest) { |
||
318 | return; |
||
319 | } |
||
320 | |||
321 | foreach ($this->cookies as $name => $value) { |
||
322 | $response->headers->setCookie( |
||
323 | Cookie::create($name, $value) |
||
324 | ); |
||
325 | } |
||
326 | } |
||
327 | |||
328 | /** |
||
329 | * Sets the project, with the domain in $this->cookies['XtoolsProject'] that will |
||
330 | * later get set on the Response headers in self::getFormattedResponse(). |
||
331 | * @param Project $project |
||
332 | */ |
||
333 | private function setProject(Project $project): void |
||
334 | { |
||
335 | // TODO: Remove after deprecated routes are retired. |
||
336 | if (false !== strpos((string)$this->request->get('_controller'), 'GlobalContribs')) { |
||
337 | return; |
||
338 | } |
||
339 | |||
340 | $this->project = $project; |
||
341 | $this->cookies['XtoolsProject'] = $project->getDomain(); |
||
342 | } |
||
343 | |||
344 | /**************************** |
||
345 | * SETTING CLASS PROPERTIES * |
||
346 | ****************************/ |
||
347 | |||
348 | /** |
||
349 | * Normalize all common parameters used by the controllers and set class properties. |
||
350 | */ |
||
351 | private function setProperties(): void |
||
352 | { |
||
353 | $this->namespace = $this->params['namespace'] ?? null; |
||
354 | |||
355 | // Offset is given as ISO timestamp and is stored as a UNIX timestamp (or false). |
||
356 | if (isset($this->params['offset'])) { |
||
357 | $this->offset = strtotime($this->params['offset']); |
||
358 | } |
||
359 | |||
360 | // Limit needs to be an int. |
||
361 | if (isset($this->params['limit'])) { |
||
362 | // Normalize. |
||
363 | $this->params['limit'] = min(max(1, (int)$this->params['limit']), $this->maxLimit()); |
||
364 | $this->limit = $this->params['limit']; |
||
365 | } |
||
366 | |||
367 | if (isset($this->params['project'])) { |
||
368 | $this->setProject($this->validateProject($this->params['project'])); |
||
369 | } elseif (null !== $this->cookies['XtoolsProject']) { |
||
370 | // Set from cookie. |
||
371 | $this->setProject( |
||
372 | $this->validateProject($this->cookies['XtoolsProject']) |
||
373 | ); |
||
374 | } |
||
375 | |||
376 | if (isset($this->params['username'])) { |
||
377 | $this->user = $this->validateUser($this->params['username']); |
||
378 | } |
||
379 | if (isset($this->params['page'])) { |
||
380 | $this->page = $this->getPageFromNsAndTitle($this->namespace, $this->params['page']); |
||
381 | } |
||
382 | |||
383 | $this->setDates(); |
||
384 | } |
||
385 | |||
386 | /** |
||
387 | * Set class properties for dates, if such params were passed in. |
||
388 | */ |
||
389 | private function setDates(): void |
||
390 | { |
||
391 | $start = $this->params['start'] ?? false; |
||
392 | $end = $this->params['end'] ?? false; |
||
393 | if ($start || $end || null !== $this->maxDays()) { |
||
394 | [$this->start, $this->end] = $this->getUnixFromDateParams($start, $end); |
||
395 | |||
396 | // Set $this->params accordingly too, so that for instance API responses will include it. |
||
397 | $this->params['start'] = is_int($this->start) ? date('Y-m-d', $this->start) : false; |
||
398 | $this->params['end'] = is_int($this->end) ? date('Y-m-d', $this->end) : false; |
||
399 | } |
||
400 | } |
||
401 | |||
402 | /** |
||
403 | * Construct a fully qualified page title given the namespace and title. |
||
404 | * @param int|string $ns Namespace ID. |
||
405 | * @param string $title Page title. |
||
406 | * @param bool $rawTitle Return only the title (and not a Page). |
||
407 | * @return Page|string |
||
408 | */ |
||
409 | protected function getPageFromNsAndTitle($ns, string $title, bool $rawTitle = false) |
||
410 | { |
||
411 | if (0 === (int)$ns) { |
||
412 | return $rawTitle ? $title : $this->validatePage($title); |
||
413 | } |
||
414 | |||
415 | // Prepend namespace and strip out duplicates. |
||
416 | $nsName = $this->project->getNamespaces()[$ns] ?? $this->i18n->msg('unknown'); |
||
417 | $title = $nsName.':'.preg_replace('/^'.$nsName.':/', '', $title); |
||
418 | return $rawTitle ? $title : $this->validatePage($title); |
||
419 | } |
||
420 | |||
421 | /** |
||
422 | * Get a Project instance from the project string, using defaults if the given project string is invalid. |
||
423 | * @return Project |
||
424 | */ |
||
425 | public function getProjectFromQuery(): Project |
||
447 | } |
||
448 | |||
449 | /************************* |
||
450 | * GETTERS / VALIDATIONS * |
||
451 | *************************/ |
||
452 | |||
453 | /** |
||
454 | * Validate the given project, returning a Project if it is valid or false otherwise. |
||
455 | * @param string $projectQuery Project domain or database name. |
||
456 | * @return Project |
||
457 | * @throws XtoolsHttpException |
||
458 | */ |
||
459 | public function validateProject(string $projectQuery): Project |
||
460 | { |
||
461 | $project = $this->projectRepo->getProject($projectQuery); |
||
462 | |||
463 | // Check if it is an explicitly allowed project for the current tool. |
||
464 | if ($this->supportedProjects() && !in_array($project->getDomain(), $this->supportedProjects())) { |
||
465 | $this->throwXtoolsException( |
||
466 | $this->getIndexRoute(), |
||
467 | 'error-authorship-unsupported-project', |
||
468 | [$this->params['project']], |
||
469 | 'project' |
||
470 | ); |
||
471 | } |
||
472 | |||
473 | if (!$project->exists()) { |
||
474 | $this->throwXtoolsException( |
||
475 | $this->getIndexRoute(), |
||
476 | 'invalid-project', |
||
477 | [$this->params['project']], |
||
478 | 'project' |
||
479 | ); |
||
480 | } |
||
481 | |||
482 | return $project; |
||
483 | } |
||
484 | |||
485 | /** |
||
486 | * Validate the given user, returning a User or Redirect if they don't exist. |
||
487 | * @param string $username |
||
488 | * @return User |
||
489 | * @throws XtoolsHttpException |
||
490 | */ |
||
491 | public function validateUser(string $username): User |
||
492 | { |
||
493 | $user = new User($this->userRepo, $username); |
||
494 | |||
495 | // Allow querying for any IP, currently with no edit count limitation... |
||
496 | // Once T188677 is resolved IPs will be affected by the EXPLAIN results. |
||
497 | if ($user->isAnon()) { |
||
498 | // Validate CIDR limits. |
||
499 | if (!$user->isQueryableRange()) { |
||
500 | $limit = $user->isIPv6() ? User::MAX_IPV6_CIDR : User::MAX_IPV4_CIDR; |
||
501 | $this->throwXtoolsException($this->getIndexRoute(), 'ip-range-too-wide', [$limit], 'username'); |
||
502 | } |
||
503 | return $user; |
||
504 | } |
||
505 | |||
506 | $originalParams = $this->params; |
||
507 | |||
508 | // Don't continue if the user doesn't exist. |
||
509 | if (isset($this->project) && !$user->existsOnProject($this->project)) { |
||
510 | $this->throwXtoolsException($this->getIndexRoute(), 'user-not-found', [], 'username'); |
||
511 | } |
||
512 | |||
513 | // Reject users with a crazy high edit count. |
||
514 | if ($this->tooHighEditCountRoute() && |
||
515 | !in_array($this->controllerAction, $this->tooHighEditCountActionAllowlist()) && |
||
516 | $user->hasTooManyEdits($this->project) |
||
517 | ) { |
||
518 | /** TODO: Somehow get this to use self::throwXtoolsException */ |
||
519 | |||
520 | // If redirecting to a different controller, show an informative message accordingly. |
||
521 | if ($this->tooHighEditCountRoute() !== $this->getIndexRoute()) { |
||
522 | // FIXME: This is currently only done for Edit Counter, redirecting to Simple Edit Counter, |
||
523 | // so this bit is hardcoded. We need to instead give the i18n key of the route. |
||
524 | $redirMsg = $this->i18n->msg('too-many-edits-redir', [ |
||
525 | $this->i18n->msg('tool-simpleeditcounter'), |
||
526 | ]); |
||
527 | $msg = $this->i18n->msg('too-many-edits', [ |
||
528 | $this->i18n->numberFormat($user->maxEdits()), |
||
529 | ]).'. '.$redirMsg; |
||
530 | $this->addFlashMessage('danger', $msg); |
||
531 | } else { |
||
532 | $this->addFlashMessage('danger', 'too-many-edits', [ |
||
533 | $this->i18n->numberFormat($user->maxEdits()), |
||
534 | ]); |
||
535 | |||
536 | // Redirecting back to index, so remove username (otherwise we'd get a redirect loop). |
||
537 | unset($this->params['username']); |
||
538 | } |
||
539 | |||
540 | // Clear flash bag for API responses, since they get intercepted in ExceptionListener |
||
541 | // and would otherwise be shown in subsequent requests. |
||
542 | if ($this->isApi) { |
||
543 | $this->get('session')->getFlashBag()->clear(); |
||
544 | } |
||
545 | |||
546 | throw new XtoolsHttpException( |
||
547 | $this->i18n->msg('too-many-edits', [ $user->maxEdits() ]), |
||
548 | $this->generateUrl($this->tooHighEditCountRoute(), $this->params), |
||
549 | $originalParams, |
||
550 | $this->isApi |
||
551 | ); |
||
552 | } |
||
553 | |||
554 | return $user; |
||
555 | } |
||
556 | |||
557 | /** |
||
558 | * Get a Page instance from the given page title, and validate that it exists. |
||
559 | * @param string $pageTitle |
||
560 | * @return Page |
||
561 | * @throws XtoolsHttpException |
||
562 | */ |
||
563 | public function validatePage(string $pageTitle): Page |
||
564 | { |
||
565 | $page = new Page($this->pageRepo, $this->project, $pageTitle); |
||
566 | |||
567 | if (!$page->exists()) { |
||
568 | $this->throwXtoolsException( |
||
569 | $this->getIndexRoute(), |
||
570 | 'no-result', |
||
571 | [$this->params['page'] ?? null], |
||
572 | 'page' |
||
573 | ); |
||
574 | } |
||
575 | |||
576 | return $page; |
||
577 | } |
||
578 | |||
579 | /** |
||
580 | * Throw an XtoolsHttpException, which the given error message and redirects to specified action. |
||
581 | * @param string $redirectAction Name of action to redirect to. |
||
582 | * @param string $message i18n key of error message. Shown in API responses. |
||
583 | * If no message with this key exists, $message is shown as-is. |
||
584 | * @param array $messageParams |
||
585 | * @param string $invalidParam This will be removed from $this->params. Omit if you don't want this to happen. |
||
586 | * @throws XtoolsHttpException |
||
587 | */ |
||
588 | public function throwXtoolsException( |
||
616 | ); |
||
617 | } |
||
618 | |||
619 | /** |
||
620 | * Get the first error message stored in the session's FlashBag. |
||
621 | * @return string |
||
622 | */ |
||
623 | public function getFlashMessage(): string |
||
624 | { |
||
625 | $key = $this->get('session')->getFlashBag()->get('danger')[0]; |
||
626 | $param = null; |
||
627 | |||
628 | if (is_array($key)) { |
||
629 | [$key, $param] = $key; |
||
630 | } |
||
631 | |||
632 | return $this->render('message.twig', [ |
||
633 | 'key' => $key, |
||
634 | 'params' => [$param], |
||
635 | ])->getContent(); |
||
636 | } |
||
637 | |||
638 | /****************** |
||
639 | * PARSING PARAMS * |
||
640 | ******************/ |
||
641 | |||
642 | /** |
||
643 | * Get all standardized parameters from the Request, either via URL query string or routing. |
||
644 | * @return string[] |
||
645 | */ |
||
646 | public function getParams(): array |
||
647 | { |
||
648 | $paramsToCheck = [ |
||
649 | 'project', |
||
650 | 'username', |
||
651 | 'namespace', |
||
652 | 'page', |
||
653 | 'categories', |
||
654 | 'group', |
||
655 | 'redirects', |
||
656 | 'deleted', |
||
657 | 'start', |
||
658 | 'end', |
||
659 | 'offset', |
||
660 | 'limit', |
||
661 | 'format', |
||
662 | 'tool', |
||
663 | 'tools', |
||
664 | 'q', |
||
665 | 'include_pattern', |
||
666 | 'exclude_pattern', |
||
667 | |||
668 | // Legacy parameters. |
||
669 | 'user', |
||
670 | 'name', |
||
671 | 'article', |
||
672 | 'wiki', |
||
673 | 'wikifam', |
||
674 | 'lang', |
||
675 | 'wikilang', |
||
676 | 'begin', |
||
677 | ]; |
||
678 | |||
679 | /** @var string[] $params Each parameter that was detected along with its value. */ |
||
680 | $params = []; |
||
681 | |||
682 | foreach ($paramsToCheck as $param) { |
||
683 | // Pull in either from URL query string or route. |
||
684 | $value = $this->request->query->get($param) ?: $this->request->get($param); |
||
685 | |||
686 | // Only store if value is given ('namespace' or 'username' could be '0'). |
||
687 | if (null !== $value && '' !== $value) { |
||
688 | $params[$param] = rawurldecode((string)$value); |
||
689 | } |
||
690 | } |
||
691 | |||
692 | return $params; |
||
693 | } |
||
694 | |||
695 | /** |
||
696 | * Parse out common parameters from the request. These include the 'project', 'username', 'namespace' and 'page', |
||
697 | * along with their legacy counterparts (e.g. 'lang' and 'wiki'). |
||
698 | * @return string[] Normalized parameters (no legacy params). |
||
699 | */ |
||
700 | public function parseQueryParams(): array |
||
701 | { |
||
702 | /** @var string[] $params Each parameter and value that was detected. */ |
||
703 | $params = $this->getParams(); |
||
704 | |||
705 | // Covert any legacy parameters, if present. |
||
706 | $params = $this->convertLegacyParams($params); |
||
707 | |||
708 | // Remove blank values. |
||
709 | return array_filter($params, function ($param) { |
||
710 | // 'namespace' or 'username' could be '0'. |
||
711 | return null !== $param && '' !== $param; |
||
712 | }); |
||
713 | } |
||
714 | |||
715 | /** |
||
716 | * Get Unix timestamps from given start and end string parameters. This also makes $start $maxDays() before |
||
717 | * $end if not present, and makes $end the current time if not present. |
||
718 | * The date range will not exceed $this->maxDays() days, if this public class property is set. |
||
719 | * @param int|string|false $start Unix timestamp or string accepted by strtotime. |
||
720 | * @param int|string|false $end Unix timestamp or string accepted by strtotime. |
||
721 | * @return int[] Start and end date as UTC timestamps. |
||
722 | */ |
||
723 | public function getUnixFromDateParams($start, $end): array |
||
724 | { |
||
725 | $today = strtotime('today midnight'); |
||
726 | |||
727 | // start time should not be in the future. |
||
728 | $startTime = min( |
||
729 | is_int($start) ? $start : strtotime((string)$start), |
||
730 | $today |
||
731 | ); |
||
732 | |||
733 | // end time defaults to now, and will not be in the future. |
||
734 | $endTime = min( |
||
735 | (is_int($end) ? $end : strtotime((string)$end)) ?: $today, |
||
736 | $today |
||
737 | ); |
||
738 | |||
739 | // Default to $this->defaultDays() or $this->maxDays() before end time if start is not present. |
||
740 | $daysOffset = $this->defaultDays() ?? $this->maxDays(); |
||
741 | if (false === $startTime && $daysOffset) { |
||
742 | $startTime = strtotime("-$daysOffset days", $endTime); |
||
743 | } |
||
744 | |||
745 | // Default to $this->defaultDays() or $this->maxDays() after start time if end is not present. |
||
746 | if (false === $end && $daysOffset) { |
||
747 | $endTime = min( |
||
748 | strtotime("+$daysOffset days", $startTime), |
||
749 | $today |
||
750 | ); |
||
751 | } |
||
752 | |||
753 | // Reverse if start date is after end date. |
||
754 | if ($startTime > $endTime && false !== $startTime && false !== $end) { |
||
755 | $newEndTime = $startTime; |
||
756 | $startTime = $endTime; |
||
757 | $endTime = $newEndTime; |
||
758 | } |
||
759 | |||
760 | // Finally, don't let the date range exceed $this->maxDays(). |
||
761 | $startObj = DateTime::createFromFormat('U', (string)$startTime); |
||
762 | $endObj = DateTime::createFromFormat('U', (string)$endTime); |
||
763 | if ($this->maxDays() && $startObj->diff($endObj)->days > $this->maxDays()) { |
||
764 | // Show warnings that the date range was truncated. |
||
765 | $this->addFlashMessage('warning', 'date-range-too-wide', [$this->maxDays()]); |
||
766 | |||
767 | $startTime = strtotime('-' . $this->maxDays() . ' days', $endTime); |
||
768 | } |
||
769 | |||
770 | return [$startTime, $endTime]; |
||
771 | } |
||
772 | |||
773 | /** |
||
774 | * Given the params hash, normalize any legacy parameters to their modern equivalent. |
||
775 | * @param string[] $params |
||
776 | * @return string[] |
||
777 | */ |
||
778 | private function convertLegacyParams(array $params): array |
||
779 | { |
||
780 | $paramMap = [ |
||
781 | 'user' => 'username', |
||
782 | 'name' => 'username', |
||
783 | 'article' => 'page', |
||
784 | 'begin' => 'start', |
||
785 | |||
786 | // Copy super legacy project params to legacy so we can concatenate below. |
||
787 | 'wikifam' => 'wiki', |
||
788 | 'wikilang' => 'lang', |
||
789 | ]; |
||
790 | |||
791 | // Copy legacy parameters to modern equivalent. |
||
792 | foreach ($paramMap as $legacy => $modern) { |
||
793 | if (isset($params[$legacy])) { |
||
794 | $params[$modern] = $params[$legacy]; |
||
795 | unset($params[$legacy]); |
||
796 | } |
||
797 | } |
||
798 | |||
799 | // Separate parameters for language and wiki. |
||
800 | if (isset($params['wiki']) && isset($params['lang'])) { |
||
801 | // 'wikifam' will be like '.wikipedia.org', vs just 'wikipedia', |
||
802 | // so we must remove leading periods and trailing .org's. |
||
803 | $params['project'] = rtrim(ltrim($params['wiki'], '.'), '.org').'.org'; |
||
804 | |||
805 | /** @var string[] $multilingualProjects Projects for which there is no specific language association. */ |
||
806 | $multilingualProjects = $this->getParameter('app.multilingual_wikis'); |
||
807 | |||
808 | // Prepend language if applicable. |
||
809 | if (isset($params['lang']) && !in_array($params['wiki'], $multilingualProjects)) { |
||
810 | $params['project'] = $params['lang'].'.'.$params['project']; |
||
811 | } |
||
812 | |||
813 | unset($params['wiki']); |
||
814 | unset($params['lang']); |
||
815 | } |
||
816 | |||
817 | return $params; |
||
818 | } |
||
819 | |||
820 | /************************ |
||
821 | * FORMATTING RESPONSES * |
||
822 | ************************/ |
||
823 | |||
824 | /** |
||
825 | * Get the rendered template for the requested format. This method also updates the cookies. |
||
826 | * @param string $templatePath Path to template without format, |
||
827 | * such as '/editCounter/latest_global'. |
||
828 | * @param array $ret Data that should be passed to the view. |
||
829 | * @return Response |
||
830 | * @codeCoverageIgnore |
||
831 | */ |
||
832 | public function getFormattedResponse(string $templatePath, array $ret): Response |
||
833 | { |
||
834 | $format = $this->request->query->get('format', 'html'); |
||
835 | if ('' == $format) { |
||
836 | // The default above doesn't work when the 'format' parameter is blank. |
||
837 | $format = 'html'; |
||
838 | } |
||
839 | |||
840 | // Merge in common default parameters, giving $ret (from the caller) the priority. |
||
841 | $ret = array_merge([ |
||
842 | 'project' => $this->project, |
||
843 | 'user' => $this->user, |
||
844 | 'page' => $this->page ?? null, |
||
845 | 'namespace' => $this->namespace, |
||
846 | 'start' => $this->start, |
||
847 | 'end' => $this->end, |
||
848 | ], $ret); |
||
849 | |||
850 | $formatMap = [ |
||
851 | 'wikitext' => 'text/plain', |
||
852 | 'csv' => 'text/csv', |
||
853 | 'tsv' => 'text/tab-separated-values', |
||
854 | 'json' => 'application/json', |
||
855 | ]; |
||
856 | |||
857 | $response = new Response(); |
||
858 | |||
859 | // Set cookies. Note this must be done before rendering the view, as the view may invoke subrequests. |
||
860 | $this->setCookies($response); |
||
861 | |||
862 | // If requested format does not exist, assume HTML. |
||
863 | if (false === $this->get('twig')->getLoader()->exists("$templatePath.$format.twig")) { |
||
864 | $format = 'html'; |
||
865 | } |
||
866 | |||
867 | $response = $this->render("$templatePath.$format.twig", $ret, $response); |
||
868 | |||
869 | $contentType = $formatMap[$format] ?? 'text/html'; |
||
870 | $response->headers->set('Content-Type', $contentType); |
||
871 | |||
872 | if (in_array($format, ['csv', 'tsv'])) { |
||
873 | $filename = $this->getFilenameForRequest(); |
||
874 | $response->headers->set( |
||
875 | 'Content-Disposition', |
||
876 | "attachment; filename=\"{$filename}.$format\"" |
||
877 | ); |
||
878 | } |
||
879 | |||
880 | return $response; |
||
881 | } |
||
882 | |||
883 | /** |
||
884 | * Returns given filename from the current Request, with problematic characters filtered out. |
||
885 | * @return string |
||
886 | */ |
||
887 | private function getFilenameForRequest(): string |
||
888 | { |
||
889 | $filename = trim($this->request->getPathInfo(), '/'); |
||
890 | return trim(preg_replace('/[-\/\\:;*?|<>%#"]+/', '-', $filename)); |
||
891 | } |
||
892 | |||
893 | /** |
||
894 | * Return a JsonResponse object pre-supplied with the requested params. |
||
895 | * @param array $data |
||
896 | * @return JsonResponse |
||
897 | */ |
||
898 | public function getFormattedApiResponse(array $data): JsonResponse |
||
899 | { |
||
900 | $response = new JsonResponse(); |
||
901 | $response->setEncodingOptions(JSON_NUMERIC_CHECK); |
||
902 | $response->setStatusCode(Response::HTTP_OK); |
||
903 | |||
904 | // Normalize display of IP ranges (they are prefixed with 'ipr-' in the params). |
||
905 | if ($this->user && $this->user->isIpRange()) { |
||
906 | $this->params['username'] = $this->user->getUsername(); |
||
907 | } |
||
908 | |||
909 | $elapsedTime = round( |
||
910 | microtime(true) - $this->request->server->get('REQUEST_TIME_FLOAT'), |
||
911 | 3 |
||
912 | ); |
||
913 | |||
914 | // Any pipe-separated values should be returned as an array. |
||
915 | foreach ($this->params as $param => $value) { |
||
916 | if (is_string($value) && false !== strpos($value, '|')) { |
||
917 | $this->params[$param] = explode('|', $value); |
||
918 | } |
||
919 | } |
||
920 | |||
921 | $ret = array_merge($this->params, [ |
||
922 | // In some controllers, $this->params['project'] may be overridden with a Project object. |
||
923 | 'project' => $this->project->getDomain(), |
||
924 | ], $data, ['elapsed_time' => $elapsedTime]); |
||
925 | |||
926 | // Merge in flash messages, putting them at the top. |
||
927 | $flashes = $this->get('session')->getFlashBag()->peekAll(); |
||
928 | $ret = array_merge($flashes, $ret); |
||
929 | |||
930 | // Flashes now can be cleared after merging into the response. |
||
931 | $this->get('session')->getFlashBag()->clear(); |
||
932 | |||
933 | $response->setData($ret); |
||
934 | |||
935 | return $response; |
||
936 | } |
||
937 | |||
938 | /** |
||
939 | * Used to standardized the format of API responses that contain revisions. |
||
940 | * Adds a 'full_page_title' key and value to each entry in $data. |
||
941 | * If there are as many entries in $data as there are $this->limit, pagination is assumed |
||
942 | * and a 'continue' key is added to the end of the response body. |
||
943 | * @param string $key Key accessing the list of revisions in $data. |
||
944 | * @param array $out Whatever data needs to appear above the $data in the response body. |
||
945 | * @param array $data The data set itself. |
||
946 | * @return array |
||
947 | */ |
||
948 | public function addFullPageTitlesAndContinue(string $key, array $out, array $data): array |
||
970 | } |
||
971 | |||
972 | /********* |
||
973 | * OTHER * |
||
974 | *********/ |
||
975 | |||
976 | /** |
||
977 | * Record usage of an API endpoint. |
||
978 | * @param string $endpoint |
||
979 | * @codeCoverageIgnore |
||
980 | */ |
||
981 | public function recordApiUsage(string $endpoint): void |
||
999 | // Do nothing. API response should still be returned rather than erroring out. |
||
1000 | } |
||
1001 | } |
||
1002 | |||
1003 | /** |
||
1004 | * Add a flash message. |
||
1005 | * @param string $type |
||
1006 | * @param string $key i18n key or raw message. |
||
1007 | * @param array $vars |
||
1008 | */ |
||
1009 | public function addFlashMessage(string $type, string $key, array $vars = []): void |
||
1014 | ); |
||
1015 | } |
||
1016 | } |
||
1017 |