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