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