3 * Base class for all changes lists.
5 * The class is used for formatting recent changes, related changes and watchlist.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Linker\LinkRenderer
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\Rdbms\ResultWrapper
;
28 class ChangesList
extends ContextSource
{
29 const CSS_CLASS_PREFIX
= 'mw-changeslist-';
36 protected $watchlist = false;
40 protected $rcCacheIndex;
41 protected $rclistOpen;
42 protected $rcMoveIndex;
45 protected $changeLinePrefixer;
47 /** @var MapCacheLRU */
48 protected $watchMsgCache;
53 protected $linkRenderer;
58 protected $filterGroups;
61 * @param Skin|IContextSource $obj
62 * @param array $filterGroups Array of ChangesListFilterGroup objects (currently optional)
64 public function __construct( $obj, array $filterGroups = [] ) {
65 if ( $obj instanceof IContextSource
) {
66 $this->setContext( $obj );
67 $this->skin
= $obj->getSkin();
69 $this->setContext( $obj->getContext() );
72 $this->preCacheMessages();
73 $this->watchMsgCache
= new MapCacheLRU( 50 );
74 $this->linkRenderer
= MediaWikiServices
::getInstance()->getLinkRenderer();
75 $this->filterGroups
= $filterGroups;
79 * Fetch an appropriate changes list class for the specified context
80 * Some users might want to use an enhanced list format, for instance
82 * @param IContextSource $context
83 * @param array $groups Array of ChangesListFilterGroup objects (currently optional)
86 public static function newFromContext( IContextSource
$context, array $groups = [] ) {
87 $user = $context->getUser();
88 $sk = $context->getSkin();
90 if ( Hooks
::run( 'FetchChangesList', [ $user, &$sk, &$list ] ) ) {
91 $new = $context->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) );
94 new EnhancedChangesList( $context, $groups ) :
95 new OldChangesList( $context, $groups );
106 * @param RecentChange &$rc Passed by reference
107 * @param bool $watched (default false)
108 * @param int|null $linenumber (default null)
110 * @return string|bool
112 public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
113 throw new RuntimeException( 'recentChangesLine should be implemented' );
117 * Get the container for highlights that are used in the new StructuredFilters
120 * @return string HTML structure of the highlight container div
122 protected function getHighlightsContainerDiv() {
123 $highlightColorDivs = '';
124 foreach ( [ 'none', 'c1', 'c2', 'c3', 'c4', 'c5' ] as $color ) {
125 $highlightColorDivs .= Html
::rawElement(
128 'class' => 'mw-rcfilters-ui-highlights-color-' . $color,
129 'data-color' => $color
134 return Html
::rawElement(
136 [ 'class' => 'mw-rcfilters-ui-highlights' ],
142 * Sets the list to use a "<li class='watchlist-(namespace)-(page)'>" tag
145 public function setWatchlistDivs( $value = true ) {
146 $this->watchlist
= $value;
150 * @return bool True when setWatchlistDivs has been called
153 public function isWatchlist() {
154 return (bool)$this->watchlist
;
158 * As we use the same small set of messages in various methods and that
159 * they are called often, we call them once and save them in $this->message
161 private function preCacheMessages() {
162 if ( !isset( $this->message
) ) {
164 'cur', 'diff', 'hist', 'enhancedrc-history', 'last', 'blocklink', 'history',
165 'semicolon-separator', 'pipe-separator' ] as $msg
167 $this->message
[$msg] = $this->msg( $msg )->escaped();
173 * Returns the appropriate flags for new page, minor change and patrolling
174 * @param array $flags Associative array of 'flag' => Bool
175 * @param string $nothing To use for empty space
178 public function recentChangesFlags( $flags, $nothing = "\u{00A0}" ) {
180 foreach ( array_keys( $this->getConfig()->get( 'RecentChangesFlags' ) ) as $flag ) {
181 $f .= isset( $flags[$flag] ) && $flags[$flag]
182 ? self
::flag( $flag, $this->getContext() )
190 * Get an array of default HTML class attributes for the change.
192 * @param RecentChange|RCCacheEntry $rc
193 * @param string|bool $watched Optionally timestamp for adding watched class
195 * @return array of classes
197 protected function getHTMLClasses( $rc, $watched ) {
198 $classes = [ self
::CSS_CLASS_PREFIX
. 'line' ];
199 $logType = $rc->mAttribs
['rc_log_type'];
202 $classes[] = self
::CSS_CLASS_PREFIX
. 'log';
203 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'log-' . $logType );
205 $classes[] = self
::CSS_CLASS_PREFIX
. 'edit';
206 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'ns' .
207 $rc->mAttribs
['rc_namespace'] . '-' . $rc->mAttribs
['rc_title'] );
210 // Indicate watched status on the line to allow for more
211 // comprehensive styling.
212 $classes[] = $watched && $rc->mAttribs
['rc_timestamp'] >= $watched
213 ? self
::CSS_CLASS_PREFIX
. 'line-watched'
214 : self
::CSS_CLASS_PREFIX
. 'line-not-watched';
216 $classes = array_merge( $classes, $this->getHTMLClassesForFilters( $rc ) );
222 * Get an array of CSS classes attributed to filters for this row. Used for highlighting
225 * @param RecentChange $rc
226 * @return array Array of CSS classes
228 protected function getHTMLClassesForFilters( $rc ) {
231 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'ns-' .
232 $rc->mAttribs
['rc_namespace'] );
234 if ( $this->filterGroups
!== null ) {
235 foreach ( $this->filterGroups
as $filterGroup ) {
236 foreach ( $filterGroup->getFilters() as $filter ) {
237 $filter->applyCssClassIfNeeded( $this, $rc, $classes );
246 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
247 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
249 * @param string $flag One key of $wgRecentChangesFlags
250 * @param IContextSource|null $context
251 * @return string HTML
253 public static function flag( $flag, IContextSource
$context = null ) {
254 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
255 static $flagInfos = null;
257 if ( is_null( $flagInfos ) ) {
258 global $wgRecentChangesFlags;
260 foreach ( $wgRecentChangesFlags as $key => $value ) {
261 $flagInfos[$key]['letter'] = $value['letter'];
262 $flagInfos[$key]['title'] = $value['title'];
263 // Allow customized class name, fall back to flag name
264 $flagInfos[$key]['class'] = $value['class'] ??
$key;
268 $context = $context ?
: RequestContext
::getMain();
270 // Inconsistent naming, kepted for b/c
271 if ( isset( $map[$flag] ) ) {
275 $info = $flagInfos[$flag];
276 return Html
::element( 'abbr', [
277 'class' => $info['class'],
278 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
279 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
283 * Returns text for the start of the tabular part of RC
286 public function beginRecentChangesList() {
287 $this->rc_cache
= [];
288 $this->rcMoveIndex
= 0;
289 $this->rcCacheIndex
= 0;
290 $this->lastdate
= '';
291 $this->rclistOpen
= false;
292 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
294 return '<div class="mw-changeslist">';
298 * @param ResultWrapper|array $rows
300 public function initChangesListRows( $rows ) {
301 Hooks
::run( 'ChangesListInitRows', [ $this, $rows ] );
305 * Show formatted char difference
307 * Needs the css module 'mediawiki.special.changeslist' to style output
309 * @param int $old Number of bytes
310 * @param int $new Number of bytes
311 * @param IContextSource|null $context
314 public static function showCharacterDifference( $old, $new, IContextSource
$context = null ) {
316 $context = RequestContext
::getMain();
321 $szdiff = $new - $old;
323 $lang = $context->getLanguage();
324 $config = $context->getConfig();
325 $code = $lang->getCode();
326 static $fastCharDiff = [];
327 if ( !isset( $fastCharDiff[$code] ) ) {
328 $fastCharDiff[$code] = $config->get( 'MiserMode' )
329 ||
$context->msg( 'rc-change-size' )->plain() === '$1';
332 $formattedSize = $lang->formatNum( $szdiff );
334 if ( !$fastCharDiff[$code] ) {
335 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
338 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
344 if ( $szdiff === 0 ) {
345 $formattedSizeClass = 'mw-plusminus-null';
346 } elseif ( $szdiff > 0 ) {
347 $formattedSize = '+' . $formattedSize;
348 $formattedSizeClass = 'mw-plusminus-pos';
350 $formattedSizeClass = 'mw-plusminus-neg';
352 $formattedSizeClass .= ' mw-diff-bytes';
354 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
356 return Html
::element( $tag,
357 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
358 $formattedSize ) . $lang->getDirMark();
362 * Format the character difference of one or several changes.
364 * @param RecentChange $old
365 * @param RecentChange|null $new Last change to use, if not provided, $old will be used
366 * @return string HTML fragment
368 public function formatCharacterDifference( RecentChange
$old, RecentChange
$new = null ) {
369 $oldlen = $old->mAttribs
['rc_old_len'];
372 $newlen = $new->mAttribs
['rc_new_len'];
374 $newlen = $old->mAttribs
['rc_new_len'];
377 if ( $oldlen === null ||
$newlen === null ) {
381 return self
::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
385 * Returns text for the end of RC
388 public function endRecentChangesList() {
389 $out = $this->rclistOpen ?
"</ul>\n" : '';
396 * @param string &$s HTML to update
397 * @param mixed $rc_timestamp
399 public function insertDateHeader( &$s, $rc_timestamp ) {
400 # Make date header if necessary
401 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
402 if ( $date != $this->lastdate
) {
403 if ( $this->lastdate
!= '' ) {
406 $s .= Xml
::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
407 $this->lastdate
= $date;
408 $this->rclistOpen
= true;
413 * @param string &$s HTML to update
414 * @param Title $title
415 * @param string $logtype
417 public function insertLog( &$s, $title, $logtype ) {
418 $page = new LogPage( $logtype );
419 $logname = $page->getName()->setContext( $this->getContext() )->text();
420 $s .= $this->msg( 'parentheses' )->rawParams(
421 $this->linkRenderer
->makeKnownLink( $title, $logname )
426 * @param string &$s HTML to update
427 * @param RecentChange &$rc
428 * @param bool|null $unpatrolled Unused variable, since 1.27.
430 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
433 $rc->mAttribs
['rc_type'] == RC_NEW ||
434 $rc->mAttribs
['rc_type'] == RC_LOG ||
435 $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
437 $diffLink = $this->message
['diff'];
438 } elseif ( !self
::userCan( $rc, Revision
::DELETED_TEXT
, $this->getUser() ) ) {
439 $diffLink = $this->message
['diff'];
442 'curid' => $rc->mAttribs
['rc_cur_id'],
443 'diff' => $rc->mAttribs
['rc_this_oldid'],
444 'oldid' => $rc->mAttribs
['rc_last_oldid']
447 $diffLink = $this->linkRenderer
->makeKnownLink(
449 new HtmlArmor( $this->message
['diff'] ),
450 [ 'class' => 'mw-changeslist-diff' ],
454 if ( $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
) {
455 $histLink = $this->message
['hist'];
457 $histLink = $this->linkRenderer
->makeKnownLink(
459 new HtmlArmor( $this->message
['hist'] ),
460 [ 'class' => 'mw-changeslist-history' ],
462 'curid' => $rc->mAttribs
['rc_cur_id'],
463 'action' => 'history'
468 $s .= Html
::rawElement( 'div', [ 'class' => 'mw-changeslist-links' ],
469 Html
::rawElement( 'span', [], $diffLink ) .
470 Html
::rawElement( 'span', [], $histLink )
472 ' <span class="mw-changeslist-separator"></span> ';
476 * @param RecentChange &$rc
477 * @param bool $unpatrolled
478 * @param bool $watched
479 * @return string HTML
482 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
484 if ( $rc->getTitle()->isRedirect() ) {
485 $params = [ 'redirect' => 'no' ];
488 $articlelink = $this->linkRenderer
->makeLink(
491 [ 'class' => 'mw-changeslist-title' ],
494 if ( $this->isDeleted( $rc, Revision
::DELETED_TEXT
) ) {
495 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
497 # To allow for boldening pages watched by this user
498 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
500 $articlelink .= $this->getLanguage()->getDirMark();
502 # TODO: Deprecate the $s argument, it seems happily unused.
504 # Avoid PHP 7.1 warning from passing $this by reference
505 $changesList = $this;
506 Hooks
::run( 'ChangesListInsertArticleLink',
507 [ &$changesList, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
509 return "{$s} {$articlelink}";
513 * Get the timestamp from $rc formatted with current user's settings
516 * @param RecentChange $rc
517 * @return string HTML fragment
519 public function getTimestamp( $rc ) {
520 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
521 return $this->message
['semicolon-separator'] . '<span class="mw-changeslist-date">' .
522 htmlspecialchars( $this->getLanguage()->userTime(
523 $rc->mAttribs
['rc_timestamp'],
525 ) ) . '</span> <span class="mw-changeslist-separator"></span> ';
529 * Insert time timestamp string from $rc into $s
531 * @param string &$s HTML to update
532 * @param RecentChange $rc
534 public function insertTimestamp( &$s, $rc ) {
535 $s .= $this->getTimestamp( $rc );
539 * Insert links to user page, user talk page and eventually a blocking link
541 * @param string &$s HTML to update
542 * @param RecentChange &$rc
544 public function insertUserRelatedLinks( &$s, &$rc ) {
545 if ( $this->isDeleted( $rc, Revision
::DELETED_USER
) ) {
546 $s .= ' <span class="history-deleted">' .
547 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
549 $s .= $this->getLanguage()->getDirMark() . Linker
::userLink( $rc->mAttribs
['rc_user'],
550 $rc->mAttribs
['rc_user_text'] );
551 $s .= Linker
::userToolLinks(
552 $rc->mAttribs
['rc_user'], $rc->mAttribs
['rc_user_text'],
554 // The text content of tools is not wrapped with parenthesises or "piped".
555 // This will be handled in CSS (T205581).
562 * Insert a formatted action
564 * @param RecentChange $rc
567 public function insertLogEntry( $rc ) {
568 $formatter = LogFormatter
::newFromRow( $rc->mAttribs
);
569 $formatter->setContext( $this->getContext() );
570 $formatter->setShowUserToolLinks( true );
571 $mark = $this->getLanguage()->getDirMark();
573 return $formatter->getActionText() . " $mark" . $formatter->getComment();
577 * Insert a formatted comment
578 * @param RecentChange $rc
581 public function insertComment( $rc ) {
582 if ( $this->isDeleted( $rc, Revision
::DELETED_COMMENT
) ) {
583 return ' <span class="history-deleted">' .
584 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
586 return Linker
::commentBlock( $rc->mAttribs
['rc_comment'], $rc->getTitle() );
591 * Returns the string which indicates the number of watching users
592 * @param int $count Number of user watching a page
595 protected function numberofWatchingusers( $count ) {
600 return $this->watchMsgCache
->getWithSetCallback(
601 "watching-users-msg:$count",
602 function () use ( $count ) {
603 return $this->msg( 'number_of_watching_users_RCview' )
604 ->numParams( $count )->escaped();
610 * Determine if said field of a revision is hidden
611 * @param RCCacheEntry|RecentChange $rc
612 * @param int $field One of DELETED_* bitfield constants
615 public static function isDeleted( $rc, $field ) {
616 return ( $rc->mAttribs
['rc_deleted'] & $field ) == $field;
620 * Determine if the current user is allowed to view a particular
621 * field of this revision, if it's marked as deleted.
622 * @param RCCacheEntry|RecentChange $rc
624 * @param User|null $user User object to check, or null to use $wgUser
627 public static function userCan( $rc, $field, User
$user = null ) {
628 if ( $rc->mAttribs
['rc_type'] == RC_LOG
) {
629 return LogEventsList
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
631 return Revision
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
636 * @param string $link
637 * @param bool $watched
640 protected function maybeWatchedLink( $link, $watched = false ) {
642 return '<strong class="mw-watched">' . $link . '</strong>';
644 return '<span class="mw-rc-unwatched">' . $link . '</span>';
649 * Insert a rollback link
652 * @param RecentChange &$rc
654 public function insertRollback( &$s, &$rc ) {
655 if ( $rc->mAttribs
['rc_type'] == RC_EDIT
656 && $rc->mAttribs
['rc_this_oldid']
657 && $rc->mAttribs
['rc_cur_id']
658 && $rc->getAttribute( 'page_latest' ) == $rc->mAttribs
['rc_this_oldid']
660 $title = $rc->getTitle();
661 /** Check for rollback permissions, disallow special pages, and only
662 * show a link on the top-most revision */
663 if ( $title->quickUserCan( 'rollback', $this->getUser() ) ) {
664 $rev = new Revision( [
666 'id' => $rc->mAttribs
['rc_this_oldid'],
667 'user' => $rc->mAttribs
['rc_user'],
668 'user_text' => $rc->mAttribs
['rc_user_text'],
669 'actor' => $rc->mAttribs
['rc_actor'] ??
null,
670 'deleted' => $rc->mAttribs
['rc_deleted']
672 $s .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
678 * @param RecentChange $rc
682 public function getRollback( RecentChange
$rc ) {
684 $this->insertRollback( $s, $rc );
690 * @param RecentChange &$rc
691 * @param array &$classes
693 public function insertTags( &$s, &$rc, &$classes ) {
694 if ( empty( $rc->mAttribs
['ts_tags'] ) ) {
698 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
699 $rc->mAttribs
['ts_tags'],
703 $classes = array_merge( $classes, $newClasses );
704 $s .= ' ' . $tagSummary;
708 * @param RecentChange $rc
709 * @param array &$classes
713 public function getTags( RecentChange
$rc, array &$classes ) {
715 $this->insertTags( $s, $rc, $classes );
719 public function insertExtra( &$s, &$rc, &$classes ) {
720 // Empty, used for subclasses to add anything special.
723 protected function showAsUnpatrolled( RecentChange
$rc ) {
724 return self
::isUnpatrolled( $rc, $this->getUser() );
728 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
732 public static function isUnpatrolled( $rc, User
$user ) {
733 if ( $rc instanceof RecentChange
) {
734 $isPatrolled = $rc->mAttribs
['rc_patrolled'];
735 $rcType = $rc->mAttribs
['rc_type'];
736 $rcLogType = $rc->mAttribs
['rc_log_type'];
738 $isPatrolled = $rc->rc_patrolled
;
739 $rcType = $rc->rc_type
;
740 $rcLogType = $rc->rc_log_type
;
743 if ( !$isPatrolled ) {
744 if ( $user->useRCPatrol() ) {
747 if ( $user->useNPPatrol() && $rcType == RC_NEW
) {
750 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
759 * Determines whether a revision is linked to this change; this may not be the case
760 * when the categorization wasn't done by an edit but a conditional parser function
764 * @param RecentChange|RCCacheEntry $rcObj
767 protected function isCategorizationWithoutRevision( $rcObj ) {
768 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
769 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
773 * Get recommended data attributes for a change line.
774 * @param RecentChange $rc
775 * @return string[] attribute name => value
777 protected function getDataAttributes( RecentChange
$rc ) {
780 $type = $rc->getAttribute( 'rc_source' );
782 case RecentChange
::SRC_EDIT
:
783 case RecentChange
::SRC_NEW
:
784 $attrs['data-mw-revid'] = $rc->mAttribs
['rc_this_oldid'];
786 case RecentChange
::SRC_LOG
:
787 $attrs['data-mw-logid'] = $rc->mAttribs
['rc_logid'];
788 $attrs['data-mw-logaction'] =
789 $rc->mAttribs
['rc_log_type'] . '/' . $rc->mAttribs
['rc_log_action'];
793 $attrs[ 'data-mw-ts' ] = $rc->getAttribute( 'rc_timestamp' );
799 * Sets the callable that generates a change line prefix added to the beginning of each line.
801 * @param callable $prefixer Callable to run that generates the change line prefix.
802 * Takes three parameters: a RecentChange object, a ChangesList object,
803 * and whether the current entry is a grouped entry.
805 public function setChangeLinePrefixer( callable
$prefixer ) {
806 $this->changeLinePrefixer
= $prefixer;