Merge "RC Filters: Disable defaults for legacy filters in structured UI"
[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\ResultWrapper;
25 use Wikimedia\Rdbms\IDatabase;
26
27 /**
28 * Special page which uses a ChangesList to show query results.
29 * @todo Way too many public functions, most of them should be protected
30 *
31 * @ingroup SpecialPage
32 */
33 abstract class ChangesListSpecialPage extends SpecialPage {
34 /** @var string */
35 protected $rcSubpage;
36
37 /** @var FormOptions */
38 protected $rcOptions;
39
40 /** @var array */
41 protected $customFilters;
42
43 // Order of both groups and filters is significant; first is top-most priority,
44 // descending from there.
45 // 'showHideSuffix' is a shortcut to and avoid spelling out
46 // details specific to subclasses here.
47 /**
48 * Definition information for the filters and their groups
49 *
50 * The value is $groupDefinition, a parameter to the ChangesListFilterGroup constructor.
51 * However, priority is dynamically added for the core groups, to ease maintenance.
52 *
53 * Groups are displayed to the user in the structured UI. However, if necessary,
54 * all of the filters in a group can be configured to only display on the
55 * unstuctured UI, in which case you don't need a group title. This is done in
56 * getFilterGroupDefinitionFromLegacyCustomFilters, for example.
57 *
58 * @var array $filterGroupDefinitions
59 */
60 private $filterGroupDefinitions;
61
62 // Same format as filterGroupDefinitions, but for a single group (reviewStatus)
63 // that is registered conditionally.
64 private $reviewStatusFilterGroupDefinition;
65
66 // Single filter registered conditionally
67 private $hideCategorizationFilterDefinition;
68
69 /**
70 * Filter groups, and their contained filters
71 * This is an associative array (with group name as key) of ChangesListFilterGroup objects.
72 *
73 * @var array $filterGroups
74 */
75 protected $filterGroups = [];
76
77 public function __construct( $name, $restriction ) {
78 parent::__construct( $name, $restriction );
79
80 $this->filterGroupDefinitions = [
81 [
82 'name' => 'registration',
83 'title' => 'rcfilters-filtergroup-registration',
84 'class' => ChangesListBooleanFilterGroup::class,
85 'filters' => [
86 [
87 'name' => 'hideliu',
88 'label' => 'rcfilters-filter-registered-label',
89 'description' => 'rcfilters-filter-registered-description',
90 // rcshowhideliu-show, rcshowhideliu-hide,
91 // wlshowhideliu
92 'showHideSuffix' => 'showhideliu',
93 'default' => false,
94 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
95 &$query_options, &$join_conds ) {
96
97 $conds[] = 'rc_user = 0';
98 },
99 'cssClassSuffix' => 'liu',
100 'isRowApplicableCallable' => function ( $ctx, $rc ) {
101 return $rc->getAttribute( 'rc_user' );
102 },
103
104 ],
105 [
106 'name' => 'hideanons',
107 'label' => 'rcfilters-filter-unregistered-label',
108 'description' => 'rcfilters-filter-unregistered-description',
109 // rcshowhideanons-show, rcshowhideanons-hide,
110 // wlshowhideanons
111 'showHideSuffix' => 'showhideanons',
112 'default' => false,
113 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
114 &$query_options, &$join_conds ) {
115
116 $conds[] = 'rc_user != 0';
117 },
118 'cssClassSuffix' => 'anon',
119 'isRowApplicableCallable' => function ( $ctx, $rc ) {
120 return !$rc->getAttribute( 'rc_user' );
121 },
122 ]
123 ],
124 ],
125
126 [
127 'name' => 'userExpLevel',
128 'title' => 'rcfilters-filtergroup-userExpLevel',
129 'class' => ChangesListStringOptionsFilterGroup::class,
130 // Excludes unregistered users
131 'isFullCoverage' => false,
132 'filters' => [
133 [
134 'name' => 'newcomer',
135 'label' => 'rcfilters-filter-user-experience-level-newcomer-label',
136 'description' => 'rcfilters-filter-user-experience-level-newcomer-description',
137 'cssClassSuffix' => 'user-newcomer',
138 'isRowApplicableCallable' => function ( $ctx, $rc ) {
139 $performer = $rc->getPerformer();
140 return $performer && $performer->isLoggedIn() &&
141 $performer->getExperienceLevel() === 'newcomer';
142 }
143 ],
144 [
145 'name' => 'learner',
146 'label' => 'rcfilters-filter-user-experience-level-learner-label',
147 'description' => 'rcfilters-filter-user-experience-level-learner-description',
148 'cssClassSuffix' => 'user-learner',
149 'isRowApplicableCallable' => function ( $ctx, $rc ) {
150 $performer = $rc->getPerformer();
151 return $performer && $performer->isLoggedIn() &&
152 $performer->getExperienceLevel() === 'learner';
153 },
154 ],
155 [
156 'name' => 'experienced',
157 'label' => 'rcfilters-filter-user-experience-level-experienced-label',
158 'description' => 'rcfilters-filter-user-experience-level-experienced-description',
159 'cssClassSuffix' => 'user-experienced',
160 'isRowApplicableCallable' => function ( $ctx, $rc ) {
161 $performer = $rc->getPerformer();
162 return $performer && $performer->isLoggedIn() &&
163 $performer->getExperienceLevel() === 'experienced';
164 },
165 ]
166 ],
167 'default' => ChangesListStringOptionsFilterGroup::NONE,
168 'queryCallable' => [ $this, 'filterOnUserExperienceLevel' ],
169 ],
170
171 [
172 'name' => 'authorship',
173 'title' => 'rcfilters-filtergroup-authorship',
174 'class' => ChangesListBooleanFilterGroup::class,
175 'filters' => [
176 [
177 'name' => 'hidemyself',
178 'label' => 'rcfilters-filter-editsbyself-label',
179 'description' => 'rcfilters-filter-editsbyself-description',
180 // rcshowhidemine-show, rcshowhidemine-hide,
181 // wlshowhidemine
182 'showHideSuffix' => 'showhidemine',
183 'default' => false,
184 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
185 &$query_options, &$join_conds ) {
186
187 $user = $ctx->getUser();
188 $conds[] = 'rc_user_text != ' . $dbr->addQuotes( $user->getName() );
189 },
190 'cssClassSuffix' => 'self',
191 'isRowApplicableCallable' => function ( $ctx, $rc ) {
192 return $ctx->getUser()->equals( $rc->getPerformer() );
193 },
194 ],
195 [
196 'name' => 'hidebyothers',
197 'label' => 'rcfilters-filter-editsbyother-label',
198 'description' => 'rcfilters-filter-editsbyother-description',
199 'default' => false,
200 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
201 &$query_options, &$join_conds ) {
202
203 $user = $ctx->getUser();
204 $conds[] = 'rc_user_text = ' . $dbr->addQuotes( $user->getName() );
205 },
206 'cssClassSuffix' => 'others',
207 'isRowApplicableCallable' => function ( $ctx, $rc ) {
208 return !$ctx->getUser()->equals( $rc->getPerformer() );
209 },
210 ]
211 ]
212 ],
213
214 [
215 'name' => 'automated',
216 'title' => 'rcfilters-filtergroup-automated',
217 'class' => ChangesListBooleanFilterGroup::class,
218 'filters' => [
219 [
220 'name' => 'hidebots',
221 'label' => 'rcfilters-filter-bots-label',
222 'description' => 'rcfilters-filter-bots-description',
223 // rcshowhidebots-show, rcshowhidebots-hide,
224 // wlshowhidebots
225 'showHideSuffix' => 'showhidebots',
226 'default' => false,
227 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
228 &$query_options, &$join_conds ) {
229
230 $conds[] = 'rc_bot = 0';
231 },
232 'cssClassSuffix' => 'bot',
233 'isRowApplicableCallable' => function ( $ctx, $rc ) {
234 return $rc->getAttribute( 'rc_bot' );
235 },
236 ],
237 [
238 'name' => 'hidehumans',
239 'label' => 'rcfilters-filter-humans-label',
240 'description' => 'rcfilters-filter-humans-description',
241 'default' => false,
242 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
243 &$query_options, &$join_conds ) {
244
245 $conds[] = 'rc_bot = 1';
246 },
247 'cssClassSuffix' => 'human',
248 'isRowApplicableCallable' => function ( $ctx, $rc ) {
249 return !$rc->getAttribute( 'rc_bot' );
250 },
251 ]
252 ]
253 ],
254
255 // reviewStatus (conditional)
256
257 [
258 'name' => 'significance',
259 'title' => 'rcfilters-filtergroup-significance',
260 'class' => ChangesListBooleanFilterGroup::class,
261 'priority' => -6,
262 'filters' => [
263 [
264 'name' => 'hideminor',
265 'label' => 'rcfilters-filter-minor-label',
266 'description' => 'rcfilters-filter-minor-description',
267 // rcshowhideminor-show, rcshowhideminor-hide,
268 // wlshowhideminor
269 'showHideSuffix' => 'showhideminor',
270 'default' => false,
271 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
272 &$query_options, &$join_conds ) {
273
274 $conds[] = 'rc_minor = 0';
275 },
276 'cssClassSuffix' => 'minor',
277 'isRowApplicableCallable' => function ( $ctx, $rc ) {
278 return $rc->getAttribute( 'rc_minor' );
279 }
280 ],
281 [
282 'name' => 'hidemajor',
283 'label' => 'rcfilters-filter-major-label',
284 'description' => 'rcfilters-filter-major-description',
285 'default' => false,
286 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
287 &$query_options, &$join_conds ) {
288
289 $conds[] = 'rc_minor = 1';
290 },
291 'cssClassSuffix' => 'major',
292 'isRowApplicableCallable' => function ( $ctx, $rc ) {
293 return !$rc->getAttribute( 'rc_minor' );
294 }
295 ]
296 ]
297 ],
298
299 // With extensions, there can be change types that will not be hidden by any of these.
300 [
301 'name' => 'changeType',
302 'title' => 'rcfilters-filtergroup-changetype',
303 'class' => ChangesListBooleanFilterGroup::class,
304 'filters' => [
305 [
306 'name' => 'hidepageedits',
307 'label' => 'rcfilters-filter-pageedits-label',
308 'description' => 'rcfilters-filter-pageedits-description',
309 'default' => false,
310 'priority' => -2,
311 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
312 &$query_options, &$join_conds ) {
313
314 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_EDIT );
315 },
316 'cssClassSuffix' => 'src-mw-edit',
317 'isRowApplicableCallable' => function ( $ctx, $rc ) {
318 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_EDIT;
319 },
320 ],
321 [
322 'name' => 'hidenewpages',
323 'label' => 'rcfilters-filter-newpages-label',
324 'description' => 'rcfilters-filter-newpages-description',
325 'default' => false,
326 'priority' => -3,
327 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
328 &$query_options, &$join_conds ) {
329
330 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_NEW );
331 },
332 'cssClassSuffix' => 'src-mw-new',
333 'isRowApplicableCallable' => function ( $ctx, $rc ) {
334 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_NEW;
335 },
336 ],
337
338 // hidecategorization
339
340 [
341 'name' => 'hidelog',
342 'label' => 'rcfilters-filter-logactions-label',
343 'description' => 'rcfilters-filter-logactions-description',
344 'default' => false,
345 'priority' => -5,
346 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
347 &$query_options, &$join_conds ) {
348
349 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_LOG );
350 },
351 'cssClassSuffix' => 'src-mw-log',
352 'isRowApplicableCallable' => function ( $ctx, $rc ) {
353 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_LOG;
354 }
355 ],
356 ],
357 ],
358 ];
359
360 $this->reviewStatusFilterGroupDefinition = [
361 [
362 'name' => 'reviewStatus',
363 'title' => 'rcfilters-filtergroup-reviewstatus',
364 'class' => ChangesListBooleanFilterGroup::class,
365 'priority' => -5,
366 'filters' => [
367 [
368 'name' => 'hidepatrolled',
369 'label' => 'rcfilters-filter-patrolled-label',
370 'description' => 'rcfilters-filter-patrolled-description',
371 // rcshowhidepatr-show, rcshowhidepatr-hide
372 // wlshowhidepatr
373 'showHideSuffix' => 'showhidepatr',
374 'default' => false,
375 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
376 &$query_options, &$join_conds ) {
377
378 $conds[] = 'rc_patrolled = 0';
379 },
380 'cssClassSuffix' => 'patrolled',
381 'isRowApplicableCallable' => function ( $ctx, $rc ) {
382 return $rc->getAttribute( 'rc_patrolled' );
383 },
384 ],
385 [
386 'name' => 'hideunpatrolled',
387 'label' => 'rcfilters-filter-unpatrolled-label',
388 'description' => 'rcfilters-filter-unpatrolled-description',
389 'default' => false,
390 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
391 &$query_options, &$join_conds ) {
392
393 $conds[] = 'rc_patrolled = 1';
394 },
395 'cssClassSuffix' => 'unpatrolled',
396 'isRowApplicableCallable' => function ( $ctx, $rc ) {
397 return !$rc->getAttribute( 'rc_patrolled' );
398 },
399 ],
400 ],
401 ]
402 ];
403
404 $this->hideCategorizationFilterDefinition = [
405 'name' => 'hidecategorization',
406 'label' => 'rcfilters-filter-categorization-label',
407 'description' => 'rcfilters-filter-categorization-description',
408 // rcshowhidecategorization-show, rcshowhidecategorization-hide.
409 // wlshowhidecategorization
410 'showHideSuffix' => 'showhidecategorization',
411 'default' => false,
412 'priority' => -4,
413 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
414 &$query_options, &$join_conds ) {
415
416 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_CATEGORIZE );
417 },
418 'cssClassSuffix' => 'src-mw-categorize',
419 'isRowApplicableCallable' => function ( $ctx, $rc ) {
420 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_CATEGORIZE;
421 },
422 ];
423 }
424
425 /**
426 * Main execution point
427 *
428 * @param string $subpage
429 */
430 public function execute( $subpage ) {
431 $this->rcSubpage = $subpage;
432
433 $this->setHeaders();
434 $this->outputHeader();
435 $this->addModules();
436
437 $rows = $this->getRows();
438 $opts = $this->getOptions();
439 if ( $rows === false ) {
440 if ( !$this->including() ) {
441 $this->doHeader( $opts, 0 );
442 $this->outputNoResults();
443 $this->getOutput()->setStatusCode( 404 );
444 }
445
446 return;
447 }
448
449 $batch = new LinkBatch;
450 foreach ( $rows as $row ) {
451 $batch->add( NS_USER, $row->rc_user_text );
452 $batch->add( NS_USER_TALK, $row->rc_user_text );
453 $batch->add( $row->rc_namespace, $row->rc_title );
454 if ( $row->rc_source === RecentChange::SRC_LOG ) {
455 $formatter = LogFormatter::newFromRow( $row );
456 foreach ( $formatter->getPreloadTitles() as $title ) {
457 $batch->addObj( $title );
458 }
459 }
460 }
461 $batch->execute();
462 $this->webOutput( $rows, $opts );
463
464 $rows->free();
465
466 if ( $this->getConfig()->get( 'EnableWANCacheReaper' ) ) {
467 // Clean up any bad page entries for titles showing up in RC
468 DeferredUpdates::addUpdate( new WANCacheReapUpdate(
469 $this->getDB(),
470 LoggerFactory::getInstance( 'objectcache' )
471 ) );
472 }
473 }
474
475 /**
476 * Add the "no results" message to the output
477 */
478 protected function outputNoResults() {
479 $this->getOutput()->addHTML(
480 '<div class="mw-changeslist-empty">' .
481 $this->msg( 'recentchanges-noresult' )->parse() .
482 '</div>'
483 );
484 }
485
486 /**
487 * Get the database result for this special page instance. Used by ApiFeedRecentChanges.
488 *
489 * @return bool|ResultWrapper Result or false
490 */
491 public function getRows() {
492 $opts = $this->getOptions();
493
494 $tables = [];
495 $fields = [];
496 $conds = [];
497 $query_options = [];
498 $join_conds = [];
499 $this->buildQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
500
501 return $this->doMainQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
502 }
503
504 /**
505 * Get the current FormOptions for this request
506 *
507 * @return FormOptions
508 */
509 public function getOptions() {
510 if ( $this->rcOptions === null ) {
511 $this->rcOptions = $this->setup( $this->rcSubpage );
512 }
513
514 return $this->rcOptions;
515 }
516
517 /**
518 * Register all filters and their groups (including those from hooks), plus handle
519 * conflicts and defaults.
520 *
521 * You might want to customize these in the same method, in subclasses. You can
522 * call getFilterGroup to access a group, and (on the group) getFilter to access a
523 * filter, then make necessary modfications to the filter or group (e.g. with
524 * setDefault).
525 */
526 protected function registerFilters() {
527 $this->registerFiltersFromDefinitions( $this->filterGroupDefinitions );
528
529 // Make sure this is not being transcluded (we don't want to show this
530 // information to all users just because the user that saves the edit can
531 // patrol)
532 if ( !$this->including() && $this->getUser()->useRCPatrol() ) {
533 $this->registerFiltersFromDefinitions( $this->reviewStatusFilterGroupDefinition );
534 }
535
536 $changeTypeGroup = $this->getFilterGroup( 'changeType' );
537
538 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
539 $transformedHideCategorizationDef = $this->transformFilterDefinition(
540 $this->hideCategorizationFilterDefinition
541 );
542
543 $transformedHideCategorizationDef['group'] = $changeTypeGroup;
544
545 $hideCategorization = new ChangesListBooleanFilter(
546 $transformedHideCategorizationDef
547 );
548 }
549
550 Hooks::run( 'ChangesListSpecialPageStructuredFilters', [ $this ] );
551
552 $unstructuredGroupDefinition =
553 $this->getFilterGroupDefinitionFromLegacyCustomFilters(
554 $this->getCustomFilters()
555 );
556 $this->registerFiltersFromDefinitions( [ $unstructuredGroupDefinition ] );
557
558 $userExperienceLevel = $this->getFilterGroup( 'userExpLevel' );
559
560 $registration = $this->getFilterGroup( 'registration' );
561 $anons = $registration->getFilter( 'hideanons' );
562
563 // This means there is a conflict between any item in user experience level
564 // being checked and only anons being *shown* (hideliu=1&hideanons=0 in the
565 // URL, or equivalent).
566 $userExperienceLevel->conflictsWith(
567 $anons,
568 'rcfilters-filtergroup-user-experience-level-conflicts-unregistered-global',
569 'rcfilters-filtergroup-user-experience-level-conflicts-unregistered',
570 'rcfilters-filter-unregistered-conflicts-user-experience-level'
571 );
572
573 $categoryFilter = $changeTypeGroup->getFilter( 'hidecategorization' );
574 $logactionsFilter = $changeTypeGroup->getFilter( 'hidelog' );
575 $pagecreationFilter = $changeTypeGroup->getFilter( 'hidenewpages' );
576
577 $significanceTypeGroup = $this->getFilterGroup( 'significance' );
578 $hideMinorFilter = $significanceTypeGroup->getFilter( 'hideminor' );
579
580 // categoryFilter is conditional; see registerFilters
581 if ( $categoryFilter !== null ) {
582 $hideMinorFilter->conflictsWith(
583 $categoryFilter,
584 'rcfilters-hideminor-conflicts-typeofchange-global',
585 'rcfilters-hideminor-conflicts-typeofchange',
586 'rcfilters-typeofchange-conflicts-hideminor'
587 );
588 }
589 $hideMinorFilter->conflictsWith(
590 $logactionsFilter,
591 'rcfilters-hideminor-conflicts-typeofchange-global',
592 'rcfilters-hideminor-conflicts-typeofchange',
593 'rcfilters-typeofchange-conflicts-hideminor'
594 );
595 $hideMinorFilter->conflictsWith(
596 $pagecreationFilter,
597 'rcfilters-hideminor-conflicts-typeofchange-global',
598 'rcfilters-hideminor-conflicts-typeofchange',
599 'rcfilters-typeofchange-conflicts-hideminor'
600 );
601 }
602
603 /**
604 * Transforms filter definition to prepare it for constructor.
605 *
606 * See overrides of this method as well.
607 *
608 * @param array $filterDefinition Original filter definition
609 *
610 * @return array Transformed definition
611 */
612 protected function transformFilterDefinition( array $filterDefinition ) {
613 return $filterDefinition;
614 }
615
616 /**
617 * Register filters from a definition object
618 *
619 * Array specifying groups and their filters; see Filter and
620 * ChangesListFilterGroup constructors.
621 *
622 * There is light processing to simplify core maintenance.
623 */
624 protected function registerFiltersFromDefinitions( array $definition ) {
625 $autoFillPriority = -1;
626 foreach ( $definition as $groupDefinition ) {
627 if ( !isset( $groupDefinition['priority'] ) ) {
628 $groupDefinition['priority'] = $autoFillPriority;
629 } else {
630 // If it's explicitly specified, start over the auto-fill
631 $autoFillPriority = $groupDefinition['priority'];
632 }
633
634 $autoFillPriority--;
635
636 $className = $groupDefinition['class'];
637 unset( $groupDefinition['class'] );
638
639 foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
640 $filterDefinition = $this->transformFilterDefinition( $filterDefinition );
641 }
642
643 $this->registerFilterGroup( new $className( $groupDefinition ) );
644 }
645 }
646
647 /**
648 * Get filter group definition from legacy custom filters
649 *
650 * @param array Custom filters from legacy hooks
651 * @return array Group definition
652 */
653 protected function getFilterGroupDefinitionFromLegacyCustomFilters( $customFilters ) {
654 // Special internal unstructured group
655 $unstructuredGroupDefinition = [
656 'name' => 'unstructured',
657 'class' => ChangesListBooleanFilterGroup::class,
658 'priority' => -1, // Won't display in structured
659 'filters' => [],
660 ];
661
662 foreach ( $customFilters as $name => $params ) {
663 $unstructuredGroupDefinition['filters'][] = [
664 'name' => $name,
665 'showHide' => $params['msg'],
666 'default' => $params['default'],
667 ];
668 }
669
670 return $unstructuredGroupDefinition;
671 }
672
673 /**
674 * Register all the filters, including legacy hook-driven ones.
675 * Then create a FormOptions object with options as specified by the user
676 *
677 * @param array $parameters
678 *
679 * @return FormOptions
680 */
681 public function setup( $parameters ) {
682 $this->registerFilters();
683
684 $opts = $this->getDefaultOptions();
685
686 $opts = $this->fetchOptionsFromRequest( $opts );
687
688 // Give precedence to subpage syntax
689 if ( $parameters !== null ) {
690 $this->parseParameters( $parameters, $opts );
691 }
692
693 $this->validateOptions( $opts );
694
695 return $opts;
696 }
697
698 /**
699 * Get a FormOptions object containing the default options. By default, returns
700 * some basic options. The filters listed explicitly here are overriden in this
701 * method, in subclasses, but most filters (e.g. hideminor, userExpLevel filters,
702 * and more) are structured. Structured filters are overriden in registerFilters.
703 * not here.
704 *
705 * @return FormOptions
706 */
707 public function getDefaultOptions() {
708 $config = $this->getConfig();
709 $opts = new FormOptions();
710 $structuredUI = $this->getUser()->getOption( 'rcenhancedfilters' );
711
712 // Add all filters
713 foreach ( $this->filterGroups as $filterGroup ) {
714 // URL parameters can be per-group, like 'userExpLevel',
715 // or per-filter, like 'hideminor'.
716 if ( $filterGroup->isPerGroupRequestParameter() ) {
717 $opts->add( $filterGroup->getName(), $filterGroup->getDefault() );
718 } else {
719 foreach ( $filterGroup->getFilters() as $filter ) {
720 $opts->add( $filter->getName(), $filter->getDefault( $structuredUI ) );
721 }
722 }
723 }
724
725 $opts->add( 'namespace', '', FormOptions::INTNULL );
726 $opts->add( 'invert', false );
727 $opts->add( 'associated', false );
728
729 return $opts;
730 }
731
732 /**
733 * Register a structured changes list filter group
734 *
735 * @param ChangesListFilterGroup $group
736 */
737 public function registerFilterGroup( ChangesListFilterGroup $group ) {
738 $groupName = $group->getName();
739
740 $this->filterGroups[$groupName] = $group;
741 }
742
743 /**
744 * Gets the currently registered filters groups
745 *
746 * @return array Associative array of ChangesListFilterGroup objects, with group name as key
747 */
748 protected function getFilterGroups() {
749 return $this->filterGroups;
750 }
751
752 /**
753 * Gets a specified ChangesListFilterGroup by name
754 *
755 * @param string $groupName Name of group
756 *
757 * @return ChangesListFilterGroup|null Group, or null if not registered
758 */
759 public function getFilterGroup( $groupName ) {
760 return isset( $this->filterGroups[$groupName] ) ?
761 $this->filterGroups[$groupName] :
762 null;
763 }
764
765 // Currently, this intentionally only includes filters that display
766 // in the structured UI. This can be changed easily, though, if we want
767 // to include data on filters that use the unstructured UI. messageKeys is a
768 // special top-level value, with the value being an array of the message keys to
769 // send to the client.
770 /**
771 * Gets structured filter information needed by JS
772 *
773 * @return array Associative array
774 * * array $return['groups'] Group data
775 * * array $return['messageKeys'] Array of message keys
776 */
777 public function getStructuredFilterJsData() {
778 $output = [
779 'groups' => [],
780 'messageKeys' => [],
781 ];
782
783 $context = $this->getContext();
784
785 usort( $this->filterGroups, function ( $a, $b ) {
786 return $b->getPriority() - $a->getPriority();
787 } );
788
789 foreach ( $this->filterGroups as $groupName => $group ) {
790 $groupOutput = $group->getJsData( $this );
791 if ( $groupOutput !== null ) {
792 $output['messageKeys'] = array_merge(
793 $output['messageKeys'],
794 $groupOutput['messageKeys']
795 );
796
797 unset( $groupOutput['messageKeys'] );
798 $output['groups'][] = $groupOutput;
799 }
800 }
801
802 return $output;
803 }
804
805 /**
806 * Get custom show/hide filters using deprecated ChangesListSpecialPageFilters
807 * hook.
808 *
809 * @return array Map of filter URL param names to properties (msg/default)
810 */
811 protected function getCustomFilters() {
812 if ( $this->customFilters === null ) {
813 $this->customFilters = [];
814 Hooks::run( 'ChangesListSpecialPageFilters', [ $this, &$this->customFilters ], '1.29' );
815 }
816
817 return $this->customFilters;
818 }
819
820 /**
821 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
822 *
823 * Intended for subclassing, e.g. to add a backwards-compatibility layer.
824 *
825 * @param FormOptions $opts
826 * @return FormOptions
827 */
828 protected function fetchOptionsFromRequest( $opts ) {
829 $opts->fetchValuesFromRequest( $this->getRequest() );
830
831 return $opts;
832 }
833
834 /**
835 * Process $par and put options found in $opts. Used when including the page.
836 *
837 * @param string $par
838 * @param FormOptions $opts
839 */
840 public function parseParameters( $par, FormOptions $opts ) {
841 $stringParameterNameSet = [];
842 $hideParameterNameSet = [];
843
844 // URL parameters can be per-group, like 'userExpLevel',
845 // or per-filter, like 'hideminor'.
846
847 foreach ( $this->filterGroups as $filterGroup ) {
848 if ( $filterGroup->isPerGroupRequestParameter() ) {
849 $stringParameterNameSet[$filterGroup->getName()] = true;
850 } elseif ( $filterGroup->getType() === ChangesListBooleanFilterGroup::TYPE ) {
851 foreach ( $filterGroup->getFilters() as $filter ) {
852 $hideParameterNameSet[$filter->getName()] = true;
853 }
854 }
855 }
856
857 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
858 foreach ( $bits as $bit ) {
859 $m = [];
860 if ( isset( $hideParameterNameSet[$bit] ) ) {
861 // hidefoo => hidefoo=true
862 $opts[$bit] = true;
863 } elseif ( isset( $hideParameterNameSet["hide$bit"] ) ) {
864 // foo => hidefoo=false
865 $opts["hide$bit"] = false;
866 } elseif ( preg_match( '/^(.*)=(.*)$/', $bit, $m ) ) {
867 if ( isset( $stringParameterNameSet[$m[1]] ) ) {
868 $opts[$m[1]] = $m[2];
869 }
870 }
871 }
872 }
873
874 /**
875 * Validate a FormOptions object generated by getDefaultOptions() with values already populated.
876 *
877 * @param FormOptions $opts
878 */
879 public function validateOptions( FormOptions $opts ) {
880 // nothing by default
881 }
882
883 /**
884 * Sets appropriate tables, fields, conditions, etc. depending on which filters
885 * the user requested.
886 *
887 * @param array &$tables Array of tables; see IDatabase::select $table
888 * @param array &$fields Array of fields; see IDatabase::select $vars
889 * @param array &$conds Array of conditions; see IDatabase::select $conds
890 * @param array &$query_options Array of query options; see IDatabase::select $options
891 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
892 * @param FormOptions $opts
893 */
894 protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
895 &$join_conds, FormOptions $opts ) {
896
897 $dbr = $this->getDB();
898 $user = $this->getUser();
899
900 $context = $this->getContext();
901 foreach ( $this->filterGroups as $filterGroup ) {
902 // URL parameters can be per-group, like 'userExpLevel',
903 // or per-filter, like 'hideminor'.
904 if ( $filterGroup->isPerGroupRequestParameter() ) {
905 $filterGroup->modifyQuery( $dbr, $this, $tables, $fields, $conds,
906 $query_options, $join_conds, $opts[$filterGroup->getName()] );
907 } else {
908 foreach ( $filterGroup->getFilters() as $filter ) {
909 if ( $opts[$filter->getName()] ) {
910 $filter->modifyQuery( $dbr, $this, $tables, $fields, $conds,
911 $query_options, $join_conds );
912 }
913 }
914 }
915 }
916
917 // Namespace filtering
918 if ( $opts['namespace'] !== '' ) {
919 $selectedNS = $dbr->addQuotes( $opts['namespace'] );
920 $operator = $opts['invert'] ? '!=' : '=';
921 $boolean = $opts['invert'] ? 'AND' : 'OR';
922
923 // Namespace association (T4429)
924 if ( !$opts['associated'] ) {
925 $condition = "rc_namespace $operator $selectedNS";
926 } else {
927 // Also add the associated namespace
928 $associatedNS = $dbr->addQuotes(
929 MWNamespace::getAssociated( $opts['namespace'] )
930 );
931 $condition = "(rc_namespace $operator $selectedNS "
932 . $boolean
933 . " rc_namespace $operator $associatedNS)";
934 }
935
936 $conds[] = $condition;
937 }
938 }
939
940 /**
941 * Process the query
942 *
943 * @param array $tables Array of tables; see IDatabase::select $table
944 * @param array $fields Array of fields; see IDatabase::select $vars
945 * @param array $conds Array of conditions; see IDatabase::select $conds
946 * @param array $query_options Array of query options; see IDatabase::select $options
947 * @param array $join_conds Array of join conditions; see IDatabase::select $join_conds
948 * @param FormOptions $opts
949 * @return bool|ResultWrapper Result or false
950 */
951 protected function doMainQuery( $tables, $fields, $conds,
952 $query_options, $join_conds, FormOptions $opts ) {
953
954 $tables[] = 'recentchanges';
955 $fields = array_merge( RecentChange::selectFields(), $fields );
956
957 ChangeTags::modifyDisplayQuery(
958 $tables,
959 $fields,
960 $conds,
961 $join_conds,
962 $query_options,
963 ''
964 );
965
966 // It makes no sense to hide both anons and logged-in users. When this occurs, try a guess on
967 // what the user meant and either show only bots or force anons to be shown.
968
969 // -------
970
971 // XXX: We're no longer doing this handling. To preserve back-compat, we need to complete
972 // T151873 (particularly the hideanons/hideliu/hidebots/hidehumans part) in conjunction
973 // with merging this.
974
975 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
976 $opts )
977 ) {
978 return false;
979 }
980
981 $dbr = $this->getDB();
982
983 return $dbr->select(
984 $tables,
985 $fields,
986 $conds,
987 __METHOD__,
988 $query_options,
989 $join_conds
990 );
991 }
992
993 protected function runMainQueryHook( &$tables, &$fields, &$conds,
994 &$query_options, &$join_conds, $opts
995 ) {
996 return Hooks::run(
997 'ChangesListSpecialPageQuery',
998 [ $this->getName(), &$tables, &$fields, &$conds, &$query_options, &$join_conds, $opts ]
999 );
1000 }
1001
1002 /**
1003 * Return a IDatabase object for reading
1004 *
1005 * @return IDatabase
1006 */
1007 protected function getDB() {
1008 return wfGetDB( DB_REPLICA );
1009 }
1010
1011 /**
1012 * Send output to the OutputPage object, only called if not used feeds
1013 *
1014 * @param ResultWrapper $rows Database rows
1015 * @param FormOptions $opts
1016 */
1017 public function webOutput( $rows, $opts ) {
1018 if ( !$this->including() ) {
1019 $this->outputFeedLinks();
1020 $this->doHeader( $opts, $rows->numRows() );
1021 }
1022
1023 $this->outputChangesList( $rows, $opts );
1024 }
1025
1026 /**
1027 * Output feed links.
1028 */
1029 public function outputFeedLinks() {
1030 // nothing by default
1031 }
1032
1033 /**
1034 * Build and output the actual changes list.
1035 *
1036 * @param ResultWrapper $rows Database rows
1037 * @param FormOptions $opts
1038 */
1039 abstract public function outputChangesList( $rows, $opts );
1040
1041 /**
1042 * Set the text to be displayed above the changes
1043 *
1044 * @param FormOptions $opts
1045 * @param int $numRows Number of rows in the result to show after this header
1046 */
1047 public function doHeader( $opts, $numRows ) {
1048 $this->setTopText( $opts );
1049
1050 // @todo Lots of stuff should be done here.
1051
1052 $this->setBottomText( $opts );
1053 }
1054
1055 /**
1056 * Send the text to be displayed before the options. Should use $this->getOutput()->addWikiText()
1057 * or similar methods to print the text.
1058 *
1059 * @param FormOptions $opts
1060 */
1061 public function setTopText( FormOptions $opts ) {
1062 // nothing by default
1063 }
1064
1065 /**
1066 * Send the text to be displayed after the options. Should use $this->getOutput()->addWikiText()
1067 * or similar methods to print the text.
1068 *
1069 * @param FormOptions $opts
1070 */
1071 public function setBottomText( FormOptions $opts ) {
1072 // nothing by default
1073 }
1074
1075 /**
1076 * Get options to be displayed in a form
1077 * @todo This should handle options returned by getDefaultOptions().
1078 * @todo Not called by anything in this class (but is in subclasses), should be
1079 * called by something… doHeader() maybe?
1080 *
1081 * @param FormOptions $opts
1082 * @return array
1083 */
1084 public function getExtraOptions( $opts ) {
1085 return [];
1086 }
1087
1088 /**
1089 * Return the legend displayed within the fieldset
1090 *
1091 * @return string
1092 */
1093 public function makeLegend() {
1094 $context = $this->getContext();
1095 $user = $context->getUser();
1096 # The legend showing what the letters and stuff mean
1097 $legend = Html::openElement( 'dl' ) . "\n";
1098 # Iterates through them and gets the messages for both letter and tooltip
1099 $legendItems = $context->getConfig()->get( 'RecentChangesFlags' );
1100 if ( !( $user->useRCPatrol() || $user->useNPPatrol() ) ) {
1101 unset( $legendItems['unpatrolled'] );
1102 }
1103 foreach ( $legendItems as $key => $item ) { # generate items of the legend
1104 $label = isset( $item['legend'] ) ? $item['legend'] : $item['title'];
1105 $letter = $item['letter'];
1106 $cssClass = isset( $item['class'] ) ? $item['class'] : $key;
1107
1108 $legend .= Html::element( 'dt',
1109 [ 'class' => $cssClass ], $context->msg( $letter )->text()
1110 ) . "\n" .
1111 Html::rawElement( 'dd',
1112 [ 'class' => Sanitizer::escapeClass( 'mw-changeslist-legend-' . $key ) ],
1113 $context->msg( $label )->parse()
1114 ) . "\n";
1115 }
1116 # (+-123)
1117 $legend .= Html::rawElement( 'dt',
1118 [ 'class' => 'mw-plusminus-pos' ],
1119 $context->msg( 'recentchanges-legend-plusminus' )->parse()
1120 ) . "\n";
1121 $legend .= Html::element(
1122 'dd',
1123 [ 'class' => 'mw-changeslist-legend-plusminus' ],
1124 $context->msg( 'recentchanges-label-plusminus' )->text()
1125 ) . "\n";
1126 $legend .= Html::closeElement( 'dl' ) . "\n";
1127
1128 # Collapsibility
1129 $legend =
1130 '<div class="mw-changeslist-legend">' .
1131 $context->msg( 'recentchanges-legend-heading' )->parse() .
1132 '<div class="mw-collapsible-content">' . $legend . '</div>' .
1133 '</div>';
1134
1135 return $legend;
1136 }
1137
1138 /**
1139 * Add page-specific modules.
1140 */
1141 protected function addModules() {
1142 $out = $this->getOutput();
1143 // Styles and behavior for the legend box (see makeLegend())
1144 $out->addModuleStyles( [
1145 'mediawiki.special.changeslist.legend',
1146 'mediawiki.special.changeslist',
1147 ] );
1148 $out->addModules( 'mediawiki.special.changeslist.legend.js' );
1149 }
1150
1151 protected function getGroupName() {
1152 return 'changes';
1153 }
1154
1155 /**
1156 * Filter on users' experience levels; this will not be called if nothing is
1157 * selected.
1158 *
1159 * @param string $specialPageClassName Class name of current special page
1160 * @param IContextSource $context Context, for e.g. user
1161 * @param IDatabase $dbr Database, for addQuotes, makeList, and similar
1162 * @param array &$tables Array of tables; see IDatabase::select $table
1163 * @param array &$fields Array of fields; see IDatabase::select $vars
1164 * @param array &$conds Array of conditions; see IDatabase::select $conds
1165 * @param array &$query_options Array of query options; see IDatabase::select $options
1166 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1167 * @param array $selectedExpLevels The allowed active values, sorted
1168 */
1169 public function filterOnUserExperienceLevel( $specialPageClassName, $context, $dbr,
1170 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedExpLevels ) {
1171
1172 global $wgLearnerEdits,
1173 $wgExperiencedUserEdits,
1174 $wgLearnerMemberSince,
1175 $wgExperiencedUserMemberSince;
1176
1177 $LEVEL_COUNT = 3;
1178
1179 // If all levels are selected, all logged-in users are included (but no
1180 // anons), so we can short-circuit.
1181 if ( count( $selectedExpLevels ) === $LEVEL_COUNT ) {
1182 $conds[] = 'rc_user != 0';
1183 return;
1184 }
1185
1186 $tables[] = 'user';
1187 $join_conds['user'] = [ 'LEFT JOIN', 'rc_user = user_id' ];
1188
1189 $now = time();
1190 $secondsPerDay = 86400;
1191 $learnerCutoff = $now - $wgLearnerMemberSince * $secondsPerDay;
1192 $experiencedUserCutoff = $now - $wgExperiencedUserMemberSince * $secondsPerDay;
1193
1194 $aboveNewcomer = $dbr->makeList(
1195 [
1196 'user_editcount >= ' . intval( $wgLearnerEdits ),
1197 'user_registration <= ' . $dbr->timestamp( $learnerCutoff ),
1198 ],
1199 IDatabase::LIST_AND
1200 );
1201
1202 $aboveLearner = $dbr->makeList(
1203 [
1204 'user_editcount >= ' . intval( $wgExperiencedUserEdits ),
1205 'user_registration <= ' . $dbr->timestamp( $experiencedUserCutoff ),
1206 ],
1207 IDatabase::LIST_AND
1208 );
1209
1210 if ( $selectedExpLevels === [ 'newcomer' ] ) {
1211 $conds[] = "NOT ( $aboveNewcomer )";
1212 } elseif ( $selectedExpLevels === [ 'learner' ] ) {
1213 $conds[] = $dbr->makeList(
1214 [ $aboveNewcomer, "NOT ( $aboveLearner )" ],
1215 IDatabase::LIST_AND
1216 );
1217 } elseif ( $selectedExpLevels === [ 'experienced' ] ) {
1218 $conds[] = $aboveLearner;
1219 } elseif ( $selectedExpLevels === [ 'learner', 'newcomer' ] ) {
1220 $conds[] = "NOT ( $aboveLearner )";
1221 } elseif ( $selectedExpLevels === [ 'experienced', 'newcomer' ] ) {
1222 $conds[] = $dbr->makeList(
1223 [ "NOT ( $aboveNewcomer )", $aboveLearner ],
1224 IDatabase::LIST_OR
1225 );
1226 } elseif ( $selectedExpLevels === [ 'experienced', 'learner' ] ) {
1227 $conds[] = $aboveNewcomer;
1228 }
1229 }
1230 }