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 * Changeslist constructor
63 * @param Skin|IContextSource $obj
64 * @param array $filterGroups Array of ChangesListFilterGroup objects (currently optional)
66 public function __construct( $obj, array $filterGroups = [] ) {
67 if ( $obj instanceof IContextSource
) {
68 $this->setContext( $obj );
69 $this->skin
= $obj->getSkin();
71 $this->setContext( $obj->getContext() );
74 $this->preCacheMessages();
75 $this->watchMsgCache
= new MapCacheLRU( 50 );
76 $this->linkRenderer
= MediaWikiServices
::getInstance()->getLinkRenderer();
77 $this->filterGroups
= $filterGroups;
81 * Fetch an appropriate changes list class for the specified context
82 * Some users might want to use an enhanced list format, for instance
84 * @param IContextSource $context
85 * @param array $groups Array of ChangesListFilterGroup objects (currently optional)
88 public static function newFromContext( IContextSource
$context, array $groups = [] ) {
89 $user = $context->getUser();
90 $sk = $context->getSkin();
92 if ( Hooks
::run( 'FetchChangesList', [ $user, &$sk, &$list ] ) ) {
93 $new = $context->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) );
96 new EnhancedChangesList( $context, $groups ) :
97 new OldChangesList( $context, $groups );
108 * @param RecentChange &$rc Passed by reference
109 * @param bool $watched (default false)
110 * @param int|null $linenumber (default null)
112 * @return string|bool
114 public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
115 throw new RuntimeException( 'recentChangesLine should be implemented' );
119 * Get the container for highlights that are used in the new StructuredFilters
122 * @return string HTML structure of the highlight container div
124 protected function getHighlightsContainerDiv() {
125 $highlightColorDivs = '';
126 foreach ( [ 'none', 'c1', 'c2', 'c3', 'c4', 'c5' ] as $color ) {
127 $highlightColorDivs .= Html
::rawElement(
130 'class' => 'mw-rcfilters-ui-highlights-color-' . $color,
131 'data-color' => $color
136 return Html
::rawElement(
138 [ 'class' => 'mw-rcfilters-ui-highlights' ],
144 * Sets the list to use a "<li class='watchlist-(namespace)-(page)'>" tag
147 public function setWatchlistDivs( $value = true ) {
148 $this->watchlist
= $value;
152 * @return bool True when setWatchlistDivs has been called
155 public function isWatchlist() {
156 return (bool)$this->watchlist
;
160 * As we use the same small set of messages in various methods and that
161 * they are called often, we call them once and save them in $this->message
163 private function preCacheMessages() {
164 if ( !isset( $this->message
) ) {
166 'cur', 'diff', 'hist', 'enhancedrc-history', 'last', 'blocklink', 'history',
167 'semicolon-separator', 'pipe-separator' ] as $msg
169 $this->message
[$msg] = $this->msg( $msg )->escaped();
175 * Returns the appropriate flags for new page, minor change and patrolling
176 * @param array $flags Associative array of 'flag' => Bool
177 * @param string $nothing To use for empty space
180 public function recentChangesFlags( $flags, $nothing = "\u{00A0}" ) {
182 foreach ( array_keys( $this->getConfig()->get( 'RecentChangesFlags' ) ) as $flag ) {
183 $f .= isset( $flags[$flag] ) && $flags[$flag]
184 ? self
::flag( $flag, $this->getContext() )
192 * Get an array of default HTML class attributes for the change.
194 * @param RecentChange|RCCacheEntry $rc
195 * @param string|bool $watched Optionally timestamp for adding watched class
197 * @return array of classes
199 protected function getHTMLClasses( $rc, $watched ) {
200 $classes = [ self
::CSS_CLASS_PREFIX
. 'line' ];
201 $logType = $rc->mAttribs
['rc_log_type'];
204 $classes[] = self
::CSS_CLASS_PREFIX
. 'log';
205 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'log-' . $logType );
207 $classes[] = self
::CSS_CLASS_PREFIX
. 'edit';
208 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'ns' .
209 $rc->mAttribs
['rc_namespace'] . '-' . $rc->mAttribs
['rc_title'] );
212 // Indicate watched status on the line to allow for more
213 // comprehensive styling.
214 $classes[] = $watched && $rc->mAttribs
['rc_timestamp'] >= $watched
215 ? self
::CSS_CLASS_PREFIX
. 'line-watched'
216 : self
::CSS_CLASS_PREFIX
. 'line-not-watched';
218 $classes = array_merge( $classes, $this->getHTMLClassesForFilters( $rc ) );
224 * Get an array of CSS classes attributed to filters for this row. Used for highlighting
227 * @param RecentChange $rc
228 * @return array Array of CSS classes
230 protected function getHTMLClassesForFilters( $rc ) {
233 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'ns-' .
234 $rc->mAttribs
['rc_namespace'] );
236 if ( $this->filterGroups
!== null ) {
237 foreach ( $this->filterGroups
as $filterGroup ) {
238 foreach ( $filterGroup->getFilters() as $filter ) {
239 $filter->applyCssClassIfNeeded( $this, $rc, $classes );
248 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
249 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
251 * @param string $flag One key of $wgRecentChangesFlags
252 * @param IContextSource|null $context
253 * @return string HTML
255 public static function flag( $flag, IContextSource
$context = null ) {
256 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
257 static $flagInfos = null;
259 if ( is_null( $flagInfos ) ) {
260 global $wgRecentChangesFlags;
262 foreach ( $wgRecentChangesFlags as $key => $value ) {
263 $flagInfos[$key]['letter'] = $value['letter'];
264 $flagInfos[$key]['title'] = $value['title'];
265 // Allow customized class name, fall back to flag name
266 $flagInfos[$key]['class'] = $value['class'] ??
$key;
270 $context = $context ?
: RequestContext
::getMain();
272 // Inconsistent naming, kepted for b/c
273 if ( isset( $map[$flag] ) ) {
277 $info = $flagInfos[$flag];
278 return Html
::element( 'abbr', [
279 'class' => $info['class'],
280 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
281 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
285 * Returns text for the start of the tabular part of RC
288 public function beginRecentChangesList() {
289 $this->rc_cache
= [];
290 $this->rcMoveIndex
= 0;
291 $this->rcCacheIndex
= 0;
292 $this->lastdate
= '';
293 $this->rclistOpen
= false;
294 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
296 return '<div class="mw-changeslist">';
300 * @param ResultWrapper|array $rows
302 public function initChangesListRows( $rows ) {
303 Hooks
::run( 'ChangesListInitRows', [ $this, $rows ] );
307 * Show formatted char difference
309 * Needs the css module 'mediawiki.special.changeslist' to style output
311 * @param int $old Number of bytes
312 * @param int $new Number of bytes
313 * @param IContextSource|null $context
316 public static function showCharacterDifference( $old, $new, IContextSource
$context = null ) {
318 $context = RequestContext
::getMain();
323 $szdiff = $new - $old;
325 $lang = $context->getLanguage();
326 $config = $context->getConfig();
327 $code = $lang->getCode();
328 static $fastCharDiff = [];
329 if ( !isset( $fastCharDiff[$code] ) ) {
330 $fastCharDiff[$code] = $config->get( 'MiserMode' )
331 ||
$context->msg( 'rc-change-size' )->plain() === '$1';
334 $formattedSize = $lang->formatNum( $szdiff );
336 if ( !$fastCharDiff[$code] ) {
337 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
340 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
346 if ( $szdiff === 0 ) {
347 $formattedSizeClass = 'mw-plusminus-null';
348 } elseif ( $szdiff > 0 ) {
349 $formattedSize = '+' . $formattedSize;
350 $formattedSizeClass = 'mw-plusminus-pos';
352 $formattedSizeClass = 'mw-plusminus-neg';
355 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
357 return Html
::element( $tag,
358 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
359 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
363 * Format the character difference of one or several changes.
365 * @param RecentChange $old
366 * @param RecentChange|null $new Last change to use, if not provided, $old will be used
367 * @return string HTML fragment
369 public function formatCharacterDifference( RecentChange
$old, RecentChange
$new = null ) {
370 $oldlen = $old->mAttribs
['rc_old_len'];
373 $newlen = $new->mAttribs
['rc_new_len'];
375 $newlen = $old->mAttribs
['rc_new_len'];
378 if ( $oldlen === null ||
$newlen === null ) {
382 return self
::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
386 * Returns text for the end of RC
389 public function endRecentChangesList() {
390 $out = $this->rclistOpen ?
"</ul>\n" : '';
397 * @param string &$s HTML to update
398 * @param mixed $rc_timestamp
400 public function insertDateHeader( &$s, $rc_timestamp ) {
401 # Make date header if necessary
402 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
403 if ( $date != $this->lastdate
) {
404 if ( $this->lastdate
!= '' ) {
407 $s .= Xml
::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
408 $this->lastdate
= $date;
409 $this->rclistOpen
= true;
414 * @param string &$s HTML to update
415 * @param Title $title
416 * @param string $logtype
418 public function insertLog( &$s, $title, $logtype ) {
419 $page = new LogPage( $logtype );
420 $logname = $page->getName()->setContext( $this->getContext() )->text();
421 $s .= $this->msg( 'parentheses' )->rawParams(
422 $this->linkRenderer
->makeKnownLink( $title, $logname )
427 * @param string &$s HTML to update
428 * @param RecentChange &$rc
429 * @param bool|null $unpatrolled Unused variable, since 1.27.
431 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
434 $rc->mAttribs
['rc_type'] == RC_NEW ||
435 $rc->mAttribs
['rc_type'] == RC_LOG ||
436 $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
438 $diffLink = $this->message
['diff'];
439 } elseif ( !self
::userCan( $rc, Revision
::DELETED_TEXT
, $this->getUser() ) ) {
440 $diffLink = $this->message
['diff'];
443 'curid' => $rc->mAttribs
['rc_cur_id'],
444 'diff' => $rc->mAttribs
['rc_this_oldid'],
445 'oldid' => $rc->mAttribs
['rc_last_oldid']
448 $diffLink = $this->linkRenderer
->makeKnownLink(
450 new HtmlArmor( $this->message
['diff'] ),
451 [ 'class' => 'mw-changeslist-diff' ],
455 if ( $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
) {
456 $diffhist = $diffLink . $this->message
['pipe-separator'] . $this->message
['hist'];
458 $diffhist = $diffLink . $this->message
['pipe-separator'];
460 $diffhist .= $this->linkRenderer
->makeKnownLink(
462 new HtmlArmor( $this->message
['hist'] ),
463 [ 'class' => 'mw-changeslist-history' ],
465 'curid' => $rc->mAttribs
['rc_cur_id'],
466 'action' => 'history'
471 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
472 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
473 ' <span class="mw-changeslist-separator">. .</span> ';
477 * @param string &$s Article link will be appended to this string, in place.
478 * @param RecentChange $rc
479 * @param bool $unpatrolled
480 * @param bool $watched
481 * @deprecated since 1.27, use getArticleLink instead.
483 public function insertArticleLink( &$s, RecentChange
$rc, $unpatrolled, $watched ) {
484 $s .= $this->getArticleLink( $rc, $unpatrolled, $watched );
488 * @param RecentChange &$rc
489 * @param bool $unpatrolled
490 * @param bool $watched
491 * @return string HTML
494 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
496 if ( $rc->getTitle()->isRedirect() ) {
497 $params = [ 'redirect' => 'no' ];
500 $articlelink = $this->linkRenderer
->makeLink(
503 [ 'class' => 'mw-changeslist-title' ],
506 if ( $this->isDeleted( $rc, Revision
::DELETED_TEXT
) ) {
507 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
509 # To allow for boldening pages watched by this user
510 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
512 $articlelink .= $this->getLanguage()->getDirMark();
514 # TODO: Deprecate the $s argument, it seems happily unused.
516 # Avoid PHP 7.1 warning from passing $this by reference
517 $changesList = $this;
518 Hooks
::run( 'ChangesListInsertArticleLink',
519 [ &$changesList, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
521 return "{$s} {$articlelink}";
525 * Get the timestamp from $rc formatted with current user's settings
528 * @param RecentChange $rc
529 * @return string HTML fragment
531 public function getTimestamp( $rc ) {
532 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
533 return $this->message
['semicolon-separator'] . '<span class="mw-changeslist-date">' .
534 $this->getLanguage()->userTime(
535 $rc->mAttribs
['rc_timestamp'],
537 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
541 * Insert time timestamp string from $rc into $s
543 * @param string &$s HTML to update
544 * @param RecentChange $rc
546 public function insertTimestamp( &$s, $rc ) {
547 $s .= $this->getTimestamp( $rc );
551 * Insert links to user page, user talk page and eventually a blocking link
553 * @param string &$s HTML to update
554 * @param RecentChange &$rc
556 public function insertUserRelatedLinks( &$s, &$rc ) {
557 if ( $this->isDeleted( $rc, Revision
::DELETED_USER
) ) {
558 $s .= ' <span class="history-deleted">' .
559 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
561 $s .= $this->getLanguage()->getDirMark() . Linker
::userLink( $rc->mAttribs
['rc_user'],
562 $rc->mAttribs
['rc_user_text'] );
563 $s .= Linker
::userToolLinks( $rc->mAttribs
['rc_user'], $rc->mAttribs
['rc_user_text'] );
568 * Insert a formatted action
570 * @param RecentChange $rc
573 public function insertLogEntry( $rc ) {
574 $formatter = LogFormatter
::newFromRow( $rc->mAttribs
);
575 $formatter->setContext( $this->getContext() );
576 $formatter->setShowUserToolLinks( true );
577 $mark = $this->getLanguage()->getDirMark();
579 return $formatter->getActionText() . " $mark" . $formatter->getComment();
583 * Insert a formatted comment
584 * @param RecentChange $rc
587 public function insertComment( $rc ) {
588 if ( $this->isDeleted( $rc, Revision
::DELETED_COMMENT
) ) {
589 return ' <span class="history-deleted">' .
590 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
592 return Linker
::commentBlock( $rc->mAttribs
['rc_comment'], $rc->getTitle() );
597 * Returns the string which indicates the number of watching users
598 * @param int $count Number of user watching a page
601 protected function numberofWatchingusers( $count ) {
606 return $this->watchMsgCache
->getWithSetCallback(
607 "watching-users-msg:$count",
608 function () use ( $count ) {
609 return $this->msg( 'number_of_watching_users_RCview' )
610 ->numParams( $count )->escaped();
616 * Determine if said field of a revision is hidden
617 * @param RCCacheEntry|RecentChange $rc
618 * @param int $field One of DELETED_* bitfield constants
621 public static function isDeleted( $rc, $field ) {
622 return ( $rc->mAttribs
['rc_deleted'] & $field ) == $field;
626 * Determine if the current user is allowed to view a particular
627 * field of this revision, if it's marked as deleted.
628 * @param RCCacheEntry|RecentChange $rc
630 * @param User|null $user User object to check, or null to use $wgUser
633 public static function userCan( $rc, $field, User
$user = null ) {
634 if ( $rc->mAttribs
['rc_type'] == RC_LOG
) {
635 return LogEventsList
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
637 return Revision
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
642 * @param string $link
643 * @param bool $watched
646 protected function maybeWatchedLink( $link, $watched = false ) {
648 return '<strong class="mw-watched">' . $link . '</strong>';
650 return '<span class="mw-rc-unwatched">' . $link . '</span>';
655 * Insert a rollback link
658 * @param RecentChange &$rc
660 public function insertRollback( &$s, &$rc ) {
661 if ( $rc->mAttribs
['rc_type'] == RC_EDIT
662 && $rc->mAttribs
['rc_this_oldid']
663 && $rc->mAttribs
['rc_cur_id']
664 && $rc->getAttribute( 'page_latest' ) == $rc->mAttribs
['rc_this_oldid']
666 $title = $rc->getTitle();
667 /** Check for rollback permissions, disallow special pages, and only
668 * show a link on the top-most revision */
669 if ( $title->quickUserCan( 'rollback', $this->getUser() ) ) {
670 $rev = new Revision( [
672 'id' => $rc->mAttribs
['rc_this_oldid'],
673 'user' => $rc->mAttribs
['rc_user'],
674 'user_text' => $rc->mAttribs
['rc_user_text'],
675 'actor' => $rc->mAttribs
['rc_actor'] ??
null,
676 'deleted' => $rc->mAttribs
['rc_deleted']
678 $s .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
684 * @param RecentChange $rc
688 public function getRollback( RecentChange
$rc ) {
690 $this->insertRollback( $s, $rc );
696 * @param RecentChange &$rc
697 * @param array &$classes
699 public function insertTags( &$s, &$rc, &$classes ) {
700 if ( empty( $rc->mAttribs
['ts_tags'] ) ) {
704 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
705 $rc->mAttribs
['ts_tags'],
709 $classes = array_merge( $classes, $newClasses );
710 $s .= ' ' . $tagSummary;
714 * @param RecentChange $rc
715 * @param array &$classes
719 public function getTags( RecentChange
$rc, array &$classes ) {
721 $this->insertTags( $s, $rc, $classes );
725 public function insertExtra( &$s, &$rc, &$classes ) {
726 // Empty, used for subclasses to add anything special.
729 protected function showAsUnpatrolled( RecentChange
$rc ) {
730 return self
::isUnpatrolled( $rc, $this->getUser() );
734 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
738 public static function isUnpatrolled( $rc, User
$user ) {
739 if ( $rc instanceof RecentChange
) {
740 $isPatrolled = $rc->mAttribs
['rc_patrolled'];
741 $rcType = $rc->mAttribs
['rc_type'];
742 $rcLogType = $rc->mAttribs
['rc_log_type'];
744 $isPatrolled = $rc->rc_patrolled
;
745 $rcType = $rc->rc_type
;
746 $rcLogType = $rc->rc_log_type
;
749 if ( !$isPatrolled ) {
750 if ( $user->useRCPatrol() ) {
753 if ( $user->useNPPatrol() && $rcType == RC_NEW
) {
756 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
765 * Determines whether a revision is linked to this change; this may not be the case
766 * when the categorization wasn't done by an edit but a conditional parser function
770 * @param RecentChange|RCCacheEntry $rcObj
773 protected function isCategorizationWithoutRevision( $rcObj ) {
774 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
775 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
779 * Get recommended data attributes for a change line.
780 * @param RecentChange $rc
781 * @return string[] attribute name => value
783 protected function getDataAttributes( RecentChange
$rc ) {
786 $type = $rc->getAttribute( 'rc_source' );
788 case RecentChange
::SRC_EDIT
:
789 case RecentChange
::SRC_NEW
:
790 $attrs['data-mw-revid'] = $rc->mAttribs
['rc_this_oldid'];
792 case RecentChange
::SRC_LOG
:
793 $attrs['data-mw-logid'] = $rc->mAttribs
['rc_logid'];
794 $attrs['data-mw-logaction'] =
795 $rc->mAttribs
['rc_log_type'] . '/' . $rc->mAttribs
['rc_log_action'];
799 $attrs[ 'data-mw-ts' ] = $rc->getAttribute( 'rc_timestamp' );
805 * Sets the callable that generates a change line prefix added to the beginning of each line.
807 * @param callable $prefixer Callable to run that generates the change line prefix.
808 * Takes three parameters: a RecentChange object, a ChangesList object,
809 * and whether the current entry is a grouped entry.
811 public function setChangeLinePrefixer( callable
$prefixer ) {
812 $this->changeLinePrefixer
= $prefixer;