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