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