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