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'] );
182 // Indicate watched status on the line to allow for more
183 // comprehensive styling.
184 $classes[] = $watched && $rc->mAttribs
['rc_timestamp'] >= $watched
185 ? self
::CSS_CLASS_PREFIX
. 'line-watched'
186 : self
::CSS_CLASS_PREFIX
. 'line-not-watched';
188 $classes = array_merge( $classes, $this->getHTMLClassesForFilters( $rc ) );
194 * Get an array of CSS classes attributed to filters for this row
196 * @param RecentChange $rc
197 * @return array Array of CSS classes
199 protected function getHTMLClassesForFilters( $rc ) {
202 if ( $this->filterGroups
!== null ) {
203 foreach ( $this->filterGroups
as $filterGroup ) {
204 foreach ( $filterGroup->getFilters() as $filter ) {
205 $filter->applyCssClassIfNeeded( $this, $rc, $classes );
214 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
215 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
217 * @param string $flag One key of $wgRecentChangesFlags
218 * @param IContextSource $context
219 * @return string HTML
221 public static function flag( $flag, IContextSource
$context = null ) {
222 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
223 static $flagInfos = null;
225 if ( is_null( $flagInfos ) ) {
226 global $wgRecentChangesFlags;
228 foreach ( $wgRecentChangesFlags as $key => $value ) {
229 $flagInfos[$key]['letter'] = $value['letter'];
230 $flagInfos[$key]['title'] = $value['title'];
231 // Allow customized class name, fall back to flag name
232 $flagInfos[$key]['class'] = isset( $value['class'] ) ?
$value['class'] : $key;
236 $context = $context ?
: RequestContext
::getMain();
238 // Inconsistent naming, kepted for b/c
239 if ( isset( $map[$flag] ) ) {
243 $info = $flagInfos[$flag];
244 return Html
::element( 'abbr', [
245 'class' => $info['class'],
246 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
247 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
251 * Returns text for the start of the tabular part of RC
254 public function beginRecentChangesList() {
255 $this->rc_cache
= [];
256 $this->rcMoveIndex
= 0;
257 $this->rcCacheIndex
= 0;
258 $this->lastdate
= '';
259 $this->rclistOpen
= false;
260 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
262 return '<div class="mw-changeslist">';
266 * @param ResultWrapper|array $rows
268 public function initChangesListRows( $rows ) {
269 Hooks
::run( 'ChangesListInitRows', [ $this, $rows ] );
273 * Show formatted char difference
275 * Needs the css module 'mediawiki.special.changeslist' to style output
277 * @param int $old Number of bytes
278 * @param int $new Number of bytes
279 * @param IContextSource $context
282 public static function showCharacterDifference( $old, $new, IContextSource
$context = null ) {
284 $context = RequestContext
::getMain();
289 $szdiff = $new - $old;
291 $lang = $context->getLanguage();
292 $config = $context->getConfig();
293 $code = $lang->getCode();
294 static $fastCharDiff = [];
295 if ( !isset( $fastCharDiff[$code] ) ) {
296 $fastCharDiff[$code] = $config->get( 'MiserMode' )
297 ||
$context->msg( 'rc-change-size' )->plain() === '$1';
300 $formattedSize = $lang->formatNum( $szdiff );
302 if ( !$fastCharDiff[$code] ) {
303 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
306 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
312 if ( $szdiff === 0 ) {
313 $formattedSizeClass = 'mw-plusminus-null';
314 } elseif ( $szdiff > 0 ) {
315 $formattedSize = '+' . $formattedSize;
316 $formattedSizeClass = 'mw-plusminus-pos';
318 $formattedSizeClass = 'mw-plusminus-neg';
321 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
323 return Html
::element( $tag,
324 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
325 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
329 * Format the character difference of one or several changes.
331 * @param RecentChange $old
332 * @param RecentChange $new Last change to use, if not provided, $old will be used
333 * @return string HTML fragment
335 public function formatCharacterDifference( RecentChange
$old, RecentChange
$new = null ) {
336 $oldlen = $old->mAttribs
['rc_old_len'];
339 $newlen = $new->mAttribs
['rc_new_len'];
341 $newlen = $old->mAttribs
['rc_new_len'];
344 if ( $oldlen === null ||
$newlen === null ) {
348 return self
::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
352 * Returns text for the end of RC
355 public function endRecentChangesList() {
356 $out = $this->rclistOpen ?
"</ul>\n" : '';
363 * @param string $s HTML to update
364 * @param mixed $rc_timestamp
366 public function insertDateHeader( &$s, $rc_timestamp ) {
367 # Make date header if necessary
368 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
369 if ( $date != $this->lastdate
) {
370 if ( $this->lastdate
!= '' ) {
373 $s .= Xml
::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
374 $this->lastdate
= $date;
375 $this->rclistOpen
= true;
380 * @param string $s HTML to update
381 * @param Title $title
382 * @param string $logtype
384 public function insertLog( &$s, $title, $logtype ) {
385 $page = new LogPage( $logtype );
386 $logname = $page->getName()->setContext( $this->getContext() )->text();
387 $s .= $this->msg( 'parentheses' )->rawParams(
388 $this->linkRenderer
->makeKnownLink( $title, $logname )
393 * @param string $s HTML to update
394 * @param RecentChange $rc
395 * @param bool|null $unpatrolled Unused variable, since 1.27.
397 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
400 $rc->mAttribs
['rc_type'] == RC_NEW ||
401 $rc->mAttribs
['rc_type'] == RC_LOG ||
402 $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
404 $diffLink = $this->message
['diff'];
405 } elseif ( !self
::userCan( $rc, Revision
::DELETED_TEXT
, $this->getUser() ) ) {
406 $diffLink = $this->message
['diff'];
409 'curid' => $rc->mAttribs
['rc_cur_id'],
410 'diff' => $rc->mAttribs
['rc_this_oldid'],
411 'oldid' => $rc->mAttribs
['rc_last_oldid']
414 $diffLink = $this->linkRenderer
->makeKnownLink(
416 new HtmlArmor( $this->message
['diff'] ),
417 [ 'class' => 'mw-changeslist-diff' ],
421 if ( $rc->mAttribs
['rc_type'] == RC_CATEGORIZE
) {
422 $diffhist = $diffLink . $this->message
['pipe-separator'] . $this->message
['hist'];
424 $diffhist = $diffLink . $this->message
['pipe-separator'];
426 $diffhist .= $this->linkRenderer
->makeKnownLink(
428 new HtmlArmor( $this->message
['hist'] ),
429 [ 'class' => 'mw-changeslist-history' ],
431 'curid' => $rc->mAttribs
['rc_cur_id'],
432 'action' => 'history'
437 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
438 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
439 ' <span class="mw-changeslist-separator">. .</span> ';
443 * @param string $s Article link will be appended to this string, in place.
444 * @param RecentChange $rc
445 * @param bool $unpatrolled
446 * @param bool $watched
447 * @deprecated since 1.27, use getArticleLink instead.
449 public function insertArticleLink( &$s, RecentChange
$rc, $unpatrolled, $watched ) {
450 $s .= $this->getArticleLink( $rc, $unpatrolled, $watched );
454 * @param RecentChange $rc
455 * @param bool $unpatrolled
456 * @param bool $watched
457 * @return string HTML
460 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
462 if ( $rc->getTitle()->isRedirect() ) {
463 $params = [ 'redirect' => 'no' ];
466 $articlelink = $this->linkRenderer
->makeLink(
469 [ 'class' => 'mw-changeslist-title' ],
472 if ( $this->isDeleted( $rc, Revision
::DELETED_TEXT
) ) {
473 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
475 # To allow for boldening pages watched by this user
476 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
478 $articlelink .= $this->getLanguage()->getDirMark();
480 # TODO: Deprecate the $s argument, it seems happily unused.
482 # Avoid PHP 7.1 warning from passing $this by reference
483 $changesList = $this;
484 Hooks
::run( 'ChangesListInsertArticleLink',
485 [ &$changesList, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
487 return "{$s} {$articlelink}";
491 * Get the timestamp from $rc formatted with current user's settings
494 * @param RecentChange $rc
495 * @return string HTML fragment
497 public function getTimestamp( $rc ) {
498 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
499 return $this->message
['semicolon-separator'] . '<span class="mw-changeslist-date">' .
500 $this->getLanguage()->userTime(
501 $rc->mAttribs
['rc_timestamp'],
503 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
507 * Insert time timestamp string from $rc into $s
509 * @param string $s HTML to update
510 * @param RecentChange $rc
512 public function insertTimestamp( &$s, $rc ) {
513 $s .= $this->getTimestamp( $rc );
517 * Insert links to user page, user talk page and eventually a blocking link
519 * @param string &$s HTML to update
520 * @param RecentChange &$rc
522 public function insertUserRelatedLinks( &$s, &$rc ) {
523 if ( $this->isDeleted( $rc, Revision
::DELETED_USER
) ) {
524 $s .= ' <span class="history-deleted">' .
525 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
527 $s .= $this->getLanguage()->getDirMark() . Linker
::userLink( $rc->mAttribs
['rc_user'],
528 $rc->mAttribs
['rc_user_text'] );
529 $s .= Linker
::userToolLinks( $rc->mAttribs
['rc_user'], $rc->mAttribs
['rc_user_text'] );
534 * Insert a formatted action
536 * @param RecentChange $rc
539 public function insertLogEntry( $rc ) {
540 $formatter = LogFormatter
::newFromRow( $rc->mAttribs
);
541 $formatter->setContext( $this->getContext() );
542 $formatter->setShowUserToolLinks( true );
543 $mark = $this->getLanguage()->getDirMark();
545 return $formatter->getActionText() . " $mark" . $formatter->getComment();
549 * Insert a formatted comment
550 * @param RecentChange $rc
553 public function insertComment( $rc ) {
554 if ( $this->isDeleted( $rc, Revision
::DELETED_COMMENT
) ) {
555 return ' <span class="history-deleted">' .
556 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
558 return Linker
::commentBlock( $rc->mAttribs
['rc_comment'], $rc->getTitle() );
563 * Returns the string which indicates the number of watching users
564 * @param int $count Number of user watching a page
567 protected function numberofWatchingusers( $count ) {
571 $cache = $this->watchMsgCache
;
572 return $cache->getWithSetCallback( $count, $cache::TTL_INDEFINITE
,
573 function () use ( $count ) {
574 return $this->msg( 'number_of_watching_users_RCview' )
575 ->numParams( $count )->escaped();
581 * Determine if said field of a revision is hidden
582 * @param RCCacheEntry|RecentChange $rc
583 * @param int $field One of DELETED_* bitfield constants
586 public static function isDeleted( $rc, $field ) {
587 return ( $rc->mAttribs
['rc_deleted'] & $field ) == $field;
591 * Determine if the current user is allowed to view a particular
592 * field of this revision, if it's marked as deleted.
593 * @param RCCacheEntry|RecentChange $rc
595 * @param User $user User object to check, or null to use $wgUser
598 public static function userCan( $rc, $field, User
$user = null ) {
599 if ( $rc->mAttribs
['rc_type'] == RC_LOG
) {
600 return LogEventsList
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
602 return Revision
::userCanBitfield( $rc->mAttribs
['rc_deleted'], $field, $user );
607 * @param string $link
608 * @param bool $watched
611 protected function maybeWatchedLink( $link, $watched = false ) {
613 return '<strong class="mw-watched">' . $link . '</strong>';
615 return '<span class="mw-rc-unwatched">' . $link . '</span>';
619 /** Inserts a rollback link
622 * @param RecentChange $rc
624 public function insertRollback( &$s, &$rc ) {
625 if ( $rc->mAttribs
['rc_type'] == RC_EDIT
626 && $rc->mAttribs
['rc_this_oldid']
627 && $rc->mAttribs
['rc_cur_id']
629 $page = $rc->getTitle();
630 /** Check for rollback and edit permissions, disallow special pages, and only
631 * show a link on the top-most revision */
632 if ( $this->getUser()->isAllowed( 'rollback' )
633 && $rc->mAttribs
['page_latest'] == $rc->mAttribs
['rc_this_oldid']
635 $rev = new Revision( [
637 'id' => $rc->mAttribs
['rc_this_oldid'],
638 'user' => $rc->mAttribs
['rc_user'],
639 'user_text' => $rc->mAttribs
['rc_user_text'],
640 'deleted' => $rc->mAttribs
['rc_deleted']
642 $s .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
648 * @param RecentChange $rc
652 public function getRollback( RecentChange
$rc ) {
654 $this->insertRollback( $s, $rc );
660 * @param RecentChange $rc
661 * @param array $classes
663 public function insertTags( &$s, &$rc, &$classes ) {
664 if ( empty( $rc->mAttribs
['ts_tags'] ) ) {
668 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
669 $rc->mAttribs
['ts_tags'],
673 $classes = array_merge( $classes, $newClasses );
674 $s .= ' ' . $tagSummary;
678 * @param RecentChange $rc
679 * @param array $classes
683 public function getTags( RecentChange
$rc, array &$classes ) {
685 $this->insertTags( $s, $rc, $classes );
689 public function insertExtra( &$s, &$rc, &$classes ) {
690 // Empty, used for subclasses to add anything special.
693 protected function showAsUnpatrolled( RecentChange
$rc ) {
694 return self
::isUnpatrolled( $rc, $this->getUser() );
698 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
702 public static function isUnpatrolled( $rc, User
$user ) {
703 if ( $rc instanceof RecentChange
) {
704 $isPatrolled = $rc->mAttribs
['rc_patrolled'];
705 $rcType = $rc->mAttribs
['rc_type'];
706 $rcLogType = $rc->mAttribs
['rc_log_type'];
708 $isPatrolled = $rc->rc_patrolled
;
709 $rcType = $rc->rc_type
;
710 $rcLogType = $rc->rc_log_type
;
713 if ( !$isPatrolled ) {
714 if ( $user->useRCPatrol() ) {
717 if ( $user->useNPPatrol() && $rcType == RC_NEW
) {
720 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
729 * Determines whether a revision is linked to this change; this may not be the case
730 * when the categorization wasn't done by an edit but a conditional parser function
734 * @param RecentChange|RCCacheEntry $rcObj
737 protected function isCategorizationWithoutRevision( $rcObj ) {
738 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
739 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;