5993d10140560adf67820921c5f0e8e4ca16ef76
[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 return;
576 }
577
578 $batch = new LinkBatch;
579 foreach ( $rows as $row ) {
580 $batch->add( NS_USER, $row->rc_user_text );
581 $batch->add( NS_USER_TALK, $row->rc_user_text );
582 $batch->add( $row->rc_namespace, $row->rc_title );
583 if ( $row->rc_source === RecentChange::SRC_LOG ) {
584 $formatter = LogFormatter::newFromRow( $row );
585 foreach ( $formatter->getPreloadTitles() as $title ) {
586 $batch->addObj( $title );
587 }
588 }
589 }
590 $batch->execute();
591
592 $this->setHeaders();
593 $this->outputHeader();
594 $this->addModules();
595 $this->webOutput( $rows, $opts );
596
597 $rows->free();
598 } catch ( DBQueryTimeoutError $timeoutException ) {
599 MWExceptionHandler::logException( $timeoutException );
600
601 $this->setHeaders();
602 $this->outputHeader();
603 $this->addModules();
604
605 $this->getOutput()->setStatusCode( 500 );
606 $this->webOutputHeader( 0, $opts );
607 $this->outputTimeout();
608 }
609
610 if ( $this->getConfig()->get( 'EnableWANCacheReaper' ) ) {
611 // Clean up any bad page entries for titles showing up in RC
612 DeferredUpdates::addUpdate( new WANCacheReapUpdate(
613 $this->getDB(),
614 LoggerFactory::getInstance( 'objectcache' )
615 ) );
616 }
617
618 $this->includeRcFiltersApp();
619 }
620
621 /**
622 * Check whether or not the page should load defaults, and if so, whether
623 * a default saved query is relevant to be redirected to. If it is relevant,
624 * redirect properly with all necessary query parameters.
625 */
626 protected function considerActionsForDefaultSavedQuery() {
627 if ( !$this->isStructuredFilterUiEnabled() || $this->including() ) {
628 return;
629 }
630
631 $knownParams = call_user_func_array(
632 [ $this->getRequest(), 'getValues' ],
633 array_keys( $this->getOptions()->getAllValues() )
634 );
635
636 // HACK: Temporarily until we can properly define "sticky" filters and parameters,
637 // we need to exclude several parameters we know should not be counted towards preventing
638 // the loading of defaults.
639 $excludedParams = [ 'limit' => '', 'days' => '', 'enhanced' => '', 'from' => '' ];
640 $knownParams = array_diff_key( $knownParams, $excludedParams );
641
642 if (
643 // If there are NO known parameters in the URL request
644 // (that are not excluded) then we need to check into loading
645 // the default saved query
646 count( $knownParams ) === 0
647 ) {
648 // Get the saved queries data and parse it
649 $savedQueries = FormatJson::decode(
650 $this->getUser()->getOption( static::$savedQueriesPreferenceName ),
651 true
652 );
653
654 if ( $savedQueries && isset( $savedQueries[ 'default' ] ) ) {
655 // Only load queries that are 'version' 2, since those
656 // have parameter representation
657 if ( isset( $savedQueries[ 'version' ] ) && $savedQueries[ 'version' ] === '2' ) {
658 $savedQueryDefaultID = $savedQueries[ 'default' ];
659 $defaultQuery = $savedQueries[ 'queries' ][ $savedQueryDefaultID ][ 'data' ];
660
661 // Build the entire parameter list
662 $query = array_merge(
663 $defaultQuery[ 'params' ],
664 $defaultQuery[ 'highlights' ],
665 [
666 'urlversion' => '2',
667 ]
668 );
669 // Add to the query any parameters that we may have ignored before
670 // but are still valid and requested in the URL
671 $query = array_merge( $this->getRequest()->getValues(), $query );
672 unset( $query[ 'title' ] );
673 $this->getOutput()->redirect( $this->getPageTitle()->getCanonicalURL( $query ) );
674 } else {
675 // There's a default, but the version is not 2, and the server can't
676 // actually recognize the query itself. This happens if it is before
677 // the conversion, so we need to tell the UI to reload saved query as
678 // it does the conversion to version 2
679 $this->getOutput()->addJsConfigVars(
680 'wgStructuredChangeFiltersDefaultSavedQueryExists',
681 true
682 );
683
684 // Add the class that tells the frontend it is still loading
685 // another query
686 $this->getOutput()->addBodyClasses( 'mw-rcfilters-ui-loading' );
687 }
688 }
689 }
690 }
691
692 /**
693 * Include the modules and configuration for the RCFilters app.
694 * Conditional on the user having the feature enabled.
695 *
696 * If it is disabled, add a <body> class marking that
697 */
698 protected function includeRcFiltersApp() {
699 $out = $this->getOutput();
700 if ( $this->isStructuredFilterUiEnabled() && !$this->including() ) {
701 $jsData = $this->getStructuredFilterJsData();
702
703 $messages = [];
704 foreach ( $jsData['messageKeys'] as $key ) {
705 $messages[$key] = $this->msg( $key )->plain();
706 }
707
708 $out->addBodyClasses( 'mw-rcfilters-enabled' );
709
710 $out->addHTML(
711 ResourceLoader::makeInlineScript(
712 ResourceLoader::makeMessageSetScript( $messages )
713 )
714 );
715
716 $out->addJsConfigVars( 'wgStructuredChangeFilters', $jsData['groups'] );
717
718 $out->addJsConfigVars(
719 'wgRCFiltersChangeTags',
720 $this->getChangeTagList()
721 );
722 $out->addJsConfigVars(
723 'StructuredChangeFiltersDisplayConfig',
724 [
725 'maxDays' => (int)$this->getConfig()->get( 'RCMaxAge' ) / ( 24 * 3600 ), // Translate to days
726 'limitArray' => $this->getConfig()->get( 'RCLinkLimits' ),
727 'limitDefault' => $this->getDefaultLimit(),
728 'daysArray' => $this->getConfig()->get( 'RCLinkDays' ),
729 'daysDefault' => $this->getDefaultDays(),
730 ]
731 );
732
733 $out->addJsConfigVars(
734 'wgStructuredChangeFiltersSavedQueriesPreferenceName',
735 static::$savedQueriesPreferenceName
736 );
737 $out->addJsConfigVars(
738 'wgStructuredChangeFiltersLimitPreferenceName',
739 static::$limitPreferenceName
740 );
741 $out->addJsConfigVars(
742 'wgStructuredChangeFiltersDaysPreferenceName',
743 static::$daysPreferenceName
744 );
745
746 $out->addJsConfigVars(
747 'StructuredChangeFiltersLiveUpdatePollingRate',
748 $this->getConfig()->get( 'StructuredChangeFiltersLiveUpdatePollingRate' )
749 );
750 } else {
751 $out->addBodyClasses( 'mw-rcfilters-disabled' );
752 }
753 }
754
755 /**
756 * Fetch the change tags list for the front end
757 *
758 * @return Array Tag data
759 */
760 protected function getChangeTagList() {
761 $cache = ObjectCache::getMainWANInstance();
762 $context = $this->getContext();
763 return $cache->getWithSetCallback(
764 $cache->makeKey( 'changeslistspecialpage-changetags', $context->getLanguage()->getCode() ),
765 $cache::TTL_MINUTE * 10,
766 function () use ( $context ) {
767 $explicitlyDefinedTags = array_fill_keys( ChangeTags::listExplicitlyDefinedTags(), 0 );
768 $softwareActivatedTags = array_fill_keys( ChangeTags::listSoftwareActivatedTags(), 0 );
769
770 // Hit counts disabled for perf reasons, see T169997
771 /*
772 $tagStats = ChangeTags::tagUsageStatistics();
773 $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags, $tagStats );
774
775 // Sort by hits
776 arsort( $tagHitCounts );
777 */
778 $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags );
779
780 // Build the list and data
781 $result = [];
782 foreach ( $tagHitCounts as $tagName => $hits ) {
783 if (
784 // Only get active tags
785 isset( $explicitlyDefinedTags[ $tagName ] ) ||
786 isset( $softwareActivatedTags[ $tagName ] )
787 ) {
788 // Parse description
789 $desc = ChangeTags::tagLongDescriptionMessage( $tagName, $context );
790
791 $result[] = [
792 'name' => $tagName,
793 'label' => Sanitizer::stripAllTags(
794 ChangeTags::tagDescription( $tagName, $context )
795 ),
796 'description' => $desc ? Sanitizer::stripAllTags( $desc->parse() ) : '',
797 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
798 'hits' => $hits,
799 ];
800 }
801 }
802
803 // Instead of sorting by hit count (disabled, see above), sort by display name
804 usort( $result, function ( $a, $b ) {
805 return strcasecmp( $a['label'], $b['label'] );
806 } );
807
808 return $result;
809 },
810 [
811 'lockTSE' => 30
812 ]
813 );
814 }
815
816 /**
817 * Add the "no results" message to the output
818 */
819 protected function outputNoResults() {
820 $this->getOutput()->addHTML(
821 '<div class="mw-changeslist-empty">' .
822 $this->msg( 'recentchanges-noresult' )->parse() .
823 '</div>'
824 );
825 }
826
827 /**
828 * Add the "timeout" message to the output
829 */
830 protected function outputTimeout() {
831 $this->getOutput()->addHTML(
832 '<div class="mw-changeslist-timeout">' .
833 $this->msg( 'recentchanges-timeout' )->parse() .
834 '</div>'
835 );
836 }
837
838 /**
839 * Get the database result for this special page instance. Used by ApiFeedRecentChanges.
840 *
841 * @return bool|ResultWrapper Result or false
842 */
843 public function getRows() {
844 $opts = $this->getOptions();
845
846 $tables = [];
847 $fields = [];
848 $conds = [];
849 $query_options = [];
850 $join_conds = [];
851 $this->buildQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
852
853 return $this->doMainQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
854 }
855
856 /**
857 * Get the current FormOptions for this request
858 *
859 * @return FormOptions
860 */
861 public function getOptions() {
862 if ( $this->rcOptions === null ) {
863 $this->rcOptions = $this->setup( $this->rcSubpage );
864 }
865
866 return $this->rcOptions;
867 }
868
869 /**
870 * Register all filters and their groups (including those from hooks), plus handle
871 * conflicts and defaults.
872 *
873 * You might want to customize these in the same method, in subclasses. You can
874 * call getFilterGroup to access a group, and (on the group) getFilter to access a
875 * filter, then make necessary modfications to the filter or group (e.g. with
876 * setDefault).
877 */
878 protected function registerFilters() {
879 $this->registerFiltersFromDefinitions( $this->filterGroupDefinitions );
880
881 // Make sure this is not being transcluded (we don't want to show this
882 // information to all users just because the user that saves the edit can
883 // patrol or is logged in)
884 if ( !$this->including() && $this->getUser()->useRCPatrol() ) {
885 $this->registerFiltersFromDefinitions( $this->reviewStatusFilterGroupDefinition );
886 }
887
888 $changeTypeGroup = $this->getFilterGroup( 'changeType' );
889
890 if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
891 $transformedHideCategorizationDef = $this->transformFilterDefinition(
892 $this->hideCategorizationFilterDefinition
893 );
894
895 $transformedHideCategorizationDef['group'] = $changeTypeGroup;
896
897 $hideCategorization = new ChangesListBooleanFilter(
898 $transformedHideCategorizationDef
899 );
900 }
901
902 Hooks::run( 'ChangesListSpecialPageStructuredFilters', [ $this ] );
903
904 $unstructuredGroupDefinition =
905 $this->getFilterGroupDefinitionFromLegacyCustomFilters(
906 $this->getCustomFilters()
907 );
908 $this->registerFiltersFromDefinitions( [ $unstructuredGroupDefinition ] );
909
910 $userExperienceLevel = $this->getFilterGroup( 'userExpLevel' );
911 $registered = $userExperienceLevel->getFilter( 'registered' );
912 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'newcomer' ) );
913 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'learner' ) );
914 $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'experienced' ) );
915
916 $categoryFilter = $changeTypeGroup->getFilter( 'hidecategorization' );
917 $logactionsFilter = $changeTypeGroup->getFilter( 'hidelog' );
918 $pagecreationFilter = $changeTypeGroup->getFilter( 'hidenewpages' );
919
920 $significanceTypeGroup = $this->getFilterGroup( 'significance' );
921 $hideMinorFilter = $significanceTypeGroup->getFilter( 'hideminor' );
922
923 // categoryFilter is conditional; see registerFilters
924 if ( $categoryFilter !== null ) {
925 $hideMinorFilter->conflictsWith(
926 $categoryFilter,
927 'rcfilters-hideminor-conflicts-typeofchange-global',
928 'rcfilters-hideminor-conflicts-typeofchange',
929 'rcfilters-typeofchange-conflicts-hideminor'
930 );
931 }
932 $hideMinorFilter->conflictsWith(
933 $logactionsFilter,
934 'rcfilters-hideminor-conflicts-typeofchange-global',
935 'rcfilters-hideminor-conflicts-typeofchange',
936 'rcfilters-typeofchange-conflicts-hideminor'
937 );
938 $hideMinorFilter->conflictsWith(
939 $pagecreationFilter,
940 'rcfilters-hideminor-conflicts-typeofchange-global',
941 'rcfilters-hideminor-conflicts-typeofchange',
942 'rcfilters-typeofchange-conflicts-hideminor'
943 );
944 }
945
946 /**
947 * Transforms filter definition to prepare it for constructor.
948 *
949 * See overrides of this method as well.
950 *
951 * @param array $filterDefinition Original filter definition
952 *
953 * @return array Transformed definition
954 */
955 protected function transformFilterDefinition( array $filterDefinition ) {
956 return $filterDefinition;
957 }
958
959 /**
960 * Register filters from a definition object
961 *
962 * Array specifying groups and their filters; see Filter and
963 * ChangesListFilterGroup constructors.
964 *
965 * There is light processing to simplify core maintenance.
966 * @param array $definition
967 */
968 protected function registerFiltersFromDefinitions( array $definition ) {
969 $autoFillPriority = -1;
970 foreach ( $definition as $groupDefinition ) {
971 if ( !isset( $groupDefinition['priority'] ) ) {
972 $groupDefinition['priority'] = $autoFillPriority;
973 } else {
974 // If it's explicitly specified, start over the auto-fill
975 $autoFillPriority = $groupDefinition['priority'];
976 }
977
978 $autoFillPriority--;
979
980 $className = $groupDefinition['class'];
981 unset( $groupDefinition['class'] );
982
983 foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
984 $filterDefinition = $this->transformFilterDefinition( $filterDefinition );
985 }
986
987 $this->registerFilterGroup( new $className( $groupDefinition ) );
988 }
989 }
990
991 /**
992 * Get filter group definition from legacy custom filters
993 *
994 * @param array $customFilters Custom filters from legacy hooks
995 * @return array Group definition
996 */
997 protected function getFilterGroupDefinitionFromLegacyCustomFilters( array $customFilters ) {
998 // Special internal unstructured group
999 $unstructuredGroupDefinition = [
1000 'name' => 'unstructured',
1001 'class' => ChangesListBooleanFilterGroup::class,
1002 'priority' => -1, // Won't display in structured
1003 'filters' => [],
1004 ];
1005
1006 foreach ( $customFilters as $name => $params ) {
1007 $unstructuredGroupDefinition['filters'][] = [
1008 'name' => $name,
1009 'showHide' => $params['msg'],
1010 'default' => $params['default'],
1011 ];
1012 }
1013
1014 return $unstructuredGroupDefinition;
1015 }
1016
1017 /**
1018 * @return array The legacy show/hide toggle filters
1019 */
1020 protected function getLegacyShowHideFilters() {
1021 $filters = [];
1022 foreach ( $this->filterGroups as $group ) {
1023 if ( $group instanceof ChangesListBooleanFilterGroup ) {
1024 foreach ( $group->getFilters() as $key => $filter ) {
1025 if ( $filter->displaysOnUnstructuredUi( $this ) ) {
1026 $filters[ $key ] = $filter;
1027 }
1028 }
1029 }
1030 }
1031 return $filters;
1032 }
1033
1034 /**
1035 * Register all the filters, including legacy hook-driven ones.
1036 * Then create a FormOptions object with options as specified by the user
1037 *
1038 * @param array $parameters
1039 *
1040 * @return FormOptions
1041 */
1042 public function setup( $parameters ) {
1043 $this->registerFilters();
1044
1045 $opts = $this->getDefaultOptions();
1046
1047 $opts = $this->fetchOptionsFromRequest( $opts );
1048
1049 // Give precedence to subpage syntax
1050 if ( $parameters !== null ) {
1051 $this->parseParameters( $parameters, $opts );
1052 }
1053
1054 $this->validateOptions( $opts );
1055
1056 return $opts;
1057 }
1058
1059 /**
1060 * Get a FormOptions object containing the default options. By default, returns
1061 * some basic options. The filters listed explicitly here are overriden in this
1062 * method, in subclasses, but most filters (e.g. hideminor, userExpLevel filters,
1063 * and more) are structured. Structured filters are overriden in registerFilters.
1064 * not here.
1065 *
1066 * @return FormOptions
1067 */
1068 public function getDefaultOptions() {
1069 $opts = new FormOptions();
1070 $structuredUI = $this->isStructuredFilterUiEnabled();
1071 // If urlversion=2 is set, ignore the filter defaults and set them all to false/empty
1072 $useDefaults = $this->getRequest()->getInt( 'urlversion' ) !== 2;
1073
1074 /** @var ChangesListFilterGroup $filterGroup */
1075 foreach ( $this->filterGroups as $filterGroup ) {
1076 $filterGroup->addOptions( $opts, $useDefaults, $structuredUI );
1077 }
1078
1079 $opts->add( 'namespace', '', FormOptions::STRING );
1080 $opts->add( 'invert', false );
1081 $opts->add( 'associated', false );
1082 $opts->add( 'urlversion', 1 );
1083 $opts->add( 'tagfilter', '' );
1084
1085 $opts->add( 'days', $this->getDefaultDays(), FormOptions::FLOAT );
1086 $opts->add( 'limit', $this->getDefaultLimit(), FormOptions::INT );
1087
1088 $opts->add( 'from', '' );
1089
1090 return $opts;
1091 }
1092
1093 /**
1094 * Register a structured changes list filter group
1095 *
1096 * @param ChangesListFilterGroup $group
1097 */
1098 public function registerFilterGroup( ChangesListFilterGroup $group ) {
1099 $groupName = $group->getName();
1100
1101 $this->filterGroups[$groupName] = $group;
1102 }
1103
1104 /**
1105 * Gets the currently registered filters groups
1106 *
1107 * @return array Associative array of ChangesListFilterGroup objects, with group name as key
1108 */
1109 protected function getFilterGroups() {
1110 return $this->filterGroups;
1111 }
1112
1113 /**
1114 * Gets a specified ChangesListFilterGroup by name
1115 *
1116 * @param string $groupName Name of group
1117 *
1118 * @return ChangesListFilterGroup|null Group, or null if not registered
1119 */
1120 public function getFilterGroup( $groupName ) {
1121 return isset( $this->filterGroups[$groupName] ) ?
1122 $this->filterGroups[$groupName] :
1123 null;
1124 }
1125
1126 // Currently, this intentionally only includes filters that display
1127 // in the structured UI. This can be changed easily, though, if we want
1128 // to include data on filters that use the unstructured UI. messageKeys is a
1129 // special top-level value, with the value being an array of the message keys to
1130 // send to the client.
1131 /**
1132 * Gets structured filter information needed by JS
1133 *
1134 * @return array Associative array
1135 * * array $return['groups'] Group data
1136 * * array $return['messageKeys'] Array of message keys
1137 */
1138 public function getStructuredFilterJsData() {
1139 $output = [
1140 'groups' => [],
1141 'messageKeys' => [],
1142 ];
1143
1144 usort( $this->filterGroups, function ( $a, $b ) {
1145 return $b->getPriority() - $a->getPriority();
1146 } );
1147
1148 foreach ( $this->filterGroups as $groupName => $group ) {
1149 $groupOutput = $group->getJsData( $this );
1150 if ( $groupOutput !== null ) {
1151 $output['messageKeys'] = array_merge(
1152 $output['messageKeys'],
1153 $groupOutput['messageKeys']
1154 );
1155
1156 unset( $groupOutput['messageKeys'] );
1157 $output['groups'][] = $groupOutput;
1158 }
1159 }
1160
1161 return $output;
1162 }
1163
1164 /**
1165 * Get custom show/hide filters using deprecated ChangesListSpecialPageFilters
1166 * hook.
1167 *
1168 * @return array Map of filter URL param names to properties (msg/default)
1169 */
1170 protected function getCustomFilters() {
1171 if ( $this->customFilters === null ) {
1172 $this->customFilters = [];
1173 Hooks::run( 'ChangesListSpecialPageFilters', [ $this, &$this->customFilters ], '1.29' );
1174 }
1175
1176 return $this->customFilters;
1177 }
1178
1179 /**
1180 * Fetch values for a FormOptions object from the WebRequest associated with this instance.
1181 *
1182 * Intended for subclassing, e.g. to add a backwards-compatibility layer.
1183 *
1184 * @param FormOptions $opts
1185 * @return FormOptions
1186 */
1187 protected function fetchOptionsFromRequest( $opts ) {
1188 $opts->fetchValuesFromRequest( $this->getRequest() );
1189
1190 return $opts;
1191 }
1192
1193 /**
1194 * Process $par and put options found in $opts. Used when including the page.
1195 *
1196 * @param string $par
1197 * @param FormOptions $opts
1198 */
1199 public function parseParameters( $par, FormOptions $opts ) {
1200 $stringParameterNameSet = [];
1201 $hideParameterNameSet = [];
1202
1203 // URL parameters can be per-group, like 'userExpLevel',
1204 // or per-filter, like 'hideminor'.
1205
1206 foreach ( $this->filterGroups as $filterGroup ) {
1207 if ( $filterGroup instanceof ChangesListStringOptionsFilterGroup ) {
1208 $stringParameterNameSet[$filterGroup->getName()] = true;
1209 } elseif ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
1210 foreach ( $filterGroup->getFilters() as $filter ) {
1211 $hideParameterNameSet[$filter->getName()] = true;
1212 }
1213 }
1214 }
1215
1216 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
1217 foreach ( $bits as $bit ) {
1218 $m = [];
1219 if ( isset( $hideParameterNameSet[$bit] ) ) {
1220 // hidefoo => hidefoo=true
1221 $opts[$bit] = true;
1222 } elseif ( isset( $hideParameterNameSet["hide$bit"] ) ) {
1223 // foo => hidefoo=false
1224 $opts["hide$bit"] = false;
1225 } elseif ( preg_match( '/^(.*)=(.*)$/', $bit, $m ) ) {
1226 if ( isset( $stringParameterNameSet[$m[1]] ) ) {
1227 $opts[$m[1]] = $m[2];
1228 }
1229 }
1230 }
1231 }
1232
1233 /**
1234 * Validate a FormOptions object generated by getDefaultOptions() with values already populated.
1235 *
1236 * @param FormOptions $opts
1237 */
1238 public function validateOptions( FormOptions $opts ) {
1239 $isContradictory = $this->fixContradictoryOptions( $opts );
1240 $isReplaced = $this->replaceOldOptions( $opts );
1241
1242 if ( $isContradictory || $isReplaced ) {
1243 $query = wfArrayToCgi( $this->convertParamsForLink( $opts->getChangedValues() ) );
1244 $this->getOutput()->redirect( $this->getPageTitle()->getCanonicalURL( $query ) );
1245 }
1246
1247 $opts->validateIntBounds( 'limit', 0, 5000 );
1248 $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1249 }
1250
1251 /**
1252 * Fix invalid options by resetting pairs that should never appear together.
1253 *
1254 * @param FormOptions $opts
1255 * @return bool True if any option was reset
1256 */
1257 private function fixContradictoryOptions( FormOptions $opts ) {
1258 $fixed = $this->fixBackwardsCompatibilityOptions( $opts );
1259
1260 foreach ( $this->filterGroups as $filterGroup ) {
1261 if ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
1262 $filters = $filterGroup->getFilters();
1263
1264 if ( count( $filters ) === 1 ) {
1265 // legacy boolean filters should not be considered
1266 continue;
1267 }
1268
1269 $allInGroupEnabled = array_reduce(
1270 $filters,
1271 function ( $carry, $filter ) use ( $opts ) {
1272 return $carry && $opts[ $filter->getName() ];
1273 },
1274 /* initialValue */ count( $filters ) > 0
1275 );
1276
1277 if ( $allInGroupEnabled ) {
1278 foreach ( $filters as $filter ) {
1279 $opts[ $filter->getName() ] = false;
1280 }
1281
1282 $fixed = true;
1283 }
1284 }
1285 }
1286
1287 return $fixed;
1288 }
1289
1290 /**
1291 * Fix a special case (hideanons=1 and hideliu=1) in a special way, for backwards
1292 * compatibility.
1293 *
1294 * This is deprecated and may be removed.
1295 *
1296 * @param FormOptions $opts
1297 * @return bool True if this change was mode
1298 */
1299 private function fixBackwardsCompatibilityOptions( FormOptions $opts ) {
1300 if ( $opts['hideanons'] && $opts['hideliu'] ) {
1301 $opts->reset( 'hideanons' );
1302 if ( !$opts['hidebots'] ) {
1303 $opts->reset( 'hideliu' );
1304 $opts['hidehumans'] = 1;
1305 }
1306
1307 return true;
1308 }
1309
1310 return false;
1311 }
1312
1313 /**
1314 * Replace old options 'hideanons' or 'hideliu' with structured UI equivalent
1315 *
1316 * @param FormOptions $opts
1317 * @return bool True if the change was made
1318 */
1319 public function replaceOldOptions( FormOptions $opts ) {
1320 if ( !$this->isStructuredFilterUiEnabled() ) {
1321 return false;
1322 }
1323
1324 // At this point 'hideanons' and 'hideliu' cannot be both true,
1325 // because fixBackwardsCompatibilityOptions resets (at least) 'hideanons' in such case
1326 if ( $opts[ 'hideanons' ] ) {
1327 $opts->reset( 'hideanons' );
1328 $opts[ 'userExpLevel' ] = 'registered';
1329 return true;
1330 }
1331
1332 if ( $opts[ 'hideliu' ] ) {
1333 $opts->reset( 'hideliu' );
1334 $opts[ 'userExpLevel' ] = 'unregistered';
1335 return true;
1336 }
1337
1338 return false;
1339 }
1340
1341 /**
1342 * Convert parameters values from true/false to 1/0
1343 * so they are not omitted by wfArrayToCgi()
1344 * Bug 36524
1345 *
1346 * @param array $params
1347 * @return array
1348 */
1349 protected function convertParamsForLink( $params ) {
1350 foreach ( $params as &$value ) {
1351 if ( $value === false ) {
1352 $value = '0';
1353 }
1354 }
1355 unset( $value );
1356 return $params;
1357 }
1358
1359 /**
1360 * Sets appropriate tables, fields, conditions, etc. depending on which filters
1361 * the user requested.
1362 *
1363 * @param array &$tables Array of tables; see IDatabase::select $table
1364 * @param array &$fields Array of fields; see IDatabase::select $vars
1365 * @param array &$conds Array of conditions; see IDatabase::select $conds
1366 * @param array &$query_options Array of query options; see IDatabase::select $options
1367 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1368 * @param FormOptions $opts
1369 */
1370 protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
1371 &$join_conds, FormOptions $opts
1372 ) {
1373 $dbr = $this->getDB();
1374 $isStructuredUI = $this->isStructuredFilterUiEnabled();
1375
1376 /** @var ChangesListFilterGroup $filterGroup */
1377 foreach ( $this->filterGroups as $filterGroup ) {
1378 $filterGroup->modifyQuery( $dbr, $this, $tables, $fields, $conds,
1379 $query_options, $join_conds, $opts, $isStructuredUI );
1380 }
1381
1382 // Namespace filtering
1383 if ( $opts[ 'namespace' ] !== '' ) {
1384 $namespaces = explode( ';', $opts[ 'namespace' ] );
1385
1386 if ( $opts[ 'associated' ] ) {
1387 $associatedNamespaces = array_map(
1388 function ( $ns ) {
1389 return MWNamespace::getAssociated( $ns );
1390 },
1391 $namespaces
1392 );
1393 $namespaces = array_unique( array_merge( $namespaces, $associatedNamespaces ) );
1394 }
1395
1396 if ( count( $namespaces ) === 1 ) {
1397 $operator = $opts[ 'invert' ] ? '!=' : '=';
1398 $value = $dbr->addQuotes( reset( $namespaces ) );
1399 } else {
1400 $operator = $opts[ 'invert' ] ? 'NOT IN' : 'IN';
1401 sort( $namespaces );
1402 $value = '(' . $dbr->makeList( $namespaces ) . ')';
1403 }
1404 $conds[] = "rc_namespace $operator $value";
1405 }
1406
1407 // Calculate cutoff
1408 $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
1409 $cutoff = $dbr->timestamp( $cutoff_unixtime );
1410
1411 $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
1412 if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
1413 $cutoff = $dbr->timestamp( $opts['from'] );
1414 } else {
1415 $opts->reset( 'from' );
1416 }
1417
1418 $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
1419 }
1420
1421 /**
1422 * Process the query
1423 *
1424 * @param array $tables Array of tables; see IDatabase::select $table
1425 * @param array $fields Array of fields; see IDatabase::select $vars
1426 * @param array $conds Array of conditions; see IDatabase::select $conds
1427 * @param array $query_options Array of query options; see IDatabase::select $options
1428 * @param array $join_conds Array of join conditions; see IDatabase::select $join_conds
1429 * @param FormOptions $opts
1430 * @return bool|ResultWrapper Result or false
1431 */
1432 protected function doMainQuery( $tables, $fields, $conds,
1433 $query_options, $join_conds, FormOptions $opts
1434 ) {
1435 $rcQuery = RecentChange::getQueryInfo();
1436 $tables = array_merge( $tables, $rcQuery['tables'] );
1437 $fields = array_merge( $rcQuery['fields'], $fields );
1438 $join_conds = array_merge( $join_conds, $rcQuery['joins'] );
1439
1440 ChangeTags::modifyDisplayQuery(
1441 $tables,
1442 $fields,
1443 $conds,
1444 $join_conds,
1445 $query_options,
1446 ''
1447 );
1448
1449 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
1450 $opts )
1451 ) {
1452 return false;
1453 }
1454
1455 $dbr = $this->getDB();
1456
1457 return $dbr->select(
1458 $tables,
1459 $fields,
1460 $conds,
1461 __METHOD__,
1462 $query_options,
1463 $join_conds
1464 );
1465 }
1466
1467 protected function runMainQueryHook( &$tables, &$fields, &$conds,
1468 &$query_options, &$join_conds, $opts
1469 ) {
1470 return Hooks::run(
1471 'ChangesListSpecialPageQuery',
1472 [ $this->getName(), &$tables, &$fields, &$conds, &$query_options, &$join_conds, $opts ]
1473 );
1474 }
1475
1476 /**
1477 * Return a IDatabase object for reading
1478 *
1479 * @return IDatabase
1480 */
1481 protected function getDB() {
1482 return wfGetDB( DB_REPLICA );
1483 }
1484
1485 /**
1486 * Send header output to the OutputPage object, only called if not using feeds
1487 *
1488 * @param int $rowCount Number of database rows
1489 * @param FormOptions $opts
1490 */
1491 private function webOutputHeader( $rowCount, $opts ) {
1492 if ( !$this->including() ) {
1493 $this->outputFeedLinks();
1494 $this->doHeader( $opts, $rowCount );
1495 }
1496 }
1497
1498 /**
1499 * Send output to the OutputPage object, only called if not used feeds
1500 *
1501 * @param ResultWrapper $rows Database rows
1502 * @param FormOptions $opts
1503 */
1504 public function webOutput( $rows, $opts ) {
1505 $this->webOutputHeader( $rows->numRows(), $opts );
1506
1507 $this->outputChangesList( $rows, $opts );
1508 }
1509
1510 /**
1511 * Output feed links.
1512 */
1513 public function outputFeedLinks() {
1514 // nothing by default
1515 }
1516
1517 /**
1518 * Build and output the actual changes list.
1519 *
1520 * @param ResultWrapper $rows Database rows
1521 * @param FormOptions $opts
1522 */
1523 abstract public function outputChangesList( $rows, $opts );
1524
1525 /**
1526 * Set the text to be displayed above the changes
1527 *
1528 * @param FormOptions $opts
1529 * @param int $numRows Number of rows in the result to show after this header
1530 */
1531 public function doHeader( $opts, $numRows ) {
1532 $this->setTopText( $opts );
1533
1534 // @todo Lots of stuff should be done here.
1535
1536 $this->setBottomText( $opts );
1537 }
1538
1539 /**
1540 * Send the text to be displayed before the options. Should use $this->getOutput()->addWikiText()
1541 * or similar methods to print the text.
1542 *
1543 * @param FormOptions $opts
1544 */
1545 public function setTopText( FormOptions $opts ) {
1546 // nothing by default
1547 }
1548
1549 /**
1550 * Send the text to be displayed after the options. Should use $this->getOutput()->addWikiText()
1551 * or similar methods to print the text.
1552 *
1553 * @param FormOptions $opts
1554 */
1555 public function setBottomText( FormOptions $opts ) {
1556 // nothing by default
1557 }
1558
1559 /**
1560 * Get options to be displayed in a form
1561 * @todo This should handle options returned by getDefaultOptions().
1562 * @todo Not called by anything in this class (but is in subclasses), should be
1563 * called by something… doHeader() maybe?
1564 *
1565 * @param FormOptions $opts
1566 * @return array
1567 */
1568 public function getExtraOptions( $opts ) {
1569 return [];
1570 }
1571
1572 /**
1573 * Return the legend displayed within the fieldset
1574 *
1575 * @return string
1576 */
1577 public function makeLegend() {
1578 $context = $this->getContext();
1579 $user = $context->getUser();
1580 # The legend showing what the letters and stuff mean
1581 $legend = Html::openElement( 'dl' ) . "\n";
1582 # Iterates through them and gets the messages for both letter and tooltip
1583 $legendItems = $context->getConfig()->get( 'RecentChangesFlags' );
1584 if ( !( $user->useRCPatrol() || $user->useNPPatrol() ) ) {
1585 unset( $legendItems['unpatrolled'] );
1586 }
1587 foreach ( $legendItems as $key => $item ) { # generate items of the legend
1588 $label = isset( $item['legend'] ) ? $item['legend'] : $item['title'];
1589 $letter = $item['letter'];
1590 $cssClass = isset( $item['class'] ) ? $item['class'] : $key;
1591
1592 $legend .= Html::element( 'dt',
1593 [ 'class' => $cssClass ], $context->msg( $letter )->text()
1594 ) . "\n" .
1595 Html::rawElement( 'dd',
1596 [ 'class' => Sanitizer::escapeClass( 'mw-changeslist-legend-' . $key ) ],
1597 $context->msg( $label )->parse()
1598 ) . "\n";
1599 }
1600 # (+-123)
1601 $legend .= Html::rawElement( 'dt',
1602 [ 'class' => 'mw-plusminus-pos' ],
1603 $context->msg( 'recentchanges-legend-plusminus' )->parse()
1604 ) . "\n";
1605 $legend .= Html::element(
1606 'dd',
1607 [ 'class' => 'mw-changeslist-legend-plusminus' ],
1608 $context->msg( 'recentchanges-label-plusminus' )->text()
1609 ) . "\n";
1610 $legend .= Html::closeElement( 'dl' ) . "\n";
1611
1612 $legendHeading = $this->isStructuredFilterUiEnabled() ?
1613 $context->msg( 'rcfilters-legend-heading' )->parse() :
1614 $context->msg( 'recentchanges-legend-heading' )->parse();
1615
1616 # Collapsible
1617 $collapsedState = $this->getRequest()->getCookie( 'changeslist-state' );
1618 $collapsedClass = $collapsedState === 'collapsed' ? ' mw-collapsed' : '';
1619 # Enhanced mode
1620 $enhancedMode = $this->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) );
1621 $enhancedClass = $enhancedMode ? ' mw-enhanced' : '';
1622
1623 $legendClasses = $collapsedClass . $enhancedClass;
1624 $legend =
1625 '<div class="mw-changeslist-legend mw-collapsible' . $legendClasses . '">' .
1626 $legendHeading .
1627 '<div class="mw-collapsible-content">' . $legend . '</div>' .
1628 '</div>';
1629
1630 return $legend;
1631 }
1632
1633 /**
1634 * Add page-specific modules.
1635 */
1636 protected function addModules() {
1637 $out = $this->getOutput();
1638 // Styles and behavior for the legend box (see makeLegend())
1639 $out->addModuleStyles( [
1640 'mediawiki.special.changeslist.legend',
1641 'mediawiki.special.changeslist',
1642 ] );
1643 $out->addModules( 'mediawiki.special.changeslist.legend.js' );
1644
1645 if ( $this->isStructuredFilterUiEnabled() && !$this->including() ) {
1646 $out->addModules( 'mediawiki.rcfilters.filters.ui' );
1647 $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
1648 }
1649 }
1650
1651 protected function getGroupName() {
1652 return 'changes';
1653 }
1654
1655 /**
1656 * Filter on users' experience levels; this will not be called if nothing is
1657 * selected.
1658 *
1659 * @param string $specialPageClassName Class name of current special page
1660 * @param IContextSource $context Context, for e.g. user
1661 * @param IDatabase $dbr Database, for addQuotes, makeList, and similar
1662 * @param array &$tables Array of tables; see IDatabase::select $table
1663 * @param array &$fields Array of fields; see IDatabase::select $vars
1664 * @param array &$conds Array of conditions; see IDatabase::select $conds
1665 * @param array &$query_options Array of query options; see IDatabase::select $options
1666 * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
1667 * @param array $selectedExpLevels The allowed active values, sorted
1668 * @param int $now Number of seconds since the UNIX epoch, or 0 if not given
1669 * (optional)
1670 */
1671 public function filterOnUserExperienceLevel( $specialPageClassName, $context, $dbr,
1672 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedExpLevels, $now = 0
1673 ) {
1674 global $wgLearnerEdits,
1675 $wgExperiencedUserEdits,
1676 $wgLearnerMemberSince,
1677 $wgExperiencedUserMemberSince;
1678
1679 $LEVEL_COUNT = 5;
1680
1681 // If all levels are selected, don't filter
1682 if ( count( $selectedExpLevels ) === $LEVEL_COUNT ) {
1683 return;
1684 }
1685
1686 // both 'registered' and 'unregistered', experience levels, if any, are included in 'registered'
1687 if (
1688 in_array( 'registered', $selectedExpLevels ) &&
1689 in_array( 'unregistered', $selectedExpLevels )
1690 ) {
1691 return;
1692 }
1693
1694 // 'registered' but not 'unregistered', experience levels, if any, are included in 'registered'
1695 if (
1696 in_array( 'registered', $selectedExpLevels ) &&
1697 !in_array( 'unregistered', $selectedExpLevels )
1698 ) {
1699 $conds[] = 'rc_user != 0';
1700 return;
1701 }
1702
1703 if ( $selectedExpLevels === [ 'unregistered' ] ) {
1704 $conds[] = 'rc_user = 0';
1705 return;
1706 }
1707
1708 $tables[] = 'user';
1709 $join_conds['user'] = [ 'LEFT JOIN', 'rc_user = user_id' ];
1710
1711 if ( $now === 0 ) {
1712 $now = time();
1713 }
1714 $secondsPerDay = 86400;
1715 $learnerCutoff = $now - $wgLearnerMemberSince * $secondsPerDay;
1716 $experiencedUserCutoff = $now - $wgExperiencedUserMemberSince * $secondsPerDay;
1717
1718 $aboveNewcomer = $dbr->makeList(
1719 [
1720 'user_editcount >= ' . intval( $wgLearnerEdits ),
1721 'user_registration <= ' . $dbr->addQuotes( $dbr->timestamp( $learnerCutoff ) ),
1722 ],
1723 IDatabase::LIST_AND
1724 );
1725
1726 $aboveLearner = $dbr->makeList(
1727 [
1728 'user_editcount >= ' . intval( $wgExperiencedUserEdits ),
1729 'user_registration <= ' .
1730 $dbr->addQuotes( $dbr->timestamp( $experiencedUserCutoff ) ),
1731 ],
1732 IDatabase::LIST_AND
1733 );
1734
1735 $conditions = [];
1736
1737 if ( in_array( 'unregistered', $selectedExpLevels ) ) {
1738 $selectedExpLevels = array_diff( $selectedExpLevels, [ 'unregistered' ] );
1739 $conditions[] = 'rc_user = 0';
1740 }
1741
1742 if ( $selectedExpLevels === [ 'newcomer' ] ) {
1743 $conditions[] = "NOT ( $aboveNewcomer )";
1744 } elseif ( $selectedExpLevels === [ 'learner' ] ) {
1745 $conditions[] = $dbr->makeList(
1746 [ $aboveNewcomer, "NOT ( $aboveLearner )" ],
1747 IDatabase::LIST_AND
1748 );
1749 } elseif ( $selectedExpLevels === [ 'experienced' ] ) {
1750 $conditions[] = $aboveLearner;
1751 } elseif ( $selectedExpLevels === [ 'learner', 'newcomer' ] ) {
1752 $conditions[] = "NOT ( $aboveLearner )";
1753 } elseif ( $selectedExpLevels === [ 'experienced', 'newcomer' ] ) {
1754 $conditions[] = $dbr->makeList(
1755 [ "NOT ( $aboveNewcomer )", $aboveLearner ],
1756 IDatabase::LIST_OR
1757 );
1758 } elseif ( $selectedExpLevels === [ 'experienced', 'learner' ] ) {
1759 $conditions[] = $aboveNewcomer;
1760 } elseif ( $selectedExpLevels === [ 'experienced', 'learner', 'newcomer' ] ) {
1761 $conditions[] = 'rc_user != 0';
1762 }
1763
1764 if ( count( $conditions ) > 1 ) {
1765 $conds[] = $dbr->makeList( $conditions, IDatabase::LIST_OR );
1766 } elseif ( count( $conditions ) === 1 ) {
1767 $conds[] = reset( $conditions );
1768 }
1769 }
1770
1771 /**
1772 * Check whether the structured filter UI is enabled
1773 *
1774 * @return bool
1775 */
1776 public function isStructuredFilterUiEnabled() {
1777 if ( $this->getRequest()->getBool( 'rcfilters' ) ) {
1778 return true;
1779 }
1780
1781 return static::checkStructuredFilterUiEnabled(
1782 $this->getConfig(),
1783 $this->getUser()
1784 );
1785 }
1786
1787 /**
1788 * Check whether the structured filter UI is enabled by default (regardless of
1789 * this particular user's setting)
1790 *
1791 * @return bool
1792 */
1793 public function isStructuredFilterUiEnabledByDefault() {
1794 if ( $this->getConfig()->get( 'StructuredChangeFiltersShowPreference' ) ) {
1795 return !$this->getUser()->getDefaultOption( 'rcenhancedfilters-disable' );
1796 } else {
1797 return $this->getUser()->getDefaultOption( 'rcenhancedfilters' );
1798 }
1799 }
1800
1801 /**
1802 * Static method to check whether StructuredFilter UI is enabled for the given user
1803 *
1804 * @since 1.31
1805 * @param Config $config
1806 * @param User $user User object
1807 * @return bool
1808 */
1809 public static function checkStructuredFilterUiEnabled( Config $config, User $user ) {
1810 if ( $config->get( 'StructuredChangeFiltersShowPreference' ) ) {
1811 return !$user->getOption( 'rcenhancedfilters-disable' );
1812 } else {
1813 return $user->getOption( 'rcenhancedfilters' );
1814 }
1815 }
1816
1817 /**
1818 * Get the default value of the number of changes to display when loading
1819 * the result set.
1820 *
1821 * @since 1.30
1822 * @return int
1823 */
1824 public function getDefaultLimit() {
1825 return $this->getUser()->getIntOption( static::$limitPreferenceName );
1826 }
1827
1828 /**
1829 * Get the default value of the number of days to display when loading
1830 * the result set.
1831 * Supports fractional values, and should be cast to a float.
1832 *
1833 * @since 1.30
1834 * @return float
1835 */
1836 public function getDefaultDays() {
1837 return floatval( $this->getUser()->getOption( static::$daysPreferenceName ) );
1838 }
1839 }