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