Merge "Send 500 http status code, instead of 200, for DBConnectionErrors"
[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 * Check if filters are in conflict and guaranteed to return no results.
427 *
428 * @return bool
429 */
430 protected function areFiltersInConflict() {
431 $opts = $this->getOptions();
432 /** @var ChangesListFilterGroup $group */
433 foreach ( $this->getFilterGroups() as $group ) {
434
435 if ( $group->getConflictingGroups() ) {
436 wfLogWarning(
437 $group->getName() .
438 " specifies conflicts with other groups but these are not supported yet."
439 );
440 }
441
442 /** @var ChangesListFilter $conflictingFilter */
443 foreach ( $group->getConflictingFilters() as $conflictingFilter ) {
444 if ( $conflictingFilter->activelyInConflictWithGroup( $group, $opts ) ) {
445 return true;
446 }
447 }
448
449 /** @var ChangesListFilter $filter */
450 foreach ( $group->getFilters() as $filter ) {
451
452 /** @var ChangesListFilter $conflictingFilter */
453 foreach ( $filter->getConflictingFilters() as $conflictingFilter ) {
454 if (
455 $conflictingFilter->activelyInConflictWithFilter( $filter, $opts ) &&
456 $filter->activelyInConflictWithFilter( $conflictingFilter, $opts )
457 ) {
458 return true;
459 }
460 }
461
462 }
463
464 }
465
466 return false;
467 }
468
469 /**
470 * Main execution point
471 *
472 * @param string $subpage
473 */
474 public function execute( $subpage ) {
475 $this->rcSubpage = $subpage;
476
477 $this->setHeaders();
478 $this->outputHeader();
479 $this->addModules();
480
481 $rows = $this->getRows();
482 $opts = $this->getOptions();
483 if ( $rows === false ) {
484 if ( !$this->including() ) {
485 $this->doHeader( $opts, 0 );
486 $this->outputNoResults();
487 $this->getOutput()->setStatusCode( 404 );
488 }
489
490 return;
491 }
492
493 $batch = new LinkBatch;
494 foreach ( $rows as $row ) {
495 $batch->add( NS_USER, $row->rc_user_text );
496 $batch->add( NS_USER_TALK, $row->rc_user_text );
497 $batch->add( $row->rc_namespace, $row->rc_title );
498 if ( $row->rc_source === RecentChange::SRC_LOG ) {
499 $formatter = LogFormatter::newFromRow( $row );
500 foreach ( $formatter->getPreloadTitles() as $title ) {
501 $batch->addObj( $title );
502 }
503 }
504 }
505 $batch->execute();
506 $this->webOutput( $rows, $opts );
507
508 $rows->free();
509
510 if ( $this->getConfig()->get( 'EnableWANCacheReaper' ) ) {
511 // Clean up any bad page entries for titles showing up in RC
512 DeferredUpdates::addUpdate( new WANCacheReapUpdate(
513 $this->getDB(),
514 LoggerFactory::getInstance( 'objectcache' )
515 ) );
516 }
517 }
518
519 /**
520 * Add the "no results" message to the output
521 */
522 protected function outputNoResults() {
523 $this->getOutput()->addHTML(
524 '<div class="mw-changeslist-empty">' .
525 $this->msg( 'recentchanges-noresult' )->parse() .
526 '</div>'
527 );
528 }
529
530 /**
531 * Get the database result for this special page instance. Used by ApiFeedRecentChanges.
532 *
533 * @return bool|ResultWrapper Result or false
534 */
535 public function getRows() {
536 $opts = $this->getOptions();
537
538 $tables = [];
539 $fields = [];
540 $conds = [];
541 $query_options = [];
542 $join_conds = [];
543 $this->buildQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
544
545 return $this->doMainQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
546 }
547
548 /**
549 * Get the current FormOptions for this request
550 *
551 * @return FormOptions
552 */
553 public function getOptions() {
554 if ( $this->rcOptions === null ) {
555 $this->rcOptions = $this->setup( $this->rcSubpage );
556 }
557
558 return $this->rcOptions;
559 }
560
561 /**
562 * Register all filters and their groups (including those from hooks), plus handle
563 * conflicts and defaults.
564 *
565 * You might want to customize these in the same method, in subclasses. You can
566 * call getFilterGroup to access a group, and (on the group) getFilter to access a
567 * filter, then make necessary modfications to the filter or group (e.g. with
568 * setDefault).
569 */
570 protected function registerFilters() {
571 $this->registerFiltersFromDefinitions( $this->filterGroupDefinitions );
572
573 // Make sure this is not being transcluded (we don't want to show this
574 // information to all users just because the user that saves the edit can
575 // patrol)
576 if ( !$this->including() && $this->getUser()->useRCPatrol() ) {
577 $this->registerFiltersFromDefinitions( $this->reviewStatusFilterGroupDefinition );
578 }
579
580 $changeTypeGroup = $this->getFilterGroup( 'changeType' );
581
582 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
583 $transformedHideCategorizationDef = $this->transformFilterDefinition(
584 $this->hideCategorizationFilterDefinition
585 );
586
587 $transformedHideCategorizationDef['group'] = $changeTypeGroup;
588
589 $hideCategorization = new ChangesListBooleanFilter(
590 $transformedHideCategorizationDef
591 );
592 }
593
594 Hooks::run( 'ChangesListSpecialPageStructuredFilters', [ $this ] );
595
596 $unstructuredGroupDefinition =
597 $this->getFilterGroupDefinitionFromLegacyCustomFilters(
598 $this->getCustomFilters()
599 );
600 $this->registerFiltersFromDefinitions( [ $unstructuredGroupDefinition ] );
601
602 $userExperienceLevel = $this->getFilterGroup( 'userExpLevel' );
603
604 $registration = $this->getFilterGroup( 'registration' );
605 $anons = $registration->getFilter( 'hideanons' );
606
607 // This means there is a conflict between any item in user experience level
608 // being checked and only anons being *shown* (hideliu=1&hideanons=0 in the
609 // URL, or equivalent).
610 $userExperienceLevel->conflictsWith(
611 $anons,
612 'rcfilters-filtergroup-user-experience-level-conflicts-unregistered-global',
613 'rcfilters-filtergroup-user-experience-level-conflicts-unregistered',
614 'rcfilters-filter-unregistered-conflicts-user-experience-level'
615 );
616
617 $categoryFilter = $changeTypeGroup->getFilter( 'hidecategorization' );
618 $logactionsFilter = $changeTypeGroup->getFilter( 'hidelog' );
619 $pagecreationFilter = $changeTypeGroup->getFilter( 'hidenewpages' );
620
621 $significanceTypeGroup = $this->getFilterGroup( 'significance' );
622 $hideMinorFilter = $significanceTypeGroup->getFilter( 'hideminor' );
623
624 // categoryFilter is conditional; see registerFilters
625 if ( $categoryFilter !== null ) {
626 $hideMinorFilter->conflictsWith(
627 $categoryFilter,
628 'rcfilters-hideminor-conflicts-typeofchange-global',
629 'rcfilters-hideminor-conflicts-typeofchange',
630 'rcfilters-typeofchange-conflicts-hideminor'
631 );
632 }
633 $hideMinorFilter->conflictsWith(
634 $logactionsFilter,
635 'rcfilters-hideminor-conflicts-typeofchange-global',
636 'rcfilters-hideminor-conflicts-typeofchange',
637 'rcfilters-typeofchange-conflicts-hideminor'
638 );
639 $hideMinorFilter->conflictsWith(
640 $pagecreationFilter,
641 'rcfilters-hideminor-conflicts-typeofchange-global',
642 'rcfilters-hideminor-conflicts-typeofchange',
643 'rcfilters-typeofchange-conflicts-hideminor'
644 );
645 }
646
647 /**
648 * Transforms filter definition to prepare it for constructor.
649 *
650 * See overrides of this method as well.
651 *
652 * @param array $filterDefinition Original filter definition
653 *
654 * @return array Transformed definition
655 */
656 protected function transformFilterDefinition( array $filterDefinition ) {
657 return $filterDefinition;
658 }
659
660 /**
661 * Register filters from a definition object
662 *
663 * Array specifying groups and their filters; see Filter and
664 * ChangesListFilterGroup constructors.
665 *
666 * There is light processing to simplify core maintenance.
667 */
668 protected function registerFiltersFromDefinitions( array $definition ) {
669 $autoFillPriority = -1;
670 foreach ( $definition as $groupDefinition ) {
671 if ( !isset( $groupDefinition['priority'] ) ) {
672 $groupDefinition['priority'] = $autoFillPriority;
673 } else {
674 // If it's explicitly specified, start over the auto-fill
675 $autoFillPriority = $groupDefinition['priority'];
676 }
677
678 $autoFillPriority--;
679
680 $className = $groupDefinition['class'];
681 unset( $groupDefinition['class'] );
682
683 foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
684 $filterDefinition = $this->transformFilterDefinition( $filterDefinition );
685 }
686
687 $this->registerFilterGroup( new $className( $groupDefinition ) );
688 }
689 }
690
691 /**
692 * Get filter group definition from legacy custom filters
693 *
694 * @param array Custom filters from legacy hooks
695 * @return array Group definition
696 */
697 protected function getFilterGroupDefinitionFromLegacyCustomFilters( $customFilters ) {
698 // Special internal unstructured group
699 $unstructuredGroupDefinition = [
700 'name' => 'unstructured',
701 'class' => ChangesListBooleanFilterGroup::class,
702 'priority' => -1, // Won't display in structured
703 'filters' => [],
704 ];
705
706 foreach ( $customFilters as $name => $params ) {
707 $unstructuredGroupDefinition['filters'][] = [
708 'name' => $name,
709 'showHide' => $params['msg'],
710 'default' => $params['default'],
711 ];
712 }
713
714 return $unstructuredGroupDefinition;
715 }
716
717 /**
718 * Register all the filters, including legacy hook-driven ones.
719 * Then create a FormOptions object with options as specified by the user
720 *
721 * @param array $parameters
722 *
723 * @return FormOptions
724 */
725 public function setup( $parameters ) {
726 $this->registerFilters();
727
728 $opts = $this->getDefaultOptions();
729
730 $opts = $this->fetchOptionsFromRequest( $opts );
731
732 // Give precedence to subpage syntax
733 if ( $parameters !== null ) {
734 $this->parseParameters( $parameters, $opts );
735 }
736
737 $this->validateOptions( $opts );
738
739 return $opts;
740 }
741
742 /**
743 * Get a FormOptions object containing the default options. By default, returns
744 * some basic options. The filters listed explicitly here are overriden in this
745 * method, in subclasses, but most filters (e.g. hideminor, userExpLevel filters,
746 * and more) are structured. Structured filters are overriden in registerFilters.
747 * not here.
748 *
749 * @return FormOptions
750 */
751 public function getDefaultOptions() {
752 $config = $this->getConfig();
753 $opts = new FormOptions();
754 $structuredUI = $this->getUser()->getOption( 'rcenhancedfilters' );
755
756 // Add all filters
757 foreach ( $this->filterGroups as $filterGroup ) {
758 // URL parameters can be per-group, like 'userExpLevel',
759 // or per-filter, like 'hideminor'.
760 if ( $filterGroup->isPerGroupRequestParameter() ) {
761 $opts->add( $filterGroup->getName(), $filterGroup->getDefault() );
762 } else {
763 foreach ( $filterGroup->getFilters() as $filter ) {
764 $opts->add( $filter->getName(), $filter->getDefault( $structuredUI ) );
765 }
766 }
767 }
768
769 $opts->add( 'namespace', '', FormOptions::INTNULL );
770 $opts->add( 'invert', false );
771 $opts->add( 'associated', false );
772
773 return $opts;
774 }
775
776 /**
777 * Register a structured changes list filter group
778 *
779 * @param ChangesListFilterGroup $group
780 */
781 public function registerFilterGroup( ChangesListFilterGroup $group ) {
782 $groupName = $group->getName();
783
784 $this->filterGroups[$groupName] = $group;
785 }
786
787 /**
788 * Gets the currently registered filters groups
789 *
790 * @return array Associative array of ChangesListFilterGroup objects, with group name as key
791 */
792 protected function getFilterGroups() {
793 return $this->filterGroups;
794 }
795
796 /**
797 * Gets a specified ChangesListFilterGroup by name
798 *
799 * @param string $groupName Name of group
800 *
801 * @return ChangesListFilterGroup|null Group, or null if not registered
802 */
803 public function getFilterGroup( $groupName ) {
804 return isset( $this->filterGroups[$groupName] ) ?
805 $this->filterGroups[$groupName] :
806 null;
807 }
808
809 // Currently, this intentionally only includes filters that display
810 // in the structured UI. This can be changed easily, though, if we want
811 // to include data on filters that use the unstructured UI. messageKeys is a
812 // special top-level value, with the value being an array of the message keys to
813 // send to the client.
814 /**
815 * Gets structured filter information needed by JS
816 *
817 * @return array Associative array
818 * * array $return['groups'] Group data
819 * * array $return['messageKeys'] Array of message keys
820 */
821 public function getStructuredFilterJsData() {
822 $output = [
823 'groups' => [],
824 'messageKeys' => [],
825 ];
826
827 $context = $this->getContext();
828
829 usort( $this->filterGroups, function ( $a, $b ) {
830 return $b->getPriority() - $a->getPriority();
831 } );
832
833 foreach ( $this->filterGroups as $groupName => $group ) {
834 $groupOutput = $group->getJsData( $this );
835 if ( $groupOutput !== null ) {
836 $output['messageKeys'] = array_merge(
837 $output['messageKeys'],
838 $groupOutput['messageKeys']
839 );
840
841 unset( $groupOutput['messageKeys'] );
842 $output['groups'][] = $groupOutput;
843 }
844 }
845
846 return $output;
847 }
848
849 /**
850 * Get custom show/hide filters using deprecated ChangesListSpecialPageFilters
851 * hook.
852 *
853 * @return array Map of filter URL param names to properties (msg/default)
854 */
855 protected function getCustomFilters() {
856 if ( $this->customFilters === null ) {
857 $this->customFilters = [];
858 Hooks::run( 'ChangesListSpecialPageFilters', [ $this, &$this->customFilters ], '1.29' );
859 }
860
861 return $this->customFilters;
862 }
863
864 /**
865 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
866 *
867 * Intended for subclassing, e.g. to add a backwards-compatibility layer.
868 *
869 * @param FormOptions $opts
870 * @return FormOptions
871 */
872 protected function fetchOptionsFromRequest( $opts ) {
873 $opts->fetchValuesFromRequest( $this->getRequest() );
874
875 return $opts;
876 }
877
878 /**
879 * Process $par and put options found in $opts. Used when including the page.
880 *
881 * @param string $par
882 * @param FormOptions $opts
883 */
884 public function parseParameters( $par, FormOptions $opts ) {
885 $stringParameterNameSet = [];
886 $hideParameterNameSet = [];
887
888 // URL parameters can be per-group, like 'userExpLevel',
889 // or per-filter, like 'hideminor'.
890
891 foreach ( $this->filterGroups as $filterGroup ) {
892 if ( $filterGroup->isPerGroupRequestParameter() ) {
893 $stringParameterNameSet[$filterGroup->getName()] = true;
894 } elseif ( $filterGroup->getType() === ChangesListBooleanFilterGroup::TYPE ) {
895 foreach ( $filterGroup->getFilters() as $filter ) {
896 $hideParameterNameSet[$filter->getName()] = true;
897 }
898 }
899 }
900
901 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
902 foreach ( $bits as $bit ) {
903 $m = [];
904 if ( isset( $hideParameterNameSet[$bit] ) ) {
905 // hidefoo => hidefoo=true
906 $opts[$bit] = true;
907 } elseif ( isset( $hideParameterNameSet["hide$bit"] ) ) {
908 // foo => hidefoo=false
909 $opts["hide$bit"] = false;
910 } elseif ( preg_match( '/^(.*)=(.*)$/', $bit, $m ) ) {
911 if ( isset( $stringParameterNameSet[$m[1]] ) ) {
912 $opts[$m[1]] = $m[2];
913 }
914 }
915 }
916 }
917
918 /**
919 * Validate a FormOptions object generated by getDefaultOptions() with values already populated.
920 *
921 * @param FormOptions $opts
922 */
923 public function validateOptions( FormOptions $opts ) {
924 // nothing by default
925 }
926
927 /**
928 * Sets appropriate tables, fields, conditions, etc. depending on which filters
929 * the user requested.
930 *
931 * @param array &$tables Array of tables; see IDatabase::select $table
932 * @param array &$fields Array of fields; see IDatabase::select $vars
933 * @param array &$conds Array of conditions; see IDatabase::select $conds
934 * @param array &$query_options Array of query options; see IDatabase::select $options
935 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
936 * @param FormOptions $opts
937 */
938 protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
939 &$join_conds, FormOptions $opts ) {
940
941 $dbr = $this->getDB();
942 $user = $this->getUser();
943
944 $context = $this->getContext();
945 foreach ( $this->filterGroups as $filterGroup ) {
946 // URL parameters can be per-group, like 'userExpLevel',
947 // or per-filter, like 'hideminor'.
948 if ( $filterGroup->isPerGroupRequestParameter() ) {
949 $filterGroup->modifyQuery( $dbr, $this, $tables, $fields, $conds,
950 $query_options, $join_conds, $opts[$filterGroup->getName()] );
951 } else {
952 foreach ( $filterGroup->getFilters() as $filter ) {
953 if ( $opts[$filter->getName()] ) {
954 $filter->modifyQuery( $dbr, $this, $tables, $fields, $conds,
955 $query_options, $join_conds );
956 }
957 }
958 }
959 }
960
961 // Namespace filtering
962 if ( $opts['namespace'] !== '' ) {
963 $selectedNS = $dbr->addQuotes( $opts['namespace'] );
964 $operator = $opts['invert'] ? '!=' : '=';
965 $boolean = $opts['invert'] ? 'AND' : 'OR';
966
967 // Namespace association (T4429)
968 if ( !$opts['associated'] ) {
969 $condition = "rc_namespace $operator $selectedNS";
970 } else {
971 // Also add the associated namespace
972 $associatedNS = $dbr->addQuotes(
973 MWNamespace::getAssociated( $opts['namespace'] )
974 );
975 $condition = "(rc_namespace $operator $selectedNS "
976 . $boolean
977 . " rc_namespace $operator $associatedNS)";
978 }
979
980 $conds[] = $condition;
981 }
982 }
983
984 /**
985 * Process the query
986 *
987 * @param array $tables Array of tables; see IDatabase::select $table
988 * @param array $fields Array of fields; see IDatabase::select $vars
989 * @param array $conds Array of conditions; see IDatabase::select $conds
990 * @param array $query_options Array of query options; see IDatabase::select $options
991 * @param array $join_conds Array of join conditions; see IDatabase::select $join_conds
992 * @param FormOptions $opts
993 * @return bool|ResultWrapper Result or false
994 */
995 protected function doMainQuery( $tables, $fields, $conds,
996 $query_options, $join_conds, FormOptions $opts ) {
997
998 $tables[] = 'recentchanges';
999 $fields = array_merge( RecentChange::selectFields(), $fields );
1000
1001 ChangeTags::modifyDisplayQuery(
1002 $tables,
1003 $fields,
1004 $conds,
1005 $join_conds,
1006 $query_options,
1007 ''
1008 );
1009
1010 // It makes no sense to hide both anons and logged-in users. When this occurs, try a guess on
1011 // what the user meant and either show only bots or force anons to be shown.
1012
1013 // -------
1014
1015 // XXX: We're no longer doing this handling. To preserve back-compat, we need to complete
1016 // T151873 (particularly the hideanons/hideliu/hidebots/hidehumans part) in conjunction
1017 // with merging this.
1018
1019 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
1020 $opts )
1021 ) {
1022 return false;
1023 }
1024
1025 $dbr = $this->getDB();
1026
1027 return $dbr->select(
1028 $tables,
1029 $fields,
1030 $conds,
1031 __METHOD__,
1032 $query_options,
1033 $join_conds
1034 );
1035 }
1036
1037 protected function runMainQueryHook( &$tables, &$fields, &$conds,
1038 &$query_options, &$join_conds, $opts
1039 ) {
1040 return Hooks::run(
1041 'ChangesListSpecialPageQuery',
1042 [ $this->getName(), &$tables, &$fields, &$conds, &$query_options, &$join_conds, $opts ]
1043 );
1044 }
1045
1046 /**
1047 * Return a IDatabase object for reading
1048 *
1049 * @return IDatabase
1050 */
1051 protected function getDB() {
1052 return wfGetDB( DB_REPLICA );
1053 }
1054
1055 /**
1056 * Send output to the OutputPage object, only called if not used feeds
1057 *
1058 * @param ResultWrapper $rows Database rows
1059 * @param FormOptions $opts
1060 */
1061 public function webOutput( $rows, $opts ) {
1062 if ( !$this->including() ) {
1063 $this->outputFeedLinks();
1064 $this->doHeader( $opts, $rows->numRows() );
1065 }
1066
1067 $this->outputChangesList( $rows, $opts );
1068 }
1069
1070 /**
1071 * Output feed links.
1072 */
1073 public function outputFeedLinks() {
1074 // nothing by default
1075 }
1076
1077 /**
1078 * Build and output the actual changes list.
1079 *
1080 * @param ResultWrapper $rows Database rows
1081 * @param FormOptions $opts
1082 */
1083 abstract public function outputChangesList( $rows, $opts );
1084
1085 /**
1086 * Set the text to be displayed above the changes
1087 *
1088 * @param FormOptions $opts
1089 * @param int $numRows Number of rows in the result to show after this header
1090 */
1091 public function doHeader( $opts, $numRows ) {
1092 $this->setTopText( $opts );
1093
1094 // @todo Lots of stuff should be done here.
1095
1096 $this->setBottomText( $opts );
1097 }
1098
1099 /**
1100 * Send the text to be displayed before the options. Should use $this->getOutput()->addWikiText()
1101 * or similar methods to print the text.
1102 *
1103 * @param FormOptions $opts
1104 */
1105 public function setTopText( FormOptions $opts ) {
1106 // nothing by default
1107 }
1108
1109 /**
1110 * Send the text to be displayed after the options. Should use $this->getOutput()->addWikiText()
1111 * or similar methods to print the text.
1112 *
1113 * @param FormOptions $opts
1114 */
1115 public function setBottomText( FormOptions $opts ) {
1116 // nothing by default
1117 }
1118
1119 /**
1120 * Get options to be displayed in a form
1121 * @todo This should handle options returned by getDefaultOptions().
1122 * @todo Not called by anything in this class (but is in subclasses), should be
1123 * called by something… doHeader() maybe?
1124 *
1125 * @param FormOptions $opts
1126 * @return array
1127 */
1128 public function getExtraOptions( $opts ) {
1129 return [];
1130 }
1131
1132 /**
1133 * Return the legend displayed within the fieldset
1134 *
1135 * @return string
1136 */
1137 public function makeLegend() {
1138 $context = $this->getContext();
1139 $user = $context->getUser();
1140 # The legend showing what the letters and stuff mean
1141 $legend = Html::openElement( 'dl' ) . "\n";
1142 # Iterates through them and gets the messages for both letter and tooltip
1143 $legendItems = $context->getConfig()->get( 'RecentChangesFlags' );
1144 if ( !( $user->useRCPatrol() || $user->useNPPatrol() ) ) {
1145 unset( $legendItems['unpatrolled'] );
1146 }
1147 foreach ( $legendItems as $key => $item ) { # generate items of the legend
1148 $label = isset( $item['legend'] ) ? $item['legend'] : $item['title'];
1149 $letter = $item['letter'];
1150 $cssClass = isset( $item['class'] ) ? $item['class'] : $key;
1151
1152 $legend .= Html::element( 'dt',
1153 [ 'class' => $cssClass ], $context->msg( $letter )->text()
1154 ) . "\n" .
1155 Html::rawElement( 'dd',
1156 [ 'class' => Sanitizer::escapeClass( 'mw-changeslist-legend-' . $key ) ],
1157 $context->msg( $label )->parse()
1158 ) . "\n";
1159 }
1160 # (+-123)
1161 $legend .= Html::rawElement( 'dt',
1162 [ 'class' => 'mw-plusminus-pos' ],
1163 $context->msg( 'recentchanges-legend-plusminus' )->parse()
1164 ) . "\n";
1165 $legend .= Html::element(
1166 'dd',
1167 [ 'class' => 'mw-changeslist-legend-plusminus' ],
1168 $context->msg( 'recentchanges-label-plusminus' )->text()
1169 ) . "\n";
1170 $legend .= Html::closeElement( 'dl' ) . "\n";
1171
1172 # Collapsibility
1173 $legend =
1174 '<div class="mw-changeslist-legend">' .
1175 $context->msg( 'recentchanges-legend-heading' )->parse() .
1176 '<div class="mw-collapsible-content">' . $legend . '</div>' .
1177 '</div>';
1178
1179 return $legend;
1180 }
1181
1182 /**
1183 * Add page-specific modules.
1184 */
1185 protected function addModules() {
1186 $out = $this->getOutput();
1187 // Styles and behavior for the legend box (see makeLegend())
1188 $out->addModuleStyles( [
1189 'mediawiki.special.changeslist.legend',
1190 'mediawiki.special.changeslist',
1191 ] );
1192 $out->addModules( 'mediawiki.special.changeslist.legend.js' );
1193 }
1194
1195 protected function getGroupName() {
1196 return 'changes';
1197 }
1198
1199 /**
1200 * Filter on users' experience levels; this will not be called if nothing is
1201 * selected.
1202 *
1203 * @param string $specialPageClassName Class name of current special page
1204 * @param IContextSource $context Context, for e.g. user
1205 * @param IDatabase $dbr Database, for addQuotes, makeList, and similar
1206 * @param array &$tables Array of tables; see IDatabase::select $table
1207 * @param array &$fields Array of fields; see IDatabase::select $vars
1208 * @param array &$conds Array of conditions; see IDatabase::select $conds
1209 * @param array &$query_options Array of query options; see IDatabase::select $options
1210 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1211 * @param array $selectedExpLevels The allowed active values, sorted
1212 */
1213 public function filterOnUserExperienceLevel( $specialPageClassName, $context, $dbr,
1214 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedExpLevels ) {
1215
1216 global $wgLearnerEdits,
1217 $wgExperiencedUserEdits,
1218 $wgLearnerMemberSince,
1219 $wgExperiencedUserMemberSince;
1220
1221 $LEVEL_COUNT = 3;
1222
1223 // If all levels are selected, all logged-in users are included (but no
1224 // anons), so we can short-circuit.
1225 if ( count( $selectedExpLevels ) === $LEVEL_COUNT ) {
1226 $conds[] = 'rc_user != 0';
1227 return;
1228 }
1229
1230 $tables[] = 'user';
1231 $join_conds['user'] = [ 'LEFT JOIN', 'rc_user = user_id' ];
1232
1233 $now = time();
1234 $secondsPerDay = 86400;
1235 $learnerCutoff = $now - $wgLearnerMemberSince * $secondsPerDay;
1236 $experiencedUserCutoff = $now - $wgExperiencedUserMemberSince * $secondsPerDay;
1237
1238 $aboveNewcomer = $dbr->makeList(
1239 [
1240 'user_editcount >= ' . intval( $wgLearnerEdits ),
1241 'user_registration <= ' . $dbr->timestamp( $learnerCutoff ),
1242 ],
1243 IDatabase::LIST_AND
1244 );
1245
1246 $aboveLearner = $dbr->makeList(
1247 [
1248 'user_editcount >= ' . intval( $wgExperiencedUserEdits ),
1249 'user_registration <= ' . $dbr->timestamp( $experiencedUserCutoff ),
1250 ],
1251 IDatabase::LIST_AND
1252 );
1253
1254 if ( $selectedExpLevels === [ 'newcomer' ] ) {
1255 $conds[] = "NOT ( $aboveNewcomer )";
1256 } elseif ( $selectedExpLevels === [ 'learner' ] ) {
1257 $conds[] = $dbr->makeList(
1258 [ $aboveNewcomer, "NOT ( $aboveLearner )" ],
1259 IDatabase::LIST_AND
1260 );
1261 } elseif ( $selectedExpLevels === [ 'experienced' ] ) {
1262 $conds[] = $aboveLearner;
1263 } elseif ( $selectedExpLevels === [ 'learner', 'newcomer' ] ) {
1264 $conds[] = "NOT ( $aboveLearner )";
1265 } elseif ( $selectedExpLevels === [ 'experienced', 'newcomer' ] ) {
1266 $conds[] = $dbr->makeList(
1267 [ "NOT ( $aboveNewcomer )", $aboveLearner ],
1268 IDatabase::LIST_OR
1269 );
1270 } elseif ( $selectedExpLevels === [ 'experienced', 'learner' ] ) {
1271 $conds[] = $aboveNewcomer;
1272 }
1273 }
1274 }