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