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