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