Debian Codegraph @

includes/specials/SpecialRecentChanges.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Specials;
22
23 use ChangesList;
24 use ChangesListBooleanFilter;
25 use ChangesListStringOptionsFilterGroup;
26 use ChangeTags;
27 use HtmlArmor;
28 use MediaWiki\ChangeTags\ChangeTagsStore;
29 use MediaWiki\Context\IContextSource;
30 use MediaWiki\Html\FormOptions;
31 use MediaWiki\Html\Html;
32 use MediaWiki\MainConfigNames;
33 use MediaWiki\MediaWikiServices;
34 use MediaWiki\SpecialPage\ChangesListSpecialPage;
35 use MediaWiki\Title\TitleValue;
36 use MediaWiki\User\Options\UserOptionsLookup;
37 use MediaWiki\User\TempUser\TempUserConfig;
38 use MediaWiki\User\UserIdentityUtils;
39 use MediaWiki\Utils\MWTimestamp;
40 use MediaWiki\Watchlist\WatchedItemStoreInterface;
41 use MessageCache;
42 use OOUI\ButtonWidget;
43 use OOUI\HtmlSnippet;
44 use RecentChange;
45 use Wikimedia\Rdbms\IReadableDatabase;
46 use Wikimedia\Rdbms\IResultWrapper;
47 use Wikimedia\Rdbms\RawSQLExpression;
48
49 /**
50 * List of the last changes made to the wiki
51 *
52 * @ingroup RecentChanges
53 * @ingroup SpecialPage
54 */
55 class SpecialRecentChanges extends ChangesListSpecialPage {
56
57 /** @var array */
58 private $watchlistFilterGroupDefinition;
59
60 private WatchedItemStoreInterface $watchedItemStore;
61 private MessageCache $messageCache;
62 private UserOptionsLookup $userOptionsLookup;
63
64 /** @var int */
65 public $denseRcSizeThreshold = 10000;
66 private ChangeTagsStore $changeTagsStore;
67
68 /**
69 * @param WatchedItemStoreInterface|null $watchedItemStore
70 * @param MessageCache|null $messageCache
71 * @param UserOptionsLookup|null $userOptionsLookup
72 * @param ChangeTagsStore|null $changeTagsStore
73 * @param UserIdentityUtils|null $userIdentityUtils
74 * @param TempUserConfig|null $tempUserConfig
75 */
76 public function __construct(
77 ?WatchedItemStoreInterface $watchedItemStore = null,
78 ?MessageCache $messageCache = null,
79 ?UserOptionsLookup $userOptionsLookup = null,
80 ?ChangeTagsStore $changeTagsStore = null,
81 ?UserIdentityUtils $userIdentityUtils = null,
82 ?TempUserConfig $tempUserConfig = null
83 ) {
84 // This class is extended and therefor fallback to global state - T265310
85 $services = MediaWikiServices::getInstance();
86
87 parent::__construct(
88 'Recentchanges',
89 '',
90 $userIdentityUtils ?? $services->getUserIdentityUtils(),
91 $tempUserConfig ?? $services->getTempUserConfig()
92 );
93 $this->watchedItemStore = $watchedItemStore ?? $services->getWatchedItemStore();
94 $this->messageCache = $messageCache ?? $services->getMessageCache();
95 $this->userOptionsLookup = $userOptionsLookup ?? $services->getUserOptionsLookup();
96 $this->changeTagsStore = $changeTagsStore ?? $services->getChangeTagsStore();
97
98 $this->watchlistFilterGroupDefinition = [
99 'name' => 'watchlist',
100 'title' => 'rcfilters-filtergroup-watchlist',
101 'class' => ChangesListStringOptionsFilterGroup::class,
102 'priority' => -9,
103 'isFullCoverage' => true,
104 'filters' => [
105 [
106 'name' => 'watched',
107 'label' => 'rcfilters-filter-watchlist-watched-label',
108 'description' => 'rcfilters-filter-watchlist-watched-description',
109 'cssClassSuffix' => 'watched',
110 'isRowApplicableCallable' => static function ( IContextSource $ctx, RecentChange $rc ) {
111 return $rc->getAttribute( 'wl_user' );
112 }
113 ],
114 [
115 'name' => 'watchednew',
116 'label' => 'rcfilters-filter-watchlist-watchednew-label',
117 'description' => 'rcfilters-filter-watchlist-watchednew-description',
118 'cssClassSuffix' => 'watchednew',
119 'isRowApplicableCallable' => static function ( IContextSource $ctx, RecentChange $rc ) {
120 return $rc->getAttribute( 'wl_user' ) &&
121 $rc->getAttribute( 'rc_timestamp' ) &&
122 $rc->getAttribute( 'wl_notificationtimestamp' ) &&
123 $rc->getAttribute( 'rc_timestamp' ) >= $rc->getAttribute( 'wl_notificationtimestamp' );
124 },
125 ],
126 [
127 'name' => 'notwatched',
128 'label' => 'rcfilters-filter-watchlist-notwatched-label',
129 'description' => 'rcfilters-filter-watchlist-notwatched-description',
130 'cssClassSuffix' => 'notwatched',
131 'isRowApplicableCallable' => static function ( IContextSource $ctx, RecentChange $rc ) {
132 return $rc->getAttribute( 'wl_user' ) === null;
133 },
134 ]
135 ],
136 'default' => ChangesListStringOptionsFilterGroup::NONE,
137 'queryCallable' => function ( string $specialClassName, IContextSource $ctx,
138 IReadableDatabase $dbr, &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedValues
139 ) {
140 sort( $selectedValues );
141 $notwatchedCond = $dbr->expr( 'wl_user', '=', null );
142 $watchedCond = $dbr->expr( 'wl_user', '!=', null );
143 if ( $this->getConfig()->get( MainConfigNames::WatchlistExpiry ) ) {
144 // Expired watchlist items stay in the DB after their expiry time until they're purged,
145 // so it's not enough to only check for wl_user.
146 $dbNow = $dbr->timestamp();
147 $notwatchedCond = $notwatchedCond
148 ->orExpr( $dbr->expr( 'we_expiry', '!=', null )->and( 'we_expiry', '<', $dbNow ) );
149 $watchedCond = $watchedCond
150 ->andExpr( $dbr->expr( 'we_expiry', '=', null )->or( 'we_expiry', '>=', $dbNow ) );
151 }
152 $newCond = new RawSQLExpression( 'rc_timestamp >= wl_notificationtimestamp' );
153
154 if ( $selectedValues === [ 'notwatched' ] ) {
155 $conds[] = $notwatchedCond;
156 return;
157 }
158
159 if ( $selectedValues === [ 'watched' ] ) {
160 $conds[] = $watchedCond;
161 return;
162 }
163
164 if ( $selectedValues === [ 'watchednew' ] ) {
165 $conds[] = $watchedCond
166 ->andExpr( $newCond );
167 return;
168 }
169
170 if ( $selectedValues === [ 'notwatched', 'watched' ] ) {
171 // no filters
172 return;
173 }
174
175 if ( $selectedValues === [ 'notwatched', 'watchednew' ] ) {
176 $conds[] = $notwatchedCond
177 ->orExpr(
178 $watchedCond
179 ->andExpr( $newCond )
180 );
181 return;
182 }
183
184 if ( $selectedValues === [ 'watched', 'watchednew' ] ) {
185 $conds[] = $watchedCond;
186 return;
187 }
188
189 if ( $selectedValues === [ 'notwatched', 'watched', 'watchednew' ] ) {
190 // no filters
191 return;
192 }
193 }
194 ];
195 }
196
197 /**
198 * @param string|null $subpage
199 */
200 public function execute( $subpage ) {
201 // Backwards-compatibility: redirect to new feed URLs
202 $feedFormat = $this->getRequest()->getVal( 'feed' );
203 if ( !$this->including() && $feedFormat ) {
204 $query = $this->getFeedQuery();
205 $query['feedformat'] = $feedFormat === 'atom' ? 'atom' : 'rss';
206 $this->getOutput()->redirect( wfAppendQuery( wfScript( 'api' ), $query ) );
207
208 return;
209 }
210
211 // 10 seconds server-side caching max
212 $out = $this->getOutput();
213 $out->setCdnMaxage( 10 );
214 // Check if the client has a cached version
215 $lastmod = $this->checkLastModified();
216 if ( $lastmod === false ) {
217 return;
218 }
219
220 $this->addHelpLink(
221 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Recent_changes',
222 true
223 );
224 parent::execute( $subpage );
225 }
226
227 /**
228 * @inheritDoc
229 */
230 protected function transformFilterDefinition( array $filterDefinition ) {
231 if ( isset( $filterDefinition['showHideSuffix'] ) ) {
232 $filterDefinition['showHide'] = 'rc' . $filterDefinition['showHideSuffix'];
233 }
234
235 return $filterDefinition;
236 }
237
238 /**
239 * Whether or not the current query needs to use watchlist data: check that the current user can
240 * use their watchlist and that this special page isn't being transcluded.
241 *
242 * @return bool
243 */
244 private function needsWatchlistFeatures(): bool {
245 return !$this->including()
246 && $this->getUser()->isRegistered()
247 && $this->getAuthority()->isAllowed( 'viewmywatchlist' );
248 }
249
250 /**
251 * @inheritDoc
252 */
253 protected function registerFilters() {
254 parent::registerFilters();
255
256 if ( $this->needsWatchlistFeatures() ) {
257 $this->registerFiltersFromDefinitions( [ $this->watchlistFilterGroupDefinition ] );
258 $watchlistGroup = $this->getFilterGroup( 'watchlist' );
259 $watchlistGroup->getFilter( 'watched' )->setAsSupersetOf(
260 $watchlistGroup->getFilter( 'watchednew' )
261 );
262 }
263
264 $user = $this->getUser();
265
266 $significance = $this->getFilterGroup( 'significance' );
267 /** @var ChangesListBooleanFilter $hideMinor */
268 $hideMinor = $significance->getFilter( 'hideminor' );
269 '@phan-var ChangesListBooleanFilter $hideMinor';
270 $hideMinor->setDefault( $this->userOptionsLookup->getBoolOption( $user, 'hideminor' ) );
271
272 $automated = $this->getFilterGroup( 'automated' );
273 /** @var ChangesListBooleanFilter $hideBots */
274 $hideBots = $automated->getFilter( 'hidebots' );
275 '@phan-var ChangesListBooleanFilter $hideBots';
276 $hideBots->setDefault( true );
277
278 /** @var ChangesListStringOptionsFilterGroup|null $reviewStatus */
279 $reviewStatus = $this->getFilterGroup( 'reviewStatus' );
280 '@phan-var ChangesListStringOptionsFilterGroup|null $reviewStatus';
281 if ( $reviewStatus !== null ) {
282 // Conditional on feature being available and rights
283 if ( $this->userOptionsLookup->getBoolOption( $user, 'hidepatrolled' ) ) {
284 $reviewStatus->setDefault( 'unpatrolled' );
285 $legacyReviewStatus = $this->getFilterGroup( 'legacyReviewStatus' );
286 /** @var ChangesListBooleanFilter $legacyHidePatrolled */
287 $legacyHidePatrolled = $legacyReviewStatus->getFilter( 'hidepatrolled' );
288 '@phan-var ChangesListBooleanFilter $legacyHidePatrolled';
289 $legacyHidePatrolled->setDefault( true );
290 }
291 }
292
293 $changeType = $this->getFilterGroup( 'changeType' );
294 /** @var ChangesListBooleanFilter $hideCategorization */
295 $hideCategorization = $changeType->getFilter( 'hidecategorization' );
296 '@phan-var ChangesListBooleanFilter $hideCategorization';
297 if ( $hideCategorization !== null ) {
298 // Conditional on feature being available
299 $hideCategorization->setDefault( $this->userOptionsLookup->getBoolOption( $user, 'hidecategorization' ) );
300 }
301 }
302
303 /**
304 * Process $par and put options found in $opts. Used when including the page.
305 *
306 * @param string $par
307 * @param FormOptions $opts
308 */
309 public function parseParameters( $par, FormOptions $opts ) {
310 parent::parseParameters( $par, $opts );
311
312 $bits = preg_split( '/\s*,\s*/', trim( $par ) );
313 foreach ( $bits as $bit ) {
314 if ( is_numeric( $bit ) ) {
315 $opts['limit'] = $bit;
316 }
317
318 $m = [];
319 if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
320 $opts['limit'] = $m[1];
321 }
322 if ( preg_match( '/^days=(\d+(?:\.\d+)?)$/', $bit, $m ) ) {
323 $opts['days'] = $m[1];
324 }
325 if ( preg_match( '/^namespace=(.*)$/', $bit, $m ) ) {
326 $opts['namespace'] = $m[1];
327 }
328 if ( preg_match( '/^tagfilter=(.*)$/', $bit, $m ) ) {
329 $opts['tagfilter'] = $m[1];
330 }
331 }
332 }
333
334 /**
335 * Add required values to a query's $tables, $fields, $joinConds, and $conds arrays to join to
336 * the watchlist and watchlist_expiry tables where appropriate.
337 *
338 * SpecialRecentChangesLinked should also be updated accordingly when something changed here.
339 *
340 * @param IReadableDatabase $dbr
341 * @param string[] &$tables
342 * @param string[] &$fields
343 * @param mixed[] &$joinConds
344 * @param mixed[] &$conds
345 */
346 protected function addWatchlistJoins( IReadableDatabase $dbr, &$tables, &$fields, &$joinConds, &$conds ) {
347 if ( !$this->needsWatchlistFeatures() ) {
348 return;
349 }
350
351 // Join on watchlist table.
352 $tables[] = 'watchlist';
353 $fields[] = 'wl_user';
354 $fields[] = 'wl_notificationtimestamp';
355 $joinConds['watchlist'] = [ 'LEFT JOIN', [
356 'wl_user' => $this->getUser()->getId(),
357 'wl_title=rc_title',
358 'wl_namespace=rc_namespace'
359 ] ];
360
361 // Exclude expired watchlist items.
362 if ( $this->getConfig()->get( MainConfigNames::WatchlistExpiry ) ) {
363 $tables[] = 'watchlist_expiry';
364 $fields[] = 'we_expiry';
365 $joinConds['watchlist_expiry'] = [ 'LEFT JOIN', 'wl_id = we_item' ];
366 }
367 }
368
369 /**
370 * @inheritDoc
371 */
372 protected function doMainQuery( $tables, $fields, $conds, $query_options,
373 $join_conds, FormOptions $opts
374 ) {
375 $dbr = $this->getDB();
376
377 $rcQuery = RecentChange::getQueryInfo();
378 $tables = array_merge( $rcQuery['tables'], $tables );
379 $fields = array_merge( $rcQuery['fields'], $fields );
380 $join_conds = array_merge( $rcQuery['joins'], $join_conds );
381
382 // Join with watchlist and watchlist_expiry tables to highlight watched rows.
383 $this->addWatchlistJoins( $dbr, $tables, $fields, $join_conds, $conds );
384
385 // JOIN on page, used for 'last revision' filter highlight
386 $tables[] = 'page';
387 $fields[] = 'page_latest';
388 $join_conds['page'] = [ 'LEFT JOIN', 'rc_cur_id=page_id' ];
389
390 $tagFilter = $opts['tagfilter'] !== '' ? explode( '|', $opts['tagfilter'] ) : [];
391 $this->changeTagsStore->modifyDisplayQuery(
392 $tables,
393 $fields,
394 $conds,
395 $join_conds,
396 $query_options,
397 $tagFilter,
398 $opts['inverttags']
399 );
400
401 if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
402 $opts )
403 ) {
404 return false;
405 }
406
407 if ( $this->areFiltersInConflict() ) {
408 return false;
409 }
410
411 $orderByAndLimit = [
412 'ORDER BY' => 'rc_timestamp DESC',
413 'LIMIT' => $opts['limit']
414 ];
415
416 // Workaround for T298225: MySQL's lack of awareness of LIMIT when
417 // choosing the join order.
418 $ctTableName = ChangeTags::DISPLAY_TABLE_ALIAS;
419 if ( isset( $join_conds[$ctTableName] )
420 && $this->isDenseTagFilter( $conds["$ctTableName.ct_tag_id"] ?? [], $opts['limit'] )
421 ) {
422 $join_conds[$ctTableName][0] = 'STRAIGHT_JOIN';
423 }
424
425 if ( in_array( 'DISTINCT', $query_options ) ) {
426 // ChangeTagsStore::modifyDisplayQuery() adds DISTINCT when filtering on multiple tags.
427 // In order to prevent DISTINCT from causing query performance problems,
428 // we have to GROUP BY the primary key. This in turn requires us to add
429 // the primary key to the end of the ORDER BY, and the old ORDER BY to the
430 // start of the GROUP BY
431 $orderByAndLimit['ORDER BY'] = 'rc_timestamp DESC, rc_id DESC';
432 $orderByAndLimit['GROUP BY'] = 'rc_timestamp, rc_id';
433 }
434
435 // rc_new is not an ENUM, but adding a redundant rc_new IN (0,1) gives mysql enough
436 // knowledge to use an index merge if it wants (it may use some other index though).
437 $conds += [ 'rc_new' => [ 0, 1 ] ];
438
439 // array_merge() is used intentionally here so that hooks can, should
440 // they so desire, override the ORDER BY / LIMIT condition(s); prior to
441 // MediaWiki 1.26 this used to use the plus operator instead, which meant
442 // that extensions weren't able to change these conditions
443 $query_options = array_merge( $orderByAndLimit, $query_options );
444 return $dbr->newSelectQueryBuilder()
445 ->tables( $tables )
446 ->fields( $fields )
447 ->conds( $conds )
448 ->caller( __METHOD__ )
449 ->options( $query_options )
450 ->joinConds( $join_conds )
451 ->setMaxExecutionTime( $this->getConfig()->get( MainConfigNames::MaxExecutionTimeForExpensiveQueries ) )
452 ->fetchResultSet();
453 }
454
455 /**
456 * Determine whether a tag filter matches a high proportion of the rows in
457 * recentchanges. If so, it is more efficient to scan recentchanges,
458 * filtering out non-matching rows, rather than scanning change_tag and
459 * then filesorting on rc_timestamp. MySQL is especially bad at making this
460 * judgement (T298225).
461 *
462 * @param int[] $tagIds
463 * @param int $limit
464 * @return bool
465 */
466 protected function isDenseTagFilter( $tagIds, $limit ) {
467 $dbr = $this->getDB();
468 if ( !$tagIds
469 // This is a MySQL-specific hack
470 || $dbr->getType() !== 'mysql'
471 // Unnecessary for small wikis
472 || !$this->getConfig()->get( MainConfigNames::MiserMode )
473 ) {
474 return false;
475 }
476
477 $rcInfo = $dbr->newSelectQueryBuilder()
478 ->select( [
479 'min_id' => 'MIN(rc_id)',
480 'max_id' => 'MAX(rc_id)',
481 ] )
482 ->from( 'recentchanges' )
483 ->caller( __METHOD__ )
484 ->fetchRow();
485 if ( !$rcInfo || $rcInfo->min_id === null ) {
486 return false;
487 }
488 $rcSize = $rcInfo->max_id - $rcInfo->min_id;
489 if ( $rcSize < $this->denseRcSizeThreshold ) {
490 // RC is too small to worry about
491 return false;
492 }
493 $tagCount = $dbr->newSelectQueryBuilder()
494 ->table( 'change_tag' )
495 ->where( [
496 $dbr->expr( 'ct_rc_id', '>=', $rcInfo->min_id ),
497 'ct_tag_id' => $tagIds
498 ] )
499 ->caller( __METHOD__ )
500 ->estimateRowCount();
501
502 // If we scan recentchanges first, the number of rows examined will be
503 // approximately the limit divided by the proportion of tagged rows,
504 // i.e. $limit / ( $tagCount / $rcSize ). If that's less than $tagCount,
505 // use a straight join. The inequality below is rearranged for
506 // simplicity and to avoid division by zero.
507 $isDense = $limit * $rcSize < $tagCount * $tagCount;
508
509 wfDebug( __METHOD__ . ": rcSize = $rcSize, tagCount = $tagCount, limit = $limit => " .
510 ( $isDense ? 'dense' : 'sparse' ) );
511 return $isDense;
512 }
513
514 public function outputFeedLinks() {
515 $this->addFeedLinks( $this->getFeedQuery() );
516 }
517
518 /**
519 * Get URL query parameters for action=feedrecentchanges API feed of current recent changes view.
520 *
521 * @return array
522 */
523 protected function getFeedQuery() {
524 $query = array_filter( $this->getOptions()->getAllValues(), static function ( $value ) {
525 // API handles empty parameters in a different way
526 return $value !== '';
527 } );
528 $query['action'] = 'feedrecentchanges';
529 $feedLimit = $this->getConfig()->get( MainConfigNames::FeedLimit );
530 if ( $query['limit'] > $feedLimit ) {
531 $query['limit'] = $feedLimit;
532 }
533
534 return $query;
535 }
536
537 /**
538 * Build and output the actual changes list.
539 *
540 * @param IResultWrapper $rows Database rows
541 * @param FormOptions $opts
542 */
543 public function outputChangesList( $rows, $opts ) {
544 $limit = $opts['limit'];
545
546 $showWatcherCount = $this->getConfig()->get( MainConfigNames::RCShowWatchingUsers )
547 && $this->userOptionsLookup->getBoolOption( $this->getUser(), 'shownumberswatching' );
548 $watcherCache = [];
549
550 $counter = 1;
551 $list = ChangesList::newFromContext( $this->getContext(), $this->filterGroups );
552 $list->initChangesListRows( $rows );
553
554 $userShowHiddenCats = $this->userOptionsLookup->getBoolOption( $this->getUser(), 'showhiddencats' );
555 $rclistOutput = $list->beginRecentChangesList();
556 if ( $this->isStructuredFilterUiEnabled() ) {
557 $rclistOutput .= $this->makeLegend();
558 }
559
560 foreach ( $rows as $obj ) {
561 if ( $limit == 0 ) {
562 break;
563 }
564 $rc = RecentChange::newFromRow( $obj );
565
566 # Skip CatWatch entries for hidden cats based on user preference
567 if (
568 $rc->getAttribute( 'rc_type' ) == RC_CATEGORIZE &&
569 !$userShowHiddenCats &&
570 $rc->getParam( 'hidden-cat' )
571 ) {
572 continue;
573 }
574
575 $rc->counter = $counter++;
576 # Check if the page has been updated since the last visit
577 if ( $this->getConfig()->get( MainConfigNames::ShowUpdatedMarker )
578 && !empty( $obj->wl_notificationtimestamp )
579 ) {
580 $rc->notificationtimestamp = ( $obj->rc_timestamp >= $obj->wl_notificationtimestamp );
581 } else {
582 $rc->notificationtimestamp = false; // Default
583 }
584 # Check the number of users watching the page
585 $rc->numberofWatchingusers = 0; // Default
586 if ( $showWatcherCount && $obj->rc_namespace >= 0 ) {
587 if ( !isset( $watcherCache[$obj->rc_namespace][$obj->rc_title] ) ) {
588 $watcherCache[$obj->rc_namespace][$obj->rc_title] =
589 $this->watchedItemStore->countWatchers(
590 new TitleValue( (int)$obj->rc_namespace, $obj->rc_title )
591 );
592 }
593 $rc->numberofWatchingusers = $watcherCache[$obj->rc_namespace][$obj->rc_title];
594 }
595
596 $watched = !empty( $obj->wl_user );
597 if ( $watched && $this->getConfig()->get( MainConfigNames::WatchlistExpiry ) ) {
598 $notExpired = $obj->we_expiry === null
599 || MWTimestamp::convert( TS_UNIX, $obj->we_expiry ) > wfTimestamp();
600 $watched = $watched && $notExpired;
601 }
602 $changeLine = $list->recentChangesLine( $rc, $watched, $counter );
603 if ( $changeLine !== false ) {
604 $rclistOutput .= $changeLine;
605 --$limit;
606 }
607 }
608 $rclistOutput .= $list->endRecentChangesList();
609
610 if ( $rows->numRows() === 0 ) {
611 $this->outputNoResults();
612 if ( !$this->including() ) {
613 $this->getOutput()->setStatusCode( 404 );
614 }
615 } else {
616 $this->getOutput()->addHTML( $rclistOutput );
617 }
618 }
619
620 /**
621 * Set the text to be displayed above the changes
622 *
623 * @param FormOptions $opts
624 * @param int $numRows Number of rows in the result to show after this header
625 */
626 public function doHeader( $opts, $numRows ) {
627 $this->setTopText( $opts );
628
629 $defaults = $opts->getAllValues();
630 $nondefaults = $opts->getChangedValues();
631
632 $panel = [];
633 if ( !$this->isStructuredFilterUiEnabled() ) {
634 $panel[] = $this->makeLegend();
635 }
636 $panel[] = $this->optionsPanel( $defaults, $nondefaults, $numRows );
637 $panel[] = '<hr />';
638
639 $extraOpts = $this->getExtraOptions( $opts );
640 $extraOptsCount = count( $extraOpts );
641 $count = 0;
642 $submit = ' ' . Html::submitButton( $this->msg( 'recentchanges-submit' )->text() );
643
644 $out = Html::openElement( 'table', [ 'class' => 'mw-recentchanges-table' ] );
645 foreach ( $extraOpts as $name => $optionRow ) {
646 # Add submit button to the last row only
647 ++$count;
648 $addSubmit = ( $count === $extraOptsCount ) ? $submit : '';
649
650 $out .= Html::openElement( 'tr', [ 'class' => $name . 'Form' ] );
651 if ( is_array( $optionRow ) ) {
652 $out .= Html::rawElement(
653 'td',
654 [ 'class' => 'mw-label mw-' . $name . '-label' ],
655 $optionRow[0]
656 );
657 $out .= Html::rawElement(
658 'td',
659 [ 'class' => 'mw-input' ],
660 $optionRow[1] . $addSubmit
661 );
662 } else {
663 $out .= Html::rawElement(
664 'td',
665 [ 'class' => 'mw-input', 'colspan' => 2 ],
666 $optionRow . $addSubmit
667 );
668 }
669 $out .= Html::closeElement( 'tr' );
670 }
671 $out .= Html::closeElement( 'table' );
672
673 $unconsumed = $opts->getUnconsumedValues();
674 foreach ( $unconsumed as $key => $value ) {
675 $out .= Html::hidden( $key, $value );
676 }
677
678 $t = $this->getPageTitle();
679 $out .= Html::hidden( 'title', $t->getPrefixedText() );
680 $form = Html::rawElement( 'form', [ 'action' => wfScript() ], $out );
681 $panel[] = $form;
682 $panelString = implode( "\n", $panel );
683
684 $rcoptions = Html::rawElement(
685 'fieldset',
686 [ 'class' => 'rcoptions cloptions' ],
687 Html::element(
688 'legend', [],
689 $this->msg( 'recentchanges-legend' )->text()
690 ) . $panelString
691 );
692
693 // Insert a placeholder for RCFilters
694 if ( $this->isStructuredFilterUiEnabled() ) {
695 $rcfilterContainer = Html::element(
696 'div',
697 [ 'class' => 'mw-rcfilters-container' ]
698 );
699
700 $loadingContainer = Html::rawElement(
701 'div',
702 [ 'class' => 'mw-rcfilters-spinner' ],
703 Html::element(
704 'div',
705 [ 'class' => 'mw-rcfilters-spinner-bounce' ]
706 )
707 );
708
709 // Wrap both with mw-rcfilters-head
710 $this->getOutput()->addHTML(
711 Html::rawElement(
712 'div',
713 [ 'class' => 'mw-rcfilters-head' ],
714 $rcfilterContainer . $rcoptions
715 )
716 );
717
718 // Add spinner
719 $this->getOutput()->addHTML( $loadingContainer );
720 } else {
721 $this->getOutput()->addHTML( $rcoptions );
722 }
723
724 $this->setBottomText( $opts );
725 }
726
727 /**
728 * Send the text to be displayed above the options
729 *
730 * @param FormOptions $opts Unused
731 */
732 public function setTopText( FormOptions $opts ) {
733 $message = $this->msg( 'recentchangestext' )->inContentLanguage();
734 if ( !$message->isDisabled() ) {
735 $contLang = $this->getContentLanguage();
736 // Parse the message in this weird ugly way to preserve the ability to include interlanguage
737 // links in it (T172461). In the future when T66969 is resolved, perhaps we can just use
738 // $message->parse() instead. This code is copied from Message::parseText().
739 $parserOutput = $this->messageCache->parse(
740 $message->plain(),
741 $this->getPageTitle(),
742 /*linestart*/true,
743 // Message class sets the interface flag to false when parsing in a language different than
744 // user language, and this is wiki content language
745 /*interface*/false,
746 $contLang
747 );
748 $content = $parserOutput->getText( [
749 'enableSectionEditLinks' => false,
750 ] );
751 // Add only metadata here (including the language links), text is added below
752 $this->getOutput()->addParserOutputMetadata( $parserOutput );
753
754 $langAttributes = [
755 'lang' => $contLang->getHtmlCode(),
756 'dir' => $contLang->getDir(),
757 ];
758
759 $topLinksAttributes = [ 'class' => 'mw-recentchanges-toplinks' ];
760
761 if ( $this->isStructuredFilterUiEnabled() ) {
762 // Check whether the widget is already collapsed or expanded
763 $collapsedState = $this->getRequest()->getCookie( 'rcfilters-toplinks-collapsed-state' );
764 // Note that an empty/unset cookie means collapsed, so check for !== 'expanded'
765 $topLinksAttributes[ 'class' ] .= $collapsedState !== 'expanded' ?
766 ' mw-recentchanges-toplinks-collapsed' : '';
767
768 $this->getOutput()->enableOOUI();
769 $contentTitle = new ButtonWidget( [
770 'classes' => [ 'mw-recentchanges-toplinks-title' ],
771 'label' => new HtmlSnippet( $this->msg( 'rcfilters-other-review-tools' )->parse() ),
772 'framed' => false,
773 'indicator' => $collapsedState !== 'expanded' ? 'down' : 'up',
774 'flags' => [ 'progressive' ],
775 ] );
776
777 $contentWrapper = Html::rawElement( 'div',
778 array_merge(
779 [ 'class' => 'mw-recentchanges-toplinks-content mw-collapsible-content' ],
780 $langAttributes
781 ),
782 $content
783 );
784 $content = $contentTitle . $contentWrapper;
785 } else {
786 // Language direction should be on the top div only
787 // if the title is not there. If it is there, it's
788 // interface direction, and the language/dir attributes
789 // should be on the content itself
790 $topLinksAttributes = array_merge( $topLinksAttributes, $langAttributes );
791 }
792
793 $this->getOutput()->addHTML(
794 Html::rawElement( 'div', $topLinksAttributes, $content )
795 );
796 }
797 }
798
799 /**
800 * Get options to be displayed in a form
801 *
802 * @param FormOptions $opts
803 * @return array
804 */
805 public function getExtraOptions( $opts ) {
806 $opts->consumeValues( [
807 'namespace', 'invert', 'associated', 'tagfilter', 'inverttags'
808 ] );
809
810 $extraOpts = [];
811 $extraOpts['namespace'] = $this->namespaceFilterForm( $opts );
812
813 $tagFilter = ChangeTags::buildTagFilterSelector(
814 $opts['tagfilter'], false, $this->getContext()
815 );
816 if ( $tagFilter ) {
817 $tagFilter[1] .= ' ' . Html::rawElement( 'span', [ 'class' => [ 'mw-input-with-label' ] ],
818 Html::element( 'input', [
819 'type' => 'checkbox', 'name' => 'inverttags', 'value' => '1', 'checked' => $opts['inverttags'],
820 'id' => 'inverttags'
821 ] ) . '&nbsp;' . Html::label( $this->msg( 'invert' )->text(), 'inverttags' )
822 );
823 $extraOpts['tagfilter'] = $tagFilter;
824 }
825
826 // Don't fire the hook for subclasses. (Or should we?)
827 if ( $this->getName() === 'Recentchanges' ) {
828 $this->getHookRunner()->onSpecialRecentChangesPanel( $extraOpts, $opts );
829 }
830
831 return $extraOpts;
832 }
833
834 /**
835 * Get last modified date, for client caching
836 * Don't use this if we are using the patrol feature, patrol changes don't
837 * update the timestamp
838 *
839 * @return string|bool
840 */
841 public function checkLastModified() {
842 $dbr = $this->getDB();
843 $lastmod = $dbr->newSelectQueryBuilder()
844 ->select( 'MAX(rc_timestamp)' )
845 ->from( 'recentchanges' )
846 ->caller( __METHOD__ )->fetchField();
847
848 return $lastmod;
849 }
850
851 /**
852 * Creates the choose namespace selection
853 *
854 * @param FormOptions $opts
855 * @return string[]
856 */
857 protected function namespaceFilterForm( FormOptions $opts ) {
858 $nsSelect = Html::namespaceSelector(
859 [ 'selected' => $opts['namespace'], 'all' => '', 'in-user-lang' => true ],
860 [ 'name' => 'namespace', 'id' => 'namespace' ]
861 );
862 $nsLabel = Html::label( $this->msg( 'namespace' )->text(), 'namespace' );
863 $invert = Html::rawElement( 'label', [
864 'class' => 'mw-input-with-label', 'title' => $this->msg( 'tooltip-invert' )->text(),
865 ], Html::element( 'input', [
866 'type' => 'checkbox', 'name' => 'invert', 'value' => '1', 'checked' => $opts['invert'],
867 ] ) . '&nbsp;' . $this->msg( 'invert' )->escaped() );
868 $associated = Html::rawElement( 'label', [
869 'class' => 'mw-input-with-label', 'title' => $this->msg( 'tooltip-namespace_association' )->text(),
870 ], Html::element( 'input', [
871 'type' => 'checkbox', 'name' => 'associated', 'value' => '1', 'checked' => $opts['associated'],
872 ] ) . '&nbsp;' . $this->msg( 'namespace_association' )->escaped() );
873
874 return [ $nsLabel, "$nsSelect $invert $associated" ];
875 }
876
877 /**
878 * Makes change an option link which carries all the other options
879 *
880 * @param string $title
881 * @param array $override Options to override
882 * @param array $options Current options
883 * @param bool $active Whether to show the link in bold
884 * @return string
885 * Annotations needed to tell taint about HtmlArmor
886 * @param-taint $title escapes_html
887 */
888 private function makeOptionsLink( $title, $override, $options, $active = false ) {
889 $params = $this->convertParamsForLink( $override + $options );
890
891 if ( $active ) {
892 $title = new HtmlArmor( '<strong>' . htmlspecialchars( $title ) . '</strong>' );
893 }
894
895 return $this->getLinkRenderer()->makeKnownLink( $this->getPageTitle(), $title, [
896 'data-params' => json_encode( $override ),
897 'data-keys' => implode( ',', array_keys( $override ) ),
898 ], $params );
899 }
900
901 /**
902 * Creates the options panel.
903 *
904 * @param array $defaults
905 * @param array $nondefaults
906 * @param int $numRows Number of rows in the result to show after this header
907 * @return string
908 */
909 private function optionsPanel( $defaults, $nondefaults, $numRows ) {
910 $options = $nondefaults + $defaults;
911
912 $note = '';
913 $msg = $this->msg( 'rclegend' );
914 if ( !$msg->isDisabled() ) {
915 $note .= Html::rawElement(
916 'div',
917 [ 'class' => 'mw-rclegend' ],
918 $msg->parse()
919 );
920 }
921
922 $lang = $this->getLanguage();
923 $user = $this->getUser();
924 $config = $this->getConfig();
925 if ( $options['from'] ) {
926 $resetLink = $this->makeOptionsLink( $this->msg( 'rclistfromreset' )->text(),
927 [ 'from' => '' ], $nondefaults );
928
929 $noteFromMsg = $this->msg( 'rcnotefrom' )
930 ->numParams( $options['limit'] )
931 ->params(
932 $lang->userTimeAndDate( $options['from'], $user ),
933 $lang->userDate( $options['from'], $user ),
934 $lang->userTime( $options['from'], $user )
935 )
936 ->numParams( $numRows );
937 $note .= Html::rawElement(
938 'span',
939 [ 'class' => 'rcnotefrom' ],
940 $noteFromMsg->parse()
941 ) .
942 ' ' .
943 Html::rawElement(
944 'span',
945 [ 'class' => 'rcoptions-listfromreset' ],
946 $this->msg( 'parentheses' )->rawParams( $resetLink )->parse()
947 ) .
948 '<br />';
949 }
950
951 # Sort data for display and make sure it's unique after we've added user data.
952 $linkLimits = $config->get( MainConfigNames::RCLinkLimits );
953 $linkLimits[] = $options['limit'];
954 sort( $linkLimits );
955 $linkLimits = array_unique( $linkLimits );
956
957 $linkDays = $this->getLinkDays();
958 $linkDays[] = $options['days'];
959 sort( $linkDays );
960 $linkDays = array_unique( $linkDays );
961
962 // limit links
963 $cl = [];
964 foreach ( $linkLimits as $value ) {
965 $cl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
966 [ 'limit' => $value ], $nondefaults, $value == $options['limit'] );
967 }
968 $cl = $lang->pipeList( $cl );
969
970 // day links, reset 'from' to none
971 $dl = [];
972 foreach ( $linkDays as $value ) {
973 $dl[] = $this->makeOptionsLink( $lang->formatNum( $value ),
974 [ 'days' => $value, 'from' => '' ], $nondefaults, $value == $options['days'] );
975 }
976 $dl = $lang->pipeList( $dl );
977
978 $showhide = [ 'show', 'hide' ];
979
980 $links = [];
981
982 foreach ( $this->getLegacyShowHideFilters() as $key => $filter ) {
983 $msg = $filter->getShowHide();
984 $linkMessage = $this->msg( $msg . '-' . $showhide[1 - $options[$key]] );
985 // Extensions can define additional filters, but don't need to define the corresponding
986 // messages. If they don't exist, just fall back to 'show' and 'hide'.
987 if ( !$linkMessage->exists() ) {
988 $linkMessage = $this->msg( $showhide[1 - $options[$key]] );
989 }
990
991 $link = $this->makeOptionsLink( $linkMessage->text(),
992 [ $key => 1 - $options[$key] ], $nondefaults );
993
994 $attribs = [
995 'class' => "$msg rcshowhideoption clshowhideoption",
996 'data-filter-name' => $filter->getName(),
997 ];
998
999 if ( $filter->isFeatureAvailableOnStructuredUi() ) {
1000 $attribs['data-feature-in-structured-ui'] = true;
1001 }
1002
1003 $links[] = Html::rawElement(
1004 'span',
1005 $attribs,
1006 $this->msg( $msg )->rawParams( $link )->parse()
1007 );
1008 }
1009
1010 // show from this onward link
1011 $timestamp = wfTimestampNow();
1012 $now = $lang->userTimeAndDate( $timestamp, $user );
1013 $timenow = $lang->userTime( $timestamp, $user );
1014 $datenow = $lang->userDate( $timestamp, $user );
1015 $pipedLinks = '<span class="rcshowhide">' . $lang->pipeList( $links ) . '</span>';
1016
1017 $rclinks = Html::rawElement(
1018 'span',
1019 [ 'class' => 'rclinks' ],
1020 $this->msg( 'rclinks' )->rawParams( $cl, $dl, '' )->parse()
1021 );
1022
1023 $rclistfrom = Html::rawElement(
1024 'span',
1025 [ 'class' => 'rclistfrom' ],
1026 $this->makeOptionsLink(
1027 $this->msg( 'rclistfrom' )->plaintextParams( $now, $timenow, $datenow )->text(),
1028 [ 'from' => $timestamp, 'fromFormatted' => $now ],
1029 $nondefaults
1030 )
1031 );
1032
1033 return "{$note}$rclinks<br />$pipedLinks<br />$rclistfrom";
1034 }
1035
1036 public function isIncludable() {
1037 return true;
1038 }
1039
1040 protected function getCacheTTL() {
1041 return 60 * 5;
1042 }
1043
1044 public function getDefaultLimit() {
1045 $systemPrefValue = $this->userOptionsLookup->getIntOption( $this->getUser(), 'rclimit' );
1046 // Prefer the RCFilters-specific preference if RCFilters is enabled
1047 if ( $this->isStructuredFilterUiEnabled() ) {
1048 return $this->userOptionsLookup->getIntOption(
1049 $this->getUser(), $this->getLimitPreferenceName(), $systemPrefValue
1050 );
1051 }
1052
1053 // Otherwise, use the system rclimit preference value
1054 return $systemPrefValue;
1055 }
1056
1057 /**
1058 * @return string
1059 */
1060 protected function getLimitPreferenceName(): string {
1061 return 'rcfilters-limit'; // Use RCFilters-specific preference
1062 }
1063
1064 /**
1065 * @return string
1066 */
1067 protected function getSavedQueriesPreferenceName(): string {
1068 return 'rcfilters-saved-queries';
1069 }
1070
1071 /**
1072 * @return string
1073 */
1074 protected function getDefaultDaysPreferenceName(): string {
1075 return 'rcdays'; // Use general RecentChanges preference
1076 }
1077
1078 /**
1079 * @return string
1080 */
1081 protected function getCollapsedPreferenceName(): string {
1082 return 'rcfilters-rc-collapsed';
1083 }
1084
1085 }
1086
1087 /**
1088 * Retain the old class name for backwards compatibility.
1089 * @deprecated since 1.41
1090 */
1091 class_alias( SpecialRecentChanges::class, 'SpecialRecentChanges' );