Replace use of &$this
[lhc/web/wiklou.git] / includes / changes / ChangesList.php
1 <?php
2 /**
3 * Base class for all changes lists.
4 *
5 * The class is used for formatting recent changes, related changes and watchlist.
6 *
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.
11 *
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.
16 *
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
21 *
22 * @file
23 */
24 use MediaWiki\Linker\LinkRenderer;
25 use MediaWiki\MediaWikiServices;
26
27 class ChangesList extends ContextSource {
28 /**
29 * @var Skin
30 */
31 public $skin;
32
33 protected $watchlist = false;
34 protected $lastdate;
35 protected $message;
36 protected $rc_cache;
37 protected $rcCacheIndex;
38 protected $rclistOpen;
39 protected $rcMoveIndex;
40
41 /** @var BagOStuff */
42 protected $watchMsgCache;
43
44 /**
45 * @var LinkRenderer
46 */
47 protected $linkRenderer;
48
49 /**
50 * Changeslist constructor
51 *
52 * @param Skin|IContextSource $obj
53 */
54 public function __construct( $obj ) {
55 if ( $obj instanceof IContextSource ) {
56 $this->setContext( $obj );
57 $this->skin = $obj->getSkin();
58 } else {
59 $this->setContext( $obj->getContext() );
60 $this->skin = $obj;
61 }
62 $this->preCacheMessages();
63 $this->watchMsgCache = new HashBagOStuff( [ 'maxKeys' => 50 ] );
64 $this->linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
65 }
66
67 /**
68 * Fetch an appropriate changes list class for the specified context
69 * Some users might want to use an enhanced list format, for instance
70 *
71 * @param IContextSource $context
72 * @return ChangesList
73 */
74 public static function newFromContext( IContextSource $context ) {
75 $user = $context->getUser();
76 $sk = $context->getSkin();
77 $list = null;
78 if ( Hooks::run( 'FetchChangesList', [ $user, &$sk, &$list ] ) ) {
79 $new = $context->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) );
80
81 return $new ? new EnhancedChangesList( $context ) : new OldChangesList( $context );
82 } else {
83 return $list;
84 }
85 }
86
87 /**
88 * Format a line
89 *
90 * @since 1.27
91 *
92 * @param RecentChange $rc Passed by reference
93 * @param bool $watched (default false)
94 * @param int $linenumber (default null)
95 *
96 * @return string|bool
97 */
98 public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
99 throw new RuntimeException( 'recentChangesLine should be implemented' );
100 }
101
102 /**
103 * Sets the list to use a "<li class='watchlist-(namespace)-(page)'>" tag
104 * @param bool $value
105 */
106 public function setWatchlistDivs( $value = true ) {
107 $this->watchlist = $value;
108 }
109
110 /**
111 * @return bool True when setWatchlistDivs has been called
112 * @since 1.23
113 */
114 public function isWatchlist() {
115 return (bool)$this->watchlist;
116 }
117
118 /**
119 * As we use the same small set of messages in various methods and that
120 * they are called often, we call them once and save them in $this->message
121 */
122 private function preCacheMessages() {
123 if ( !isset( $this->message ) ) {
124 foreach ( [
125 'cur', 'diff', 'hist', 'enhancedrc-history', 'last', 'blocklink', 'history',
126 'semicolon-separator', 'pipe-separator' ] as $msg
127 ) {
128 $this->message[$msg] = $this->msg( $msg )->escaped();
129 }
130 }
131 }
132
133 /**
134 * Returns the appropriate flags for new page, minor change and patrolling
135 * @param array $flags Associative array of 'flag' => Bool
136 * @param string $nothing To use for empty space
137 * @return string
138 */
139 public function recentChangesFlags( $flags, $nothing = '&#160;' ) {
140 $f = '';
141 foreach ( array_keys( $this->getConfig()->get( 'RecentChangesFlags' ) ) as $flag ) {
142 $f .= isset( $flags[$flag] ) && $flags[$flag]
143 ? self::flag( $flag, $this->getContext() )
144 : $nothing;
145 }
146
147 return $f;
148 }
149
150 /**
151 * Get an array of default HTML class attributes for the change.
152 *
153 * @param RecentChange|RCCacheEntry $rc
154 * @param string|bool $watched Optionally timestamp for adding watched class
155 *
156 * @return array of classes
157 */
158 protected function getHTMLClasses( $rc, $watched ) {
159 $classes = [];
160 $logType = $rc->mAttribs['rc_log_type'];
161
162 if ( $logType ) {
163 $classes[] = Sanitizer::escapeClass( 'mw-changeslist-log-' . $logType );
164 } else {
165 $classes[] = Sanitizer::escapeClass( 'mw-changeslist-ns' .
166 $rc->mAttribs['rc_namespace'] . '-' . $rc->mAttribs['rc_title'] );
167 }
168
169 // Indicate watched status on the line to allow for more
170 // comprehensive styling.
171 $classes[] = $watched && $rc->mAttribs['rc_timestamp'] >= $watched
172 ? 'mw-changeslist-line-watched'
173 : 'mw-changeslist-line-not-watched';
174
175 return $classes;
176 }
177
178 /**
179 * Make an "<abbr>" element for a given change flag. The flag indicating a new page, minor edit,
180 * bot edit, or unpatrolled edit. In English it typically contains "N", "m", "b", or "!".
181 *
182 * @param string $flag One key of $wgRecentChangesFlags
183 * @param IContextSource $context
184 * @return string HTML
185 */
186 public static function flag( $flag, IContextSource $context = null ) {
187 static $map = [ 'minoredit' => 'minor', 'botedit' => 'bot' ];
188 static $flagInfos = null;
189
190 if ( is_null( $flagInfos ) ) {
191 global $wgRecentChangesFlags;
192 $flagInfos = [];
193 foreach ( $wgRecentChangesFlags as $key => $value ) {
194 $flagInfos[$key]['letter'] = $value['letter'];
195 $flagInfos[$key]['title'] = $value['title'];
196 // Allow customized class name, fall back to flag name
197 $flagInfos[$key]['class'] = isset( $value['class'] ) ? $value['class'] : $key;
198 }
199 }
200
201 $context = $context ?: RequestContext::getMain();
202
203 // Inconsistent naming, kepted for b/c
204 if ( isset( $map[$flag] ) ) {
205 $flag = $map[$flag];
206 }
207
208 $info = $flagInfos[$flag];
209 return Html::element( 'abbr', [
210 'class' => $info['class'],
211 'title' => wfMessage( $info['title'] )->setContext( $context )->text(),
212 ], wfMessage( $info['letter'] )->setContext( $context )->text() );
213 }
214
215 /**
216 * Returns text for the start of the tabular part of RC
217 * @return string
218 */
219 public function beginRecentChangesList() {
220 $this->rc_cache = [];
221 $this->rcMoveIndex = 0;
222 $this->rcCacheIndex = 0;
223 $this->lastdate = '';
224 $this->rclistOpen = false;
225 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
226
227 return '<div class="mw-changeslist">';
228 }
229
230 /**
231 * @param ResultWrapper|array $rows
232 */
233 public function initChangesListRows( $rows ) {
234 Hooks::run( 'ChangesListInitRows', [ $this, $rows ] );
235 }
236
237 /**
238 * Show formatted char difference
239 *
240 * Needs the css module 'mediawiki.special.changeslist' to style output
241 *
242 * @param int $old Number of bytes
243 * @param int $new Number of bytes
244 * @param IContextSource $context
245 * @return string
246 */
247 public static function showCharacterDifference( $old, $new, IContextSource $context = null ) {
248 if ( !$context ) {
249 $context = RequestContext::getMain();
250 }
251
252 $new = (int)$new;
253 $old = (int)$old;
254 $szdiff = $new - $old;
255
256 $lang = $context->getLanguage();
257 $config = $context->getConfig();
258 $code = $lang->getCode();
259 static $fastCharDiff = [];
260 if ( !isset( $fastCharDiff[$code] ) ) {
261 $fastCharDiff[$code] = $config->get( 'MiserMode' )
262 || $context->msg( 'rc-change-size' )->plain() === '$1';
263 }
264
265 $formattedSize = $lang->formatNum( $szdiff );
266
267 if ( !$fastCharDiff[$code] ) {
268 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
269 }
270
271 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
272 $tag = 'strong';
273 } else {
274 $tag = 'span';
275 }
276
277 if ( $szdiff === 0 ) {
278 $formattedSizeClass = 'mw-plusminus-null';
279 } elseif ( $szdiff > 0 ) {
280 $formattedSize = '+' . $formattedSize;
281 $formattedSizeClass = 'mw-plusminus-pos';
282 } else {
283 $formattedSizeClass = 'mw-plusminus-neg';
284 }
285
286 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
287
288 return Html::element( $tag,
289 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
290 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
291 }
292
293 /**
294 * Format the character difference of one or several changes.
295 *
296 * @param RecentChange $old
297 * @param RecentChange $new Last change to use, if not provided, $old will be used
298 * @return string HTML fragment
299 */
300 public function formatCharacterDifference( RecentChange $old, RecentChange $new = null ) {
301 $oldlen = $old->mAttribs['rc_old_len'];
302
303 if ( $new ) {
304 $newlen = $new->mAttribs['rc_new_len'];
305 } else {
306 $newlen = $old->mAttribs['rc_new_len'];
307 }
308
309 if ( $oldlen === null || $newlen === null ) {
310 return '';
311 }
312
313 return self::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
314 }
315
316 /**
317 * Returns text for the end of RC
318 * @return string
319 */
320 public function endRecentChangesList() {
321 $out = $this->rclistOpen ? "</ul>\n" : '';
322 $out .= '</div>';
323
324 return $out;
325 }
326
327 /**
328 * @param string $s HTML to update
329 * @param mixed $rc_timestamp
330 */
331 public function insertDateHeader( &$s, $rc_timestamp ) {
332 # Make date header if necessary
333 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
334 if ( $date != $this->lastdate ) {
335 if ( $this->lastdate != '' ) {
336 $s .= "</ul>\n";
337 }
338 $s .= Xml::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
339 $this->lastdate = $date;
340 $this->rclistOpen = true;
341 }
342 }
343
344 /**
345 * @param string $s HTML to update
346 * @param Title $title
347 * @param string $logtype
348 */
349 public function insertLog( &$s, $title, $logtype ) {
350 $page = new LogPage( $logtype );
351 $logname = $page->getName()->setContext( $this->getContext() )->text();
352 $s .= $this->msg( 'parentheses' )->rawParams(
353 $this->linkRenderer->makeKnownLink( $title, $logname )
354 )->escaped();
355 }
356
357 /**
358 * @param string $s HTML to update
359 * @param RecentChange $rc
360 * @param bool|null $unpatrolled Unused variable, since 1.27.
361 */
362 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
363 # Diff link
364 if (
365 $rc->mAttribs['rc_type'] == RC_NEW ||
366 $rc->mAttribs['rc_type'] == RC_LOG ||
367 $rc->mAttribs['rc_type'] == RC_CATEGORIZE
368 ) {
369 $diffLink = $this->message['diff'];
370 } elseif ( !self::userCan( $rc, Revision::DELETED_TEXT, $this->getUser() ) ) {
371 $diffLink = $this->message['diff'];
372 } else {
373 $query = [
374 'curid' => $rc->mAttribs['rc_cur_id'],
375 'diff' => $rc->mAttribs['rc_this_oldid'],
376 'oldid' => $rc->mAttribs['rc_last_oldid']
377 ];
378
379 $diffLink = $this->linkRenderer->makeKnownLink(
380 $rc->getTitle(),
381 new HtmlArmor( $this->message['diff'] ),
382 [],
383 $query
384 );
385 }
386 if ( $rc->mAttribs['rc_type'] == RC_CATEGORIZE ) {
387 $diffhist = $diffLink . $this->message['pipe-separator'] . $this->message['hist'];
388 } else {
389 $diffhist = $diffLink . $this->message['pipe-separator'];
390 # History link
391 $diffhist .= $this->linkRenderer->makeKnownLink(
392 $rc->getTitle(),
393 new HtmlArmor( $this->message['hist'] ),
394 [],
395 [
396 'curid' => $rc->mAttribs['rc_cur_id'],
397 'action' => 'history'
398 ]
399 );
400 }
401
402 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
403 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
404 ' <span class="mw-changeslist-separator">. .</span> ';
405 }
406
407 /**
408 * @param string $s Article link will be appended to this string, in place.
409 * @param RecentChange $rc
410 * @param bool $unpatrolled
411 * @param bool $watched
412 * @deprecated since 1.27, use getArticleLink instead.
413 */
414 public function insertArticleLink( &$s, RecentChange $rc, $unpatrolled, $watched ) {
415 $s .= $this->getArticleLink( $rc, $unpatrolled, $watched );
416 }
417
418 /**
419 * @param RecentChange $rc
420 * @param bool $unpatrolled
421 * @param bool $watched
422 * @return string HTML
423 * @since 1.26
424 */
425 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
426 $params = [];
427 if ( $rc->getTitle()->isRedirect() ) {
428 $params = [ 'redirect' => 'no' ];
429 }
430
431 $articlelink = $this->linkRenderer->makeLink(
432 $rc->getTitle(),
433 null,
434 [ 'class' => 'mw-changeslist-title' ],
435 $params
436 );
437 if ( $this->isDeleted( $rc, Revision::DELETED_TEXT ) ) {
438 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
439 }
440 # To allow for boldening pages watched by this user
441 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
442 # RTL/LTR marker
443 $articlelink .= $this->getLanguage()->getDirMark();
444
445 # TODO: Deprecate the $s argument, it seems happily unused.
446 $s = '';
447 # Avoid PHP 7.1 warning from passing $this by reference
448 $changesList = $this;
449 Hooks::run( 'ChangesListInsertArticleLink',
450 [ &$changesList, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
451
452 return "{$s} {$articlelink}";
453 }
454
455 /**
456 * Get the timestamp from $rc formatted with current user's settings
457 * and a separator
458 *
459 * @param RecentChange $rc
460 * @return string HTML fragment
461 */
462 public function getTimestamp( $rc ) {
463 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
464 return $this->message['semicolon-separator'] . '<span class="mw-changeslist-date">' .
465 $this->getLanguage()->userTime(
466 $rc->mAttribs['rc_timestamp'],
467 $this->getUser()
468 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
469 }
470
471 /**
472 * Insert time timestamp string from $rc into $s
473 *
474 * @param string $s HTML to update
475 * @param RecentChange $rc
476 */
477 public function insertTimestamp( &$s, $rc ) {
478 $s .= $this->getTimestamp( $rc );
479 }
480
481 /**
482 * Insert links to user page, user talk page and eventually a blocking link
483 *
484 * @param string &$s HTML to update
485 * @param RecentChange &$rc
486 */
487 public function insertUserRelatedLinks( &$s, &$rc ) {
488 if ( $this->isDeleted( $rc, Revision::DELETED_USER ) ) {
489 $s .= ' <span class="history-deleted">' .
490 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
491 } else {
492 $s .= $this->getLanguage()->getDirMark() . Linker::userLink( $rc->mAttribs['rc_user'],
493 $rc->mAttribs['rc_user_text'] );
494 $s .= Linker::userToolLinks( $rc->mAttribs['rc_user'], $rc->mAttribs['rc_user_text'] );
495 }
496 }
497
498 /**
499 * Insert a formatted action
500 *
501 * @param RecentChange $rc
502 * @return string
503 */
504 public function insertLogEntry( $rc ) {
505 $formatter = LogFormatter::newFromRow( $rc->mAttribs );
506 $formatter->setContext( $this->getContext() );
507 $formatter->setShowUserToolLinks( true );
508 $mark = $this->getLanguage()->getDirMark();
509
510 return $formatter->getActionText() . " $mark" . $formatter->getComment();
511 }
512
513 /**
514 * Insert a formatted comment
515 * @param RecentChange $rc
516 * @return string
517 */
518 public function insertComment( $rc ) {
519 if ( $this->isDeleted( $rc, Revision::DELETED_COMMENT ) ) {
520 return ' <span class="history-deleted">' .
521 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
522 } else {
523 return Linker::commentBlock( $rc->mAttribs['rc_comment'], $rc->getTitle() );
524 }
525 }
526
527 /**
528 * Returns the string which indicates the number of watching users
529 * @param int $count Number of user watching a page
530 * @return string
531 */
532 protected function numberofWatchingusers( $count ) {
533 if ( $count <= 0 ) {
534 return '';
535 }
536 $cache = $this->watchMsgCache;
537 return $cache->getWithSetCallback( $count, $cache::TTL_INDEFINITE,
538 function () use ( $count ) {
539 return $this->msg( 'number_of_watching_users_RCview' )
540 ->numParams( $count )->escaped();
541 }
542 );
543 }
544
545 /**
546 * Determine if said field of a revision is hidden
547 * @param RCCacheEntry|RecentChange $rc
548 * @param int $field One of DELETED_* bitfield constants
549 * @return bool
550 */
551 public static function isDeleted( $rc, $field ) {
552 return ( $rc->mAttribs['rc_deleted'] & $field ) == $field;
553 }
554
555 /**
556 * Determine if the current user is allowed to view a particular
557 * field of this revision, if it's marked as deleted.
558 * @param RCCacheEntry|RecentChange $rc
559 * @param int $field
560 * @param User $user User object to check, or null to use $wgUser
561 * @return bool
562 */
563 public static function userCan( $rc, $field, User $user = null ) {
564 if ( $rc->mAttribs['rc_type'] == RC_LOG ) {
565 return LogEventsList::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $user );
566 } else {
567 return Revision::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $user );
568 }
569 }
570
571 /**
572 * @param string $link
573 * @param bool $watched
574 * @return string
575 */
576 protected function maybeWatchedLink( $link, $watched = false ) {
577 if ( $watched ) {
578 return '<strong class="mw-watched">' . $link . '</strong>';
579 } else {
580 return '<span class="mw-rc-unwatched">' . $link . '</span>';
581 }
582 }
583
584 /** Inserts a rollback link
585 *
586 * @param string $s
587 * @param RecentChange $rc
588 */
589 public function insertRollback( &$s, &$rc ) {
590 if ( $rc->mAttribs['rc_type'] == RC_EDIT
591 && $rc->mAttribs['rc_this_oldid']
592 && $rc->mAttribs['rc_cur_id']
593 ) {
594 $page = $rc->getTitle();
595 /** Check for rollback and edit permissions, disallow special pages, and only
596 * show a link on the top-most revision */
597 if ( $this->getUser()->isAllowed( 'rollback' )
598 && $rc->mAttribs['page_latest'] == $rc->mAttribs['rc_this_oldid']
599 ) {
600 $rev = new Revision( [
601 'title' => $page,
602 'id' => $rc->mAttribs['rc_this_oldid'],
603 'user' => $rc->mAttribs['rc_user'],
604 'user_text' => $rc->mAttribs['rc_user_text'],
605 'deleted' => $rc->mAttribs['rc_deleted']
606 ] );
607 $s .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
608 }
609 }
610 }
611
612 /**
613 * @param RecentChange $rc
614 * @return string
615 * @since 1.26
616 */
617 public function getRollback( RecentChange $rc ) {
618 $s = '';
619 $this->insertRollback( $s, $rc );
620 return $s;
621 }
622
623 /**
624 * @param string $s
625 * @param RecentChange $rc
626 * @param array $classes
627 */
628 public function insertTags( &$s, &$rc, &$classes ) {
629 if ( empty( $rc->mAttribs['ts_tags'] ) ) {
630 return;
631 }
632
633 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
634 $rc->mAttribs['ts_tags'],
635 'changeslist',
636 $this->getContext()
637 );
638 $classes = array_merge( $classes, $newClasses );
639 $s .= ' ' . $tagSummary;
640 }
641
642 /**
643 * @param RecentChange $rc
644 * @param array $classes
645 * @return string
646 * @since 1.26
647 */
648 public function getTags( RecentChange $rc, array &$classes ) {
649 $s = '';
650 $this->insertTags( $s, $rc, $classes );
651 return $s;
652 }
653
654 public function insertExtra( &$s, &$rc, &$classes ) {
655 // Empty, used for subclasses to add anything special.
656 }
657
658 protected function showAsUnpatrolled( RecentChange $rc ) {
659 return self::isUnpatrolled( $rc, $this->getUser() );
660 }
661
662 /**
663 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
664 * @param User $user
665 * @return bool
666 */
667 public static function isUnpatrolled( $rc, User $user ) {
668 if ( $rc instanceof RecentChange ) {
669 $isPatrolled = $rc->mAttribs['rc_patrolled'];
670 $rcType = $rc->mAttribs['rc_type'];
671 $rcLogType = $rc->mAttribs['rc_log_type'];
672 } else {
673 $isPatrolled = $rc->rc_patrolled;
674 $rcType = $rc->rc_type;
675 $rcLogType = $rc->rc_log_type;
676 }
677
678 if ( !$isPatrolled ) {
679 if ( $user->useRCPatrol() ) {
680 return true;
681 }
682 if ( $user->useNPPatrol() && $rcType == RC_NEW ) {
683 return true;
684 }
685 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
686 return true;
687 }
688 }
689
690 return false;
691 }
692
693 /**
694 * Determines whether a revision is linked to this change; this may not be the case
695 * when the categorization wasn't done by an edit but a conditional parser function
696 *
697 * @since 1.27
698 *
699 * @param RecentChange|RCCacheEntry $rcObj
700 * @return bool
701 */
702 protected function isCategorizationWithoutRevision( $rcObj ) {
703 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
704 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
705 }
706
707 }