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