Debian Codegraph @

includes/recentchanges/ChangesList.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 use MediaWiki\CommentFormatter\RowCommentFormatter;
22 use MediaWiki\Context\ContextSource;
23 use MediaWiki\Context\IContextSource;
24 use MediaWiki\Context\RequestContext;
25 use MediaWiki\HookContainer\HookRunner;
26 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
27 use MediaWiki\Html\Html;
28 use MediaWiki\Language\Language;
29 use MediaWiki\Linker\Linker;
30 use MediaWiki\Linker\LinkRenderer;
31 use MediaWiki\MainConfigNames;
32 use MediaWiki\MediaWikiServices;
33 use MediaWiki\Pager\PagerTools;
34 use MediaWiki\Parser\Sanitizer;
35 use MediaWiki\Permissions\Authority;
36 use MediaWiki\Revision\MutableRevisionRecord;
37 use MediaWiki\Revision\RevisionRecord;
38 use MediaWiki\Title\Title;
39 use MediaWiki\User\User;
40 use MediaWiki\User\UserIdentityValue;
41 use MediaWiki\Watchlist\WatchedItem;
42 use OOUI\IconWidget;
43 use Wikimedia\Rdbms\IResultWrapper;
44
45 /**
46 * Base class for lists of recent changes shown on special pages.
47 *
48 * This is used via ChangesListSpecialPage by recent changes (SpecialRecentChanges),
49 * related changes (SpecialRecentChangesLinked), and watchlist (SpecialWatchlist).
50 *
51 * @ingroup RecentChanges
52 */
53 class ChangesList extends ContextSource {
54 use ProtectedHookAccessorTrait;
55
56 public const CSS_CLASS_PREFIX = 'mw-changeslist-';
57
58 /** @var bool */
59 protected $watchlist = false;
60 /** @var string */
61 protected $lastdate;
62 /** @var string[] */
63 protected $message;
64 /** @var array */
65 protected $rc_cache;
66 /** @var int */
67 protected $rcCacheIndex;
68 /** @var bool */
69 protected $rclistOpen;
70 /** @var int */
71 protected $rcMoveIndex;
72
73 /** @var callable */
74 protected $changeLinePrefixer;
75
76 /** @var MapCacheLRU */
77 protected $watchMsgCache;
78
79 /**
80 * @var LinkRenderer
81 */
82 protected $linkRenderer;
83
84 /**
85 * @var RowCommentFormatter
86 */
87 protected $commentFormatter;
88
89 /**
90 * @var string[] Comments indexed by rc_id
91 */
92 protected $formattedComments;
93
94 /**
95 * @var ChangesListFilterGroup[]
96 */
97 protected $filterGroups;
98
99 /**
100 * @var MapCacheLRU
101 */
102 protected $tagsCache;
103
104 /**
105 * @var MapCacheLRU
106 */
107 protected $userLinkCache;
108
109 private LogFormatterFactory $logFormatterFactory;
110
111 /**
112 * @param IContextSource $context
113 * @param ChangesListFilterGroup[] $filterGroups Array of ChangesListFilterGroup objects (currently optional)
114 */
115 public function __construct( $context, array $filterGroups = [] ) {
116 $this->setContext( $context );
117 $this->preCacheMessages();
118 $this->watchMsgCache = new MapCacheLRU( 50 );
119 $this->filterGroups = $filterGroups;
120
121 $services = MediaWikiServices::getInstance();
122 $this->linkRenderer = $services->getLinkRenderer();
123 $this->commentFormatter = $services->getRowCommentFormatter();
124 $this->logFormatterFactory = $services->getLogFormatterFactory();
125 $this->tagsCache = new MapCacheLRU( 50 );
126 $this->userLinkCache = new MapCacheLRU( 50 );
127 }
128
129 /**
130 * Fetch an appropriate changes list class for the specified context
131 * Some users might want to use an enhanced list format, for instance
132 *
133 * @param IContextSource $context
134 * @param array $groups Array of ChangesListFilterGroup objects (currently optional)
135 * @return ChangesList
136 */
137 public static function newFromContext( IContextSource $context, array $groups = [] ) {
138 $user = $context->getUser();
139 $sk = $context->getSkin();
140 $services = MediaWikiServices::getInstance();
141 $list = null;
142 if ( ( new HookRunner( $services->getHookContainer() ) )->onFetchChangesList( $user, $sk, $list, $groups ) ) {
143 $userOptionsLookup = $services->getUserOptionsLookup();
144 $new = $context->getRequest()->getBool(
145 'enhanced',
146 $userOptionsLookup->getBoolOption( $user, 'usenewrc' )
147 );
148
149 return $new ?
150 new EnhancedChangesList( $context, $groups ) :
151 new OldChangesList( $context, $groups );
152 } else {
153 return $list;
154 }
155 }
156
157 /**
158 * Format a line
159 *
160 * @since 1.27
161 *
162 * @param RecentChange &$rc Passed by reference
163 * @param bool $watched (default false)
164 * @param int|null $linenumber (default null)
165 *
166 * @return string|bool
167 */
168 public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
169 throw new RuntimeException( 'recentChangesLine should be implemented' );
170 }
171
172 /**
173 * Get the container for highlights that are used in the new StructuredFilters
174 * system
175 *
176 * @return string HTML structure of the highlight container div
177 */
178 protected function getHighlightsContainerDiv() {
179 $highlightColorDivs = '';
180 foreach ( [ 'none', 'c1', 'c2', 'c3', 'c4', 'c5' ] as $color ) {
181 $highlightColorDivs .= Html::rawElement(
182 'div',
183 [
184 'class' => 'mw-rcfilters-ui-highlights-color-' . $color,
185 'data-color' => $color
186 ]
187 );
188 }
189
190 return Html::rawElement(
191 'div',
192 [ 'class' => 'mw-rcfilters-ui-highlights' ],
193 $highlightColorDivs
194 );
195 }
196
197 /**
198 * Sets the list to use a "<li class='watchlist-(namespace)-(page)'>" tag
199 * @param bool $value
200 */
201 public function setWatchlistDivs( $value = true ) {
202 $this->watchlist = $value;
203 }
204
205 /**
206 * @return bool True when setWatchlistDivs has been called
207 * @since 1.23
208 */
209 public function isWatchlist() {
210 return (bool)$this->watchlist;
211 }
212
213 /**
214 * As we use the same small set of messages in various methods and that
215 * they are called often, we call them once and save them in $this->message
216 */
217 private function preCacheMessages() {
218 if ( !isset( $this->message ) ) {
219 $this->message = [];
220 foreach ( [
221 'cur', 'diff', 'hist', 'enhancedrc-history', 'last', 'blocklink', 'history',
222 'semicolon-separator', 'pipe-separator', 'word-separator' ] as $msg
223 ) {
224 $this->message[$msg] = $this->msg( $msg )->escaped();
225 }
226 }
227 }
228
229 /**
230 * Returns the appropriate flags for new page, minor change and patrolling
231 * @param array $flags Associative array of 'flag' => Bool
232 * @param string $nothing To use for empty space
233 * @return string
234 */
235 public function recentChangesFlags( $flags, $nothing = "\u{00A0}" ) {
236 $f = '';
237 foreach (
238 $this->getConfig()->get( MainConfigNames::RecentChangesFlags ) as $flag => $_
239 ) {
240 $f .= isset( $flags[$flag] ) && $flags[$flag]
241 ? self::flag( $flag, $this->getContext() )
242 : $nothing;
243 }
244
245 return $f;
246 }
247
248 /**
249 * Get an array of default HTML class attributes for the change.
250 *
251 * @param RecentChange|RCCacheEntry $rc
252 * @param string|bool $watched Optionally timestamp for adding watched class
253 *
254 * @return string[] List of CSS class names
255 */
256 protected function getHTMLClasses( $rc, $watched ) {
257 $classes = [ self::CSS_CLASS_PREFIX . 'line' ];
258 $logType = $rc->mAttribs['rc_log_type'];
259
260 if ( $logType ) {
261 $classes[] = self::CSS_CLASS_PREFIX . 'log';
262 $classes[] = Sanitizer::escapeClass( self::CSS_CLASS_PREFIX . 'log-' . $logType );
263 } else {
264 $classes[] = self::CSS_CLASS_PREFIX . 'edit';
265 $classes[] = Sanitizer::escapeClass( self::CSS_CLASS_PREFIX . 'ns' .
266 $rc->mAttribs['rc_namespace'] . '-' . $rc->mAttribs['rc_title'] );
267 }
268
269 // Indicate watched status on the line to allow for more
270 // comprehensive styling.
271 $classes[] = $watched && $rc->mAttribs['rc_timestamp'] >= $watched
272 ? self::CSS_CLASS_PREFIX . 'line-watched'
273 : self::CSS_CLASS_PREFIX . 'line-not-watched';
274
275 $classes = array_merge( $classes, $this->getHTMLClassesForFilters( $rc ) );
276
277 return $classes;
278 }
279
280 /**
281 * Get an array of CSS classes attributed to filters for this row. Used for highlighting
282 * in the front-end.
283 *
284 * @param RecentChange $rc
285 * @return string[] Array of CSS classes
286 */
287 protected function getHTMLClassesForFilters( $rc ) {
288 $classes = [];
289
290 $classes[] = Sanitizer::escapeClass( self::CSS_CLASS_PREFIX . 'ns-' .
291 $rc->mAttribs['rc_namespace'] );
292
293 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
294 $classes[] = Sanitizer::escapeClass(
295 self::CSS_CLASS_PREFIX .
296 'ns-' .
297 ( $nsInfo->isTalk( $rc->mAttribs['rc_namespace'] ) ? 'talk' : 'subject' )
298 );
299
300 foreach ( $this->filterGroups as $filterGroup ) {
301 foreach ( $filterGroup->getFilters() as $filter ) {
302 $filter->applyCssClassIfNeeded( $this, $rc, $classes );
303 }
304 }
305
306 return $classes;
307 }
308
309 /**
310 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
311 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
312 *
313 * Styling for these flags is provided through mediawiki.interface.helpers.styles.
314 *
315 * @param string $flag One key of $wgRecentChangesFlags
316 * @param IContextSource|null $context
317 * @return string HTML
318 */
319 public static function flag( $flag, ?IContextSource $context = null ) {
320 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
321 static $flagInfos = null;
322
323 if ( $flagInfos === null ) {
324 $recentChangesFlags = MediaWikiServices::getInstance()->getMainConfig()
325 ->get( MainConfigNames::RecentChangesFlags );
326 $flagInfos = [];
327 foreach ( $recentChangesFlags as $key => $value ) {
328 $flagInfos[$key]['letter'] = $value['letter'];
329 $flagInfos[$key]['title'] = $value['title'];
330 // Allow customized class name, fall back to flag name
331 $flagInfos[$key]['class'] = $value['class'] ?? $key;
332 }
333 }
334
335 $context = $context ?: RequestContext::getMain();
336
337 // Inconsistent naming, kept for b/c
338 if ( isset( $map[$flag] ) ) {
339 $flag = $map[$flag];
340 }
341
342 $info = $flagInfos[$flag];
343 return Html::element( 'abbr', [
344 'class' => $info['class'],
345 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
346 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
347 }
348
349 /**
350 * Returns text for the start of the tabular part of RC
351 * @return string
352 */
353 public function beginRecentChangesList() {
354 $this->rc_cache = [];
355 $this->rcMoveIndex = 0;
356 $this->rcCacheIndex = 0;
357 $this->lastdate = '';
358 $this->rclistOpen = false;
359 $this->getOutput()->addModuleStyles( [
360 'mediawiki.interface.helpers.styles',
361 'mediawiki.special.changeslist'
362 ] );
363
364 return '<div class="mw-changeslist">';
365 }
366
367 /**
368 * @param IResultWrapper|stdClass[] $rows
369 */
370 public function initChangesListRows( $rows ) {
371 $this->getHookRunner()->onChangesListInitRows( $this, $rows );
372 $this->formattedComments = $this->commentFormatter->createBatch()
373 ->comments(
374 $this->commentFormatter->rows( $rows )
375 ->commentKey( 'rc_comment' )
376 ->namespaceField( 'rc_namespace' )
377 ->titleField( 'rc_title' )
378 ->indexField( 'rc_id' )
379 )
380 ->useBlock()
381 ->execute();
382 }
383
384 /**
385 * Show formatted char difference
386 *
387 * Needs the css module 'mediawiki.special.changeslist' to style output
388 *
389 * @param int $old Number of bytes
390 * @param int $new Number of bytes
391 * @param IContextSource|null $context
392 * @return string
393 */
394 public static function showCharacterDifference( $old, $new, ?IContextSource $context = null ) {
395 if ( !$context ) {
396 $context = RequestContext::getMain();
397 }
398
399 $new = (int)$new;
400 $old = (int)$old;
401 $szdiff = $new - $old;
402
403 $lang = $context->getLanguage();
404 $config = $context->getConfig();
405 $code = $lang->getCode();
406 static $fastCharDiff = [];
407 if ( !isset( $fastCharDiff[$code] ) ) {
408 $fastCharDiff[$code] = $config->get( MainConfigNames::MiserMode )
409 || $context->msg( 'rc-change-size' )->plain() === '$1';
410 }
411
412 $formattedSize = $lang->formatNum( $szdiff );
413
414 if ( !$fastCharDiff[$code] ) {
415 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
416 }
417
418 if ( abs( $szdiff ) > abs( $config->get( MainConfigNames::RCChangedSizeThreshold ) ) ) {
419 $tag = 'strong';
420 } else {
421 $tag = 'span';
422 }
423
424 if ( $szdiff === 0 ) {
425 $formattedSizeClass = 'mw-plusminus-null';
426 } elseif ( $szdiff > 0 ) {
427 $formattedSize = '+' . $formattedSize;
428 $formattedSizeClass = 'mw-plusminus-pos';
429 } else {
430 $formattedSizeClass = 'mw-plusminus-neg';
431 }
432 $formattedSizeClass .= ' mw-diff-bytes';
433
434 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
435
436 return Html::element( $tag,
437 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
438 $formattedSize );
439 }
440
441 /**
442 * Format the character difference of one or several changes.
443 *
444 * @param RecentChange $old
445 * @param RecentChange|null $new Last change to use, if not provided, $old will be used
446 * @return string HTML fragment
447 */
448 public function formatCharacterDifference( RecentChange $old, ?RecentChange $new = null ) {
449 $oldlen = $old->mAttribs['rc_old_len'];
450
451 if ( $new ) {
452 $newlen = $new->mAttribs['rc_new_len'];
453 } else {
454 $newlen = $old->mAttribs['rc_new_len'];
455 }
456
457 if ( $oldlen === null || $newlen === null ) {
458 return '';
459 }
460
461 return self::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
462 }
463
464 /**
465 * Returns text for the end of RC
466 * @return string
467 */
468 public function endRecentChangesList() {
469 $out = $this->rclistOpen ? "</ul>\n" : '';
470 $out .= '</div>';
471
472 return $out;
473 }
474
475 /**
476 * Render the date and time of a revision in the current user language
477 * based on whether the user is able to view this information or not.
478 * @param RevisionRecord $rev
479 * @param Authority $performer
480 * @param Language $lang
481 * @param Title|null $title (optional) where Title does not match
482 * the Title associated with the RevisionRecord
483 * @param string $className (optional) to append to .mw-changelist-date element for access to the
484 * associated timestamp string.
485 * @internal For usage by Pager classes only (e.g. HistoryPager, NewPagesPager and ContribsPager).
486 * @return string HTML
487 */
488 public static function revDateLink(
489 RevisionRecord $rev,
490 Authority $performer,
491 Language $lang,
492 $title = null,
493 $className = ''
494 ) {
495 $ts = $rev->getTimestamp();
496 $time = $lang->userTime( $ts, $performer->getUser() );
497 $date = $lang->userTimeAndDate( $ts, $performer->getUser() );
498 $class = trim( 'mw-changeslist-date ' . $className );
499 if ( $rev->userCan( RevisionRecord::DELETED_TEXT, $performer ) ) {
500 $link = Html::rawElement( 'bdi', [ 'dir' => $lang->getDir() ],
501 MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
502 $title ?? $rev->getPageAsLinkTarget(),
503 $date,
504 [ 'class' => $class ],
505 [ 'oldid' => $rev->getId() ]
506 )
507 );
508 } else {
509 $link = htmlspecialchars( $date );
510 }
511 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
512 $class = Linker::getRevisionDeletedClass( $rev ) . " $class";
513 $link = "<span class=\"$class\">$link</span>";
514 }
515 return Html::element( 'span', [
516 'class' => 'mw-changeslist-time'
517 ], $time ) . $link;
518 }
519
520 /**
521 * @param string &$s HTML to update
522 * @param mixed $rc_timestamp
523 */
524 public function insertDateHeader( &$s, $rc_timestamp ) {
525 # Make date header if necessary
526 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
527 if ( $date != $this->lastdate ) {
528 if ( $this->lastdate != '' ) {
529 $s .= "</ul>\n";
530 }
531 $s .= Html::element( 'h4', [], $date ) . "\n<ul class=\"special\">";
532 $this->lastdate = $date;
533 $this->rclistOpen = true;
534 }
535 }
536
537 /**
538 * @param string &$s HTML to update
539 * @param Title $title
540 * @param string $logtype
541 * @param bool $useParentheses (optional) Wrap log entry in parentheses where needed
542 */
543 public function insertLog( &$s, $title, $logtype, $useParentheses = true ) {
544 $page = new LogPage( $logtype );
545 $logname = $page->getName()->setContext( $this->getContext() )->text();
546 $link = $this->linkRenderer->makeKnownLink( $title, $logname, [
547 'class' => $useParentheses ? '' : 'mw-changeslist-links'
548 ] );
549 if ( $useParentheses ) {
550 $s .= $this->msg( 'parentheses' )->rawParams(
551 $link
552 )->escaped();
553 } else {
554 $s .= $link;
555 }
556 }
557
558 /**
559 * @param string &$s HTML to update
560 * @param RecentChange &$rc
561 * @param bool|null $unpatrolled Unused variable, since 1.27.
562 */
563 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
564 # Diff link
565 if (
566 $rc->mAttribs['rc_type'] == RC_NEW ||
567 $rc->mAttribs['rc_type'] == RC_LOG ||
568 $rc->mAttribs['rc_type'] == RC_CATEGORIZE
569 ) {
570 $diffLink = $this->message['diff'];
571 } elseif ( !self::userCan( $rc, RevisionRecord::DELETED_TEXT, $this->getAuthority() ) ) {
572 $diffLink = $this->message['diff'];
573 } else {
574 $query = [
575 'curid' => $rc->mAttribs['rc_cur_id'],
576 'diff' => $rc->mAttribs['rc_this_oldid'],
577 'oldid' => $rc->mAttribs['rc_last_oldid']
578 ];
579
580 $diffLink = $this->linkRenderer->makeKnownLink(
581 $rc->getTitle(),
582 new HtmlArmor( $this->message['diff'] ),
583 [ 'class' => 'mw-changeslist-diff' ],
584 $query
585 );
586 }
587 if ( $rc->mAttribs['rc_type'] == RC_CATEGORIZE ) {
588 $histLink = $this->message['hist'];
589 } else {
590 $histLink = $this->linkRenderer->makeKnownLink(
591 $rc->getTitle(),
592 new HtmlArmor( $this->message['hist'] ),
593 [ 'class' => 'mw-changeslist-history' ],
594 [
595 'curid' => $rc->mAttribs['rc_cur_id'],
596 'action' => 'history'
597 ]
598 );
599 }
600
601 $s .= Html::rawElement( 'span', [ 'class' => 'mw-changeslist-links' ],
602 Html::rawElement( 'span', [], $diffLink ) .
603 Html::rawElement( 'span', [], $histLink )
604 ) .
605 ' <span class="mw-changeslist-separator"></span> ';
606 }
607
608 /**
609 * Get the HTML link to the changed page, possibly with a prefix from hook handlers, and a
610 * suffix for temporarily watched items.
611 *
612 * @param RecentChange &$rc
613 * @param bool $unpatrolled
614 * @param bool $watched
615 * @return string HTML
616 * @since 1.26
617 */
618 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
619 $params = [];
620 if ( $rc->getTitle()->isRedirect() ) {
621 $params = [ 'redirect' => 'no' ];
622 }
623
624 $articlelink = $this->linkRenderer->makeLink(
625 $rc->getTitle(),
626 null,
627 [ 'class' => 'mw-changeslist-title' ],
628 $params
629 );
630 if ( static::isDeleted( $rc, RevisionRecord::DELETED_TEXT ) ) {
631 $class = 'history-deleted';
632 if ( static::isDeleted( $rc, RevisionRecord::DELETED_RESTRICTED ) ) {
633 $class .= ' mw-history-suppressed';
634 }
635 $articlelink = '<span class="' . $class . '">' . $articlelink . '</span>';
636 }
637 $dir = $this->getLanguage()->getDir();
638 $articlelink = Html::rawElement( 'bdi', [ 'dir' => $dir ], $articlelink );
639 # To allow for boldening pages watched by this user
640 # Don't wrap result of this with another tag, see T376814
641 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
642
643 # TODO: Deprecate the $s argument, it seems happily unused.
644 $s = '';
645 $this->getHookRunner()->onChangesListInsertArticleLink( $this, $articlelink,
646 $s, $rc, $unpatrolled, $watched );
647
648 // Watchlist expiry icon.
649 $watchlistExpiry = '';
650 if ( isset( $rc->watchlistExpiry ) && $rc->watchlistExpiry ) {
651 $watchlistExpiry = $this->getWatchlistExpiry( $rc );
652 }
653
654 return "{$s} {$articlelink}{$watchlistExpiry}";
655 }
656
657 /**
658 * Get HTML to display the clock icon for watched items that have a watchlist expiry time.
659 * @since 1.35
660 * @param RecentChange $recentChange
661 * @return string The HTML to display an indication of the expiry time.
662 */
663 public function getWatchlistExpiry( RecentChange $recentChange ): string {
664 $item = WatchedItem::newFromRecentChange( $recentChange, $this->getUser() );
665 // Guard against expired items, even though they shouldn't come here.
666 if ( $item->isExpired() ) {
667 return '';
668 }
669 $daysLeftText = $item->getExpiryInDaysText( $this->getContext() );
670 // Matching widget is also created in ChangesListSpecialPage, for the legend.
671 $widget = new IconWidget( [
672 'icon' => 'clock',
673 'title' => $daysLeftText,
674 'classes' => [ 'mw-changesList-watchlistExpiry' ],
675 ] );
676 $widget->setAttributes( [
677 // Add labels for assistive technologies.
678 'role' => 'img',
679 'aria-label' => $this->msg( 'watchlist-expires-in-aria-label' )->text(),
680 // Days-left is used in resources/src/mediawiki.special.changeslist.watchlistexpiry/watchlistexpiry.js
681 'data-days-left' => $item->getExpiryInDays(),
682 ] );
683 // Add spaces around the widget (the page title is to one side,
684 // and a semicolon or opening-parenthesis to the other).
685 return " $widget ";
686 }
687
688 /**
689 * Get the timestamp from $rc formatted with current user's settings
690 * and a separator
691 *
692 * @param RecentChange $rc
693 * @deprecated since 1.43; use revDateLink instead.
694 * @return string HTML fragment
695 */
696 public function getTimestamp( $rc ) {
697 // This uses the semi-colon separator unless there's a watchlist expiry date for the entry,
698 // because in that case the timestamp is preceded by a clock icon.
699 // A space is important after `.mw-changeslist-separator--semicolon` to make sure
700 // that whatever comes before it is distinguishable.
701 // (Otherwise your have the text of titles pushing up against the timestamp)
702 // A specific element is used for this purpose rather than styling `.mw-changeslist-date`
703 // as the `.mw-changeslist-date` class is used in a variety
704 // of other places with a different position and the information proceeding getTimestamp can vary.
705 // The `.mw-changeslist-time` class allows us to distinguish from `.mw-changeslist-date` elements that
706 // contain the full date (month, year) and adds consistency with Special:Contributions
707 // and other pages.
708 $separatorClass = $rc->watchlistExpiry ? 'mw-changeslist-separator' : 'mw-changeslist-separator--semicolon';
709 return Html::element( 'span', [ 'class' => $separatorClass ] ) . ' ' .
710 '<span class="mw-changeslist-date mw-changeslist-time">' .
711 htmlspecialchars( $this->getLanguage()->userTime(
712 $rc->mAttribs['rc_timestamp'],
713 $this->getUser()
714 ) ) . '</span> <span class="mw-changeslist-separator"></span> ';
715 }
716
717 /**
718 * Insert time timestamp string from $rc into $s
719 *
720 * @param string &$s HTML to update
721 * @param RecentChange $rc
722 */
723 public function insertTimestamp( &$s, $rc ) {
724 $s .= $this->getTimestamp( $rc );
725 }
726
727 /**
728 * Insert links to user page, user talk page and eventually a blocking link
729 *
730 * @param string &$s HTML to update
731 * @param RecentChange &$rc
732 */
733 public function insertUserRelatedLinks( &$s, &$rc ) {
734 if ( static::isDeleted( $rc, RevisionRecord::DELETED_USER ) ) {
735 $deletedClass = 'history-deleted';
736 if ( static::isDeleted( $rc, RevisionRecord::DELETED_RESTRICTED ) ) {
737 $deletedClass .= ' mw-history-suppressed';
738 }
739 $s .= ' <span class="' . $deletedClass . '">' .
740 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
741 } else {
742 # Don't wrap result of this with another tag, see T376814
743 $s .= $this->userLinkCache->getWithSetCallback(
744 $this->userLinkCache->makeKey(
745 $rc->mAttribs['rc_user_text'],
746 $this->getUser()->getName(),
747 $this->getLanguage()->getCode()
748 ),
749 static function () use ( $rc ) {
750 return Linker::userLink(
751 $rc->mAttribs['rc_user'],
752 $rc->mAttribs['rc_user_text']
753 ) . Linker::userToolLinks(
754 $rc->mAttribs['rc_user'], $rc->mAttribs['rc_user_text'],
755 false, 0, null,
756 // The text content of tools is not wrapped with parentheses or "piped".
757 // This will be handled in CSS (T205581).
758 false
759 );
760 }
761 );
762 }
763 }
764
765 /**
766 * Insert a formatted action
767 *
768 * @param RecentChange $rc
769 * @return string
770 */
771 public function insertLogEntry( $rc ) {
772 $formatter = $this->logFormatterFactory->newFromRow( $rc->mAttribs );
773 $formatter->setContext( $this->getContext() );
774 $formatter->setShowUserToolLinks( true );
775
776 $comment = $formatter->getComment();
777 if ( $comment !== '' ) {
778 $dir = $this->getLanguage()->getDir();
779 $comment = Html::rawElement( 'bdi', [ 'dir' => $dir ], $comment );
780 }
781
782 return Html::openElement( 'span', [ 'class' => 'mw-changeslist-log-entry' ] )
783 . $formatter->getActionText()
784 . ' '
785 . $comment
786 . $this->message['word-separator']
787 . $formatter->getActionLinks()
788 . Html::closeElement( 'span' );
789 }
790
791 /**
792 * Insert a formatted comment
793 * @param RecentChange $rc
794 * @return string
795 */
796 public function insertComment( $rc ) {
797 if ( static::isDeleted( $rc, RevisionRecord::DELETED_COMMENT ) ) {
798 $deletedClass = 'history-deleted';
799 if ( static::isDeleted( $rc, RevisionRecord::DELETED_RESTRICTED ) ) {
800 $deletedClass .= ' mw-history-suppressed';
801 }
802 return ' <span class="' . $deletedClass . ' comment">' .
803 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
804 } elseif ( isset( $rc->mAttribs['rc_id'] )
805 && isset( $this->formattedComments[$rc->mAttribs['rc_id']] )
806 ) {
807 return $this->formattedComments[$rc->mAttribs['rc_id']];
808 } else {
809 return $this->commentFormatter->formatBlock(
810 $rc->mAttribs['rc_comment'],
811 $rc->getTitle(),
812 // Whether section links should refer to local page (using default false)
813 false,
814 // wikid to generate links for (using default null) */
815 null,
816 // whether parentheses should be rendered as part of the message
817 false
818 );
819 }
820 }
821
822 /**
823 * Returns the string which indicates the number of watching users
824 * @param int $count Number of user watching a page
825 * @return string
826 */
827 protected function numberofWatchingusers( $count ) {
828 if ( $count <= 0 ) {
829 return '';
830 }
831
832 return $this->watchMsgCache->getWithSetCallback(
833 $this->watchMsgCache->makeKey(
834 'watching-users-msg',
835 strval( $count ),
836 $this->getUser()->getName(),
837 $this->getLanguage()->getCode()
838 ),
839 function () use ( $count ) {
840 return $this->msg( 'number-of-watching-users-for-recent-changes' )
841 ->numParams( $count )->escaped();
842 }
843 );
844 }
845
846 /**
847 * Determine if said field of a revision is hidden
848 * @param RCCacheEntry|RecentChange $rc
849 * @param int $field One of DELETED_* bitfield constants
850 * @return bool
851 */
852 public static function isDeleted( $rc, $field ) {
853 return ( $rc->mAttribs['rc_deleted'] & $field ) == $field;
854 }
855
856 /**
857 * Determine if the current user is allowed to view a particular
858 * field of this revision, if it's marked as deleted.
859 * @param RCCacheEntry|RecentChange $rc
860 * @param int $field
861 * @param Authority|null $performer to check permissions against. If null, the global RequestContext's
862 * User is assumed instead.
863 * @return bool
864 */
865 public static function userCan( $rc, $field, ?Authority $performer = null ) {
866 $performer ??= RequestContext::getMain()->getAuthority();
867
868 if ( $rc->mAttribs['rc_type'] == RC_LOG ) {
869 return LogEventsList::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $performer );
870 }
871
872 return RevisionRecord::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $performer );
873 }
874
875 /**
876 * @param string $link
877 * @param bool $watched
878 * @return string
879 */
880 protected function maybeWatchedLink( $link, $watched = false ) {
881 if ( $watched ) {
882 return '<strong class="mw-watched">' . $link . '</strong>';
883 } else {
884 return '<span class="mw-rc-unwatched">' . $link . '</span>';
885 }
886 }
887
888 /**
889 * Insert a rollback link
890 *
891 * @param string &$s
892 * @param RecentChange &$rc
893 */
894 public function insertRollback( &$s, &$rc ) {
895 $this->insertPageTools( $s, $rc );
896 }
897
898 /**
899 * Insert an extensible set of page tools into the changelist row
900 * which includes a rollback link and undo link if applicable.
901 *
902 * @param string &$s
903 * @param RecentChange &$rc
904 *
905 */
906 private function insertPageTools( &$s, &$rc ) {
907 // FIXME Some page tools (e.g. thanks) might make sense for log entries.
908 if ( !in_array( $rc->mAttribs['rc_type'], [ RC_EDIT, RC_NEW ] )
909 // FIXME When would either of these not exist when type is RC_EDIT? Document.
910 || !$rc->mAttribs['rc_this_oldid']
911 || !$rc->mAttribs['rc_cur_id']
912 ) {
913 return;
914 }
915
916 // Construct a fake revision for PagerTools. FIXME can't we just obtain the real one?
917 $title = $rc->getTitle();
918 $revRecord = new MutableRevisionRecord( $title );
919 $revRecord->setId( (int)$rc->mAttribs['rc_this_oldid'] );
920 $revRecord->setVisibility( (int)$rc->mAttribs['rc_deleted'] );
921 $user = new UserIdentityValue(
922 (int)$rc->mAttribs['rc_user'],
923 $rc->mAttribs['rc_user_text']
924 );
925 $revRecord->setUser( $user );
926
927 $tools = new PagerTools(
928 $revRecord,
929 null,
930 // only show a rollback link on the top-most revision
931 $rc->getAttribute( 'page_latest' ) == $rc->mAttribs['rc_this_oldid']
932 && $rc->mAttribs['rc_type'] != RC_NEW,
933 $this->getHookRunner(),
934 $title,
935 $this->getContext(),
936 // @todo: Inject
937 MediaWikiServices::getInstance()->getLinkRenderer()
938 );
939
940 $s .= $tools->toHTML();
941 }
942
943 /**
944 * @param RecentChange $rc
945 * @return string
946 * @since 1.26
947 */
948 public function getRollback( RecentChange $rc ) {
949 $s = '';
950 $this->insertRollback( $s, $rc );
951 return $s;
952 }
953
954 /**
955 * @param string &$s
956 * @param RecentChange &$rc
957 * @param string[] &$classes
958 */
959 public function insertTags( &$s, &$rc, &$classes ) {
960 if ( empty( $rc->mAttribs['ts_tags'] ) ) {
961 return;
962 }
963
964 /**
965 * Tags are repeated for a lot of the records, so during single run of RecentChanges, we
966 * should cache those that were already processed as doing that for each record takes
967 * significant amount of time.
968 */
969 [ $tagSummary, $newClasses ] = $this->tagsCache->getWithSetCallback(
970 $this->tagsCache->makeKey(
971 $rc->mAttribs['ts_tags'],
972 $this->getUser()->getName(),
973 $this->getLanguage()->getCode()
974 ),
975 fn () => ChangeTags::formatSummaryRow(
976 $rc->mAttribs['ts_tags'],
977 'changeslist',
978 $this->getContext()
979 )
980 );
981 $classes = array_merge( $classes, $newClasses );
982 $s .= ' ' . $tagSummary;
983 }
984
985 /**
986 * @param RecentChange $rc
987 * @param string[] &$classes
988 * @return string
989 * @since 1.26
990 */
991 public function getTags( RecentChange $rc, array &$classes ) {
992 $s = '';
993 $this->insertTags( $s, $rc, $classes );
994 return $s;
995 }
996
997 public function insertExtra( &$s, &$rc, &$classes ) {
998 // Empty, used for subclasses to add anything special.
999 }
1000
1001 protected function showAsUnpatrolled( RecentChange $rc ) {
1002 return self::isUnpatrolled( $rc, $this->getUser() );
1003 }
1004
1005 /**
1006 * @param stdClass|RecentChange $rc Database row from recentchanges or a RecentChange object
1007 * @param User $user
1008 * @return bool
1009 */
1010 public static function isUnpatrolled( $rc, User $user ) {
1011 if ( $rc instanceof RecentChange ) {
1012 $isPatrolled = $rc->mAttribs['rc_patrolled'];
1013 $rcType = $rc->mAttribs['rc_type'];
1014 $rcLogType = $rc->mAttribs['rc_log_type'];
1015 } else {
1016 $isPatrolled = $rc->rc_patrolled;
1017 $rcType = $rc->rc_type;
1018 $rcLogType = $rc->rc_log_type;
1019 }
1020
1021 if ( $isPatrolled ) {
1022 return false;
1023 }
1024
1025 return $user->useRCPatrol() ||
1026 ( $rcType == RC_NEW && $user->useNPPatrol() ) ||
1027 ( $rcLogType === 'upload' && $user->useFilePatrol() );
1028 }
1029
1030 /**
1031 * Determines whether a revision is linked to this change; this may not be the case
1032 * when the categorization wasn't done by an edit but a conditional parser function
1033 *
1034 * @since 1.27
1035 *
1036 * @param RecentChange|RCCacheEntry $rcObj
1037 * @return bool
1038 */
1039 protected function isCategorizationWithoutRevision( $rcObj ) {
1040 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
1041 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
1042 }
1043
1044 /**
1045 * Get recommended data attributes for a change line.
1046 * @param RecentChange $rc
1047 * @return string[] attribute name => value
1048 */
1049 protected function getDataAttributes( RecentChange $rc ) {
1050 $attrs = [];
1051
1052 $type = $rc->getAttribute( 'rc_source' );
1053 switch ( $type ) {
1054 case RecentChange::SRC_EDIT:
1055 case RecentChange::SRC_CATEGORIZE:
1056 case RecentChange::SRC_NEW:
1057 $attrs['data-mw-revid'] = $rc->mAttribs['rc_this_oldid'];
1058 break;
1059 case RecentChange::SRC_LOG:
1060 $attrs['data-mw-logid'] = $rc->mAttribs['rc_logid'];
1061 $attrs['data-mw-logaction'] =
1062 $rc->mAttribs['rc_log_type'] . '/' . $rc->mAttribs['rc_log_action'];
1063 break;
1064 }
1065
1066 $attrs[ 'data-mw-ts' ] = $rc->getAttribute( 'rc_timestamp' );
1067
1068 return $attrs;
1069 }
1070
1071 /**
1072 * Sets the callable that generates a change line prefix added to the beginning of each line.
1073 *
1074 * @param callable $prefixer Callable to run that generates the change line prefix.
1075 * Takes three parameters: a RecentChange object, a ChangesList object,
1076 * and whether the current entry is a grouped entry.
1077 */
1078 public function setChangeLinePrefixer( callable $prefixer ) {
1079 $this->changeLinePrefixer = $prefixer;
1080 }
1081 }