RCFilters: Preserve collapsed state and adjust display
[lhc/web/wiklou.git] / includes / specialpage / ChangesListSpecialPage.php
1 <?php
2 /**
3 * Special page which uses a ChangesList to show query results.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23 use MediaWiki\Logger\LoggerFactory;
24 use Wikimedia\Rdbms\DBQueryTimeoutError;
25 use Wikimedia\Rdbms\IResultWrapper;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27 use Wikimedia\Rdbms\IDatabase;
28
29 /**
30 * Special page which uses a ChangesList to show query results.
31 * @todo Way too many public functions, most of them should be protected
32 *
33 * @ingroup SpecialPage
34 */
35 abstract class ChangesListSpecialPage extends SpecialPage {
36 /**
37 * Maximum length of a tag description in UTF-8 characters.
38 * Longer descriptions will be truncated.
39 */
40 const TAG_DESC_CHARACTER_LIMIT = 120;
41
42 /**
43 * Preference name for saved queries. Subclasses that use saved queries should override this.
44 * @var string
45 */
46 protected static $savedQueriesPreferenceName;
47
48 /**
49 * Preference name for 'days'. Subclasses should override this.
50 * @var string
51 */
52 protected static $daysPreferenceName;
53
54 /**
55 * Preference name for 'limit'. Subclasses should override this.
56 * @var string
57 */
58 protected static $limitPreferenceName;
59
60 /**
61 * Preference name for collapsing the active filter display. Subclasses should override this.
62 * @var string
63 */
64 protected static $collapsedPreferenceName;
65
66 /** @var string */
67 protected $rcSubpage;
68
69 /** @var FormOptions */
70 protected $rcOptions;
71
72 /** @var array */
73 protected $customFilters;
74
75 // Order of both groups and filters is significant; first is top-most priority,
76 // descending from there.
77 // 'showHideSuffix' is a shortcut to and avoid spelling out
78 // details specific to subclasses here.
79 /**
80 * Definition information for the filters and their groups
81 *
82 * The value is $groupDefinition, a parameter to the ChangesListFilterGroup constructor.
83 * However, priority is dynamically added for the core groups, to ease maintenance.
84 *
85 * Groups are displayed to the user in the structured UI. However, if necessary,
86 * all of the filters in a group can be configured to only display on the
87 * unstuctured UI, in which case you don't need a group title. This is done in
88 * getFilterGroupDefinitionFromLegacyCustomFilters, for example.
89 *
90 * @var array $filterGroupDefinitions
91 */
92 private $filterGroupDefinitions;
93
94 // Same format as filterGroupDefinitions, but for a single group (reviewStatus)
95 // that is registered conditionally.
96 private $legacyReviewStatusFilterGroupDefinition;
97
98 // Single filter group registered conditionally
99 private $reviewStatusFilterGroupDefinition;
100
101 // Single filter group registered conditionally
102 private $hideCategorizationFilterDefinition;
103
104 /**
105 * Filter groups, and their contained filters
106 * This is an associative array (with group name as key) of ChangesListFilterGroup objects.
107 *
108 * @var array $filterGroups
109 */
110 protected $filterGroups = [];
111
112 public function __construct( $name, $restriction ) {
113 parent::__construct( $name, $restriction );
114
115 $nonRevisionTypes = [ RC_LOG ];
116 Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', [ &$nonRevisionTypes ] );
117
118 $this->filterGroupDefinitions = [
119 [
120 'name' => 'registration',
121 'title' => 'rcfilters-filtergroup-registration',
122 'class' => ChangesListBooleanFilterGroup::class,
123 'filters' => [
124 [
125 'name' => 'hideliu',
126 // rcshowhideliu-show, rcshowhideliu-hide,
127 // wlshowhideliu
128 'showHideSuffix' => 'showhideliu',
129 'default' => false,
130 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
131 &$query_options, &$join_conds
132 ) {
133 $actorMigration = ActorMigration::newMigration();
134 $actorQuery = $actorMigration->getJoin( 'rc_user' );
135 $tables += $actorQuery['tables'];
136 $join_conds += $actorQuery['joins'];
137 $conds[] = $actorMigration->isAnon( $actorQuery['fields']['rc_user'] );
138 },
139 'isReplacedInStructuredUi' => true,
140
141 ],
142 [
143 'name' => 'hideanons',
144 // rcshowhideanons-show, rcshowhideanons-hide,
145 // wlshowhideanons
146 'showHideSuffix' => 'showhideanons',
147 'default' => false,
148 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
149 &$query_options, &$join_conds
150 ) {
151 $actorMigration = ActorMigration::newMigration();
152 $actorQuery = $actorMigration->getJoin( 'rc_user' );
153 $tables += $actorQuery['tables'];
154 $join_conds += $actorQuery['joins'];
155 $conds[] = $actorMigration->isNotAnon( $actorQuery['fields']['rc_user'] );
156 },
157 'isReplacedInStructuredUi' => true,
158 ]
159 ],
160 ],
161
162 [
163 'name' => 'userExpLevel',
164 'title' => 'rcfilters-filtergroup-userExpLevel',
165 'class' => ChangesListStringOptionsFilterGroup::class,
166 'isFullCoverage' => true,
167 'filters' => [
168 [
169 'name' => 'unregistered',
170 'label' => 'rcfilters-filter-user-experience-level-unregistered-label',
171 'description' => 'rcfilters-filter-user-experience-level-unregistered-description',
172 'cssClassSuffix' => 'user-unregistered',
173 'isRowApplicableCallable' => function ( $ctx, $rc ) {
174 return !$rc->getAttribute( 'rc_user' );
175 }
176 ],
177 [
178 'name' => 'registered',
179 'label' => 'rcfilters-filter-user-experience-level-registered-label',
180 'description' => 'rcfilters-filter-user-experience-level-registered-description',
181 'cssClassSuffix' => 'user-registered',
182 'isRowApplicableCallable' => function ( $ctx, $rc ) {
183 return $rc->getAttribute( 'rc_user' );
184 }
185 ],
186 [
187 'name' => 'newcomer',
188 'label' => 'rcfilters-filter-user-experience-level-newcomer-label',
189 'description' => 'rcfilters-filter-user-experience-level-newcomer-description',
190 'cssClassSuffix' => 'user-newcomer',
191 'isRowApplicableCallable' => function ( $ctx, $rc ) {
192 $performer = $rc->getPerformer();
193 return $performer && $performer->isLoggedIn() &&
194 $performer->getExperienceLevel() === 'newcomer';
195 }
196 ],
197 [
198 'name' => 'learner',
199 'label' => 'rcfilters-filter-user-experience-level-learner-label',
200 'description' => 'rcfilters-filter-user-experience-level-learner-description',
201 'cssClassSuffix' => 'user-learner',
202 'isRowApplicableCallable' => function ( $ctx, $rc ) {
203 $performer = $rc->getPerformer();
204 return $performer && $performer->isLoggedIn() &&
205 $performer->getExperienceLevel() === 'learner';
206 },
207 ],
208 [
209 'name' => 'experienced',
210 'label' => 'rcfilters-filter-user-experience-level-experienced-label',
211 'description' => 'rcfilters-filter-user-experience-level-experienced-description',
212 'cssClassSuffix' => 'user-experienced',
213 'isRowApplicableCallable' => function ( $ctx, $rc ) {
214 $performer = $rc->getPerformer();
215 return $performer && $performer->isLoggedIn() &&
216 $performer->getExperienceLevel() === 'experienced';
217 },
218 ]
219 ],
220 'default' => ChangesListStringOptionsFilterGroup::NONE,
221 'queryCallable' => [ $this, 'filterOnUserExperienceLevel' ],
222 ],
223
224 [
225 'name' => 'authorship',
226 'title' => 'rcfilters-filtergroup-authorship',
227 'class' => ChangesListBooleanFilterGroup::class,
228 'filters' => [
229 [
230 'name' => 'hidemyself',
231 'label' => 'rcfilters-filter-editsbyself-label',
232 'description' => 'rcfilters-filter-editsbyself-description',
233 // rcshowhidemine-show, rcshowhidemine-hide,
234 // wlshowhidemine
235 'showHideSuffix' => 'showhidemine',
236 'default' => false,
237 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
238 &$query_options, &$join_conds
239 ) {
240 $actorQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $ctx->getUser() );
241 $tables += $actorQuery['tables'];
242 $join_conds += $actorQuery['joins'];
243 $conds[] = 'NOT(' . $actorQuery['conds'] . ')';
244 },
245 'cssClassSuffix' => 'self',
246 'isRowApplicableCallable' => function ( $ctx, $rc ) {
247 return $ctx->getUser()->equals( $rc->getPerformer() );
248 },
249 ],
250 [
251 'name' => 'hidebyothers',
252 'label' => 'rcfilters-filter-editsbyother-label',
253 'description' => 'rcfilters-filter-editsbyother-description',
254 'default' => false,
255 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
256 &$query_options, &$join_conds
257 ) {
258 $actorQuery = ActorMigration::newMigration()
259 ->getWhere( $dbr, 'rc_user', $ctx->getUser(), false );
260 $tables += $actorQuery['tables'];
261 $join_conds += $actorQuery['joins'];
262 $conds[] = $actorQuery['conds'];
263 },
264 'cssClassSuffix' => 'others',
265 'isRowApplicableCallable' => function ( $ctx, $rc ) {
266 return !$ctx->getUser()->equals( $rc->getPerformer() );
267 },
268 ]
269 ]
270 ],
271
272 [
273 'name' => 'automated',
274 'title' => 'rcfilters-filtergroup-automated',
275 'class' => ChangesListBooleanFilterGroup::class,
276 'filters' => [
277 [
278 'name' => 'hidebots',
279 'label' => 'rcfilters-filter-bots-label',
280 'description' => 'rcfilters-filter-bots-description',
281 // rcshowhidebots-show, rcshowhidebots-hide,
282 // wlshowhidebots
283 'showHideSuffix' => 'showhidebots',
284 'default' => false,
285 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
286 &$query_options, &$join_conds
287 ) {
288 $conds['rc_bot'] = 0;
289 },
290 'cssClassSuffix' => 'bot',
291 'isRowApplicableCallable' => function ( $ctx, $rc ) {
292 return $rc->getAttribute( 'rc_bot' );
293 },
294 ],
295 [
296 'name' => 'hidehumans',
297 'label' => 'rcfilters-filter-humans-label',
298 'description' => 'rcfilters-filter-humans-description',
299 'default' => false,
300 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
301 &$query_options, &$join_conds
302 ) {
303 $conds['rc_bot'] = 1;
304 },
305 'cssClassSuffix' => 'human',
306 'isRowApplicableCallable' => function ( $ctx, $rc ) {
307 return !$rc->getAttribute( 'rc_bot' );
308 },
309 ]
310 ]
311 ],
312
313 // significance (conditional)
314
315 [
316 'name' => 'significance',
317 'title' => 'rcfilters-filtergroup-significance',
318 'class' => ChangesListBooleanFilterGroup::class,
319 'priority' => -6,
320 'filters' => [
321 [
322 'name' => 'hideminor',
323 'label' => 'rcfilters-filter-minor-label',
324 'description' => 'rcfilters-filter-minor-description',
325 // rcshowhideminor-show, rcshowhideminor-hide,
326 // wlshowhideminor
327 'showHideSuffix' => 'showhideminor',
328 'default' => false,
329 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
330 &$query_options, &$join_conds
331 ) {
332 $conds[] = 'rc_minor = 0';
333 },
334 'cssClassSuffix' => 'minor',
335 'isRowApplicableCallable' => function ( $ctx, $rc ) {
336 return $rc->getAttribute( 'rc_minor' );
337 }
338 ],
339 [
340 'name' => 'hidemajor',
341 'label' => 'rcfilters-filter-major-label',
342 'description' => 'rcfilters-filter-major-description',
343 'default' => false,
344 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
345 &$query_options, &$join_conds
346 ) {
347 $conds[] = 'rc_minor = 1';
348 },
349 'cssClassSuffix' => 'major',
350 'isRowApplicableCallable' => function ( $ctx, $rc ) {
351 return !$rc->getAttribute( 'rc_minor' );
352 }
353 ]
354 ]
355 ],
356
357 [
358 'name' => 'lastRevision',
359 'title' => 'rcfilters-filtergroup-lastRevision',
360 'class' => ChangesListBooleanFilterGroup::class,
361 'priority' => -7,
362 'filters' => [
363 [
364 'name' => 'hidelastrevision',
365 'label' => 'rcfilters-filter-lastrevision-label',
366 'description' => 'rcfilters-filter-lastrevision-description',
367 'default' => false,
368 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
369 &$query_options, &$join_conds ) use ( $nonRevisionTypes ) {
370 $conds[] = $dbr->makeList(
371 [
372 'rc_this_oldid <> page_latest',
373 'rc_type' => $nonRevisionTypes,
374 ],
375 LIST_OR
376 );
377 },
378 'cssClassSuffix' => 'last',
379 'isRowApplicableCallable' => function ( $ctx, $rc ) {
380 return $rc->getAttribute( 'rc_this_oldid' ) === $rc->getAttribute( 'page_latest' );
381 }
382 ],
383 [
384 'name' => 'hidepreviousrevisions',
385 'label' => 'rcfilters-filter-previousrevision-label',
386 'description' => 'rcfilters-filter-previousrevision-description',
387 'default' => false,
388 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
389 &$query_options, &$join_conds ) use ( $nonRevisionTypes ) {
390 $conds[] = $dbr->makeList(
391 [
392 'rc_this_oldid = page_latest',
393 'rc_type' => $nonRevisionTypes,
394 ],
395 LIST_OR
396 );
397 },
398 'cssClassSuffix' => 'previous',
399 'isRowApplicableCallable' => function ( $ctx, $rc ) {
400 return $rc->getAttribute( 'rc_this_oldid' ) !== $rc->getAttribute( 'page_latest' );
401 }
402 ]
403 ]
404 ],
405
406 // With extensions, there can be change types that will not be hidden by any of these.
407 [
408 'name' => 'changeType',
409 'title' => 'rcfilters-filtergroup-changetype',
410 'class' => ChangesListBooleanFilterGroup::class,
411 'priority' => -8,
412 'filters' => [
413 [
414 'name' => 'hidepageedits',
415 'label' => 'rcfilters-filter-pageedits-label',
416 'description' => 'rcfilters-filter-pageedits-description',
417 'default' => false,
418 'priority' => -2,
419 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
420 &$query_options, &$join_conds
421 ) {
422 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_EDIT );
423 },
424 'cssClassSuffix' => 'src-mw-edit',
425 'isRowApplicableCallable' => function ( $ctx, $rc ) {
426 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_EDIT;
427 },
428 ],
429 [
430 'name' => 'hidenewpages',
431 'label' => 'rcfilters-filter-newpages-label',
432 'description' => 'rcfilters-filter-newpages-description',
433 'default' => false,
434 'priority' => -3,
435 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
436 &$query_options, &$join_conds
437 ) {
438 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_NEW );
439 },
440 'cssClassSuffix' => 'src-mw-new',
441 'isRowApplicableCallable' => function ( $ctx, $rc ) {
442 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_NEW;
443 },
444 ],
445
446 // hidecategorization
447
448 [
449 'name' => 'hidelog',
450 'label' => 'rcfilters-filter-logactions-label',
451 'description' => 'rcfilters-filter-logactions-description',
452 'default' => false,
453 'priority' => -5,
454 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
455 &$query_options, &$join_conds
456 ) {
457 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_LOG );
458 },
459 'cssClassSuffix' => 'src-mw-log',
460 'isRowApplicableCallable' => function ( $ctx, $rc ) {
461 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_LOG;
462 }
463 ],
464 ],
465 ],
466
467 ];
468
469 $this->legacyReviewStatusFilterGroupDefinition = [
470 [
471 'name' => 'legacyReviewStatus',
472 'title' => 'rcfilters-filtergroup-reviewstatus',
473 'class' => ChangesListBooleanFilterGroup::class,
474 'filters' => [
475 [
476 'name' => 'hidepatrolled',
477 // rcshowhidepatr-show, rcshowhidepatr-hide
478 // wlshowhidepatr
479 'showHideSuffix' => 'showhidepatr',
480 'default' => false,
481 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
482 &$query_options, &$join_conds
483 ) {
484 $conds['rc_patrolled'] = RecentChange::PRC_UNPATROLLED;
485 },
486 'isReplacedInStructuredUi' => true,
487 ],
488 [
489 'name' => 'hideunpatrolled',
490 'default' => false,
491 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
492 &$query_options, &$join_conds
493 ) {
494 $conds[] = 'rc_patrolled != ' . RecentChange::PRC_UNPATROLLED;
495 },
496 'isReplacedInStructuredUi' => true,
497 ],
498 ],
499 ]
500 ];
501
502 $this->reviewStatusFilterGroupDefinition = [
503 [
504 'name' => 'reviewStatus',
505 'title' => 'rcfilters-filtergroup-reviewstatus',
506 'class' => ChangesListStringOptionsFilterGroup::class,
507 'isFullCoverage' => true,
508 'priority' => -5,
509 'filters' => [
510 [
511 'name' => 'unpatrolled',
512 'label' => 'rcfilters-filter-reviewstatus-unpatrolled-label',
513 'description' => 'rcfilters-filter-reviewstatus-unpatrolled-description',
514 'cssClassSuffix' => 'reviewstatus-unpatrolled',
515 'isRowApplicableCallable' => function ( $ctx, $rc ) {
516 return $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_UNPATROLLED;
517 },
518 ],
519 [
520 'name' => 'manual',
521 'label' => 'rcfilters-filter-reviewstatus-manual-label',
522 'description' => 'rcfilters-filter-reviewstatus-manual-description',
523 'cssClassSuffix' => 'reviewstatus-manual',
524 'isRowApplicableCallable' => function ( $ctx, $rc ) {
525 return $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_PATROLLED;
526 },
527 ],
528 [
529 'name' => 'auto',
530 'label' => 'rcfilters-filter-reviewstatus-auto-label',
531 'description' => 'rcfilters-filter-reviewstatus-auto-description',
532 'cssClassSuffix' => 'reviewstatus-auto',
533 'isRowApplicableCallable' => function ( $ctx, $rc ) {
534 return $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_AUTOPATROLLED;
535 },
536 ],
537 ],
538 'default' => ChangesListStringOptionsFilterGroup::NONE,
539 'queryCallable' => function ( $specialPageClassName, $ctx, $dbr,
540 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selected
541 ) {
542 if ( $selected === [] ) {
543 return;
544 }
545 $rcPatrolledValues = [
546 'unpatrolled' => RecentChange::PRC_UNPATROLLED,
547 'manual' => RecentChange::PRC_PATROLLED,
548 'auto' => RecentChange::PRC_AUTOPATROLLED,
549 ];
550 // e.g. rc_patrolled IN (0, 2)
551 $conds['rc_patrolled'] = array_map( function ( $s ) use ( $rcPatrolledValues ) {
552 return $rcPatrolledValues[ $s ];
553 }, $selected );
554 }
555 ]
556 ];
557
558 $this->hideCategorizationFilterDefinition = [
559 'name' => 'hidecategorization',
560 'label' => 'rcfilters-filter-categorization-label',
561 'description' => 'rcfilters-filter-categorization-description',
562 // rcshowhidecategorization-show, rcshowhidecategorization-hide.
563 // wlshowhidecategorization
564 'showHideSuffix' => 'showhidecategorization',
565 'default' => false,
566 'priority' => -4,
567 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
568 &$query_options, &$join_conds
569 ) {
570 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_CATEGORIZE );
571 },
572 'cssClassSuffix' => 'src-mw-categorize',
573 'isRowApplicableCallable' => function ( $ctx, $rc ) {
574 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_CATEGORIZE;
575 },
576 ];
577 }
578
579 /**
580 * Check if filters are in conflict and guaranteed to return no results.
581 *
582 * @return bool
583 */
584 protected function areFiltersInConflict() {
585 $opts = $this->getOptions();
586 /** @var ChangesListFilterGroup $group */
587 foreach ( $this->getFilterGroups() as $group ) {
588 if ( $group->getConflictingGroups() ) {
589 wfLogWarning(
590 $group->getName() .
591 " specifies conflicts with other groups but these are not supported yet."
592 );
593 }
594
595 /** @var ChangesListFilter $conflictingFilter */
596 foreach ( $group->getConflictingFilters() as $conflictingFilter ) {
597 if ( $conflictingFilter->activelyInConflictWithGroup( $group, $opts ) ) {
598 return true;
599 }
600 }
601
602 /** @var ChangesListFilter $filter */
603 foreach ( $group->getFilters() as $filter ) {
604 /** @var ChangesListFilter $conflictingFilter */
605 foreach ( $filter->getConflictingFilters() as $conflictingFilter ) {
606 if (
607 $conflictingFilter->activelyInConflictWithFilter( $filter, $opts ) &&
608 $filter->activelyInConflictWithFilter( $conflictingFilter, $opts )
609 ) {
610 return true;
611 }
612 }
613
614 }
615
616 }
617
618 return false;
619 }
620
621 /**
622 * Main execution point
623 *
624 * @param string $subpage
625 */
626 public function execute( $subpage ) {
627 $this->rcSubpage = $subpage;
628
629 $this->considerActionsForDefaultSavedQuery( $subpage );
630
631 $opts = $this->getOptions();
632 try {
633 $rows = $this->getRows();
634 if ( $rows === false ) {
635 $rows = new FakeResultWrapper( [] );
636 }
637
638 // Used by Structured UI app to get results without MW chrome
639 if ( $this->getRequest()->getVal( 'action' ) === 'render' ) {
640 $this->getOutput()->setArticleBodyOnly( true );
641 }
642
643 // Used by "live update" and "view newest" to check
644 // if there's new changes with minimal data transfer
645 if ( $this->getRequest()->getBool( 'peek' ) ) {
646 $code = $rows->numRows() > 0 ? 200 : 204;
647 $this->getOutput()->setStatusCode( $code );
648
649 if ( $this->getUser()->isAnon() !==
650 $this->getRequest()->getFuzzyBool( 'isAnon' )
651 ) {
652 $this->getOutput()->setStatusCode( 205 );
653 }
654
655 return;
656 }
657
658 $batch = new LinkBatch;
659 foreach ( $rows as $row ) {
660 $batch->add( NS_USER, $row->rc_user_text );
661 $batch->add( NS_USER_TALK, $row->rc_user_text );
662 $batch->add( $row->rc_namespace, $row->rc_title );
663 if ( $row->rc_source === RecentChange::SRC_LOG ) {
664 $formatter = LogFormatter::newFromRow( $row );
665 foreach ( $formatter->getPreloadTitles() as $title ) {
666 $batch->addObj( $title );
667 }
668 }
669 }
670 $batch->execute();
671
672 $this->setHeaders();
673 $this->outputHeader();
674 $this->addModules();
675 $this->webOutput( $rows, $opts );
676
677 $rows->free();
678 } catch ( DBQueryTimeoutError $timeoutException ) {
679 MWExceptionHandler::logException( $timeoutException );
680
681 $this->setHeaders();
682 $this->outputHeader();
683 $this->addModules();
684
685 $this->getOutput()->setStatusCode( 500 );
686 $this->webOutputHeader( 0, $opts );
687 $this->outputTimeout();
688 }
689
690 if ( $this->getConfig()->get( 'EnableWANCacheReaper' ) ) {
691 // Clean up any bad page entries for titles showing up in RC
692 DeferredUpdates::addUpdate( new WANCacheReapUpdate(
693 $this->getDB(),
694 LoggerFactory::getInstance( 'objectcache' )
695 ) );
696 }
697
698 $this->includeRcFiltersApp();
699 }
700
701 /**
702 * Check whether or not the page should load defaults, and if so, whether
703 * a default saved query is relevant to be redirected to. If it is relevant,
704 * redirect properly with all necessary query parameters.
705 *
706 * @param string $subpage
707 */
708 protected function considerActionsForDefaultSavedQuery( $subpage ) {
709 if ( !$this->isStructuredFilterUiEnabled() || $this->including() ) {
710 return;
711 }
712
713 $knownParams = $this->getRequest()->getValues(
714 ...array_keys( $this->getOptions()->getAllValues() )
715 );
716
717 // HACK: Temporarily until we can properly define "sticky" filters and parameters,
718 // we need to exclude several parameters we know should not be counted towards preventing
719 // the loading of defaults.
720 $excludedParams = [ 'limit' => '', 'days' => '', 'enhanced' => '', 'from' => '' ];
721 $knownParams = array_diff_key( $knownParams, $excludedParams );
722
723 if (
724 // If there are NO known parameters in the URL request
725 // (that are not excluded) then we need to check into loading
726 // the default saved query
727 count( $knownParams ) === 0
728 ) {
729 // Get the saved queries data and parse it
730 $savedQueries = FormatJson::decode(
731 $this->getUser()->getOption( static::$savedQueriesPreferenceName ),
732 true
733 );
734
735 if ( $savedQueries && isset( $savedQueries[ 'default' ] ) ) {
736 // Only load queries that are 'version' 2, since those
737 // have parameter representation
738 if ( isset( $savedQueries[ 'version' ] ) && $savedQueries[ 'version' ] === '2' ) {
739 $savedQueryDefaultID = $savedQueries[ 'default' ];
740 $defaultQuery = $savedQueries[ 'queries' ][ $savedQueryDefaultID ][ 'data' ];
741
742 // Build the entire parameter list
743 $query = array_merge(
744 $defaultQuery[ 'params' ],
745 $defaultQuery[ 'highlights' ],
746 [
747 'urlversion' => '2',
748 ]
749 );
750 // Add to the query any parameters that we may have ignored before
751 // but are still valid and requested in the URL
752 $query = array_merge( $this->getRequest()->getValues(), $query );
753 unset( $query[ 'title' ] );
754 $this->getOutput()->redirect( $this->getPageTitle( $subpage )->getCanonicalURL( $query ) );
755 } else {
756 // There's a default, but the version is not 2, and the server can't
757 // actually recognize the query itself. This happens if it is before
758 // the conversion, so we need to tell the UI to reload saved query as
759 // it does the conversion to version 2
760 $this->getOutput()->addJsConfigVars(
761 'wgStructuredChangeFiltersDefaultSavedQueryExists',
762 true
763 );
764
765 // Add the class that tells the frontend it is still loading
766 // another query
767 $this->getOutput()->addBodyClasses( 'mw-rcfilters-ui-loading' );
768 }
769 }
770 }
771 }
772
773 /**
774 * Include the modules and configuration for the RCFilters app.
775 * Conditional on the user having the feature enabled.
776 *
777 * If it is disabled, add a <body> class marking that
778 */
779 protected function includeRcFiltersApp() {
780 $out = $this->getOutput();
781 if ( $this->isStructuredFilterUiEnabled() && !$this->including() ) {
782 $jsData = $this->getStructuredFilterJsData();
783
784 $messages = [];
785 foreach ( $jsData['messageKeys'] as $key ) {
786 $messages[$key] = $this->msg( $key )->plain();
787 }
788 $out->addBodyClasses( 'mw-rcfilters-enabled' );
789
790 $collapsed = $this->getUser()->getBoolOption( static::$collapsedPreferenceName );
791 if ( $collapsed ) {
792 $out->addBodyClasses( 'mw-rcfilters-collapsed' );
793 }
794
795 $out->addHTML(
796 ResourceLoader::makeInlineScript(
797 ResourceLoader::makeMessageSetScript( $messages ),
798 $out->getCSPNonce()
799 )
800 );
801
802 $out->addJsConfigVars( 'wgStructuredChangeFilters', $jsData['groups'] );
803 $out->addJsConfigVars( 'wgStructuredChangeFiltersCollapsedState', $collapsed );
804
805 $out->addJsConfigVars(
806 'wgRCFiltersChangeTags',
807 $this->getChangeTagList()
808 );
809 $out->addJsConfigVars(
810 'StructuredChangeFiltersDisplayConfig',
811 [
812 'maxDays' => (int)$this->getConfig()->get( 'RCMaxAge' ) / ( 24 * 3600 ), // Translate to days
813 'limitArray' => $this->getConfig()->get( 'RCLinkLimits' ),
814 'limitDefault' => $this->getDefaultLimit(),
815 'daysArray' => $this->getConfig()->get( 'RCLinkDays' ),
816 'daysDefault' => $this->getDefaultDays(),
817 ]
818 );
819
820 $out->addJsConfigVars(
821 'wgStructuredChangeFiltersSavedQueriesPreferenceName',
822 static::$savedQueriesPreferenceName
823 );
824 $out->addJsConfigVars(
825 'wgStructuredChangeFiltersLimitPreferenceName',
826 static::$limitPreferenceName
827 );
828 $out->addJsConfigVars(
829 'wgStructuredChangeFiltersDaysPreferenceName',
830 static::$daysPreferenceName
831 );
832 $out->addJsConfigVars(
833 'wgStructuredChangeFiltersCollapsedPreferenceName',
834 static::$collapsedPreferenceName
835 );
836
837 $out->addJsConfigVars(
838 'StructuredChangeFiltersLiveUpdatePollingRate',
839 $this->getConfig()->get( 'StructuredChangeFiltersLiveUpdatePollingRate' )
840 );
841 } else {
842 $out->addBodyClasses( 'mw-rcfilters-disabled' );
843 }
844 }
845
846 /**
847 * Fetch the change tags list for the front end
848 *
849 * @return Array Tag data
850 */
851 protected function getChangeTagList() {
852 $cache = ObjectCache::getMainWANInstance();
853 $context = $this->getContext();
854 return $cache->getWithSetCallback(
855 $cache->makeKey( 'changeslistspecialpage-changetags', $context->getLanguage()->getCode() ),
856 $cache::TTL_MINUTE * 10,
857 function () use ( $context ) {
858 $explicitlyDefinedTags = array_fill_keys( ChangeTags::listExplicitlyDefinedTags(), 0 );
859 $softwareActivatedTags = array_fill_keys( ChangeTags::listSoftwareActivatedTags(), 0 );
860
861 // Hit counts disabled for perf reasons, see T169997
862 /*
863 $tagStats = ChangeTags::tagUsageStatistics();
864 $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags, $tagStats );
865
866 // Sort by hits
867 arsort( $tagHitCounts );
868 */
869 $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags );
870
871 // Build the list and data
872 $result = [];
873 foreach ( $tagHitCounts as $tagName => $hits ) {
874 if (
875 // Only get active tags
876 isset( $explicitlyDefinedTags[ $tagName ] ) ||
877 isset( $softwareActivatedTags[ $tagName ] )
878 ) {
879 $result[] = [
880 'name' => $tagName,
881 'label' => Sanitizer::stripAllTags(
882 ChangeTags::tagDescription( $tagName, $context )
883 ),
884 'description' =>
885 ChangeTags::truncateTagDescription(
886 $tagName, self::TAG_DESC_CHARACTER_LIMIT, $context
887 ),
888 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
889 'hits' => $hits,
890 ];
891 }
892 }
893
894 // Instead of sorting by hit count (disabled, see above), sort by display name
895 usort( $result, function ( $a, $b ) {
896 return strcasecmp( $a['label'], $b['label'] );
897 } );
898
899 return $result;
900 },
901 [
902 'lockTSE' => 30
903 ]
904 );
905 }
906
907 /**
908 * Add the "no results" message to the output
909 */
910 protected function outputNoResults() {
911 $this->getOutput()->addHTML(
912 '<div class="mw-changeslist-empty">' .
913 $this->msg( 'recentchanges-noresult' )->parse() .
914 '</div>'
915 );
916 }
917
918 /**
919 * Add the "timeout" message to the output
920 */
921 protected function outputTimeout() {
922 $this->getOutput()->addHTML(
923 '<div class="mw-changeslist-empty mw-changeslist-timeout">' .
924 $this->msg( 'recentchanges-timeout' )->parse() .
925 '</div>'
926 );
927 }
928
929 /**
930 * Get the database result for this special page instance. Used by ApiFeedRecentChanges.
931 *
932 * @return bool|IResultWrapper Result or false
933 */
934 public function getRows() {
935 $opts = $this->getOptions();
936
937 $tables = [];
938 $fields = [];
939 $conds = [];
940 $query_options = [];
941 $join_conds = [];
942 $this->buildQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
943
944 return $this->doMainQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
945 }
946
947 /**
948 * Get the current FormOptions for this request
949 *
950 * @return FormOptions
951 */
952 public function getOptions() {
953 if ( $this->rcOptions === null ) {
954 $this->rcOptions = $this->setup( $this->rcSubpage );
955 }
956
957 return $this->rcOptions;
958 }
959
960 /**
961 * Register all filters and their groups (including those from hooks), plus handle
962 * conflicts and defaults.
963 *
964 * You might want to customize these in the same method, in subclasses. You can
965 * call getFilterGroup to access a group, and (on the group) getFilter to access a
966 * filter, then make necessary modfications to the filter or group (e.g. with
967 * setDefault).
968 */
969 protected function registerFilters() {
970 $this->registerFiltersFromDefinitions( $this->filterGroupDefinitions );
971
972 // Make sure this is not being transcluded (we don't want to show this
973 // information to all users just because the user that saves the edit can
974 // patrol or is logged in)
975 if ( !$this->including() && $this->getUser()->useRCPatrol() ) {
976 $this->registerFiltersFromDefinitions( $this->legacyReviewStatusFilterGroupDefinition );
977 $this->registerFiltersFromDefinitions( $this->reviewStatusFilterGroupDefinition );
978 }
979
980 $changeTypeGroup = $this->getFilterGroup( 'changeType' );
981
982 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
983 $transformedHideCategorizationDef = $this->transformFilterDefinition(
984 $this->hideCategorizationFilterDefinition
985 );
986
987 $transformedHideCategorizationDef['group'] = $changeTypeGroup;
988
989 $hideCategorization = new ChangesListBooleanFilter(
990 $transformedHideCategorizationDef
991 );
992 }
993
994 Hooks::run( 'ChangesListSpecialPageStructuredFilters', [ $this ] );
995
996 $unstructuredGroupDefinition =
997 $this->getFilterGroupDefinitionFromLegacyCustomFilters(
998 $this->getCustomFilters()
999 );
1000 $this->registerFiltersFromDefinitions( [ $unstructuredGroupDefinition ] );
1001
1002 $userExperienceLevel = $this->getFilterGroup( 'userExpLevel' );
1003 $registered = $userExperienceLevel->getFilter( 'registered' );
1004 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'newcomer' ) );
1005 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'learner' ) );
1006 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'experienced' ) );
1007
1008 $categoryFilter = $changeTypeGroup->getFilter( 'hidecategorization' );
1009 $logactionsFilter = $changeTypeGroup->getFilter( 'hidelog' );
1010 $pagecreationFilter = $changeTypeGroup->getFilter( 'hidenewpages' );
1011
1012 $significanceTypeGroup = $this->getFilterGroup( 'significance' );
1013 $hideMinorFilter = $significanceTypeGroup->getFilter( 'hideminor' );
1014
1015 // categoryFilter is conditional; see registerFilters
1016 if ( $categoryFilter !== null ) {
1017 $hideMinorFilter->conflictsWith(
1018 $categoryFilter,
1019 'rcfilters-hideminor-conflicts-typeofchange-global',
1020 'rcfilters-hideminor-conflicts-typeofchange',
1021 'rcfilters-typeofchange-conflicts-hideminor'
1022 );
1023 }
1024 $hideMinorFilter->conflictsWith(
1025 $logactionsFilter,
1026 'rcfilters-hideminor-conflicts-typeofchange-global',
1027 'rcfilters-hideminor-conflicts-typeofchange',
1028 'rcfilters-typeofchange-conflicts-hideminor'
1029 );
1030 $hideMinorFilter->conflictsWith(
1031 $pagecreationFilter,
1032 'rcfilters-hideminor-conflicts-typeofchange-global',
1033 'rcfilters-hideminor-conflicts-typeofchange',
1034 'rcfilters-typeofchange-conflicts-hideminor'
1035 );
1036 }
1037
1038 /**
1039 * Transforms filter definition to prepare it for constructor.
1040 *
1041 * See overrides of this method as well.
1042 *
1043 * @param array $filterDefinition Original filter definition
1044 *
1045 * @return array Transformed definition
1046 */
1047 protected function transformFilterDefinition( array $filterDefinition ) {
1048 return $filterDefinition;
1049 }
1050
1051 /**
1052 * Register filters from a definition object
1053 *
1054 * Array specifying groups and their filters; see Filter and
1055 * ChangesListFilterGroup constructors.
1056 *
1057 * There is light processing to simplify core maintenance.
1058 * @param array $definition
1059 */
1060 protected function registerFiltersFromDefinitions( array $definition ) {
1061 $autoFillPriority = -1;
1062 foreach ( $definition as $groupDefinition ) {
1063 if ( !isset( $groupDefinition['priority'] ) ) {
1064 $groupDefinition['priority'] = $autoFillPriority;
1065 } else {
1066 // If it's explicitly specified, start over the auto-fill
1067 $autoFillPriority = $groupDefinition['priority'];
1068 }
1069
1070 $autoFillPriority--;
1071
1072 $className = $groupDefinition['class'];
1073 unset( $groupDefinition['class'] );
1074
1075 foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
1076 $filterDefinition = $this->transformFilterDefinition( $filterDefinition );
1077 }
1078
1079 $this->registerFilterGroup( new $className( $groupDefinition ) );
1080 }
1081 }
1082
1083 /**
1084 * Get filter group definition from legacy custom filters
1085 *
1086 * @param array $customFilters Custom filters from legacy hooks
1087 * @return array Group definition
1088 */
1089 protected function getFilterGroupDefinitionFromLegacyCustomFilters( array $customFilters ) {
1090 // Special internal unstructured group
1091 $unstructuredGroupDefinition = [
1092 'name' => 'unstructured',
1093 'class' => ChangesListBooleanFilterGroup::class,
1094 'priority' => -1, // Won't display in structured
1095 'filters' => [],
1096 ];
1097
1098 foreach ( $customFilters as $name => $params ) {
1099 $unstructuredGroupDefinition['filters'][] = [
1100 'name' => $name,
1101 'showHide' => $params['msg'],
1102 'default' => $params['default'],
1103 ];
1104 }
1105
1106 return $unstructuredGroupDefinition;
1107 }
1108
1109 /**
1110 * @return array The legacy show/hide toggle filters
1111 */
1112 protected function getLegacyShowHideFilters() {
1113 $filters = [];
1114 foreach ( $this->filterGroups as $group ) {
1115 if ( $group instanceof ChangesListBooleanFilterGroup ) {
1116 foreach ( $group->getFilters() as $key => $filter ) {
1117 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
1118 $filters[ $key ] = $filter;
1119 }
1120 }
1121 }
1122 }
1123 return $filters;
1124 }
1125
1126 /**
1127 * Register all the filters, including legacy hook-driven ones.
1128 * Then create a FormOptions object with options as specified by the user
1129 *
1130 * @param array $parameters
1131 *
1132 * @return FormOptions
1133 */
1134 public function setup( $parameters ) {
1135 $this->registerFilters();
1136
1137 $opts = $this->getDefaultOptions();
1138
1139 $opts = $this->fetchOptionsFromRequest( $opts );
1140
1141 // Give precedence to subpage syntax
1142 if ( $parameters !== null ) {
1143 $this->parseParameters( $parameters, $opts );
1144 }
1145
1146 $this->validateOptions( $opts );
1147
1148 return $opts;
1149 }
1150
1151 /**
1152 * Get a FormOptions object containing the default options. By default, returns
1153 * some basic options. The filters listed explicitly here are overriden in this
1154 * method, in subclasses, but most filters (e.g. hideminor, userExpLevel filters,
1155 * and more) are structured. Structured filters are overriden in registerFilters.
1156 * not here.
1157 *
1158 * @return FormOptions
1159 */
1160 public function getDefaultOptions() {
1161 $opts = new FormOptions();
1162 $structuredUI = $this->isStructuredFilterUiEnabled();
1163 // If urlversion=2 is set, ignore the filter defaults and set them all to false/empty
1164 $useDefaults = $this->getRequest()->getInt( 'urlversion' ) !== 2;
1165
1166 /** @var ChangesListFilterGroup $filterGroup */
1167 foreach ( $this->filterGroups as $filterGroup ) {
1168 $filterGroup->addOptions( $opts, $useDefaults, $structuredUI );
1169 }
1170
1171 $opts->add( 'namespace', '', FormOptions::STRING );
1172 $opts->add( 'invert', false );
1173 $opts->add( 'associated', false );
1174 $opts->add( 'urlversion', 1 );
1175 $opts->add( 'tagfilter', '' );
1176
1177 $opts->add( 'days', $this->getDefaultDays(), FormOptions::FLOAT );
1178 $opts->add( 'limit', $this->getDefaultLimit(), FormOptions::INT );
1179
1180 $opts->add( 'from', '' );
1181
1182 return $opts;
1183 }
1184
1185 /**
1186 * Register a structured changes list filter group
1187 *
1188 * @param ChangesListFilterGroup $group
1189 */
1190 public function registerFilterGroup( ChangesListFilterGroup $group ) {
1191 $groupName = $group->getName();
1192
1193 $this->filterGroups[$groupName] = $group;
1194 }
1195
1196 /**
1197 * Gets the currently registered filters groups
1198 *
1199 * @return array Associative array of ChangesListFilterGroup objects, with group name as key
1200 */
1201 protected function getFilterGroups() {
1202 return $this->filterGroups;
1203 }
1204
1205 /**
1206 * Gets a specified ChangesListFilterGroup by name
1207 *
1208 * @param string $groupName Name of group
1209 *
1210 * @return ChangesListFilterGroup|null Group, or null if not registered
1211 */
1212 public function getFilterGroup( $groupName ) {
1213 return $this->filterGroups[$groupName] ?? null;
1214 }
1215
1216 // Currently, this intentionally only includes filters that display
1217 // in the structured UI. This can be changed easily, though, if we want
1218 // to include data on filters that use the unstructured UI. messageKeys is a
1219 // special top-level value, with the value being an array of the message keys to
1220 // send to the client.
1221 /**
1222 * Gets structured filter information needed by JS
1223 *
1224 * @return array Associative array
1225 * * array $return['groups'] Group data
1226 * * array $return['messageKeys'] Array of message keys
1227 */
1228 public function getStructuredFilterJsData() {
1229 $output = [
1230 'groups' => [],
1231 'messageKeys' => [],
1232 ];
1233
1234 usort( $this->filterGroups, function ( $a, $b ) {
1235 return $b->getPriority() <=> $a->getPriority();
1236 } );
1237
1238 foreach ( $this->filterGroups as $groupName => $group ) {
1239 $groupOutput = $group->getJsData( $this );
1240 if ( $groupOutput !== null ) {
1241 $output['messageKeys'] = array_merge(
1242 $output['messageKeys'],
1243 $groupOutput['messageKeys']
1244 );
1245
1246 unset( $groupOutput['messageKeys'] );
1247 $output['groups'][] = $groupOutput;
1248 }
1249 }
1250
1251 return $output;
1252 }
1253
1254 /**
1255 * Get custom show/hide filters using deprecated ChangesListSpecialPageFilters
1256 * hook.
1257 *
1258 * @return array Map of filter URL param names to properties (msg/default)
1259 */
1260 protected function getCustomFilters() {
1261 if ( $this->customFilters === null ) {
1262 $this->customFilters = [];
1263 Hooks::run( 'ChangesListSpecialPageFilters', [ $this, &$this->customFilters ], '1.29' );
1264 }
1265
1266 return $this->customFilters;
1267 }
1268
1269 /**
1270 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
1271 *
1272 * Intended for subclassing, e.g. to add a backwards-compatibility layer.
1273 *
1274 * @param FormOptions $opts
1275 * @return FormOptions
1276 */
1277 protected function fetchOptionsFromRequest( $opts ) {
1278 $opts->fetchValuesFromRequest( $this->getRequest() );
1279
1280 return $opts;
1281 }
1282
1283 /**
1284 * Process $par and put options found in $opts. Used when including the page.
1285 *
1286 * @param string $par
1287 * @param FormOptions $opts
1288 */
1289 public function parseParameters( $par, FormOptions $opts ) {
1290 $stringParameterNameSet = [];
1291 $hideParameterNameSet = [];
1292
1293 // URL parameters can be per-group, like 'userExpLevel',
1294 // or per-filter, like 'hideminor'.
1295
1296 foreach ( $this->filterGroups as $filterGroup ) {
1297 if ( $filterGroup instanceof ChangesListStringOptionsFilterGroup ) {
1298 $stringParameterNameSet[$filterGroup->getName()] = true;
1299 } elseif ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
1300 foreach ( $filterGroup->getFilters() as $filter ) {
1301 $hideParameterNameSet[$filter->getName()] = true;
1302 }
1303 }
1304 }
1305
1306 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
1307 foreach ( $bits as $bit ) {
1308 $m = [];
1309 if ( isset( $hideParameterNameSet[$bit] ) ) {
1310 // hidefoo => hidefoo=true
1311 $opts[$bit] = true;
1312 } elseif ( isset( $hideParameterNameSet["hide$bit"] ) ) {
1313 // foo => hidefoo=false
1314 $opts["hide$bit"] = false;
1315 } elseif ( preg_match( '/^(.*)=(.*)$/', $bit, $m ) ) {
1316 if ( isset( $stringParameterNameSet[$m[1]] ) ) {
1317 $opts[$m[1]] = $m[2];
1318 }
1319 }
1320 }
1321 }
1322
1323 /**
1324 * Validate a FormOptions object generated by getDefaultOptions() with values already populated.
1325 *
1326 * @param FormOptions $opts
1327 */
1328 public function validateOptions( FormOptions $opts ) {
1329 $isContradictory = $this->fixContradictoryOptions( $opts );
1330 $isReplaced = $this->replaceOldOptions( $opts );
1331
1332 if ( $isContradictory || $isReplaced ) {
1333 $query = wfArrayToCgi( $this->convertParamsForLink( $opts->getChangedValues() ) );
1334 $this->getOutput()->redirect( $this->getPageTitle()->getCanonicalURL( $query ) );
1335 }
1336
1337 $opts->validateIntBounds( 'limit', 0, 5000 );
1338 $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1339 }
1340
1341 /**
1342 * Fix invalid options by resetting pairs that should never appear together.
1343 *
1344 * @param FormOptions $opts
1345 * @return bool True if any option was reset
1346 */
1347 private function fixContradictoryOptions( FormOptions $opts ) {
1348 $fixed = $this->fixBackwardsCompatibilityOptions( $opts );
1349
1350 foreach ( $this->filterGroups as $filterGroup ) {
1351 if ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
1352 $filters = $filterGroup->getFilters();
1353
1354 if ( count( $filters ) === 1 ) {
1355 // legacy boolean filters should not be considered
1356 continue;
1357 }
1358
1359 $allInGroupEnabled = array_reduce(
1360 $filters,
1361 function ( $carry, $filter ) use ( $opts ) {
1362 return $carry && $opts[ $filter->getName() ];
1363 },
1364 /* initialValue */ count( $filters ) > 0
1365 );
1366
1367 if ( $allInGroupEnabled ) {
1368 foreach ( $filters as $filter ) {
1369 $opts[ $filter->getName() ] = false;
1370 }
1371
1372 $fixed = true;
1373 }
1374 }
1375 }
1376
1377 return $fixed;
1378 }
1379
1380 /**
1381 * Fix a special case (hideanons=1 and hideliu=1) in a special way, for backwards
1382 * compatibility.
1383 *
1384 * This is deprecated and may be removed.
1385 *
1386 * @param FormOptions $opts
1387 * @return bool True if this change was mode
1388 */
1389 private function fixBackwardsCompatibilityOptions( FormOptions $opts ) {
1390 if ( $opts['hideanons'] && $opts['hideliu'] ) {
1391 $opts->reset( 'hideanons' );
1392 if ( !$opts['hidebots'] ) {
1393 $opts->reset( 'hideliu' );
1394 $opts['hidehumans'] = 1;
1395 }
1396
1397 return true;
1398 }
1399
1400 return false;
1401 }
1402
1403 /**
1404 * Replace old options with their structured UI equivalents
1405 *
1406 * @param FormOptions $opts
1407 * @return bool True if the change was made
1408 */
1409 public function replaceOldOptions( FormOptions $opts ) {
1410 if ( !$this->isStructuredFilterUiEnabled() ) {
1411 return false;
1412 }
1413
1414 $changed = false;
1415
1416 // At this point 'hideanons' and 'hideliu' cannot be both true,
1417 // because fixBackwardsCompatibilityOptions resets (at least) 'hideanons' in such case
1418 if ( $opts[ 'hideanons' ] ) {
1419 $opts->reset( 'hideanons' );
1420 $opts[ 'userExpLevel' ] = 'registered';
1421 $changed = true;
1422 }
1423
1424 if ( $opts[ 'hideliu' ] ) {
1425 $opts->reset( 'hideliu' );
1426 $opts[ 'userExpLevel' ] = 'unregistered';
1427 $changed = true;
1428 }
1429
1430 if ( $this->getFilterGroup( 'legacyReviewStatus' ) ) {
1431 if ( $opts[ 'hidepatrolled' ] ) {
1432 $opts->reset( 'hidepatrolled' );
1433 $opts[ 'reviewStatus' ] = 'unpatrolled';
1434 $changed = true;
1435 }
1436
1437 if ( $opts[ 'hideunpatrolled' ] ) {
1438 $opts->reset( 'hideunpatrolled' );
1439 $opts[ 'reviewStatus' ] = implode(
1440 ChangesListStringOptionsFilterGroup::SEPARATOR,
1441 [ 'manual', 'auto' ]
1442 );
1443 $changed = true;
1444 }
1445 }
1446
1447 return $changed;
1448 }
1449
1450 /**
1451 * Convert parameters values from true/false to 1/0
1452 * so they are not omitted by wfArrayToCgi()
1453 * Bug 36524
1454 *
1455 * @param array $params
1456 * @return array
1457 */
1458 protected function convertParamsForLink( $params ) {
1459 foreach ( $params as &$value ) {
1460 if ( $value === false ) {
1461 $value = '0';
1462 }
1463 }
1464 unset( $value );
1465 return $params;
1466 }
1467
1468 /**
1469 * Sets appropriate tables, fields, conditions, etc. depending on which filters
1470 * the user requested.
1471 *
1472 * @param array &$tables Array of tables; see IDatabase::select $table
1473 * @param array &$fields Array of fields; see IDatabase::select $vars
1474 * @param array &$conds Array of conditions; see IDatabase::select $conds
1475 * @param array &$query_options Array of query options; see IDatabase::select $options
1476 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1477 * @param FormOptions $opts
1478 */
1479 protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
1480 &$join_conds, FormOptions $opts
1481 ) {
1482 $dbr = $this->getDB();
1483 $isStructuredUI = $this->isStructuredFilterUiEnabled();
1484
1485 /** @var ChangesListFilterGroup $filterGroup */
1486 foreach ( $this->filterGroups as $filterGroup ) {
1487 $filterGroup->modifyQuery( $dbr, $this, $tables, $fields, $conds,
1488 $query_options, $join_conds, $opts, $isStructuredUI );
1489 }
1490
1491 // Namespace filtering
1492 if ( $opts[ 'namespace' ] !== '' ) {
1493 $namespaces = explode( ';', $opts[ 'namespace' ] );
1494
1495 if ( $opts[ 'associated' ] ) {
1496 $associatedNamespaces = array_map(
1497 function ( $ns ) {
1498 return MWNamespace::getAssociated( $ns );
1499 },
1500 $namespaces
1501 );
1502 $namespaces = array_unique( array_merge( $namespaces, $associatedNamespaces ) );
1503 }
1504
1505 if ( count( $namespaces ) === 1 ) {
1506 $operator = $opts[ 'invert' ] ? '!=' : '=';
1507 $value = $dbr->addQuotes( reset( $namespaces ) );
1508 } else {
1509 $operator = $opts[ 'invert' ] ? 'NOT IN' : 'IN';
1510 sort( $namespaces );
1511 $value = '(' . $dbr->makeList( $namespaces ) . ')';
1512 }
1513 $conds[] = "rc_namespace $operator $value";
1514 }
1515
1516 // Calculate cutoff
1517 $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
1518 $cutoff = $dbr->timestamp( $cutoff_unixtime );
1519
1520 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
1521 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
1522 $cutoff = $dbr->timestamp( $opts['from'] );
1523 } else {
1524 $opts->reset( 'from' );
1525 }
1526
1527 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
1528 }
1529
1530 /**
1531 * Process the query
1532 *
1533 * @param array $tables Array of tables; see IDatabase::select $table
1534 * @param array $fields Array of fields; see IDatabase::select $vars
1535 * @param array $conds Array of conditions; see IDatabase::select $conds
1536 * @param array $query_options Array of query options; see IDatabase::select $options
1537 * @param array $join_conds Array of join conditions; see IDatabase::select $join_conds
1538 * @param FormOptions $opts
1539 * @return bool|IResultWrapper Result or false
1540 */
1541 protected function doMainQuery( $tables, $fields, $conds,
1542 $query_options, $join_conds, FormOptions $opts
1543 ) {
1544 $rcQuery = RecentChange::getQueryInfo();
1545 $tables = array_merge( $tables, $rcQuery['tables'] );
1546 $fields = array_merge( $rcQuery['fields'], $fields );
1547 $join_conds = array_merge( $join_conds, $rcQuery['joins'] );
1548
1549 ChangeTags::modifyDisplayQuery(
1550 $tables,
1551 $fields,
1552 $conds,
1553 $join_conds,
1554 $query_options,
1555 ''
1556 );
1557
1558 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
1559 $opts )
1560 ) {
1561 return false;
1562 }
1563
1564 $dbr = $this->getDB();
1565
1566 return $dbr->select(
1567 $tables,
1568 $fields,
1569 $conds,
1570 __METHOD__,
1571 $query_options,
1572 $join_conds
1573 );
1574 }
1575
1576 protected function runMainQueryHook( &$tables, &$fields, &$conds,
1577 &$query_options, &$join_conds, $opts
1578 ) {
1579 return Hooks::run(
1580 'ChangesListSpecialPageQuery',
1581 [ $this->getName(), &$tables, &$fields, &$conds, &$query_options, &$join_conds, $opts ]
1582 );
1583 }
1584
1585 /**
1586 * Return a IDatabase object for reading
1587 *
1588 * @return IDatabase
1589 */
1590 protected function getDB() {
1591 return wfGetDB( DB_REPLICA );
1592 }
1593
1594 /**
1595 * Send header output to the OutputPage object, only called if not using feeds
1596 *
1597 * @param int $rowCount Number of database rows
1598 * @param FormOptions $opts
1599 */
1600 private function webOutputHeader( $rowCount, $opts ) {
1601 if ( !$this->including() ) {
1602 $this->outputFeedLinks();
1603 $this->doHeader( $opts, $rowCount );
1604 }
1605 }
1606
1607 /**
1608 * Send output to the OutputPage object, only called if not used feeds
1609 *
1610 * @param IResultWrapper $rows Database rows
1611 * @param FormOptions $opts
1612 */
1613 public function webOutput( $rows, $opts ) {
1614 $this->webOutputHeader( $rows->numRows(), $opts );
1615
1616 $this->outputChangesList( $rows, $opts );
1617 }
1618
1619 /**
1620 * Output feed links.
1621 */
1622 public function outputFeedLinks() {
1623 // nothing by default
1624 }
1625
1626 /**
1627 * Build and output the actual changes list.
1628 *
1629 * @param IResultWrapper $rows Database rows
1630 * @param FormOptions $opts
1631 */
1632 abstract public function outputChangesList( $rows, $opts );
1633
1634 /**
1635 * Set the text to be displayed above the changes
1636 *
1637 * @param FormOptions $opts
1638 * @param int $numRows Number of rows in the result to show after this header
1639 */
1640 public function doHeader( $opts, $numRows ) {
1641 $this->setTopText( $opts );
1642
1643 // @todo Lots of stuff should be done here.
1644
1645 $this->setBottomText( $opts );
1646 }
1647
1648 /**
1649 * Send the text to be displayed before the options. Should use $this->getOutput()->addWikiText()
1650 * or similar methods to print the text.
1651 *
1652 * @param FormOptions $opts
1653 */
1654 public function setTopText( FormOptions $opts ) {
1655 // nothing by default
1656 }
1657
1658 /**
1659 * Send the text to be displayed after the options. Should use $this->getOutput()->addWikiText()
1660 * or similar methods to print the text.
1661 *
1662 * @param FormOptions $opts
1663 */
1664 public function setBottomText( FormOptions $opts ) {
1665 // nothing by default
1666 }
1667
1668 /**
1669 * Get options to be displayed in a form
1670 * @todo This should handle options returned by getDefaultOptions().
1671 * @todo Not called by anything in this class (but is in subclasses), should be
1672 * called by something… doHeader() maybe?
1673 *
1674 * @param FormOptions $opts
1675 * @return array
1676 */
1677 public function getExtraOptions( $opts ) {
1678 return [];
1679 }
1680
1681 /**
1682 * Return the legend displayed within the fieldset
1683 *
1684 * @return string
1685 */
1686 public function makeLegend() {
1687 $context = $this->getContext();
1688 $user = $context->getUser();
1689 # The legend showing what the letters and stuff mean
1690 $legend = Html::openElement( 'dl' ) . "\n";
1691 # Iterates through them and gets the messages for both letter and tooltip
1692 $legendItems = $context->getConfig()->get( 'RecentChangesFlags' );
1693 if ( !( $user->useRCPatrol() || $user->useNPPatrol() ) ) {
1694 unset( $legendItems['unpatrolled'] );
1695 }
1696 foreach ( $legendItems as $key => $item ) { # generate items of the legend
1697 $label = $item['legend'] ?? $item['title'];
1698 $letter = $item['letter'];
1699 $cssClass = $item['class'] ?? $key;
1700
1701 $legend .= Html::element( 'dt',
1702 [ 'class' => $cssClass ], $context->msg( $letter )->text()
1703 ) . "\n" .
1704 Html::rawElement( 'dd',
1705 [ 'class' => Sanitizer::escapeClass( 'mw-changeslist-legend-' . $key ) ],
1706 $context->msg( $label )->parse()
1707 ) . "\n";
1708 }
1709 # (+-123)
1710 $legend .= Html::rawElement( 'dt',
1711 [ 'class' => 'mw-plusminus-pos' ],
1712 $context->msg( 'recentchanges-legend-plusminus' )->parse()
1713 ) . "\n";
1714 $legend .= Html::element(
1715 'dd',
1716 [ 'class' => 'mw-changeslist-legend-plusminus' ],
1717 $context->msg( 'recentchanges-label-plusminus' )->text()
1718 ) . "\n";
1719 $legend .= Html::closeElement( 'dl' ) . "\n";
1720
1721 $legendHeading = $this->isStructuredFilterUiEnabled() ?
1722 $context->msg( 'rcfilters-legend-heading' )->parse() :
1723 $context->msg( 'recentchanges-legend-heading' )->parse();
1724
1725 # Collapsible
1726 $collapsedState = $this->getRequest()->getCookie( 'changeslist-state' );
1727 $collapsedClass = $collapsedState === 'collapsed' ? ' mw-collapsed' : '';
1728
1729 $legend =
1730 '<div class="mw-changeslist-legend mw-collapsible' . $collapsedClass . '">' .
1731 $legendHeading .
1732 '<div class="mw-collapsible-content">' . $legend . '</div>' .
1733 '</div>';
1734
1735 return $legend;
1736 }
1737
1738 /**
1739 * Add page-specific modules.
1740 */
1741 protected function addModules() {
1742 $out = $this->getOutput();
1743 // Styles and behavior for the legend box (see makeLegend())
1744 $out->addModuleStyles( [
1745 'mediawiki.special.changeslist.legend',
1746 'mediawiki.special.changeslist',
1747 ] );
1748 $out->addModules( 'mediawiki.special.changeslist.legend.js' );
1749
1750 if ( $this->isStructuredFilterUiEnabled() && !$this->including() ) {
1751 $out->addModules( 'mediawiki.rcfilters.filters.ui' );
1752 $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
1753 }
1754 }
1755
1756 protected function getGroupName() {
1757 return 'changes';
1758 }
1759
1760 /**
1761 * Filter on users' experience levels; this will not be called if nothing is
1762 * selected.
1763 *
1764 * @param string $specialPageClassName Class name of current special page
1765 * @param IContextSource $context Context, for e.g. user
1766 * @param IDatabase $dbr Database, for addQuotes, makeList, and similar
1767 * @param array &$tables Array of tables; see IDatabase::select $table
1768 * @param array &$fields Array of fields; see IDatabase::select $vars
1769 * @param array &$conds Array of conditions; see IDatabase::select $conds
1770 * @param array &$query_options Array of query options; see IDatabase::select $options
1771 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1772 * @param array $selectedExpLevels The allowed active values, sorted
1773 * @param int $now Number of seconds since the UNIX epoch, or 0 if not given
1774 * (optional)
1775 */
1776 public function filterOnUserExperienceLevel( $specialPageClassName, $context, $dbr,
1777 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedExpLevels, $now = 0
1778 ) {
1779 global $wgLearnerEdits,
1780 $wgExperiencedUserEdits,
1781 $wgLearnerMemberSince,
1782 $wgExperiencedUserMemberSince;
1783
1784 $LEVEL_COUNT = 5;
1785
1786 // If all levels are selected, don't filter
1787 if ( count( $selectedExpLevels ) === $LEVEL_COUNT ) {
1788 return;
1789 }
1790
1791 // both 'registered' and 'unregistered', experience levels, if any, are included in 'registered'
1792 if (
1793 in_array( 'registered', $selectedExpLevels ) &&
1794 in_array( 'unregistered', $selectedExpLevels )
1795 ) {
1796 return;
1797 }
1798
1799 $actorMigration = ActorMigration::newMigration();
1800 $actorQuery = $actorMigration->getJoin( 'rc_user' );
1801 $tables += $actorQuery['tables'];
1802 $join_conds += $actorQuery['joins'];
1803
1804 // 'registered' but not 'unregistered', experience levels, if any, are included in 'registered'
1805 if (
1806 in_array( 'registered', $selectedExpLevels ) &&
1807 !in_array( 'unregistered', $selectedExpLevels )
1808 ) {
1809 $conds[] = $actorMigration->isNotAnon( $actorQuery['fields']['rc_user'] );
1810 return;
1811 }
1812
1813 if ( $selectedExpLevels === [ 'unregistered' ] ) {
1814 $conds[] = $actorMigration->isAnon( $actorQuery['fields']['rc_user'] );
1815 return;
1816 }
1817
1818 $tables[] = 'user';
1819 $join_conds['user'] = [ 'LEFT JOIN', $actorQuery['fields']['rc_user'] . ' = user_id' ];
1820
1821 if ( $now === 0 ) {
1822 $now = time();
1823 }
1824 $secondsPerDay = 86400;
1825 $learnerCutoff = $now - $wgLearnerMemberSince * $secondsPerDay;
1826 $experiencedUserCutoff = $now - $wgExperiencedUserMemberSince * $secondsPerDay;
1827
1828 $aboveNewcomer = $dbr->makeList(
1829 [
1830 'user_editcount >= ' . intval( $wgLearnerEdits ),
1831 'user_registration <= ' . $dbr->addQuotes( $dbr->timestamp( $learnerCutoff ) ),
1832 ],
1833 IDatabase::LIST_AND
1834 );
1835
1836 $aboveLearner = $dbr->makeList(
1837 [
1838 'user_editcount >= ' . intval( $wgExperiencedUserEdits ),
1839 'user_registration <= ' .
1840 $dbr->addQuotes( $dbr->timestamp( $experiencedUserCutoff ) ),
1841 ],
1842 IDatabase::LIST_AND
1843 );
1844
1845 $conditions = [];
1846
1847 if ( in_array( 'unregistered', $selectedExpLevels ) ) {
1848 $selectedExpLevels = array_diff( $selectedExpLevels, [ 'unregistered' ] );
1849 $conditions[] = $actorMigration->isAnon( $actorQuery['fields']['rc_user'] );
1850 }
1851
1852 if ( $selectedExpLevels === [ 'newcomer' ] ) {
1853 $conditions[] = "NOT ( $aboveNewcomer )";
1854 } elseif ( $selectedExpLevels === [ 'learner' ] ) {
1855 $conditions[] = $dbr->makeList(
1856 [ $aboveNewcomer, "NOT ( $aboveLearner )" ],
1857 IDatabase::LIST_AND
1858 );
1859 } elseif ( $selectedExpLevels === [ 'experienced' ] ) {
1860 $conditions[] = $aboveLearner;
1861 } elseif ( $selectedExpLevels === [ 'learner', 'newcomer' ] ) {
1862 $conditions[] = "NOT ( $aboveLearner )";
1863 } elseif ( $selectedExpLevels === [ 'experienced', 'newcomer' ] ) {
1864 $conditions[] = $dbr->makeList(
1865 [ "NOT ( $aboveNewcomer )", $aboveLearner ],
1866 IDatabase::LIST_OR
1867 );
1868 } elseif ( $selectedExpLevels === [ 'experienced', 'learner' ] ) {
1869 $conditions[] = $aboveNewcomer;
1870 } elseif ( $selectedExpLevels === [ 'experienced', 'learner', 'newcomer' ] ) {
1871 $conditions[] = $actorMigration->isNotAnon( $actorQuery['fields']['rc_user'] );
1872 }
1873
1874 if ( count( $conditions ) > 1 ) {
1875 $conds[] = $dbr->makeList( $conditions, IDatabase::LIST_OR );
1876 } elseif ( count( $conditions ) === 1 ) {
1877 $conds[] = reset( $conditions );
1878 }
1879 }
1880
1881 /**
1882 * Check whether the structured filter UI is enabled
1883 *
1884 * @return bool
1885 */
1886 public function isStructuredFilterUiEnabled() {
1887 if ( $this->getRequest()->getBool( 'rcfilters' ) ) {
1888 return true;
1889 }
1890
1891 return static::checkStructuredFilterUiEnabled(
1892 $this->getConfig(),
1893 $this->getUser()
1894 );
1895 }
1896
1897 /**
1898 * Check whether the structured filter UI is enabled by default (regardless of
1899 * this particular user's setting)
1900 *
1901 * @return bool
1902 */
1903 public function isStructuredFilterUiEnabledByDefault() {
1904 if ( $this->getConfig()->get( 'StructuredChangeFiltersShowPreference' ) ) {
1905 return !$this->getUser()->getDefaultOption( 'rcenhancedfilters-disable' );
1906 } else {
1907 return $this->getUser()->getDefaultOption( 'rcenhancedfilters' );
1908 }
1909 }
1910
1911 /**
1912 * Static method to check whether StructuredFilter UI is enabled for the given user
1913 *
1914 * @since 1.31
1915 * @param Config $config
1916 * @param User $user
1917 * @return bool
1918 */
1919 public static function checkStructuredFilterUiEnabled( Config $config, User $user ) {
1920 if ( $config->get( 'StructuredChangeFiltersShowPreference' ) ) {
1921 return !$user->getOption( 'rcenhancedfilters-disable' );
1922 } else {
1923 return $user->getOption( 'rcenhancedfilters' );
1924 }
1925 }
1926
1927 /**
1928 * Get the default value of the number of changes to display when loading
1929 * the result set.
1930 *
1931 * @since 1.30
1932 * @return int
1933 */
1934 public function getDefaultLimit() {
1935 return $this->getUser()->getIntOption( static::$limitPreferenceName );
1936 }
1937
1938 /**
1939 * Get the default value of the number of days to display when loading
1940 * the result set.
1941 * Supports fractional values, and should be cast to a float.
1942 *
1943 * @since 1.30
1944 * @return float
1945 */
1946 public function getDefaultDays() {
1947 return floatval( $this->getUser()->getOption( static::$daysPreferenceName ) );
1948 }
1949 }