Merge "Chinese Conversion Table Update 2016-3"
[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 * @param int $old Number of bytes
240 * @param int $new Number of bytes
241 * @param IContextSource $context
242 * @return string
243 */
244 public static function showCharacterDifference( $old, $new, IContextSource $context = null ) {
245 if ( !$context ) {
246 $context = RequestContext::getMain();
247 }
248
249 $new = (int)$new;
250 $old = (int)$old;
251 $szdiff = $new - $old;
252
253 $lang = $context->getLanguage();
254 $config = $context->getConfig();
255 $code = $lang->getCode();
256 static $fastCharDiff = [];
257 if ( !isset( $fastCharDiff[$code] ) ) {
258 $fastCharDiff[$code] = $config->get( 'MiserMode' )
259 || $context->msg( 'rc-change-size' )->plain() === '$1';
260 }
261
262 $formattedSize = $lang->formatNum( $szdiff );
263
264 if ( !$fastCharDiff[$code] ) {
265 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
266 }
267
268 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
269 $tag = 'strong';
270 } else {
271 $tag = 'span';
272 }
273
274 if ( $szdiff === 0 ) {
275 $formattedSizeClass = 'mw-plusminus-null';
276 } elseif ( $szdiff > 0 ) {
277 $formattedSize = '+' . $formattedSize;
278 $formattedSizeClass = 'mw-plusminus-pos';
279 } else {
280 $formattedSizeClass = 'mw-plusminus-neg';
281 }
282
283 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
284
285 return Html::element( $tag,
286 [ 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ],
287 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
288 }
289
290 /**
291 * Format the character difference of one or several changes.
292 *
293 * @param RecentChange $old
294 * @param RecentChange $new Last change to use, if not provided, $old will be used
295 * @return string HTML fragment
296 */
297 public function formatCharacterDifference( RecentChange $old, RecentChange $new = null ) {
298 $oldlen = $old->mAttribs['rc_old_len'];
299
300 if ( $new ) {
301 $newlen = $new->mAttribs['rc_new_len'];
302 } else {
303 $newlen = $old->mAttribs['rc_new_len'];
304 }
305
306 if ( $oldlen === null || $newlen === null ) {
307 return '';
308 }
309
310 return self::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
311 }
312
313 /**
314 * Returns text for the end of RC
315 * @return string
316 */
317 public function endRecentChangesList() {
318 $out = $this->rclistOpen ? "</ul>\n" : '';
319 $out .= '</div>';
320
321 return $out;
322 }
323
324 /**
325 * @param string $s HTML to update
326 * @param mixed $rc_timestamp
327 */
328 public function insertDateHeader( &$s, $rc_timestamp ) {
329 # Make date header if necessary
330 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
331 if ( $date != $this->lastdate ) {
332 if ( $this->lastdate != '' ) {
333 $s .= "</ul>\n";
334 }
335 $s .= Xml::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
336 $this->lastdate = $date;
337 $this->rclistOpen = true;
338 }
339 }
340
341 /**
342 * @param string $s HTML to update
343 * @param Title $title
344 * @param string $logtype
345 */
346 public function insertLog( &$s, $title, $logtype ) {
347 $page = new LogPage( $logtype );
348 $logname = $page->getName()->setContext( $this->getContext() )->text();
349 $s .= $this->msg( 'parentheses' )->rawParams(
350 $this->linkRenderer->makeKnownLink( $title, $logname )
351 )->escaped();
352 }
353
354 /**
355 * @param string $s HTML to update
356 * @param RecentChange $rc
357 * @param bool|null $unpatrolled Unused variable, since 1.27.
358 */
359 public function insertDiffHist( &$s, &$rc, $unpatrolled = null ) {
360 # Diff link
361 if (
362 $rc->mAttribs['rc_type'] == RC_NEW ||
363 $rc->mAttribs['rc_type'] == RC_LOG ||
364 $rc->mAttribs['rc_type'] == RC_CATEGORIZE
365 ) {
366 $diffLink = $this->message['diff'];
367 } elseif ( !self::userCan( $rc, Revision::DELETED_TEXT, $this->getUser() ) ) {
368 $diffLink = $this->message['diff'];
369 } else {
370 $query = [
371 'curid' => $rc->mAttribs['rc_cur_id'],
372 'diff' => $rc->mAttribs['rc_this_oldid'],
373 'oldid' => $rc->mAttribs['rc_last_oldid']
374 ];
375
376 $diffLink = $this->linkRenderer->makeKnownLink(
377 $rc->getTitle(),
378 new HtmlArmor( $this->message['diff'] ),
379 [],
380 $query
381 );
382 }
383 if ( $rc->mAttribs['rc_type'] == RC_CATEGORIZE ) {
384 $diffhist = $diffLink . $this->message['pipe-separator'] . $this->message['hist'];
385 } else {
386 $diffhist = $diffLink . $this->message['pipe-separator'];
387 # History link
388 $diffhist .= $this->linkRenderer->makeKnownLink(
389 $rc->getTitle(),
390 new HtmlArmor( $this->message['hist'] ),
391 [],
392 [
393 'curid' => $rc->mAttribs['rc_cur_id'],
394 'action' => 'history'
395 ]
396 );
397 }
398
399 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
400 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
401 ' <span class="mw-changeslist-separator">. .</span> ';
402 }
403
404 /**
405 * @param string $s Article link will be appended to this string, in place.
406 * @param RecentChange $rc
407 * @param bool $unpatrolled
408 * @param bool $watched
409 * @deprecated since 1.27, use getArticleLink instead.
410 */
411 public function insertArticleLink( &$s, RecentChange $rc, $unpatrolled, $watched ) {
412 $s .= $this->getArticleLink( $rc, $unpatrolled, $watched );
413 }
414
415 /**
416 * @param RecentChange $rc
417 * @param bool $unpatrolled
418 * @param bool $watched
419 * @return string HTML
420 * @since 1.26
421 */
422 public function getArticleLink( &$rc, $unpatrolled, $watched ) {
423 $params = [];
424 if ( $rc->getTitle()->isRedirect() ) {
425 $params = [ 'redirect' => 'no' ];
426 }
427
428 $articlelink = $this->linkRenderer->makeLink(
429 $rc->getTitle(),
430 null,
431 [ 'class' => 'mw-changeslist-title' ],
432 $params
433 );
434 if ( $this->isDeleted( $rc, Revision::DELETED_TEXT ) ) {
435 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
436 }
437 # To allow for boldening pages watched by this user
438 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
439 # RTL/LTR marker
440 $articlelink .= $this->getLanguage()->getDirMark();
441
442 # TODO: Deprecate the $s argument, it seems happily unused.
443 $s = '';
444 Hooks::run( 'ChangesListInsertArticleLink',
445 [ &$this, &$articlelink, &$s, &$rc, $unpatrolled, $watched ] );
446
447 return "{$s} {$articlelink}";
448 }
449
450 /**
451 * Get the timestamp from $rc formatted with current user's settings
452 * and a separator
453 *
454 * @param RecentChange $rc
455 * @return string HTML fragment
456 */
457 public function getTimestamp( $rc ) {
458 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
459 return $this->message['semicolon-separator'] . '<span class="mw-changeslist-date">' .
460 $this->getLanguage()->userTime(
461 $rc->mAttribs['rc_timestamp'],
462 $this->getUser()
463 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
464 }
465
466 /**
467 * Insert time timestamp string from $rc into $s
468 *
469 * @param string $s HTML to update
470 * @param RecentChange $rc
471 */
472 public function insertTimestamp( &$s, $rc ) {
473 $s .= $this->getTimestamp( $rc );
474 }
475
476 /**
477 * Insert links to user page, user talk page and eventually a blocking link
478 *
479 * @param string &$s HTML to update
480 * @param RecentChange &$rc
481 */
482 public function insertUserRelatedLinks( &$s, &$rc ) {
483 if ( $this->isDeleted( $rc, Revision::DELETED_USER ) ) {
484 $s .= ' <span class="history-deleted">' .
485 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
486 } else {
487 $s .= $this->getLanguage()->getDirMark() . Linker::userLink( $rc->mAttribs['rc_user'],
488 $rc->mAttribs['rc_user_text'] );
489 $s .= Linker::userToolLinks( $rc->mAttribs['rc_user'], $rc->mAttribs['rc_user_text'] );
490 }
491 }
492
493 /**
494 * Insert a formatted action
495 *
496 * @param RecentChange $rc
497 * @return string
498 */
499 public function insertLogEntry( $rc ) {
500 $formatter = LogFormatter::newFromRow( $rc->mAttribs );
501 $formatter->setContext( $this->getContext() );
502 $formatter->setShowUserToolLinks( true );
503 $mark = $this->getLanguage()->getDirMark();
504
505 return $formatter->getActionText() . " $mark" . $formatter->getComment();
506 }
507
508 /**
509 * Insert a formatted comment
510 * @param RecentChange $rc
511 * @return string
512 */
513 public function insertComment( $rc ) {
514 if ( $this->isDeleted( $rc, Revision::DELETED_COMMENT ) ) {
515 return ' <span class="history-deleted">' .
516 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
517 } else {
518 return Linker::commentBlock( $rc->mAttribs['rc_comment'], $rc->getTitle() );
519 }
520 }
521
522 /**
523 * Returns the string which indicates the number of watching users
524 * @param int $count Number of user watching a page
525 * @return string
526 */
527 protected function numberofWatchingusers( $count ) {
528 if ( $count <= 0 ) {
529 return '';
530 }
531 $cache = $this->watchMsgCache;
532 return $cache->getWithSetCallback( $count, $cache::TTL_INDEFINITE,
533 function () use ( $count ) {
534 return $this->msg( 'number_of_watching_users_RCview' )
535 ->numParams( $count )->escaped();
536 }
537 );
538 }
539
540 /**
541 * Determine if said field of a revision is hidden
542 * @param RCCacheEntry|RecentChange $rc
543 * @param int $field One of DELETED_* bitfield constants
544 * @return bool
545 */
546 public static function isDeleted( $rc, $field ) {
547 return ( $rc->mAttribs['rc_deleted'] & $field ) == $field;
548 }
549
550 /**
551 * Determine if the current user is allowed to view a particular
552 * field of this revision, if it's marked as deleted.
553 * @param RCCacheEntry|RecentChange $rc
554 * @param int $field
555 * @param User $user User object to check, or null to use $wgUser
556 * @return bool
557 */
558 public static function userCan( $rc, $field, User $user = null ) {
559 if ( $rc->mAttribs['rc_type'] == RC_LOG ) {
560 return LogEventsList::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $user );
561 } else {
562 return Revision::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $user );
563 }
564 }
565
566 /**
567 * @param string $link
568 * @param bool $watched
569 * @return string
570 */
571 protected function maybeWatchedLink( $link, $watched = false ) {
572 if ( $watched ) {
573 return '<strong class="mw-watched">' . $link . '</strong>';
574 } else {
575 return '<span class="mw-rc-unwatched">' . $link . '</span>';
576 }
577 }
578
579 /** Inserts a rollback link
580 *
581 * @param string $s
582 * @param RecentChange $rc
583 */
584 public function insertRollback( &$s, &$rc ) {
585 if ( $rc->mAttribs['rc_type'] == RC_EDIT
586 && $rc->mAttribs['rc_this_oldid']
587 && $rc->mAttribs['rc_cur_id']
588 ) {
589 $page = $rc->getTitle();
590 /** Check for rollback and edit permissions, disallow special pages, and only
591 * show a link on the top-most revision */
592 if ( $this->getUser()->isAllowed( 'rollback' )
593 && $rc->mAttribs['page_latest'] == $rc->mAttribs['rc_this_oldid']
594 ) {
595 $rev = new Revision( [
596 'title' => $page,
597 'id' => $rc->mAttribs['rc_this_oldid'],
598 'user' => $rc->mAttribs['rc_user'],
599 'user_text' => $rc->mAttribs['rc_user_text'],
600 'deleted' => $rc->mAttribs['rc_deleted']
601 ] );
602 $s .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
603 }
604 }
605 }
606
607 /**
608 * @param RecentChange $rc
609 * @return string
610 * @since 1.26
611 */
612 public function getRollback( RecentChange $rc ) {
613 $s = '';
614 $this->insertRollback( $s, $rc );
615 return $s;
616 }
617
618 /**
619 * @param string $s
620 * @param RecentChange $rc
621 * @param array $classes
622 */
623 public function insertTags( &$s, &$rc, &$classes ) {
624 if ( empty( $rc->mAttribs['ts_tags'] ) ) {
625 return;
626 }
627
628 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
629 $rc->mAttribs['ts_tags'],
630 'changeslist',
631 $this->getContext()
632 );
633 $classes = array_merge( $classes, $newClasses );
634 $s .= ' ' . $tagSummary;
635 }
636
637 /**
638 * @param RecentChange $rc
639 * @param array $classes
640 * @return string
641 * @since 1.26
642 */
643 public function getTags( RecentChange $rc, array &$classes ) {
644 $s = '';
645 $this->insertTags( $s, $rc, $classes );
646 return $s;
647 }
648
649 public function insertExtra( &$s, &$rc, &$classes ) {
650 // Empty, used for subclasses to add anything special.
651 }
652
653 protected function showAsUnpatrolled( RecentChange $rc ) {
654 return self::isUnpatrolled( $rc, $this->getUser() );
655 }
656
657 /**
658 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
659 * @param User $user
660 * @return bool
661 */
662 public static function isUnpatrolled( $rc, User $user ) {
663 if ( $rc instanceof RecentChange ) {
664 $isPatrolled = $rc->mAttribs['rc_patrolled'];
665 $rcType = $rc->mAttribs['rc_type'];
666 $rcLogType = $rc->mAttribs['rc_log_type'];
667 } else {
668 $isPatrolled = $rc->rc_patrolled;
669 $rcType = $rc->rc_type;
670 $rcLogType = $rc->rc_log_type;
671 }
672
673 if ( !$isPatrolled ) {
674 if ( $user->useRCPatrol() ) {
675 return true;
676 }
677 if ( $user->useNPPatrol() && $rcType == RC_NEW ) {
678 return true;
679 }
680 if ( $user->useFilePatrol() && $rcLogType == 'upload' ) {
681 return true;
682 }
683 }
684
685 return false;
686 }
687
688 /**
689 * Determines whether a revision is linked to this change; this may not be the case
690 * when the categorization wasn't done by an edit but a conditional parser function
691 *
692 * @since 1.27
693 *
694 * @param RecentChange|RCCacheEntry $rcObj
695 * @return bool
696 */
697 protected function isCategorizationWithoutRevision( $rcObj ) {
698 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
699 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
700 }
701
702 }