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 $watchMsgCache;
50 protected $linkRenderer;
55 protected $filterGroups;
58 * Changeslist constructor
60 * @param Skin|IContextSource $obj
61 * @param array $filterGroups Array of ChangesListFilterGroup objects (currently optional)
63 public function __construct( $obj, array $filterGroups = [] ) {
64 if ( $obj instanceof IContextSource
) {
65 $this->setContext( $obj );
66 $this->skin
= $obj->getSkin();
68 $this->setContext( $obj->getContext() );
71 $this->preCacheMessages();
72 $this->watchMsgCache
= new HashBagOStuff( [ 'maxKeys' => 50 ] );
73 $this->linkRenderer
= MediaWikiServices
::getInstance()->getLinkRenderer();
74 $this->filterGroups
= $filterGroups;
78 * Fetch an appropriate changes list class for the specified context
79 * Some users might want to use an enhanced list format, for instance
81 * @param IContextSource $context
82 * @param array $groups Array of ChangesListFilterGroup objects (currently optional)
85 public static function newFromContext( IContextSource
$context, array $groups = [] ) {
86 $user = $context->getUser();
87 $sk = $context->getSkin();
89 if ( Hooks
::run( 'FetchChangesList', [ $user, &$sk, &$list ] ) ) {
90 $new = $context->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) );
93 new EnhancedChangesList( $context, $groups ) :
94 new OldChangesList( $context, $groups );
105 * @param RecentChange $rc Passed by reference
106 * @param bool $watched (default false)
107 * @param int $linenumber (default null)
109 * @return string|bool
111 public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
112 throw new RuntimeException( 'recentChangesLine should be implemented' );
116 * Sets the list to use a "<li class='watchlist-(namespace)-(page)'>" tag
119 public function setWatchlistDivs( $value = true ) {
120 $this->watchlist
= $value;
124 * @return bool True when setWatchlistDivs has been called
127 public function isWatchlist() {
128 return (bool)$this->watchlist
;
132 * As we use the same small set of messages in various methods and that
133 * they are called often, we call them once and save them in $this->message
135 private function preCacheMessages() {
136 if ( !isset( $this->message
) ) {
138 'cur', 'diff', 'hist', 'enhancedrc-history', 'last', 'blocklink', 'history',
139 'semicolon-separator', 'pipe-separator' ] as $msg
141 $this->message
[$msg] = $this->msg( $msg )->escaped();
147 * Returns the appropriate flags for new page, minor change and patrolling
148 * @param array $flags Associative array of 'flag' => Bool
149 * @param string $nothing To use for empty space
152 public function recentChangesFlags( $flags, $nothing = ' ' ) {
154 foreach ( array_keys( $this->getConfig()->get( 'RecentChangesFlags' ) ) as $flag ) {
155 $f .= isset( $flags[$flag] ) && $flags[$flag]
156 ? self
::flag( $flag, $this->getContext() )
164 * Get an array of default HTML class attributes for the change.
166 * @param RecentChange|RCCacheEntry $rc
167 * @param string|bool $watched Optionally timestamp for adding watched class
169 * @return array of classes
171 protected function getHTMLClasses( $rc, $watched ) {
173 $logType = $rc->mAttribs
['rc_log_type'];
176 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'log-' . $logType );
178 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'ns' .
179 $rc->mAttribs
['rc_namespace'] . '-' . $rc->mAttribs
['rc_title'] );
180 $classes[] = Sanitizer
::escapeClass( self
::CSS_CLASS_PREFIX
. 'ns-' .
181 $rc->mAttribs
['rc_namespace'] );
184 // Indicate watched status on the line to allow for more
185 // comprehensive styling.
186 $classes[] = $watched && $rc->mAttribs
['rc_timestamp'] >= $watched
187 ? self
::CSS_CLASS_PREFIX
. 'line-watched'
188 : self
::CSS_CLASS_PREFIX
. 'line-not-watched';
190 $classes = array_merge( $classes, $this->getHTMLClassesForFilters( $rc ) );
196 * Get an array of CSS classes attributed to filters for this row
198 * @param RecentChange $rc
199 * @return array Array of CSS classes
201 protected function getHTMLClassesForFilters( $rc ) {
204 if ( $this->filterGroups
!== null ) {
205 foreach ( $this->filterGroups
as $filterGroup ) {
206 foreach ( $filterGroup->getFilters() as $filter ) {
207 $filter->applyCssClassIfNeeded( $this, $rc, $classes );
216 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
217 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
219 * @param string $flag One key of $wgRecentChangesFlags
220 * @param IContextSource $context
221 * @return string HTML
223 public static function flag( $flag, IContextSource
$context = null ) {
224 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
225 static $flagInfos = null;
227 if ( is_null( $flagInfos ) ) {
228 global $wgRecentChangesFlags;
230 foreach ( $wgRecentChangesFlags as $key => $value ) {
231 $flagInfos[$key]['letter'] = $value['letter'];
232 $flagInfos[$key]['title'] = $value['title'];
233 // Allow customized class name, fall back to flag name
234 $flagInfos[$key]['class'] = isset( $value['class'] ) ?
$value['class'] : $key;
238 $context = $context ?
: RequestContext
::getMain();
240 // Inconsistent naming, kepted for b/c
241 if ( isset( $map[$flag] ) ) {
245 $info = $flagInfos[$flag];
246 return Html
::element( 'abbr', [
247 'class' => $info['class'],
248 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
249 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
253 * Returns text for the start of the tabular part of RC
256 public function beginRecentChangesList() {
257 $this->rc_cache
= [];
258 $this->rcMoveIndex
= 0;
259 $this->rcCacheIndex
= 0;
260 $this->lastdate
= '';
261 $this->rclistOpen
= false;
262 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
264 return '<div class="mw-changeslist">';
268 * @param ResultWrapper|array $rows
270 public function initChangesListRows( $rows ) {
271 Hooks
::run( 'ChangesListInitRows', [ $this, $rows ] );
275 * Show formatted char difference
277 * Needs the css module 'mediawiki.special.changeslist' to style output
279 * @param int $old Number of bytes
280 * @param int $new Number of bytes
281 * @param IContextSource $context
284 public static function showCharacterDifference( $old, $new, IContextSource
$context = null ) {
286 $context = RequestContext
::getMain();
291 $szdiff = $new - $old;
293 $lang = $context->getLanguage();
294 $config = $context->getConfig();
295 $code = $lang->getCode();
296 static $fastCharDiff = [];
297 if ( !isset( $fastCharDiff[$code] ) ) {
298 $fastCharDiff[$code] = $config->get( 'MiserMode' )
299 ||
$context->msg( 'rc-change-size' )->plain() === '$1';
302 $formattedSize = $lang->formatNum( $szdiff );
304 if ( !$fastCharDiff[$code] ) {
305 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
308 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
314 if ( $szdiff === 0 ) {
315 $formattedSizeClass = 'mw-plusminus-null';
316 } elseif ( $szdiff > 0 ) {
317 $formattedSize = '+' . $formattedSize;
318 $formattedSizeClass = 'mw-plusminus-pos';
320 $formattedSizeClass = 'mw-plusminus-neg';
323 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
325 return Html
::element( $tag,
326 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
327 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
331 * Format the character difference of one or several changes.
333 * @param RecentChange $old
334 * @param RecentChange $new Last change to use, if not provided, $old will be used
335 * @return string HTML fragment
337 public function formatCharacterDifference( RecentChange
$old, RecentChange
$new = null ) {
338 $oldlen = $old->mAttribs
['rc_old_len'];
341 $newlen = $new->mAttribs
['rc_new_len'];
343 $newlen = $old->mAttribs
['rc_new_len'];
346 if ( $oldlen === null ||
$newlen === null ) {
350 return self
::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
354 * Returns text for the end of RC
357 public function endRecentChangesList() {
358 $out = $this->rclistOpen ?
"</ul>\n" : '';
365 * @param string $s HTML to update
366 * @param mixed $rc_timestamp
368 public function insertDateHeader( &$s, $rc_timestamp ) {
369 # Make date header if necessary
370 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
371 if ( $date != $this->lastdate
) {
372 if ( $this->lastdate
!= '' ) {
375 $s .= Xml
::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
376 $this->lastdate
= $date;
377 $this->rclistOpen
= true;
382 * @param string $s HTML to update
383 * @param Title $title
384 * @param string $logtype
386 public function insertLog( &$s, $title, $logtype ) {
387 $page = new LogPage( $logtype );
388 $logname = $page->getName()->setContext( $this->getContext() )->text();
389 $s .= $this->msg( 'parentheses' )->rawParams(
390 $this->linkRenderer
->makeKnownLink( $title, $logname )
395 * @param string $s HTML to update
396 * @param RecentChange $rc
397 * @param bool|null $unpatrolled Unused variable, since 1.27.
399 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
402 $rc->mAttribs
['rc_type'] == RC_NEW ||
403 $rc->mAttribs
['rc_type'] == RC_LOG ||
404 $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
406 $diffLink = $this->message
['diff'];
407 } elseif ( !self
::userCan( $rc, Revision
::DELETED_TEXT
, $this->getUser() ) ) {
408 $diffLink = $this->message
['diff'];
411 'curid' => $rc->mAttribs
['rc_cur_id'],
412 'diff' => $rc->mAttribs
['rc_this_oldid'],
413 'oldid' => $rc->mAttribs
['rc_last_oldid']
416 $diffLink = $this->linkRenderer
->makeKnownLink(
418 new HtmlArmor( $this->message
['diff'] ),
419 [ 'class' => 'mw-changeslist-diff' ],
423 if ( $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
) {
424 $diffhist = $diffLink . $this->message
['pipe-separator'] . $this->message
['hist'];
426 $diffhist = $diffLink . $this->message
['pipe-separator'];
428 $diffhist .= $this->linkRenderer
->makeKnownLink(
430 new HtmlArmor( $this->message
['hist'] ),
431 [ 'class' => 'mw-changeslist-history' ],
433 'curid' => $rc->mAttribs
['rc_cur_id'],
434 'action' => 'history'
439 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
440 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
441 ' <span class="mw-changeslist-separator">. .</span> ';
445 * @param string $s Article link will be appended to this string, in place.
446 * @param RecentChange $rc
447 * @param bool $unpatrolled
448 * @param bool $watched
449 * @deprecated since 1.27, use getArticleLink instead.
451 public function insertArticleLink( &$s, RecentChange
$rc, $unpatrolled, $watched ) {
452 $s .= $this->getArticleLink( $rc, $unpatrolled, $watched );
456 * @param RecentChange $rc
457 * @param bool $unpatrolled
458 * @param bool $watched
459 * @return string HTML
462 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
464 if ( $rc->getTitle()->isRedirect() ) {
465 $params = [ 'redirect' => 'no' ];
468 $articlelink = $this->linkRenderer
->makeLink(
471 [ 'class' => 'mw-changeslist-title' ],
474 if ( $this->isDeleted( $rc, Revision
::DELETED_TEXT
) ) {
475 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
477 # To allow for boldening pages watched by this user
478 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
480 $articlelink .= $this->getLanguage()->getDirMark();
482 # TODO: Deprecate the $s argument, it seems happily unused.
484 # Avoid PHP 7.1 warning from passing $this by reference
485 $changesList = $this;
486 Hooks
::run( 'ChangesListInsertArticleLink',
487 [ &$changesList, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
489 return "{$s} {$articlelink}";
493 * Get the timestamp from $rc formatted with current user's settings
496 * @param RecentChange $rc
497 * @return string HTML fragment
499 public function getTimestamp( $rc ) {
500 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
501 return $this->message
['semicolon-separator'] . '<span class="mw-changeslist-date">' .
502 $this->getLanguage()->userTime(
503 $rc->mAttribs
['rc_timestamp'],
505 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
509 * Insert time timestamp string from $rc into $s
511 * @param string $s HTML to update
512 * @param RecentChange $rc
514 public function insertTimestamp( &$s, $rc ) {
515 $s .= $this->getTimestamp( $rc );
519 * Insert links to user page, user talk page and eventually a blocking link
521 * @param string &$s HTML to update
522 * @param RecentChange &$rc
524 public function insertUserRelatedLinks( &$s, &$rc ) {
525 if ( $this->isDeleted( $rc, Revision
::DELETED_USER
) ) {
526 $s .= ' <span class="history-deleted">' .
527 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
529 $s .= $this->getLanguage()->getDirMark() . Linker
::userLink( $rc->mAttribs
['rc_user'],
530 $rc->mAttribs
['rc_user_text'] );
531 $s .= Linker
::userToolLinks( $rc->mAttribs
['rc_user'], $rc->mAttribs
['rc_user_text'] );
536 * Insert a formatted action
538 * @param RecentChange $rc
541 public function insertLogEntry( $rc ) {
542 $formatter = LogFormatter
::newFromRow( $rc->mAttribs
);
543 $formatter->setContext( $this->getContext() );
544 $formatter->setShowUserToolLinks( true );
545 $mark = $this->getLanguage()->getDirMark();
547 return $formatter->getActionText() . " $mark" . $formatter->getComment();
551 * Insert a formatted comment
552 * @param RecentChange $rc
555 public function insertComment( $rc ) {
556 if ( $this->isDeleted( $rc, Revision
::DELETED_COMMENT
) ) {
557 return ' <span class="history-deleted">' .
558 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
560 return Linker
::commentBlock( $rc->mAttribs
['rc_comment'], $rc->getTitle() );
565 * Returns the string which indicates the number of watching users
566 * @param int $count Number of user watching a page
569 protected function numberofWatchingusers( $count ) {
573 $cache = $this->watchMsgCache
;
574 return $cache->getWithSetCallback( $count, $cache::TTL_INDEFINITE
,
575 function () use ( $count ) {
576 return $this->msg( 'number_of_watching_users_RCview' )
577 ->numParams( $count )->escaped();
583 * Determine if said field of a revision is hidden
584 * @param RCCacheEntry|RecentChange $rc
585 * @param int $field One of DELETED_* bitfield constants
588 public static function isDeleted( $rc, $field ) {
589 return ( $rc->mAttribs
['rc_deleted'] & $field ) == $field;
593 * Determine if the current user is allowed to view a particular
594 * field of this revision, if it's marked as deleted.
595 * @param RCCacheEntry|RecentChange $rc
597 * @param User $user User object to check, or null to use $wgUser
600 public static function userCan( $rc, $field, User
$user = null ) {
601 if ( $rc->mAttribs
['rc_type'] == RC_LOG
) {
602 return LogEventsList
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
604 return Revision
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
609 * @param string $link
610 * @param bool $watched
613 protected function maybeWatchedLink( $link, $watched = false ) {
615 return '<strong class="mw-watched">' . $link . '</strong>';
617 return '<span class="mw-rc-unwatched">' . $link . '</span>';
621 /** Inserts a rollback link
624 * @param RecentChange $rc
626 public function insertRollback( &$s, &$rc ) {
627 if ( $rc->mAttribs
['rc_type'] == RC_EDIT
628 && $rc->mAttribs
['rc_this_oldid']
629 && $rc->mAttribs
['rc_cur_id']
631 $page = $rc->getTitle();
632 /** Check for rollback and edit permissions, disallow special pages, and only
633 * show a link on the top-most revision */
634 if ( $this->getUser()->isAllowed( 'rollback' )
635 && $rc->mAttribs
['page_latest'] == $rc->mAttribs
['rc_this_oldid']
637 $rev = new Revision( [
639 'id' => $rc->mAttribs
['rc_this_oldid'],
640 'user' => $rc->mAttribs
['rc_user'],
641 'user_text' => $rc->mAttribs
['rc_user_text'],
642 'deleted' => $rc->mAttribs
['rc_deleted']
644 $s .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
650 * @param RecentChange $rc
654 public function getRollback( RecentChange
$rc ) {
656 $this->insertRollback( $s, $rc );
662 * @param RecentChange $rc
663 * @param array $classes
665 public function insertTags( &$s, &$rc, &$classes ) {
666 if ( empty( $rc->mAttribs
['ts_tags'] ) ) {
670 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
671 $rc->mAttribs
['ts_tags'],
675 $classes = array_merge( $classes, $newClasses );
676 $s .= ' ' . $tagSummary;
680 * @param RecentChange $rc
681 * @param array $classes
685 public function getTags( RecentChange
$rc, array &$classes ) {
687 $this->insertTags( $s, $rc, $classes );
691 public function insertExtra( &$s, &$rc, &$classes ) {
692 // Empty, used for subclasses to add anything special.
695 protected function showAsUnpatrolled( RecentChange
$rc ) {
696 return self
::isUnpatrolled( $rc, $this->getUser() );
700 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
704 public static function isUnpatrolled( $rc, User
$user ) {
705 if ( $rc instanceof RecentChange
) {
706 $isPatrolled = $rc->mAttribs
['rc_patrolled'];
707 $rcType = $rc->mAttribs
['rc_type'];
708 $rcLogType = $rc->mAttribs
['rc_log_type'];
710 $isPatrolled = $rc->rc_patrolled
;
711 $rcType = $rc->rc_type
;
712 $rcLogType = $rc->rc_log_type
;
715 if ( !$isPatrolled ) {
716 if ( $user->useRCPatrol() ) {
719 if ( $user->useNPPatrol() && $rcType == RC_NEW
) {
722 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
731 * Determines whether a revision is linked to this change; this may not be the case
732 * when the categorization wasn't done by an edit but a conditional parser function
736 * @param RecentChange|RCCacheEntry $rcObj
739 protected function isCategorizationWithoutRevision( $rcObj ) {
740 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
741 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
745 * Get recommended data attributes for a change line.
746 * @param RecentChange $rc
747 * @return string[] attribute name => value
749 protected function getDataAttributes( RecentChange
$rc ) {
750 $type = $rc->getAttribute( 'rc_source' );
752 case RecentChange
::SRC_EDIT
:
753 case RecentChange
::SRC_NEW
:
755 'data-mw-revid' => $rc->mAttribs
['rc_this_oldid'],
757 case RecentChange
::SRC_LOG
:
759 'data-mw-logid' => $rc->mAttribs
['rc_logid'],
760 'data-mw-logaction' => $rc->mAttribs
['rc_log_type'] . '/' . $rc->mAttribs
['rc_log_action'],