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