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