67f68ea10aa26fc5a61c435a228b9702826d60a6
[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\FakeResultWrapper;
26 use Wikimedia\Rdbms\IDatabase;
27
28 /**
29 * Special page which uses a ChangesList to show query results.
30 * @todo Way too many public functions, most of them should be protected
31 *
32 * @ingroup SpecialPage
33 */
34 abstract class ChangesListSpecialPage extends SpecialPage {
35 /**
36 * Preference name for saved queries. Subclasses that use saved queries should override this.
37 * @var string
38 */
39 protected static $savedQueriesPreferenceName;
40
41 /** @var string */
42 protected $rcSubpage;
43
44 /** @var FormOptions */
45 protected $rcOptions;
46
47 /** @var array */
48 protected $customFilters;
49
50 // Order of both groups and filters is significant; first is top-most priority,
51 // descending from there.
52 // 'showHideSuffix' is a shortcut to and avoid spelling out
53 // details specific to subclasses here.
54 /**
55 * Definition information for the filters and their groups
56 *
57 * The value is $groupDefinition, a parameter to the ChangesListFilterGroup constructor.
58 * However, priority is dynamically added for the core groups, to ease maintenance.
59 *
60 * Groups are displayed to the user in the structured UI. However, if necessary,
61 * all of the filters in a group can be configured to only display on the
62 * unstuctured UI, in which case you don't need a group title. This is done in
63 * getFilterGroupDefinitionFromLegacyCustomFilters, for example.
64 *
65 * @var array $filterGroupDefinitions
66 */
67 private $filterGroupDefinitions;
68
69 // Same format as filterGroupDefinitions, but for a single group (reviewStatus)
70 // that is registered conditionally.
71 private $reviewStatusFilterGroupDefinition;
72
73 // Single filter registered conditionally
74 private $hideCategorizationFilterDefinition;
75
76 /**
77 * Filter groups, and their contained filters
78 * This is an associative array (with group name as key) of ChangesListFilterGroup objects.
79 *
80 * @var array $filterGroups
81 */
82 protected $filterGroups = [];
83
84 public function __construct( $name, $restriction ) {
85 parent::__construct( $name, $restriction );
86
87 $nonRevisionTypes = [ RC_LOG ];
88 Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', [ &$nonRevisionTypes ] );
89
90 $this->filterGroupDefinitions = [
91 [
92 'name' => 'registration',
93 'title' => 'rcfilters-filtergroup-registration',
94 'class' => ChangesListBooleanFilterGroup::class,
95 'filters' => [
96 [
97 'name' => 'hideliu',
98 // rcshowhideliu-show, rcshowhideliu-hide,
99 // wlshowhideliu
100 'showHideSuffix' => 'showhideliu',
101 'default' => false,
102 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
103 &$query_options, &$join_conds
104 ) {
105 $conds[] = 'rc_user = 0';
106 },
107 'isReplacedInStructuredUi' => true,
108
109 ],
110 [
111 'name' => 'hideanons',
112 // rcshowhideanons-show, rcshowhideanons-hide,
113 // wlshowhideanons
114 'showHideSuffix' => 'showhideanons',
115 'default' => false,
116 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
117 &$query_options, &$join_conds
118 ) {
119 $conds[] = 'rc_user != 0';
120 },
121 'isReplacedInStructuredUi' => true,
122 ]
123 ],
124 ],
125
126 [
127 'name' => 'userExpLevel',
128 'title' => 'rcfilters-filtergroup-userExpLevel',
129 'class' => ChangesListStringOptionsFilterGroup::class,
130 'isFullCoverage' => true,
131 'filters' => [
132 [
133 'name' => 'unregistered',
134 'label' => 'rcfilters-filter-user-experience-level-unregistered-label',
135 'description' => 'rcfilters-filter-user-experience-level-unregistered-description',
136 'cssClassSuffix' => 'user-unregistered',
137 'isRowApplicableCallable' => function ( $ctx, $rc ) {
138 return !$rc->getAttribute( 'rc_user' );
139 }
140 ],
141 [
142 'name' => 'registered',
143 'label' => 'rcfilters-filter-user-experience-level-registered-label',
144 'description' => 'rcfilters-filter-user-experience-level-registered-description',
145 'cssClassSuffix' => 'user-registered',
146 'isRowApplicableCallable' => function ( $ctx, $rc ) {
147 return $rc->getAttribute( 'rc_user' );
148 }
149 ],
150 [
151 'name' => 'newcomer',
152 'label' => 'rcfilters-filter-user-experience-level-newcomer-label',
153 'description' => 'rcfilters-filter-user-experience-level-newcomer-description',
154 'cssClassSuffix' => 'user-newcomer',
155 'isRowApplicableCallable' => function ( $ctx, $rc ) {
156 $performer = $rc->getPerformer();
157 return $performer && $performer->isLoggedIn() &&
158 $performer->getExperienceLevel() === 'newcomer';
159 }
160 ],
161 [
162 'name' => 'learner',
163 'label' => 'rcfilters-filter-user-experience-level-learner-label',
164 'description' => 'rcfilters-filter-user-experience-level-learner-description',
165 'cssClassSuffix' => 'user-learner',
166 'isRowApplicableCallable' => function ( $ctx, $rc ) {
167 $performer = $rc->getPerformer();
168 return $performer && $performer->isLoggedIn() &&
169 $performer->getExperienceLevel() === 'learner';
170 },
171 ],
172 [
173 'name' => 'experienced',
174 'label' => 'rcfilters-filter-user-experience-level-experienced-label',
175 'description' => 'rcfilters-filter-user-experience-level-experienced-description',
176 'cssClassSuffix' => 'user-experienced',
177 'isRowApplicableCallable' => function ( $ctx, $rc ) {
178 $performer = $rc->getPerformer();
179 return $performer && $performer->isLoggedIn() &&
180 $performer->getExperienceLevel() === 'experienced';
181 },
182 ]
183 ],
184 'default' => ChangesListStringOptionsFilterGroup::NONE,
185 'queryCallable' => [ $this, 'filterOnUserExperienceLevel' ],
186 ],
187
188 [
189 'name' => 'authorship',
190 'title' => 'rcfilters-filtergroup-authorship',
191 'class' => ChangesListBooleanFilterGroup::class,
192 'filters' => [
193 [
194 'name' => 'hidemyself',
195 'label' => 'rcfilters-filter-editsbyself-label',
196 'description' => 'rcfilters-filter-editsbyself-description',
197 // rcshowhidemine-show, rcshowhidemine-hide,
198 // wlshowhidemine
199 'showHideSuffix' => 'showhidemine',
200 'default' => false,
201 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
202 &$query_options, &$join_conds
203 ) {
204 $user = $ctx->getUser();
205 $conds[] = 'rc_user_text != ' . $dbr->addQuotes( $user->getName() );
206 },
207 'cssClassSuffix' => 'self',
208 'isRowApplicableCallable' => function ( $ctx, $rc ) {
209 return $ctx->getUser()->equals( $rc->getPerformer() );
210 },
211 ],
212 [
213 'name' => 'hidebyothers',
214 'label' => 'rcfilters-filter-editsbyother-label',
215 'description' => 'rcfilters-filter-editsbyother-description',
216 'default' => false,
217 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
218 &$query_options, &$join_conds
219 ) {
220 $user = $ctx->getUser();
221 $conds[] = 'rc_user_text = ' . $dbr->addQuotes( $user->getName() );
222 },
223 'cssClassSuffix' => 'others',
224 'isRowApplicableCallable' => function ( $ctx, $rc ) {
225 return !$ctx->getUser()->equals( $rc->getPerformer() );
226 },
227 ]
228 ]
229 ],
230
231 [
232 'name' => 'automated',
233 'title' => 'rcfilters-filtergroup-automated',
234 'class' => ChangesListBooleanFilterGroup::class,
235 'filters' => [
236 [
237 'name' => 'hidebots',
238 'label' => 'rcfilters-filter-bots-label',
239 'description' => 'rcfilters-filter-bots-description',
240 // rcshowhidebots-show, rcshowhidebots-hide,
241 // wlshowhidebots
242 'showHideSuffix' => 'showhidebots',
243 'default' => false,
244 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
245 &$query_options, &$join_conds
246 ) {
247 $conds[] = 'rc_bot = 0';
248 },
249 'cssClassSuffix' => 'bot',
250 'isRowApplicableCallable' => function ( $ctx, $rc ) {
251 return $rc->getAttribute( 'rc_bot' );
252 },
253 ],
254 [
255 'name' => 'hidehumans',
256 'label' => 'rcfilters-filter-humans-label',
257 'description' => 'rcfilters-filter-humans-description',
258 'default' => false,
259 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
260 &$query_options, &$join_conds
261 ) {
262 $conds[] = 'rc_bot = 1';
263 },
264 'cssClassSuffix' => 'human',
265 'isRowApplicableCallable' => function ( $ctx, $rc ) {
266 return !$rc->getAttribute( 'rc_bot' );
267 },
268 ]
269 ]
270 ],
271
272 // reviewStatus (conditional)
273
274 [
275 'name' => 'significance',
276 'title' => 'rcfilters-filtergroup-significance',
277 'class' => ChangesListBooleanFilterGroup::class,
278 'priority' => -6,
279 'filters' => [
280 [
281 'name' => 'hideminor',
282 'label' => 'rcfilters-filter-minor-label',
283 'description' => 'rcfilters-filter-minor-description',
284 // rcshowhideminor-show, rcshowhideminor-hide,
285 // wlshowhideminor
286 'showHideSuffix' => 'showhideminor',
287 'default' => false,
288 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
289 &$query_options, &$join_conds
290 ) {
291 $conds[] = 'rc_minor = 0';
292 },
293 'cssClassSuffix' => 'minor',
294 'isRowApplicableCallable' => function ( $ctx, $rc ) {
295 return $rc->getAttribute( 'rc_minor' );
296 }
297 ],
298 [
299 'name' => 'hidemajor',
300 'label' => 'rcfilters-filter-major-label',
301 'description' => 'rcfilters-filter-major-description',
302 'default' => false,
303 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
304 &$query_options, &$join_conds
305 ) {
306 $conds[] = 'rc_minor = 1';
307 },
308 'cssClassSuffix' => 'major',
309 'isRowApplicableCallable' => function ( $ctx, $rc ) {
310 return !$rc->getAttribute( 'rc_minor' );
311 }
312 ]
313 ]
314 ],
315
316 [
317 'name' => 'lastRevision',
318 'title' => 'rcfilters-filtergroup-lastRevision',
319 'class' => ChangesListBooleanFilterGroup::class,
320 'priority' => -7,
321 'filters' => [
322 [
323 'name' => 'hidelastrevision',
324 'label' => 'rcfilters-filter-lastrevision-label',
325 'description' => 'rcfilters-filter-lastrevision-description',
326 'default' => false,
327 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
328 &$query_options, &$join_conds ) use ( $nonRevisionTypes ) {
329 $conds[] = $dbr->makeList(
330 [
331 'rc_this_oldid <> page_latest',
332 'rc_type' => $nonRevisionTypes,
333 ],
334 LIST_OR
335 );
336 },
337 'cssClassSuffix' => 'last',
338 'isRowApplicableCallable' => function ( $ctx, $rc ) {
339 return $rc->getAttribute( 'rc_this_oldid' ) === $rc->getAttribute( 'page_latest' );
340 }
341 ],
342 [
343 'name' => 'hidepreviousrevisions',
344 'label' => 'rcfilters-filter-previousrevision-label',
345 'description' => 'rcfilters-filter-previousrevision-description',
346 'default' => false,
347 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
348 &$query_options, &$join_conds ) use ( $nonRevisionTypes ) {
349 $conds[] = $dbr->makeList(
350 [
351 'rc_this_oldid = page_latest',
352 'rc_type' => $nonRevisionTypes,
353 ],
354 LIST_OR
355 );
356 },
357 'cssClassSuffix' => 'previous',
358 'isRowApplicableCallable' => function ( $ctx, $rc ) {
359 return $rc->getAttribute( 'rc_this_oldid' ) !== $rc->getAttribute( 'page_latest' );
360 }
361 ]
362 ]
363 ],
364
365 // With extensions, there can be change types that will not be hidden by any of these.
366 [
367 'name' => 'changeType',
368 'title' => 'rcfilters-filtergroup-changetype',
369 'class' => ChangesListBooleanFilterGroup::class,
370 'priority' => -8,
371 'filters' => [
372 [
373 'name' => 'hidepageedits',
374 'label' => 'rcfilters-filter-pageedits-label',
375 'description' => 'rcfilters-filter-pageedits-description',
376 'default' => false,
377 'priority' => -2,
378 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
379 &$query_options, &$join_conds
380 ) {
381 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_EDIT );
382 },
383 'cssClassSuffix' => 'src-mw-edit',
384 'isRowApplicableCallable' => function ( $ctx, $rc ) {
385 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_EDIT;
386 },
387 ],
388 [
389 'name' => 'hidenewpages',
390 'label' => 'rcfilters-filter-newpages-label',
391 'description' => 'rcfilters-filter-newpages-description',
392 'default' => false,
393 'priority' => -3,
394 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
395 &$query_options, &$join_conds
396 ) {
397 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_NEW );
398 },
399 'cssClassSuffix' => 'src-mw-new',
400 'isRowApplicableCallable' => function ( $ctx, $rc ) {
401 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_NEW;
402 },
403 ],
404
405 // hidecategorization
406
407 [
408 'name' => 'hidelog',
409 'label' => 'rcfilters-filter-logactions-label',
410 'description' => 'rcfilters-filter-logactions-description',
411 'default' => false,
412 'priority' => -5,
413 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
414 &$query_options, &$join_conds
415 ) {
416 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_LOG );
417 },
418 'cssClassSuffix' => 'src-mw-log',
419 'isRowApplicableCallable' => function ( $ctx, $rc ) {
420 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_LOG;
421 }
422 ],
423 ],
424 ],
425
426 ];
427
428 $this->reviewStatusFilterGroupDefinition = [
429 [
430 'name' => 'reviewStatus',
431 'title' => 'rcfilters-filtergroup-reviewstatus',
432 'class' => ChangesListBooleanFilterGroup::class,
433 'priority' => -5,
434 'filters' => [
435 [
436 'name' => 'hidepatrolled',
437 'label' => 'rcfilters-filter-patrolled-label',
438 'description' => 'rcfilters-filter-patrolled-description',
439 // rcshowhidepatr-show, rcshowhidepatr-hide
440 // wlshowhidepatr
441 'showHideSuffix' => 'showhidepatr',
442 'default' => false,
443 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
444 &$query_options, &$join_conds
445 ) {
446 $conds[] = 'rc_patrolled = 0';
447 },
448 'cssClassSuffix' => 'patrolled',
449 'isRowApplicableCallable' => function ( $ctx, $rc ) {
450 return $rc->getAttribute( 'rc_patrolled' );
451 },
452 ],
453 [
454 'name' => 'hideunpatrolled',
455 'label' => 'rcfilters-filter-unpatrolled-label',
456 'description' => 'rcfilters-filter-unpatrolled-description',
457 'default' => false,
458 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
459 &$query_options, &$join_conds
460 ) {
461 $conds[] = 'rc_patrolled = 1';
462 },
463 'cssClassSuffix' => 'unpatrolled',
464 'isRowApplicableCallable' => function ( $ctx, $rc ) {
465 return !$rc->getAttribute( 'rc_patrolled' );
466 },
467 ],
468 ],
469 ]
470 ];
471
472 $this->hideCategorizationFilterDefinition = [
473 'name' => 'hidecategorization',
474 'label' => 'rcfilters-filter-categorization-label',
475 'description' => 'rcfilters-filter-categorization-description',
476 // rcshowhidecategorization-show, rcshowhidecategorization-hide.
477 // wlshowhidecategorization
478 'showHideSuffix' => 'showhidecategorization',
479 'default' => false,
480 'priority' => -4,
481 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
482 &$query_options, &$join_conds
483 ) {
484 $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_CATEGORIZE );
485 },
486 'cssClassSuffix' => 'src-mw-categorize',
487 'isRowApplicableCallable' => function ( $ctx, $rc ) {
488 return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_CATEGORIZE;
489 },
490 ];
491 }
492
493 /**
494 * Check if filters are in conflict and guaranteed to return no results.
495 *
496 * @return bool
497 */
498 protected function areFiltersInConflict() {
499 $opts = $this->getOptions();
500 /** @var ChangesListFilterGroup $group */
501 foreach ( $this->getFilterGroups() as $group ) {
502 if ( $group->getConflictingGroups() ) {
503 wfLogWarning(
504 $group->getName() .
505 " specifies conflicts with other groups but these are not supported yet."
506 );
507 }
508
509 /** @var ChangesListFilter $conflictingFilter */
510 foreach ( $group->getConflictingFilters() as $conflictingFilter ) {
511 if ( $conflictingFilter->activelyInConflictWithGroup( $group, $opts ) ) {
512 return true;
513 }
514 }
515
516 /** @var ChangesListFilter $filter */
517 foreach ( $group->getFilters() as $filter ) {
518 /** @var ChangesListFilter $conflictingFilter */
519 foreach ( $filter->getConflictingFilters() as $conflictingFilter ) {
520 if (
521 $conflictingFilter->activelyInConflictWithFilter( $filter, $opts ) &&
522 $filter->activelyInConflictWithFilter( $conflictingFilter, $opts )
523 ) {
524 return true;
525 }
526 }
527
528 }
529
530 }
531
532 return false;
533 }
534
535 /**
536 * Main execution point
537 *
538 * @param string $subpage
539 */
540 public function execute( $subpage ) {
541 $this->rcSubpage = $subpage;
542
543 $this->considerActionsForDefaultSavedQuery();
544
545 $rows = $this->getRows();
546 $opts = $this->getOptions();
547 if ( $rows === false ) {
548 $rows = new FakeResultWrapper( [] );
549 }
550
551 // Used by Structured UI app to get results without MW chrome
552 if ( $this->getRequest()->getVal( 'action' ) === 'render' ) {
553 $this->getOutput()->setArticleBodyOnly( true );
554 }
555
556 // Used by "live update" and "view newest" to check
557 // if there's new changes with minimal data transfer
558 if ( $this->getRequest()->getBool( 'peek' ) ) {
559 $code = $rows->numRows() > 0 ? 200 : 204;
560 $this->getOutput()->setStatusCode( $code );
561 return;
562 }
563
564 $batch = new LinkBatch;
565 foreach ( $rows as $row ) {
566 $batch->add( NS_USER, $row->rc_user_text );
567 $batch->add( NS_USER_TALK, $row->rc_user_text );
568 $batch->add( $row->rc_namespace, $row->rc_title );
569 if ( $row->rc_source === RecentChange::SRC_LOG ) {
570 $formatter = LogFormatter::newFromRow( $row );
571 foreach ( $formatter->getPreloadTitles() as $title ) {
572 $batch->addObj( $title );
573 }
574 }
575 }
576 $batch->execute();
577
578 $this->setHeaders();
579 $this->outputHeader();
580 $this->addModules();
581 $this->webOutput( $rows, $opts );
582
583 $rows->free();
584
585 if ( $this->getConfig()->get( 'EnableWANCacheReaper' ) ) {
586 // Clean up any bad page entries for titles showing up in RC
587 DeferredUpdates::addUpdate( new WANCacheReapUpdate(
588 $this->getDB(),
589 LoggerFactory::getInstance( 'objectcache' )
590 ) );
591 }
592
593 $this->includeRcFiltersApp();
594 }
595
596 /**
597 * Check whether or not the page should load defaults, and if so, whether
598 * a default saved query is relevant to be redirected to. If it is relevant,
599 * redirect properly with all necessary query parameters.
600 */
601 protected function considerActionsForDefaultSavedQuery() {
602 if ( !$this->isStructuredFilterUiEnabled() ) {
603 return;
604 }
605
606 $knownParams = call_user_func_array(
607 [ $this->getRequest(), 'getValues' ],
608 array_keys( $this->getOptions()->getAllValues() )
609 );
610
611 // HACK: Temporarily until we can properly define "sticky" filters and parameters,
612 // we need to exclude several parameters we know should not be counted towards preventing
613 // the loading of defaults.
614 $excludedParams = [ 'limit' => '', 'days' => '', 'enhanced' => '', 'from' => '' ];
615 $knownParams = array_diff_key( $knownParams, $excludedParams );
616
617 if (
618 // If there are NO known parameters in the URL request
619 // (that are not excluded) then we need to check into loading
620 // the default saved query
621 count( $knownParams ) === 0
622 ) {
623 // Get the saved queries data and parse it
624 $savedQueries = FormatJson::decode(
625 $this->getUser()->getOption( static::$savedQueriesPreferenceName ),
626 true
627 );
628
629 if ( $savedQueries && isset( $savedQueries[ 'default' ] ) ) {
630 // Only load queries that are 'version' 2, since those
631 // have parameter representation
632 if ( isset( $savedQueries[ 'version' ] ) && $savedQueries[ 'version' ] === '2' ) {
633 $savedQueryDefaultID = $savedQueries[ 'default' ];
634 $defaultQuery = $savedQueries[ 'queries' ][ $savedQueryDefaultID ][ 'data' ];
635
636 // Build the entire parameter list
637 $query = array_merge(
638 $defaultQuery[ 'params' ],
639 $defaultQuery[ 'highlights' ],
640 [
641 'urlversion' => '2',
642 ]
643 );
644 // Add to the query any parameters that we may have ignored before
645 // but are still valid and requested in the URL
646 $query = array_merge( $this->getRequest()->getValues(), $query );
647 unset( $query[ 'title' ] );
648 $this->getOutput()->redirect( $this->getPageTitle()->getCanonicalURL( $query ) );
649 } else {
650 // There's a default, but the version is not 2, and the server can't
651 // actually recognize the query itself. This happens if it is before
652 // the conversion, so we need to tell the UI to reload saved query as
653 // it does the conversion to version 2
654 $this->getOutput()->addJsConfigVars(
655 'wgStructuredChangeFiltersDefaultSavedQueryExists',
656 true
657 );
658
659 // Add the class that tells the frontend it is still loading
660 // another query
661 $this->getOutput()->addBodyClasses( 'mw-rcfilters-ui-loading' );
662 }
663 }
664 }
665 }
666
667 /**
668 * Include the modules and configuration for the RCFilters app.
669 * Conditional on the user having the feature enabled.
670 *
671 * If it is disabled, add a <body> class marking that
672 */
673 protected function includeRcFiltersApp() {
674 $out = $this->getOutput();
675 if ( $this->isStructuredFilterUiEnabled() ) {
676 $jsData = $this->getStructuredFilterJsData();
677
678 $messages = [];
679 foreach ( $jsData['messageKeys'] as $key ) {
680 $messages[$key] = $this->msg( $key )->plain();
681 }
682
683 $out->addBodyClasses( 'mw-rcfilters-enabled' );
684
685 $out->addHTML(
686 ResourceLoader::makeInlineScript(
687 ResourceLoader::makeMessageSetScript( $messages )
688 )
689 );
690
691 $out->addJsConfigVars( 'wgStructuredChangeFilters', $jsData['groups'] );
692
693 $out->addJsConfigVars(
694 'wgRCFiltersChangeTags',
695 $this->getChangeTagList()
696 );
697 $out->addJsConfigVars(
698 'StructuredChangeFiltersDisplayConfig',
699 [
700 'maxDays' => (int)$this->getConfig()->get( 'RCMaxAge' ) / ( 24 * 3600 ), // Translate to days
701 'limitArray' => $this->getConfig()->get( 'RCLinkLimits' ),
702 'limitDefault' => $this->getDefaultLimit(),
703 'daysArray' => $this->getConfig()->get( 'RCLinkDays' ),
704 'daysDefault' => $this->getDefaultDays(),
705 ]
706 );
707
708 $out->addJsConfigVars(
709 'wgStructuredChangeFiltersSavedQueriesPreferenceName',
710 static::$savedQueriesPreferenceName
711 );
712
713 $out->addJsConfigVars(
714 'StructuredChangeFiltersLiveUpdatePollingRate',
715 $this->getConfig()->get( 'StructuredChangeFiltersLiveUpdatePollingRate' )
716 );
717 } else {
718 $out->addBodyClasses( 'mw-rcfilters-disabled' );
719 }
720 }
721
722 /**
723 * Fetch the change tags list for the front end
724 *
725 * @return Array Tag data
726 */
727 protected function getChangeTagList() {
728 $cache = ObjectCache::getMainWANInstance();
729 $context = $this->getContext();
730 return $cache->getWithSetCallback(
731 $cache->makeKey( 'changeslistspecialpage-changetags', $context->getLanguage()->getCode() ),
732 $cache::TTL_MINUTE * 10,
733 function () use ( $context ) {
734 $explicitlyDefinedTags = array_fill_keys( ChangeTags::listExplicitlyDefinedTags(), 0 );
735 $softwareActivatedTags = array_fill_keys( ChangeTags::listSoftwareActivatedTags(), 0 );
736
737 // Hit counts disabled for perf reasons, see T169997
738 /*
739 $tagStats = ChangeTags::tagUsageStatistics();
740 $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags, $tagStats );
741
742 // Sort by hits
743 arsort( $tagHitCounts );
744 */
745 $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags );
746
747 // Build the list and data
748 $result = [];
749 foreach ( $tagHitCounts as $tagName => $hits ) {
750 if (
751 // Only get active tags
752 isset( $explicitlyDefinedTags[ $tagName ] ) ||
753 isset( $softwareActivatedTags[ $tagName ] )
754 ) {
755 // Parse description
756 $desc = ChangeTags::tagLongDescriptionMessage( $tagName, $context );
757
758 $result[] = [
759 'name' => $tagName,
760 'label' => Sanitizer::stripAllTags(
761 ChangeTags::tagDescription( $tagName, $context )
762 ),
763 'description' => $desc ? Sanitizer::stripAllTags( $desc->parse() ) : '',
764 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
765 'hits' => $hits,
766 ];
767 }
768 }
769
770 // Instead of sorting by hit count (disabled, see above), sort by display name
771 usort( $result, function ( $a, $b ) {
772 return strcasecmp( $a['label'], $b['label'] );
773 } );
774
775 return $result;
776 },
777 [
778 'lockTSE' => 30
779 ]
780 );
781 }
782
783 /**
784 * Add the "no results" message to the output
785 */
786 protected function outputNoResults() {
787 $this->getOutput()->addHTML(
788 '<div class="mw-changeslist-empty">' .
789 $this->msg( 'recentchanges-noresult' )->parse() .
790 '</div>'
791 );
792 }
793
794 /**
795 * Get the database result for this special page instance. Used by ApiFeedRecentChanges.
796 *
797 * @return bool|ResultWrapper Result or false
798 */
799 public function getRows() {
800 $opts = $this->getOptions();
801
802 $tables = [];
803 $fields = [];
804 $conds = [];
805 $query_options = [];
806 $join_conds = [];
807 $this->buildQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
808
809 return $this->doMainQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
810 }
811
812 /**
813 * Get the current FormOptions for this request
814 *
815 * @return FormOptions
816 */
817 public function getOptions() {
818 if ( $this->rcOptions === null ) {
819 $this->rcOptions = $this->setup( $this->rcSubpage );
820 }
821
822 return $this->rcOptions;
823 }
824
825 /**
826 * Register all filters and their groups (including those from hooks), plus handle
827 * conflicts and defaults.
828 *
829 * You might want to customize these in the same method, in subclasses. You can
830 * call getFilterGroup to access a group, and (on the group) getFilter to access a
831 * filter, then make necessary modfications to the filter or group (e.g. with
832 * setDefault).
833 */
834 protected function registerFilters() {
835 $this->registerFiltersFromDefinitions( $this->filterGroupDefinitions );
836
837 // Make sure this is not being transcluded (we don't want to show this
838 // information to all users just because the user that saves the edit can
839 // patrol or is logged in)
840 if ( !$this->including() && $this->getUser()->useRCPatrol() ) {
841 $this->registerFiltersFromDefinitions( $this->reviewStatusFilterGroupDefinition );
842 }
843
844 $changeTypeGroup = $this->getFilterGroup( 'changeType' );
845
846 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
847 $transformedHideCategorizationDef = $this->transformFilterDefinition(
848 $this->hideCategorizationFilterDefinition
849 );
850
851 $transformedHideCategorizationDef['group'] = $changeTypeGroup;
852
853 $hideCategorization = new ChangesListBooleanFilter(
854 $transformedHideCategorizationDef
855 );
856 }
857
858 Hooks::run( 'ChangesListSpecialPageStructuredFilters', [ $this ] );
859
860 $unstructuredGroupDefinition =
861 $this->getFilterGroupDefinitionFromLegacyCustomFilters(
862 $this->getCustomFilters()
863 );
864 $this->registerFiltersFromDefinitions( [ $unstructuredGroupDefinition ] );
865
866 $userExperienceLevel = $this->getFilterGroup( 'userExpLevel' );
867 $registered = $userExperienceLevel->getFilter( 'registered' );
868 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'newcomer' ) );
869 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'learner' ) );
870 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'experienced' ) );
871
872 $categoryFilter = $changeTypeGroup->getFilter( 'hidecategorization' );
873 $logactionsFilter = $changeTypeGroup->getFilter( 'hidelog' );
874 $pagecreationFilter = $changeTypeGroup->getFilter( 'hidenewpages' );
875
876 $significanceTypeGroup = $this->getFilterGroup( 'significance' );
877 $hideMinorFilter = $significanceTypeGroup->getFilter( 'hideminor' );
878
879 // categoryFilter is conditional; see registerFilters
880 if ( $categoryFilter !== null ) {
881 $hideMinorFilter->conflictsWith(
882 $categoryFilter,
883 'rcfilters-hideminor-conflicts-typeofchange-global',
884 'rcfilters-hideminor-conflicts-typeofchange',
885 'rcfilters-typeofchange-conflicts-hideminor'
886 );
887 }
888 $hideMinorFilter->conflictsWith(
889 $logactionsFilter,
890 'rcfilters-hideminor-conflicts-typeofchange-global',
891 'rcfilters-hideminor-conflicts-typeofchange',
892 'rcfilters-typeofchange-conflicts-hideminor'
893 );
894 $hideMinorFilter->conflictsWith(
895 $pagecreationFilter,
896 'rcfilters-hideminor-conflicts-typeofchange-global',
897 'rcfilters-hideminor-conflicts-typeofchange',
898 'rcfilters-typeofchange-conflicts-hideminor'
899 );
900 }
901
902 /**
903 * Transforms filter definition to prepare it for constructor.
904 *
905 * See overrides of this method as well.
906 *
907 * @param array $filterDefinition Original filter definition
908 *
909 * @return array Transformed definition
910 */
911 protected function transformFilterDefinition( array $filterDefinition ) {
912 return $filterDefinition;
913 }
914
915 /**
916 * Register filters from a definition object
917 *
918 * Array specifying groups and their filters; see Filter and
919 * ChangesListFilterGroup constructors.
920 *
921 * There is light processing to simplify core maintenance.
922 * @param array $definition
923 */
924 protected function registerFiltersFromDefinitions( array $definition ) {
925 $autoFillPriority = -1;
926 foreach ( $definition as $groupDefinition ) {
927 if ( !isset( $groupDefinition['priority'] ) ) {
928 $groupDefinition['priority'] = $autoFillPriority;
929 } else {
930 // If it's explicitly specified, start over the auto-fill
931 $autoFillPriority = $groupDefinition['priority'];
932 }
933
934 $autoFillPriority--;
935
936 $className = $groupDefinition['class'];
937 unset( $groupDefinition['class'] );
938
939 foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
940 $filterDefinition = $this->transformFilterDefinition( $filterDefinition );
941 }
942
943 $this->registerFilterGroup( new $className( $groupDefinition ) );
944 }
945 }
946
947 /**
948 * Get filter group definition from legacy custom filters
949 *
950 * @param array $customFilters Custom filters from legacy hooks
951 * @return array Group definition
952 */
953 protected function getFilterGroupDefinitionFromLegacyCustomFilters( array $customFilters ) {
954 // Special internal unstructured group
955 $unstructuredGroupDefinition = [
956 'name' => 'unstructured',
957 'class' => ChangesListBooleanFilterGroup::class,
958 'priority' => -1, // Won't display in structured
959 'filters' => [],
960 ];
961
962 foreach ( $customFilters as $name => $params ) {
963 $unstructuredGroupDefinition['filters'][] = [
964 'name' => $name,
965 'showHide' => $params['msg'],
966 'default' => $params['default'],
967 ];
968 }
969
970 return $unstructuredGroupDefinition;
971 }
972
973 /**
974 * @return array The legacy show/hide toggle filters
975 */
976 protected function getLegacyShowHideFilters() {
977 $filters = [];
978 foreach ( $this->filterGroups as $group ) {
979 if ( $group instanceof ChangesListBooleanFilterGroup ) {
980 foreach ( $group->getFilters() as $key => $filter ) {
981 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
982 $filters[ $key ] = $filter;
983 }
984 }
985 }
986 }
987 return $filters;
988 }
989
990 /**
991 * Register all the filters, including legacy hook-driven ones.
992 * Then create a FormOptions object with options as specified by the user
993 *
994 * @param array $parameters
995 *
996 * @return FormOptions
997 */
998 public function setup( $parameters ) {
999 $this->registerFilters();
1000
1001 $opts = $this->getDefaultOptions();
1002
1003 $opts = $this->fetchOptionsFromRequest( $opts );
1004
1005 // Give precedence to subpage syntax
1006 if ( $parameters !== null ) {
1007 $this->parseParameters( $parameters, $opts );
1008 }
1009
1010 $this->validateOptions( $opts );
1011
1012 return $opts;
1013 }
1014
1015 /**
1016 * Get a FormOptions object containing the default options. By default, returns
1017 * some basic options. The filters listed explicitly here are overriden in this
1018 * method, in subclasses, but most filters (e.g. hideminor, userExpLevel filters,
1019 * and more) are structured. Structured filters are overriden in registerFilters.
1020 * not here.
1021 *
1022 * @return FormOptions
1023 */
1024 public function getDefaultOptions() {
1025 $opts = new FormOptions();
1026 $structuredUI = $this->isStructuredFilterUiEnabled();
1027 // If urlversion=2 is set, ignore the filter defaults and set them all to false/empty
1028 $useDefaults = $this->getRequest()->getInt( 'urlversion' ) !== 2;
1029
1030 /** @var ChangesListFilterGroup $filterGroup */
1031 foreach ( $this->filterGroups as $filterGroup ) {
1032 $filterGroup->addOptions( $opts, $useDefaults, $structuredUI );
1033 }
1034
1035 $opts->add( 'namespace', '', FormOptions::STRING );
1036 $opts->add( 'invert', false );
1037 $opts->add( 'associated', false );
1038 $opts->add( 'urlversion', 1 );
1039 $opts->add( 'tagfilter', '' );
1040
1041 $opts->add( 'days', $this->getDefaultDays(), FormOptions::FLOAT );
1042 $opts->add( 'limit', $this->getDefaultLimit(), FormOptions::INT );
1043
1044 $opts->add( 'from', '' );
1045
1046 return $opts;
1047 }
1048
1049 /**
1050 * Register a structured changes list filter group
1051 *
1052 * @param ChangesListFilterGroup $group
1053 */
1054 public function registerFilterGroup( ChangesListFilterGroup $group ) {
1055 $groupName = $group->getName();
1056
1057 $this->filterGroups[$groupName] = $group;
1058 }
1059
1060 /**
1061 * Gets the currently registered filters groups
1062 *
1063 * @return array Associative array of ChangesListFilterGroup objects, with group name as key
1064 */
1065 protected function getFilterGroups() {
1066 return $this->filterGroups;
1067 }
1068
1069 /**
1070 * Gets a specified ChangesListFilterGroup by name
1071 *
1072 * @param string $groupName Name of group
1073 *
1074 * @return ChangesListFilterGroup|null Group, or null if not registered
1075 */
1076 public function getFilterGroup( $groupName ) {
1077 return isset( $this->filterGroups[$groupName] ) ?
1078 $this->filterGroups[$groupName] :
1079 null;
1080 }
1081
1082 // Currently, this intentionally only includes filters that display
1083 // in the structured UI. This can be changed easily, though, if we want
1084 // to include data on filters that use the unstructured UI. messageKeys is a
1085 // special top-level value, with the value being an array of the message keys to
1086 // send to the client.
1087 /**
1088 * Gets structured filter information needed by JS
1089 *
1090 * @return array Associative array
1091 * * array $return['groups'] Group data
1092 * * array $return['messageKeys'] Array of message keys
1093 */
1094 public function getStructuredFilterJsData() {
1095 $output = [
1096 'groups' => [],
1097 'messageKeys' => [],
1098 ];
1099
1100 usort( $this->filterGroups, function ( $a, $b ) {
1101 return $b->getPriority() - $a->getPriority();
1102 } );
1103
1104 foreach ( $this->filterGroups as $groupName => $group ) {
1105 $groupOutput = $group->getJsData( $this );
1106 if ( $groupOutput !== null ) {
1107 $output['messageKeys'] = array_merge(
1108 $output['messageKeys'],
1109 $groupOutput['messageKeys']
1110 );
1111
1112 unset( $groupOutput['messageKeys'] );
1113 $output['groups'][] = $groupOutput;
1114 }
1115 }
1116
1117 return $output;
1118 }
1119
1120 /**
1121 * Get custom show/hide filters using deprecated ChangesListSpecialPageFilters
1122 * hook.
1123 *
1124 * @return array Map of filter URL param names to properties (msg/default)
1125 */
1126 protected function getCustomFilters() {
1127 if ( $this->customFilters === null ) {
1128 $this->customFilters = [];
1129 Hooks::run( 'ChangesListSpecialPageFilters', [ $this, &$this->customFilters ], '1.29' );
1130 }
1131
1132 return $this->customFilters;
1133 }
1134
1135 /**
1136 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
1137 *
1138 * Intended for subclassing, e.g. to add a backwards-compatibility layer.
1139 *
1140 * @param FormOptions $opts
1141 * @return FormOptions
1142 */
1143 protected function fetchOptionsFromRequest( $opts ) {
1144 $opts->fetchValuesFromRequest( $this->getRequest() );
1145
1146 return $opts;
1147 }
1148
1149 /**
1150 * Process $par and put options found in $opts. Used when including the page.
1151 *
1152 * @param string $par
1153 * @param FormOptions $opts
1154 */
1155 public function parseParameters( $par, FormOptions $opts ) {
1156 $stringParameterNameSet = [];
1157 $hideParameterNameSet = [];
1158
1159 // URL parameters can be per-group, like 'userExpLevel',
1160 // or per-filter, like 'hideminor'.
1161
1162 foreach ( $this->filterGroups as $filterGroup ) {
1163 if ( $filterGroup instanceof ChangesListStringOptionsFilterGroup ) {
1164 $stringParameterNameSet[$filterGroup->getName()] = true;
1165 } elseif ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
1166 foreach ( $filterGroup->getFilters() as $filter ) {
1167 $hideParameterNameSet[$filter->getName()] = true;
1168 }
1169 }
1170 }
1171
1172 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
1173 foreach ( $bits as $bit ) {
1174 $m = [];
1175 if ( isset( $hideParameterNameSet[$bit] ) ) {
1176 // hidefoo => hidefoo=true
1177 $opts[$bit] = true;
1178 } elseif ( isset( $hideParameterNameSet["hide$bit"] ) ) {
1179 // foo => hidefoo=false
1180 $opts["hide$bit"] = false;
1181 } elseif ( preg_match( '/^(.*)=(.*)$/', $bit, $m ) ) {
1182 if ( isset( $stringParameterNameSet[$m[1]] ) ) {
1183 $opts[$m[1]] = $m[2];
1184 }
1185 }
1186 }
1187 }
1188
1189 /**
1190 * Validate a FormOptions object generated by getDefaultOptions() with values already populated.
1191 *
1192 * @param FormOptions $opts
1193 */
1194 public function validateOptions( FormOptions $opts ) {
1195 $isContradictory = $this->fixContradictoryOptions( $opts );
1196 $isReplaced = $this->replaceOldOptions( $opts );
1197
1198 if ( $isContradictory || $isReplaced ) {
1199 $query = wfArrayToCgi( $this->convertParamsForLink( $opts->getChangedValues() ) );
1200 $this->getOutput()->redirect( $this->getPageTitle()->getCanonicalURL( $query ) );
1201 }
1202
1203 $opts->validateIntBounds( 'limit', 0, 5000 );
1204 $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1205 }
1206
1207 /**
1208 * Fix invalid options by resetting pairs that should never appear together.
1209 *
1210 * @param FormOptions $opts
1211 * @return bool True if any option was reset
1212 */
1213 private function fixContradictoryOptions( FormOptions $opts ) {
1214 $fixed = $this->fixBackwardsCompatibilityOptions( $opts );
1215
1216 foreach ( $this->filterGroups as $filterGroup ) {
1217 if ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
1218 $filters = $filterGroup->getFilters();
1219
1220 if ( count( $filters ) === 1 ) {
1221 // legacy boolean filters should not be considered
1222 continue;
1223 }
1224
1225 $allInGroupEnabled = array_reduce(
1226 $filters,
1227 function ( $carry, $filter ) use ( $opts ) {
1228 return $carry && $opts[ $filter->getName() ];
1229 },
1230 /* initialValue */ count( $filters ) > 0
1231 );
1232
1233 if ( $allInGroupEnabled ) {
1234 foreach ( $filters as $filter ) {
1235 $opts[ $filter->getName() ] = false;
1236 }
1237
1238 $fixed = true;
1239 }
1240 }
1241 }
1242
1243 return $fixed;
1244 }
1245
1246 /**
1247 * Fix a special case (hideanons=1 and hideliu=1) in a special way, for backwards
1248 * compatibility.
1249 *
1250 * This is deprecated and may be removed.
1251 *
1252 * @param FormOptions $opts
1253 * @return bool True if this change was mode
1254 */
1255 private function fixBackwardsCompatibilityOptions( FormOptions $opts ) {
1256 if ( $opts['hideanons'] && $opts['hideliu'] ) {
1257 $opts->reset( 'hideanons' );
1258 if ( !$opts['hidebots'] ) {
1259 $opts->reset( 'hideliu' );
1260 $opts['hidehumans'] = 1;
1261 }
1262
1263 return true;
1264 }
1265
1266 return false;
1267 }
1268
1269 /**
1270 * Replace old options 'hideanons' or 'hideliu' with structured UI equivalent
1271 *
1272 * @param FormOptions $opts
1273 * @return bool True if the change was made
1274 */
1275 public function replaceOldOptions( FormOptions $opts ) {
1276 if ( !$this->isStructuredFilterUiEnabled() ) {
1277 return false;
1278 }
1279
1280 // At this point 'hideanons' and 'hideliu' cannot be both true,
1281 // because fixBackwardsCompatibilityOptions resets (at least) 'hideanons' in such case
1282 if ( $opts[ 'hideanons' ] ) {
1283 $opts->reset( 'hideanons' );
1284 $opts[ 'userExpLevel' ] = 'registered';
1285 return true;
1286 }
1287
1288 if ( $opts[ 'hideliu' ] ) {
1289 $opts->reset( 'hideliu' );
1290 $opts[ 'userExpLevel' ] = 'unregistered';
1291 return true;
1292 }
1293
1294 return false;
1295 }
1296
1297 /**
1298 * Convert parameters values from true/false to 1/0
1299 * so they are not omitted by wfArrayToCgi()
1300 * Bug 36524
1301 *
1302 * @param array $params
1303 * @return array
1304 */
1305 protected function convertParamsForLink( $params ) {
1306 foreach ( $params as &$value ) {
1307 if ( $value === false ) {
1308 $value = '0';
1309 }
1310 }
1311 unset( $value );
1312 return $params;
1313 }
1314
1315 /**
1316 * Sets appropriate tables, fields, conditions, etc. depending on which filters
1317 * the user requested.
1318 *
1319 * @param array &$tables Array of tables; see IDatabase::select $table
1320 * @param array &$fields Array of fields; see IDatabase::select $vars
1321 * @param array &$conds Array of conditions; see IDatabase::select $conds
1322 * @param array &$query_options Array of query options; see IDatabase::select $options
1323 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1324 * @param FormOptions $opts
1325 */
1326 protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
1327 &$join_conds, FormOptions $opts
1328 ) {
1329 $dbr = $this->getDB();
1330 $isStructuredUI = $this->isStructuredFilterUiEnabled();
1331
1332 /** @var ChangesListFilterGroup $filterGroup */
1333 foreach ( $this->filterGroups as $filterGroup ) {
1334 $filterGroup->modifyQuery( $dbr, $this, $tables, $fields, $conds,
1335 $query_options, $join_conds, $opts, $isStructuredUI );
1336 }
1337
1338 // Namespace filtering
1339 if ( $opts[ 'namespace' ] !== '' ) {
1340 $namespaces = explode( ';', $opts[ 'namespace' ] );
1341
1342 if ( $opts[ 'associated' ] ) {
1343 $associatedNamespaces = array_map(
1344 function ( $ns ) {
1345 return MWNamespace::getAssociated( $ns );
1346 },
1347 $namespaces
1348 );
1349 $namespaces = array_unique( array_merge( $namespaces, $associatedNamespaces ) );
1350 }
1351
1352 if ( count( $namespaces ) === 1 ) {
1353 $operator = $opts[ 'invert' ] ? '!=' : '=';
1354 $value = $dbr->addQuotes( reset( $namespaces ) );
1355 } else {
1356 $operator = $opts[ 'invert' ] ? 'NOT IN' : 'IN';
1357 sort( $namespaces );
1358 $value = '(' . $dbr->makeList( $namespaces ) . ')';
1359 }
1360 $conds[] = "rc_namespace $operator $value";
1361 }
1362
1363 // Calculate cutoff
1364 $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
1365 $cutoff = $dbr->timestamp( $cutoff_unixtime );
1366
1367 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
1368 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
1369 $cutoff = $dbr->timestamp( $opts['from'] );
1370 } else {
1371 $opts->reset( 'from' );
1372 }
1373
1374 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
1375 }
1376
1377 /**
1378 * Process the query
1379 *
1380 * @param array $tables Array of tables; see IDatabase::select $table
1381 * @param array $fields Array of fields; see IDatabase::select $vars
1382 * @param array $conds Array of conditions; see IDatabase::select $conds
1383 * @param array $query_options Array of query options; see IDatabase::select $options
1384 * @param array $join_conds Array of join conditions; see IDatabase::select $join_conds
1385 * @param FormOptions $opts
1386 * @return bool|ResultWrapper Result or false
1387 */
1388 protected function doMainQuery( $tables, $fields, $conds,
1389 $query_options, $join_conds, FormOptions $opts
1390 ) {
1391 $tables[] = 'recentchanges';
1392 $fields = array_merge( RecentChange::selectFields(), $fields );
1393
1394 ChangeTags::modifyDisplayQuery(
1395 $tables,
1396 $fields,
1397 $conds,
1398 $join_conds,
1399 $query_options,
1400 ''
1401 );
1402
1403 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
1404 $opts )
1405 ) {
1406 return false;
1407 }
1408
1409 $dbr = $this->getDB();
1410
1411 return $dbr->select(
1412 $tables,
1413 $fields,
1414 $conds,
1415 __METHOD__,
1416 $query_options,
1417 $join_conds
1418 );
1419 }
1420
1421 protected function runMainQueryHook( &$tables, &$fields, &$conds,
1422 &$query_options, &$join_conds, $opts
1423 ) {
1424 return Hooks::run(
1425 'ChangesListSpecialPageQuery',
1426 [ $this->getName(), &$tables, &$fields, &$conds, &$query_options, &$join_conds, $opts ]
1427 );
1428 }
1429
1430 /**
1431 * Return a IDatabase object for reading
1432 *
1433 * @return IDatabase
1434 */
1435 protected function getDB() {
1436 return wfGetDB( DB_REPLICA );
1437 }
1438
1439 /**
1440 * Send output to the OutputPage object, only called if not used feeds
1441 *
1442 * @param ResultWrapper $rows Database rows
1443 * @param FormOptions $opts
1444 */
1445 public function webOutput( $rows, $opts ) {
1446 if ( !$this->including() ) {
1447 $this->outputFeedLinks();
1448 $this->doHeader( $opts, $rows->numRows() );
1449 }
1450
1451 $this->outputChangesList( $rows, $opts );
1452 }
1453
1454 /**
1455 * Output feed links.
1456 */
1457 public function outputFeedLinks() {
1458 // nothing by default
1459 }
1460
1461 /**
1462 * Build and output the actual changes list.
1463 *
1464 * @param ResultWrapper $rows Database rows
1465 * @param FormOptions $opts
1466 */
1467 abstract public function outputChangesList( $rows, $opts );
1468
1469 /**
1470 * Set the text to be displayed above the changes
1471 *
1472 * @param FormOptions $opts
1473 * @param int $numRows Number of rows in the result to show after this header
1474 */
1475 public function doHeader( $opts, $numRows ) {
1476 $this->setTopText( $opts );
1477
1478 // @todo Lots of stuff should be done here.
1479
1480 $this->setBottomText( $opts );
1481 }
1482
1483 /**
1484 * Send the text to be displayed before the options. Should use $this->getOutput()->addWikiText()
1485 * or similar methods to print the text.
1486 *
1487 * @param FormOptions $opts
1488 */
1489 public function setTopText( FormOptions $opts ) {
1490 // nothing by default
1491 }
1492
1493 /**
1494 * Send the text to be displayed after the options. Should use $this->getOutput()->addWikiText()
1495 * or similar methods to print the text.
1496 *
1497 * @param FormOptions $opts
1498 */
1499 public function setBottomText( FormOptions $opts ) {
1500 // nothing by default
1501 }
1502
1503 /**
1504 * Get options to be displayed in a form
1505 * @todo This should handle options returned by getDefaultOptions().
1506 * @todo Not called by anything in this class (but is in subclasses), should be
1507 * called by something… doHeader() maybe?
1508 *
1509 * @param FormOptions $opts
1510 * @return array
1511 */
1512 public function getExtraOptions( $opts ) {
1513 return [];
1514 }
1515
1516 /**
1517 * Return the legend displayed within the fieldset
1518 *
1519 * @return string
1520 */
1521 public function makeLegend() {
1522 $context = $this->getContext();
1523 $user = $context->getUser();
1524 # The legend showing what the letters and stuff mean
1525 $legend = Html::openElement( 'dl' ) . "\n";
1526 # Iterates through them and gets the messages for both letter and tooltip
1527 $legendItems = $context->getConfig()->get( 'RecentChangesFlags' );
1528 if ( !( $user->useRCPatrol() || $user->useNPPatrol() ) ) {
1529 unset( $legendItems['unpatrolled'] );
1530 }
1531 foreach ( $legendItems as $key => $item ) { # generate items of the legend
1532 $label = isset( $item['legend'] ) ? $item['legend'] : $item['title'];
1533 $letter = $item['letter'];
1534 $cssClass = isset( $item['class'] ) ? $item['class'] : $key;
1535
1536 $legend .= Html::element( 'dt',
1537 [ 'class' => $cssClass ], $context->msg( $letter )->text()
1538 ) . "\n" .
1539 Html::rawElement( 'dd',
1540 [ 'class' => Sanitizer::escapeClass( 'mw-changeslist-legend-' . $key ) ],
1541 $context->msg( $label )->parse()
1542 ) . "\n";
1543 }
1544 # (+-123)
1545 $legend .= Html::rawElement( 'dt',
1546 [ 'class' => 'mw-plusminus-pos' ],
1547 $context->msg( 'recentchanges-legend-plusminus' )->parse()
1548 ) . "\n";
1549 $legend .= Html::element(
1550 'dd',
1551 [ 'class' => 'mw-changeslist-legend-plusminus' ],
1552 $context->msg( 'recentchanges-label-plusminus' )->text()
1553 ) . "\n";
1554 $legend .= Html::closeElement( 'dl' ) . "\n";
1555
1556 $legendHeading = $this->isStructuredFilterUiEnabled() ?
1557 $context->msg( 'rcfilters-legend-heading' )->parse() :
1558 $context->msg( 'recentchanges-legend-heading' )->parse();
1559
1560 # Collapsible
1561 $collapsedState = $this->getRequest()->getCookie( 'changeslist-state' );
1562 $collapsedClass = $collapsedState === 'collapsed' ? ' mw-collapsed' : '';
1563 $legend =
1564 '<div class="mw-changeslist-legend mw-collapsible' . $collapsedClass . '">' .
1565 $legendHeading .
1566 '<div class="mw-collapsible-content">' . $legend . '</div>' .
1567 '</div>';
1568
1569 return $legend;
1570 }
1571
1572 /**
1573 * Add page-specific modules.
1574 */
1575 protected function addModules() {
1576 $out = $this->getOutput();
1577 // Styles and behavior for the legend box (see makeLegend())
1578 $out->addModuleStyles( [
1579 'mediawiki.special.changeslist.legend',
1580 'mediawiki.special.changeslist',
1581 ] );
1582 $out->addModules( 'mediawiki.special.changeslist.legend.js' );
1583
1584 if ( $this->isStructuredFilterUiEnabled() ) {
1585 $out->addModules( 'mediawiki.rcfilters.filters.ui' );
1586 $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
1587 }
1588 }
1589
1590 protected function getGroupName() {
1591 return 'changes';
1592 }
1593
1594 /**
1595 * Filter on users' experience levels; this will not be called if nothing is
1596 * selected.
1597 *
1598 * @param string $specialPageClassName Class name of current special page
1599 * @param IContextSource $context Context, for e.g. user
1600 * @param IDatabase $dbr Database, for addQuotes, makeList, and similar
1601 * @param array &$tables Array of tables; see IDatabase::select $table
1602 * @param array &$fields Array of fields; see IDatabase::select $vars
1603 * @param array &$conds Array of conditions; see IDatabase::select $conds
1604 * @param array &$query_options Array of query options; see IDatabase::select $options
1605 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1606 * @param array $selectedExpLevels The allowed active values, sorted
1607 * @param int $now Number of seconds since the UNIX epoch, or 0 if not given
1608 * (optional)
1609 */
1610 public function filterOnUserExperienceLevel( $specialPageClassName, $context, $dbr,
1611 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedExpLevels, $now = 0
1612 ) {
1613 global $wgLearnerEdits,
1614 $wgExperiencedUserEdits,
1615 $wgLearnerMemberSince,
1616 $wgExperiencedUserMemberSince;
1617
1618 $LEVEL_COUNT = 5;
1619
1620 // If all levels are selected, don't filter
1621 if ( count( $selectedExpLevels ) === $LEVEL_COUNT ) {
1622 return;
1623 }
1624
1625 // both 'registered' and 'unregistered', experience levels, if any, are included in 'registered'
1626 if (
1627 in_array( 'registered', $selectedExpLevels ) &&
1628 in_array( 'unregistered', $selectedExpLevels )
1629 ) {
1630 return;
1631 }
1632
1633 // 'registered' but not 'unregistered', experience levels, if any, are included in 'registered'
1634 if (
1635 in_array( 'registered', $selectedExpLevels ) &&
1636 !in_array( 'unregistered', $selectedExpLevels )
1637 ) {
1638 $conds[] = 'rc_user != 0';
1639 return;
1640 }
1641
1642 if ( $selectedExpLevels === [ 'unregistered' ] ) {
1643 $conds[] = 'rc_user = 0';
1644 return;
1645 }
1646
1647 $tables[] = 'user';
1648 $join_conds['user'] = [ 'LEFT JOIN', 'rc_user = user_id' ];
1649
1650 if ( $now === 0 ) {
1651 $now = time();
1652 }
1653 $secondsPerDay = 86400;
1654 $learnerCutoff = $now - $wgLearnerMemberSince * $secondsPerDay;
1655 $experiencedUserCutoff = $now - $wgExperiencedUserMemberSince * $secondsPerDay;
1656
1657 $aboveNewcomer = $dbr->makeList(
1658 [
1659 'user_editcount >= ' . intval( $wgLearnerEdits ),
1660 'user_registration <= ' . $dbr->addQuotes( $dbr->timestamp( $learnerCutoff ) ),
1661 ],
1662 IDatabase::LIST_AND
1663 );
1664
1665 $aboveLearner = $dbr->makeList(
1666 [
1667 'user_editcount >= ' . intval( $wgExperiencedUserEdits ),
1668 'user_registration <= ' .
1669 $dbr->addQuotes( $dbr->timestamp( $experiencedUserCutoff ) ),
1670 ],
1671 IDatabase::LIST_AND
1672 );
1673
1674 $conditions = [];
1675
1676 if ( in_array( 'unregistered', $selectedExpLevels ) ) {
1677 $selectedExpLevels = array_diff( $selectedExpLevels, [ 'unregistered' ] );
1678 $conditions[] = 'rc_user = 0';
1679 }
1680
1681 if ( $selectedExpLevels === [ 'newcomer' ] ) {
1682 $conditions[] = "NOT ( $aboveNewcomer )";
1683 } elseif ( $selectedExpLevels === [ 'learner' ] ) {
1684 $conditions[] = $dbr->makeList(
1685 [ $aboveNewcomer, "NOT ( $aboveLearner )" ],
1686 IDatabase::LIST_AND
1687 );
1688 } elseif ( $selectedExpLevels === [ 'experienced' ] ) {
1689 $conditions[] = $aboveLearner;
1690 } elseif ( $selectedExpLevels === [ 'learner', 'newcomer' ] ) {
1691 $conditions[] = "NOT ( $aboveLearner )";
1692 } elseif ( $selectedExpLevels === [ 'experienced', 'newcomer' ] ) {
1693 $conditions[] = $dbr->makeList(
1694 [ "NOT ( $aboveNewcomer )", $aboveLearner ],
1695 IDatabase::LIST_OR
1696 );
1697 } elseif ( $selectedExpLevels === [ 'experienced', 'learner' ] ) {
1698 $conditions[] = $aboveNewcomer;
1699 } elseif ( $selectedExpLevels === [ 'experienced', 'learner', 'newcomer' ] ) {
1700 $conditions[] = 'rc_user != 0';
1701 }
1702
1703 if ( count( $conditions ) > 1 ) {
1704 $conds[] = $dbr->makeList( $conditions, IDatabase::LIST_OR );
1705 } elseif ( count( $conditions ) === 1 ) {
1706 $conds[] = reset( $conditions );
1707 }
1708 }
1709
1710 /**
1711 * Check whether the structured filter UI is enabled
1712 *
1713 * @return bool
1714 */
1715 public function isStructuredFilterUiEnabled() {
1716 if ( $this->getRequest()->getBool( 'rcfilters' ) ) {
1717 return true;
1718 }
1719
1720 if ( $this->getConfig()->get( 'StructuredChangeFiltersShowPreference' ) ) {
1721 return !$this->getUser()->getOption( 'rcenhancedfilters-disable' );
1722 } else {
1723 return $this->getUser()->getOption( 'rcenhancedfilters' );
1724 }
1725 }
1726
1727 /**
1728 * Check whether the structured filter UI is enabled by default (regardless of
1729 * this particular user's setting)
1730 *
1731 * @return bool
1732 */
1733 public function isStructuredFilterUiEnabledByDefault() {
1734 if ( $this->getConfig()->get( 'StructuredChangeFiltersShowPreference' ) ) {
1735 return !$this->getUser()->getDefaultOption( 'rcenhancedfilters-disable' );
1736 } else {
1737 return $this->getUser()->getDefaultOption( 'rcenhancedfilters' );
1738 }
1739 }
1740
1741 abstract function getDefaultLimit();
1742
1743 /**
1744 * Get the default value of the number of days to display when loading
1745 * the result set.
1746 * Supports fractional values, and should be cast to a float.
1747 *
1748 * @return float
1749 */
1750 abstract function getDefaultDays();
1751 }