user: Allow "CAS update failed" exceptions to be normalised
[lhc/web/wiklou.git] / includes / specials / SpecialRecentchanges.php
1 <?php
2 /**
3 * Implements Special:Recentchanges
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
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\IResultWrapper;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27
28 /**
29 * A special page that lists last changes made to the wiki
30 *
31 * @ingroup SpecialPage
32 */
33 class SpecialRecentChanges extends ChangesListSpecialPage {
34
35 protected static $savedQueriesPreferenceName = 'rcfilters-saved-queries';
36 protected static $daysPreferenceName = 'rcdays'; // Use general RecentChanges preference
37 protected static $limitPreferenceName = 'rcfilters-limit'; // Use RCFilters-specific preference
38 protected static $collapsedPreferenceName = 'rcfilters-rc-collapsed';
39
40 private $watchlistFilterGroupDefinition;
41
42 public function __construct( $name = 'Recentchanges', $restriction = '' ) {
43 parent::__construct( $name, $restriction );
44
45 $this->watchlistFilterGroupDefinition = [
46 'name' => 'watchlist',
47 'title' => 'rcfilters-filtergroup-watchlist',
48 'class' => ChangesListStringOptionsFilterGroup::class,
49 'priority' => -9,
50 'isFullCoverage' => true,
51 'filters' => [
52 [
53 'name' => 'watched',
54 'label' => 'rcfilters-filter-watchlist-watched-label',
55 'description' => 'rcfilters-filter-watchlist-watched-description',
56 'cssClassSuffix' => 'watched',
57 'isRowApplicableCallable' => function ( $ctx, $rc ) {
58 return $rc->getAttribute( 'wl_user' );
59 }
60 ],
61 [
62 'name' => 'watchednew',
63 'label' => 'rcfilters-filter-watchlist-watchednew-label',
64 'description' => 'rcfilters-filter-watchlist-watchednew-description',
65 'cssClassSuffix' => 'watchednew',
66 'isRowApplicableCallable' => function ( $ctx, $rc ) {
67 return $rc->getAttribute( 'wl_user' ) &&
68 $rc->getAttribute( 'rc_timestamp' ) &&
69 $rc->getAttribute( 'wl_notificationtimestamp' ) &&
70 $rc->getAttribute( 'rc_timestamp' ) >= $rc->getAttribute( 'wl_notificationtimestamp' );
71 },
72 ],
73 [
74 'name' => 'notwatched',
75 'label' => 'rcfilters-filter-watchlist-notwatched-label',
76 'description' => 'rcfilters-filter-watchlist-notwatched-description',
77 'cssClassSuffix' => 'notwatched',
78 'isRowApplicableCallable' => function ( $ctx, $rc ) {
79 return $rc->getAttribute( 'wl_user' ) === null;
80 },
81 ]
82 ],
83 'default' => ChangesListStringOptionsFilterGroup::NONE,
84 'queryCallable' => function ( $specialPageClassName, $context, $dbr,
85 &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedValues ) {
86 sort( $selectedValues );
87 $notwatchedCond = 'wl_user IS NULL';
88 $watchedCond = 'wl_user IS NOT NULL';
89 $newCond = 'rc_timestamp >= wl_notificationtimestamp';
90
91 if ( $selectedValues === [ 'notwatched' ] ) {
92 $conds[] = $notwatchedCond;
93 return;
94 }
95
96 if ( $selectedValues === [ 'watched' ] ) {
97 $conds[] = $watchedCond;
98 return;
99 }
100
101 if ( $selectedValues === [ 'watchednew' ] ) {
102 $conds[] = $dbr->makeList( [
103 $watchedCond,
104 $newCond
105 ], LIST_AND );
106 return;
107 }
108
109 if ( $selectedValues === [ 'notwatched', 'watched' ] ) {
110 // no filters
111 return;
112 }
113
114 if ( $selectedValues === [ 'notwatched', 'watchednew' ] ) {
115 $conds[] = $dbr->makeList( [
116 $notwatchedCond,
117 $dbr->makeList( [
118 $watchedCond,
119 $newCond
120 ], LIST_AND )
121 ], LIST_OR );
122 return;
123 }
124
125 if ( $selectedValues === [ 'watched', 'watchednew' ] ) {
126 $conds[] = $watchedCond;
127 return;
128 }
129
130 if ( $selectedValues === [ 'notwatched', 'watched', 'watchednew' ] ) {
131 // no filters
132 return;
133 }
134 }
135 ];
136 }
137
138 /**
139 * Main execution point
140 *
141 * @param string $subpage
142 */
143 public function execute( $subpage ) {
144 // Backwards-compatibility: redirect to new feed URLs
145 $feedFormat = $this->getRequest()->getVal( 'feed' );
146 if ( !$this->including() && $feedFormat ) {
147 $query = $this->getFeedQuery();
148 $query['feedformat'] = $feedFormat === 'atom' ? 'atom' : 'rss';
149 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
150
151 return;
152 }
153
154 // 10 seconds server-side caching max
155 $out = $this->getOutput();
156 $out->setCdnMaxage( 10 );
157 // Check if the client has a cached version
158 $lastmod = $this->checkLastModified();
159 if ( $lastmod === false ) {
160 return;
161 }
162
163 $this->addHelpLink(
164 '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Recent_changes',
165 true
166 );
167 parent::execute( $subpage );
168 }
169
170 /**
171 * @inheritDoc
172 */
173 protected function transformFilterDefinition( array $filterDefinition ) {
174 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
175 $filterDefinition['showHide'] = 'rc' . $filterDefinition['showHideSuffix'];
176 }
177
178 return $filterDefinition;
179 }
180
181 /**
182 * @inheritDoc
183 */
184 protected function registerFilters() {
185 parent::registerFilters();
186
187 if (
188 !$this->including() &&
189 $this->getUser()->isLoggedIn() &&
190 $this->getUser()->isAllowed( 'viewmywatchlist' )
191 ) {
192 $this->registerFiltersFromDefinitions( [ $this->watchlistFilterGroupDefinition ] );
193 $watchlistGroup = $this->getFilterGroup( 'watchlist' );
194 $watchlistGroup->getFilter( 'watched' )->setAsSupersetOf(
195 $watchlistGroup->getFilter( 'watchednew' )
196 );
197 }
198
199 $user = $this->getUser();
200
201 $significance = $this->getFilterGroup( 'significance' );
202 $hideMinor = $significance->getFilter( 'hideminor' );
203 $hideMinor->setDefault( $user->getBoolOption( 'hideminor' ) );
204
205 $automated = $this->getFilterGroup( 'automated' );
206 $hideBots = $automated->getFilter( 'hidebots' );
207 $hideBots->setDefault( true );
208
209 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
210 if ( $reviewStatus !== null ) {
211 // Conditional on feature being available and rights
212 if ( $user->getBoolOption( 'hidepatrolled' ) ) {
213 $reviewStatus->setDefault( 'unpatrolled' );
214 $legacyReviewStatus = $this->getFilterGroup( 'legacyReviewStatus' );
215 $legacyHidePatrolled = $legacyReviewStatus->getFilter( 'hidepatrolled' );
216 $legacyHidePatrolled->setDefault( true );
217 }
218 }
219
220 $changeType = $this->getFilterGroup( 'changeType' );
221 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
222 if ( $hideCategorization !== null ) {
223 // Conditional on feature being available
224 $hideCategorization->setDefault( $user->getBoolOption( 'hidecategorization' ) );
225 }
226 }
227
228 /**
229 * Get all custom filters
230 *
231 * @return array Map of filter URL param names to properties (msg/default)
232 */
233 protected function getCustomFilters() {
234 if ( $this->customFilters === null ) {
235 $this->customFilters = parent::getCustomFilters();
236 Hooks::run( 'SpecialRecentChangesFilters', [ $this, &$this->customFilters ], '1.23' );
237 }
238
239 return $this->customFilters;
240 }
241
242 /**
243 * Process $par and put options found in $opts. Used when including the page.
244 *
245 * @param string $par
246 * @param FormOptions $opts
247 */
248 public function parseParameters( $par, FormOptions $opts ) {
249 parent::parseParameters( $par, $opts );
250
251 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
252 foreach ( $bits as $bit ) {
253 if ( is_numeric( $bit ) ) {
254 $opts['limit'] = $bit;
255 }
256
257 $m = [];
258 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
259 $opts['limit'] = $m[1];
260 }
261 if ( preg_match( '/^days=(\d+(?:\.\d+)?)$/', $bit, $m ) ) {
262 $opts['days'] = $m[1];
263 }
264 if ( preg_match( '/^namespace=(.*)$/', $bit, $m ) ) {
265 $opts['namespace'] = $m[1];
266 }
267 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
268 $opts['tagfilter'] = $m[1];
269 }
270 }
271 }
272
273 /**
274 * @inheritDoc
275 */
276 protected function doMainQuery( $tables, $fields, $conds, $query_options,
277 $join_conds, FormOptions $opts
278 ) {
279 $dbr = $this->getDB();
280 $user = $this->getUser();
281
282 $rcQuery = RecentChange::getQueryInfo();
283 $tables = array_merge( $tables, $rcQuery['tables'] );
284 $fields = array_merge( $rcQuery['fields'], $fields );
285 $join_conds = array_merge( $join_conds, $rcQuery['joins'] );
286
287 // JOIN on watchlist for users
288 if ( $user->isLoggedIn() && $user->isAllowed( 'viewmywatchlist' ) ) {
289 $tables[] = 'watchlist';
290 $fields[] = 'wl_user';
291 $fields[] = 'wl_notificationtimestamp';
292 $join_conds['watchlist'] = [ 'LEFT JOIN', [
293 'wl_user' => $user->getId(),
294 'wl_title=rc_title',
295 'wl_namespace=rc_namespace'
296 ] ];
297 }
298
299 // JOIN on page, used for 'last revision' filter highlight
300 $tables[] = 'page';
301 $fields[] = 'page_latest';
302 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
303
304 $tagFilter = $opts['tagfilter'] ? explode( '|', $opts['tagfilter'] ) : [];
305 ChangeTags::modifyDisplayQuery(
306 $tables,
307 $fields,
308 $conds,
309 $join_conds,
310 $query_options,
311 $tagFilter
312 );
313
314 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
315 $opts )
316 ) {
317 return false;
318 }
319
320 if ( $this->areFiltersInConflict() ) {
321 return false;
322 }
323
324 $orderByAndLimit = [
325 'ORDER BY' => 'rc_timestamp DESC',
326 'LIMIT' => $opts['limit']
327 ];
328 if ( in_array( 'DISTINCT', $query_options ) ) {
329 // ChangeTags::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
330 // In order to prevent DISTINCT from causing query performance problems,
331 // we have to GROUP BY the primary key. This in turn requires us to add
332 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
333 // start of the GROUP BY
334 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
335 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
336 }
337 // array_merge() is used intentionally here so that hooks can, should
338 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
339 // MediaWiki 1.26 this used to use the plus operator instead, which meant
340 // that extensions weren't able to change these conditions
341 $query_options = array_merge( $orderByAndLimit, $query_options );
342 $rows = $dbr->select(
343 $tables,
344 $fields,
345 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
346 // knowledge to use an index merge if it wants (it may use some other index though).
347 $conds + [ 'rc_new' => [ 0, 1 ] ],
348 __METHOD__,
349 $query_options,
350 $join_conds
351 );
352
353 return $rows;
354 }
355
356 protected function runMainQueryHook( &$tables, &$fields, &$conds,
357 &$query_options, &$join_conds, $opts
358 ) {
359 return parent::runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds, $opts )
360 && Hooks::run(
361 'SpecialRecentChangesQuery',
362 [ &$conds, &$tables, &$join_conds, $opts, &$query_options, &$fields ],
363 '1.23'
364 );
365 }
366
367 protected function getDB() {
368 return wfGetDB( DB_REPLICA, 'recentchanges' );
369 }
370
371 public function outputFeedLinks() {
372 $this->addFeedLinks( $this->getFeedQuery() );
373 }
374
375 /**
376 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
377 *
378 * @return array
379 */
380 protected function getFeedQuery() {
381 $query = array_filter( $this->getOptions()->getAllValues(), function ( $value ) {
382 // API handles empty parameters in a different way
383 return $value !== '';
384 } );
385 $query['action'] = 'feedrecentchanges';
386 $feedLimit = $this->getConfig()->get( 'FeedLimit' );
387 if ( $query['limit'] > $feedLimit ) {
388 $query['limit'] = $feedLimit;
389 }
390
391 return $query;
392 }
393
394 /**
395 * Build and output the actual changes list.
396 *
397 * @param IResultWrapper $rows Database rows
398 * @param FormOptions $opts
399 */
400 public function outputChangesList( $rows, $opts ) {
401 $limit = $opts['limit'];
402
403 $showWatcherCount = $this->getConfig()->get( 'RCShowWatchingUsers' )
404 && $this->getUser()->getOption( 'shownumberswatching' );
405 $watcherCache = [];
406
407 $counter = 1;
408 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
409 $list->initChangesListRows( $rows );
410
411 $userShowHiddenCats = $this->getUser()->getBoolOption( 'showhiddencats' );
412 $rclistOutput = $list->beginRecentChangesList();
413 if ( $this->isStructuredFilterUiEnabled() ) {
414 $rclistOutput .= $this->makeLegend();
415 }
416
417 foreach ( $rows as $obj ) {
418 if ( $limit == 0 ) {
419 break;
420 }
421 $rc = RecentChange::newFromRow( $obj );
422
423 # Skip CatWatch entries for hidden cats based on user preference
424 if (
425 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
426 !$userShowHiddenCats &&
427 $rc->getParam( 'hidden-cat' )
428 ) {
429 continue;
430 }
431
432 $rc->counter = $counter++;
433 # Check if the page has been updated since the last visit
434 if ( $this->getConfig()->get( 'ShowUpdatedMarker' )
435 && !empty( $obj->wl_notificationtimestamp )
436 ) {
437 $rc->notificationtimestamp = ( $obj->rc_timestamp >= $obj->wl_notificationtimestamp );
438 } else {
439 $rc->notificationtimestamp = false; // Default
440 }
441 # Check the number of users watching the page
442 $rc->numberofWatchingusers = 0; // Default
443 if ( $showWatcherCount && $obj->rc_namespace >= 0 ) {
444 if ( !isset( $watcherCache[$obj->rc_namespace][$obj->rc_title] ) ) {
445 $watcherCache[$obj->rc_namespace][$obj->rc_title] =
446 MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchers(
447 new TitleValue( (int)$obj->rc_namespace, $obj->rc_title )
448 );
449 }
450 $rc->numberofWatchingusers = $watcherCache[$obj->rc_namespace][$obj->rc_title];
451 }
452
453 $changeLine = $list->recentChangesLine( $rc, !empty( $obj->wl_user ), $counter );
454 if ( $changeLine !== false ) {
455 $rclistOutput .= $changeLine;
456 --$limit;
457 }
458 }
459 $rclistOutput .= $list->endRecentChangesList();
460
461 if ( $rows->numRows() === 0 ) {
462 $this->outputNoResults();
463 if ( !$this->including() ) {
464 $this->getOutput()->setStatusCode( 404 );
465 }
466 } else {
467 $this->getOutput()->addHTML( $rclistOutput );
468 }
469 }
470
471 /**
472 * Set the text to be displayed above the changes
473 *
474 * @param FormOptions $opts
475 * @param int $numRows Number of rows in the result to show after this header
476 */
477 public function doHeader( $opts, $numRows ) {
478 $this->setTopText( $opts );
479
480 $defaults = $opts->getAllValues();
481 $nondefaults = $opts->getChangedValues();
482
483 $panel = [];
484 if ( !$this->isStructuredFilterUiEnabled() ) {
485 $panel[] = $this->makeLegend();
486 }
487 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
488 $panel[] = '<hr />';
489
490 $extraOpts = $this->getExtraOptions( $opts );
491 $extraOptsCount = count( $extraOpts );
492 $count = 0;
493 $submit = ' ' . Xml::submitButton( $this->msg( 'recentchanges-submit' )->text() );
494
495 $out = Xml::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
496 foreach ( $extraOpts as $name => $optionRow ) {
497 # Add submit button to the last row only
498 ++$count;
499 $addSubmit = ( $count === $extraOptsCount ) ? $submit : '';
500
501 $out .= Xml::openElement( 'tr', [ 'class' => $name . 'Form' ] );
502 if ( is_array( $optionRow ) ) {
503 $out .= Xml::tags(
504 'td',
505 [ 'class' => 'mw-label mw-' . $name . '-label' ],
506 $optionRow[0]
507 );
508 $out .= Xml::tags(
509 'td',
510 [ 'class' => 'mw-input' ],
511 $optionRow[1] . $addSubmit
512 );
513 } else {
514 $out .= Xml::tags(
515 'td',
516 [ 'class' => 'mw-input', 'colspan' => 2 ],
517 $optionRow . $addSubmit
518 );
519 }
520 $out .= Xml::closeElement( 'tr' );
521 }
522 $out .= Xml::closeElement( 'table' );
523
524 $unconsumed = $opts->getUnconsumedValues();
525 foreach ( $unconsumed as $key => $value ) {
526 $out .= Html::hidden( $key, $value );
527 }
528
529 $t = $this->getPageTitle();
530 $out .= Html::hidden( 'title', $t->getPrefixedText() );
531 $form = Xml::tags( 'form', [ 'action' => wfScript() ], $out );
532 $panel[] = $form;
533 $panelString = implode( "\n", $panel );
534
535 $rcoptions = Xml::fieldset(
536 $this->msg( 'recentchanges-legend' )->text(),
537 $panelString,
538 [ 'class' => 'rcoptions cloptions' ]
539 );
540
541 // Insert a placeholder for RCFilters
542 if ( $this->isStructuredFilterUiEnabled() ) {
543 $rcfilterContainer = Html::element(
544 'div',
545 [ 'class' => 'rcfilters-container' ]
546 );
547
548 $loadingContainer = Html::rawElement(
549 'div',
550 [ 'class' => 'rcfilters-spinner' ],
551 Html::element(
552 'div',
553 [ 'class' => 'rcfilters-spinner-bounce' ]
554 )
555 );
556
557 // Wrap both with rcfilters-head
558 $this->getOutput()->addHTML(
559 Html::rawElement(
560 'div',
561 [ 'class' => 'rcfilters-head' ],
562 $rcfilterContainer . $rcoptions
563 )
564 );
565
566 // Add spinner
567 $this->getOutput()->addHTML( $loadingContainer );
568 } else {
569 $this->getOutput()->addHTML( $rcoptions );
570 }
571
572 $this->setBottomText( $opts );
573 }
574
575 /**
576 * Send the text to be displayed above the options
577 *
578 * @param FormOptions $opts Unused
579 */
580 function setTopText( FormOptions $opts ) {
581 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
582 if ( !$message->isDisabled() ) {
583 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
584 // Parse the message in this weird ugly way to preserve the ability to include interlanguage
585 // links in it (T172461). In the future when T66969 is resolved, perhaps we can just use
586 // $message->parse() instead. This code is copied from Message::parseText().
587 $parserOutput = MessageCache::singleton()->parse(
588 $message->plain(),
589 $this->getPageTitle(),
590 /*linestart*/true,
591 // Message class sets the interface flag to false when parsing in a language different than
592 // user language, and this is wiki content language
593 /*interface*/false,
594 $contLang
595 );
596 $content = $parserOutput->getText( [
597 'enableSectionEditLinks' => false,
598 ] );
599 // Add only metadata here (including the language links), text is added below
600 $this->getOutput()->addParserOutputMetadata( $parserOutput );
601
602 $langAttributes = [
603 'lang' => $contLang->getHtmlCode(),
604 'dir' => $contLang->getDir(),
605 ];
606
607 $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ];
608
609 if ( $this->isStructuredFilterUiEnabled() ) {
610 // Check whether the widget is already collapsed or expanded
611 $collapsedState = $this->getRequest()->getCookie( 'rcfilters-toplinks-collapsed-state' );
612 // Note that an empty/unset cookie means collapsed, so check for !== 'expanded'
613 $topLinksAttributes[ 'class' ] .= $collapsedState !== 'expanded' ?
614 ' mw-recentchanges-toplinks-collapsed' : '';
615
616 $this->getOutput()->enableOOUI();
617 $contentTitle = new OOUI\ButtonWidget( [
618 'classes' => [ 'mw-recentchanges-toplinks-title' ],
619 'label' => new OOUI\HtmlSnippet( $this->msg( 'rcfilters-other-review-tools' )->parse() ),
620 'framed' => false,
621 'indicator' => $collapsedState !== 'expanded' ? 'down' : 'up',
622 'flags' => [ 'progressive' ],
623 ] );
624
625 $contentWrapper = Html::rawElement( 'div',
626 array_merge(
627 [ 'class' => 'mw-recentchanges-toplinks-content mw-collapsible-content' ],
628 $langAttributes
629 ),
630 $content
631 );
632 $content = $contentTitle . $contentWrapper;
633 } else {
634 // Language direction should be on the top div only
635 // if the title is not there. If it is there, it's
636 // interface direction, and the language/dir attributes
637 // should be on the content itself
638 $topLinksAttributes = array_merge( $topLinksAttributes, $langAttributes );
639 }
640
641 $this->getOutput()->addHTML(
642 Html::rawElement( 'div', $topLinksAttributes, $content )
643 );
644 }
645 }
646
647 /**
648 * Get options to be displayed in a form
649 *
650 * @param FormOptions $opts
651 * @return array
652 */
653 function getExtraOptions( $opts ) {
654 $opts->consumeValues( [
655 'namespace', 'invert', 'associated', 'tagfilter'
656 ] );
657
658 $extraOpts = [];
659 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
660
661 $tagFilter = ChangeTags::buildTagFilterSelector(
662 $opts['tagfilter'], false, $this->getContext() );
663 if ( count( $tagFilter ) ) {
664 $extraOpts['tagfilter'] = $tagFilter;
665 }
666
667 // Don't fire the hook for subclasses. (Or should we?)
668 if ( $this->getName() === 'Recentchanges' ) {
669 Hooks::run( 'SpecialRecentChangesPanel', [ &$extraOpts, $opts ] );
670 }
671
672 return $extraOpts;
673 }
674
675 /**
676 * Add page-specific modules.
677 */
678 protected function addModules() {
679 parent::addModules();
680 $out = $this->getOutput();
681 $out->addModules( 'mediawiki.special.recentchanges' );
682 }
683
684 /**
685 * Get last modified date, for client caching
686 * Don't use this if we are using the patrol feature, patrol changes don't
687 * update the timestamp
688 *
689 * @return string|bool
690 */
691 public function checkLastModified() {
692 $dbr = $this->getDB();
693 $lastmod = $dbr->selectField( 'recentchanges', 'MAX(rc_timestamp)', '', __METHOD__ );
694
695 return $lastmod;
696 }
697
698 /**
699 * Creates the choose namespace selection
700 *
701 * @param FormOptions $opts
702 * @return string
703 */
704 protected function namespaceFilterForm( FormOptions $opts ) {
705 $nsSelect = Html::namespaceSelector(
706 [ 'selected' => $opts['namespace'], 'all' => '' ],
707 [ 'name' => 'namespace', 'id' => 'namespace' ]
708 );
709 $nsLabel = Xml::label( $this->msg( 'namespace' )->text(), 'namespace' );
710 $invert = Xml::checkLabel(
711 $this->msg( 'invert' )->text(), 'invert', 'nsinvert',
712 $opts['invert'],
713 [ 'title' => $this->msg( 'tooltip-invert' )->text() ]
714 );
715 $associated = Xml::checkLabel(
716 $this->msg( 'namespace_association' )->text(), 'associated', 'nsassociated',
717 $opts['associated'],
718 [ 'title' => $this->msg( 'tooltip-namespace_association' )->text() ]
719 );
720
721 return [ $nsLabel, "$nsSelect $invert $associated" ];
722 }
723
724 /**
725 * Filter $rows by categories set in $opts
726 *
727 * @deprecated since 1.31
728 *
729 * @param IResultWrapper &$rows Database rows
730 * @param FormOptions $opts
731 */
732 function filterByCategories( &$rows, FormOptions $opts ) {
733 wfDeprecated( __METHOD__, '1.31' );
734
735 $categories = array_map( 'trim', explode( '|', $opts['categories'] ) );
736
737 if ( !count( $categories ) ) {
738 return;
739 }
740
741 # Filter categories
742 $cats = [];
743 foreach ( $categories as $cat ) {
744 $cat = trim( $cat );
745 if ( $cat == '' ) {
746 continue;
747 }
748 $cats[] = $cat;
749 }
750
751 # Filter articles
752 $articles = [];
753 $a2r = [];
754 $rowsarr = [];
755 foreach ( $rows as $k => $r ) {
756 $nt = Title::makeTitle( $r->rc_namespace, $r->rc_title );
757 $id = $nt->getArticleID();
758 if ( $id == 0 ) {
759 continue; # Page might have been deleted...
760 }
761 if ( !in_array( $id, $articles ) ) {
762 $articles[] = $id;
763 }
764 if ( !isset( $a2r[$id] ) ) {
765 $a2r[$id] = [];
766 }
767 $a2r[$id][] = $k;
768 $rowsarr[$k] = $r;
769 }
770
771 # Shortcut?
772 if ( !count( $articles ) || !count( $cats ) ) {
773 return;
774 }
775
776 # Look up
777 $catFind = new CategoryFinder;
778 $catFind->seed( $articles, $cats, $opts['categories_any'] ? 'OR' : 'AND' );
779 $match = $catFind->run();
780
781 # Filter
782 $newrows = [];
783 foreach ( $match as $id ) {
784 foreach ( $a2r[$id] as $rev ) {
785 $k = $rev;
786 $newrows[$k] = $rowsarr[$k];
787 }
788 }
789 $rows = new FakeResultWrapper( array_values( $newrows ) );
790 }
791
792 /**
793 * Makes change an option link which carries all the other options
794 *
795 * @param string $title
796 * @param array $override Options to override
797 * @param array $options Current options
798 * @param bool $active Whether to show the link in bold
799 * @return string
800 */
801 function makeOptionsLink( $title, $override, $options, $active = false ) {
802 $params = $this->convertParamsForLink( $override + $options );
803
804 if ( $active ) {
805 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
806 }
807
808 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
809 'data-params' => json_encode( $override ),
810 'data-keys' => implode( ',', array_keys( $override ) ),
811 ], $params );
812 }
813
814 /**
815 * Creates the options panel.
816 *
817 * @param array $defaults
818 * @param array $nondefaults
819 * @param int $numRows Number of rows in the result to show after this header
820 * @return string
821 */
822 function optionsPanel( $defaults, $nondefaults, $numRows ) {
823 $options = $nondefaults + $defaults;
824
825 $note = '';
826 $msg = $this->msg( 'rclegend' );
827 if ( !$msg->isDisabled() ) {
828 $note .= '<div class="mw-rclegend">' . $msg->parse() . "</div>\n";
829 }
830
831 $lang = $this->getLanguage();
832 $user = $this->getUser();
833 $config = $this->getConfig();
834 if ( $options['from'] ) {
835 $resetLink = $this->makeOptionsLink( $this->msg( 'rclistfromreset' ),
836 [ 'from' => '' ], $nondefaults );
837
838 $noteFromMsg = $this->msg( 'rcnotefrom' )
839 ->numParams( $options['limit'] )
840 ->params(
841 $lang->userTimeAndDate( $options['from'], $user ),
842 $lang->userDate( $options['from'], $user ),
843 $lang->userTime( $options['from'], $user )
844 )
845 ->numParams( $numRows );
846 $note .= Html::rawElement(
847 'span',
848 [ 'class' => 'rcnotefrom' ],
849 $noteFromMsg->parse()
850 ) .
851 ' ' .
852 Html::rawElement(
853 'span',
854 [ 'class' => 'rcoptions-listfromreset' ],
855 $this->msg( 'parentheses' )->rawParams( $resetLink )->parse()
856 ) .
857 '<br />';
858 }
859
860 # Sort data for display and make sure it's unique after we've added user data.
861 $linkLimits = $config->get( 'RCLinkLimits' );
862 $linkLimits[] = $options['limit'];
863 sort( $linkLimits );
864 $linkLimits = array_unique( $linkLimits );
865
866 $linkDays = $config->get( 'RCLinkDays' );
867 $linkDays[] = $options['days'];
868 sort( $linkDays );
869 $linkDays = array_unique( $linkDays );
870
871 // limit links
872 $cl = [];
873 foreach ( $linkLimits as $value ) {
874 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
875 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
876 }
877 $cl = $lang->pipeList( $cl );
878
879 // day links, reset 'from' to none
880 $dl = [];
881 foreach ( $linkDays as $value ) {
882 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
883 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
884 }
885 $dl = $lang->pipeList( $dl );
886
887 $showhide = [ 'show', 'hide' ];
888
889 $links = [];
890
891 foreach ( $this->getLegacyShowHideFilters() as $key => $filter ) {
892 $msg = $filter->getShowHide();
893 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
894 // Extensions can define additional filters, but don't need to define the corresponding
895 // messages. If they don't exist, just fall back to 'show' and 'hide'.
896 if ( !$linkMessage->exists() ) {
897 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
898 }
899
900 $link = $this->makeOptionsLink( $linkMessage->text(),
901 [ $key => 1 - $options[$key] ], $nondefaults );
902
903 $attribs = [
904 'class' => "$msg rcshowhideoption clshowhideoption",
905 'data-filter-name' => $filter->getName(),
906 ];
907
908 if ( $filter->isFeatureAvailableOnStructuredUi( $this ) ) {
909 $attribs['data-feature-in-structured-ui'] = true;
910 }
911
912 $links[] = Html::rawElement(
913 'span',
914 $attribs,
915 $this->msg( $msg )->rawParams( $link )->parse()
916 );
917 }
918
919 // show from this onward link
920 $timestamp = wfTimestampNow();
921 $now = $lang->userTimeAndDate( $timestamp, $user );
922 $timenow = $lang->userTime( $timestamp, $user );
923 $datenow = $lang->userDate( $timestamp, $user );
924 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
925
926 $rclinks = '<span class="rclinks">' . $this->msg( 'rclinks' )->rawParams( $cl, $dl, '' )
927 ->parse() . '</span>';
928
929 $rclistfrom = '<span class="rclistfrom">' . $this->makeOptionsLink(
930 $this->msg( 'rclistfrom' )->rawParams( $now, $timenow, $datenow )->parse(),
931 [ 'from' => $timestamp ],
932 $nondefaults
933 ) . '</span>';
934
935 return "{$note}$rclinks<br />$pipedLinks<br />$rclistfrom";
936 }
937
938 public function isIncludable() {
939 return true;
940 }
941
942 protected function getCacheTTL() {
943 return 60 * 5;
944 }
945
946 public function getDefaultLimit() {
947 $systemPrefValue = $this->getUser()->getIntOption( 'rclimit' );
948 // Prefer the RCFilters-specific preference if RCFilters is enabled
949 if ( $this->isStructuredFilterUiEnabled() ) {
950 return $this->getUser()->getIntOption( static::$limitPreferenceName, $systemPrefValue );
951 }
952
953 // Otherwise, use the system rclimit preference value
954 return $systemPrefValue;
955 }
956 }