Merge "Enable users to watch category membership changes #2"
[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 MapCacheLRU */
40 protected $watchingCache;
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->watchingCache = new MapCacheLRU( 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', array( $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 ( array(
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 )
136 : $nothing;
137 }
138
139 return $f;
140 }
141
142 /**
143 * Provide the "<abbr>" element appropriate to a given abbreviated flag,
144 * namely the flag indicating a new page, a minor edit, a bot edit, or an
145 * unpatrolled edit. By default in English it will contain "N", "m", "b",
146 * "!" respectively, plus it will have an appropriate title and class.
147 *
148 * @param string $flag One key of $wgRecentChangesFlags
149 * @return string Raw HTML
150 */
151 public static function flag( $flag ) {
152 static $flagInfos = null;
153 if ( is_null( $flagInfos ) ) {
154 global $wgRecentChangesFlags;
155 $flagInfos = array();
156 foreach ( $wgRecentChangesFlags as $key => $value ) {
157 $flagInfos[$key]['letter'] = wfMessage( $value['letter'] )->escaped();
158 $flagInfos[$key]['title'] = wfMessage( $value['title'] )->escaped();
159 // Allow customized class name, fall back to flag name
160 $flagInfos[$key]['class'] = Sanitizer::escapeClass(
161 isset( $value['class'] ) ? $value['class'] : $key );
162 }
163 }
164
165 // Inconsistent naming, bleh, kepted for b/c
166 $map = array(
167 'minoredit' => 'minor',
168 'botedit' => 'bot',
169 );
170 if ( isset( $map[$flag] ) ) {
171 $flag = $map[$flag];
172 }
173
174 return "<abbr class='" . $flagInfos[$flag]['class'] . "' title='" .
175 $flagInfos[$flag]['title'] . "'>" . $flagInfos[$flag]['letter'] .
176 '</abbr>';
177 }
178
179 /**
180 * Returns text for the start of the tabular part of RC
181 * @return string
182 */
183 public function beginRecentChangesList() {
184 $this->rc_cache = array();
185 $this->rcMoveIndex = 0;
186 $this->rcCacheIndex = 0;
187 $this->lastdate = '';
188 $this->rclistOpen = false;
189 $this->getOutput()->addModuleStyles( 'mediawiki.special.changeslist' );
190
191 return '<div class="mw-changeslist">';
192 }
193
194 /**
195 * @param ResultWrapper|array $rows
196 */
197 public function initChangesListRows( $rows ) {
198 Hooks::run( 'ChangesListInitRows', array( $this, $rows ) );
199 }
200
201 /**
202 * Show formatted char difference
203 * @param int $old Number of bytes
204 * @param int $new Number of bytes
205 * @param IContextSource $context
206 * @return string
207 */
208 public static function showCharacterDifference( $old, $new, IContextSource $context = null ) {
209 if ( !$context ) {
210 $context = RequestContext::getMain();
211 }
212
213 $new = (int)$new;
214 $old = (int)$old;
215 $szdiff = $new - $old;
216
217 $lang = $context->getLanguage();
218 $config = $context->getConfig();
219 $code = $lang->getCode();
220 static $fastCharDiff = array();
221 if ( !isset( $fastCharDiff[$code] ) ) {
222 $fastCharDiff[$code] = $config->get( 'MiserMode' )
223 || $context->msg( 'rc-change-size' )->plain() === '$1';
224 }
225
226 $formattedSize = $lang->formatNum( $szdiff );
227
228 if ( !$fastCharDiff[$code] ) {
229 $formattedSize = $context->msg( 'rc-change-size', $formattedSize )->text();
230 }
231
232 if ( abs( $szdiff ) > abs( $config->get( 'RCChangedSizeThreshold' ) ) ) {
233 $tag = 'strong';
234 } else {
235 $tag = 'span';
236 }
237
238 if ( $szdiff === 0 ) {
239 $formattedSizeClass = 'mw-plusminus-null';
240 } elseif ( $szdiff > 0 ) {
241 $formattedSize = '+' . $formattedSize;
242 $formattedSizeClass = 'mw-plusminus-pos';
243 } else {
244 $formattedSizeClass = 'mw-plusminus-neg';
245 }
246
247 $formattedTotalSize = $context->msg( 'rc-change-size-new' )->numParams( $new )->text();
248
249 return Html::element( $tag,
250 array( 'dir' => 'ltr', 'class' => $formattedSizeClass, 'title' => $formattedTotalSize ),
251 $context->msg( 'parentheses', $formattedSize )->plain() ) . $lang->getDirMark();
252 }
253
254 /**
255 * Format the character difference of one or several changes.
256 *
257 * @param RecentChange $old
258 * @param RecentChange $new Last change to use, if not provided, $old will be used
259 * @return string HTML fragment
260 */
261 public function formatCharacterDifference( RecentChange $old, RecentChange $new = null ) {
262 $oldlen = $old->mAttribs['rc_old_len'];
263
264 if ( $new ) {
265 $newlen = $new->mAttribs['rc_new_len'];
266 } else {
267 $newlen = $old->mAttribs['rc_new_len'];
268 }
269
270 if ( $oldlen === null || $newlen === null ) {
271 return '';
272 }
273
274 return self::showCharacterDifference( $oldlen, $newlen, $this->getContext() );
275 }
276
277 /**
278 * Returns text for the end of RC
279 * @return string
280 */
281 public function endRecentChangesList() {
282 $out = $this->rclistOpen ? "</ul>\n" : '';
283 $out .= '</div>';
284
285 return $out;
286 }
287
288 /**
289 * @param string $s HTML to update
290 * @param mixed $rc_timestamp
291 */
292 public function insertDateHeader( &$s, $rc_timestamp ) {
293 # Make date header if necessary
294 $date = $this->getLanguage()->userDate( $rc_timestamp, $this->getUser() );
295 if ( $date != $this->lastdate ) {
296 if ( $this->lastdate != '' ) {
297 $s .= "</ul>\n";
298 }
299 $s .= Xml::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
300 $this->lastdate = $date;
301 $this->rclistOpen = true;
302 }
303 }
304
305 /**
306 * @param string $s HTML to update
307 * @param Title $title
308 * @param string $logtype
309 */
310 public function insertLog( &$s, $title, $logtype ) {
311 $page = new LogPage( $logtype );
312 $logname = $page->getName()->escaped();
313 $s .= $this->msg( 'parentheses' )->rawParams( Linker::linkKnown( $title, $logname ) )->escaped();
314 }
315
316 /**
317 * @param string $s HTML to update
318 * @param RecentChange $rc
319 * @param bool $unpatrolled
320 */
321 public function insertDiffHist( &$s, &$rc, $unpatrolled ) {
322 # Diff link
323 if (
324 $rc->mAttribs['rc_type'] == RC_NEW ||
325 $rc->mAttribs['rc_type'] == RC_LOG ||
326 $rc->mAttribs['rc_type'] == RC_CATEGORIZE
327 ) {
328 $diffLink = $this->message['diff'];
329 } elseif ( !self::userCan( $rc, Revision::DELETED_TEXT, $this->getUser() ) ) {
330 $diffLink = $this->message['diff'];
331 } else {
332 $query = array(
333 'curid' => $rc->mAttribs['rc_cur_id'],
334 'diff' => $rc->mAttribs['rc_this_oldid'],
335 'oldid' => $rc->mAttribs['rc_last_oldid']
336 );
337
338 $diffLink = Linker::linkKnown(
339 $rc->getTitle(),
340 $this->message['diff'],
341 array( 'tabindex' => $rc->counter ),
342 $query
343 );
344 }
345 if ( $rc->mAttribs['rc_type'] == RC_CATEGORIZE ) {
346 $diffhist = $diffLink . $this->message['pipe-separator'] . $this->message['hist'];
347 } else {
348 $diffhist = $diffLink . $this->message['pipe-separator'];
349 # History link
350 $diffhist .= Linker::linkKnown(
351 $rc->getTitle(),
352 $this->message['hist'],
353 array(),
354 array(
355 'curid' => $rc->mAttribs['rc_cur_id'],
356 'action' => 'history'
357 )
358 );
359 }
360
361 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
362 $s .= $this->msg( 'parentheses' )->rawParams( $diffhist )->escaped() .
363 ' <span class="mw-changeslist-separator">. .</span> ';
364 }
365
366 /**
367 * @param string $s HTML to update
368 * @param RecentChange $rc
369 * @param bool $unpatrolled
370 * @param bool $watched
371 */
372 public function insertArticleLink( &$s, &$rc, $unpatrolled, $watched ) {
373 $params = array();
374 if ( $rc->getTitle()->isRedirect() ) {
375 $params = array( 'redirect' => 'no' );
376 }
377
378 $articlelink = Linker::linkKnown(
379 $rc->getTitle(),
380 null,
381 array( 'class' => 'mw-changeslist-title' ),
382 $params
383 );
384 if ( $this->isDeleted( $rc, Revision::DELETED_TEXT ) ) {
385 $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
386 }
387 # To allow for boldening pages watched by this user
388 $articlelink = "<span class=\"mw-title\">{$articlelink}</span>";
389 # RTL/LTR marker
390 $articlelink .= $this->getLanguage()->getDirMark();
391
392 Hooks::run( 'ChangesListInsertArticleLink',
393 array( &$this, &$articlelink, &$s, &$rc, $unpatrolled, $watched ) );
394
395 $s .= " $articlelink";
396 }
397
398 /**
399 * @param RecentChange $rc
400 * @param bool $unpatrolled
401 * @param bool $watched
402 * @return string
403 * @since 1.26
404 */
405 public function getArticleLink( RecentChange $rc, $unpatrolled, $watched ) {
406 $s = '';
407 $this->insertArticleLink( $s, $rc, $unpatrolled, $watched );
408 return $s;
409 }
410
411 /**
412 * Get the timestamp from $rc formatted with current user's settings
413 * and a separator
414 *
415 * @param RecentChange $rc
416 * @return string HTML fragment
417 */
418 public function getTimestamp( $rc ) {
419 // @todo FIXME: Hard coded ". .". Is there a message for this? Should there be?
420 return $this->message['semicolon-separator'] . '<span class="mw-changeslist-date">' .
421 $this->getLanguage()->userTime(
422 $rc->mAttribs['rc_timestamp'],
423 $this->getUser()
424 ) . '</span> <span class="mw-changeslist-separator">. .</span> ';
425 }
426
427 /**
428 * Insert time timestamp string from $rc into $s
429 *
430 * @param string $s HTML to update
431 * @param RecentChange $rc
432 */
433 public function insertTimestamp( &$s, $rc ) {
434 $s .= $this->getTimestamp( $rc );
435 }
436
437 /**
438 * Insert links to user page, user talk page and eventually a blocking link
439 *
440 * @param string &$s HTML to update
441 * @param RecentChange &$rc
442 */
443 public function insertUserRelatedLinks( &$s, &$rc ) {
444 if ( $this->isDeleted( $rc, Revision::DELETED_USER ) ) {
445 $s .= ' <span class="history-deleted">' .
446 $this->msg( 'rev-deleted-user' )->escaped() . '</span>';
447 } else {
448 $s .= $this->getLanguage()->getDirMark() . Linker::userLink( $rc->mAttribs['rc_user'],
449 $rc->mAttribs['rc_user_text'] );
450 $s .= Linker::userToolLinks( $rc->mAttribs['rc_user'], $rc->mAttribs['rc_user_text'] );
451 }
452 }
453
454 /**
455 * Insert a formatted action
456 *
457 * @param RecentChange $rc
458 * @return string
459 */
460 public function insertLogEntry( $rc ) {
461 $formatter = LogFormatter::newFromRow( $rc->mAttribs );
462 $formatter->setContext( $this->getContext() );
463 $formatter->setShowUserToolLinks( true );
464 $mark = $this->getLanguage()->getDirMark();
465
466 return $formatter->getActionText() . " $mark" . $formatter->getComment();
467 }
468
469 /**
470 * Insert a formatted comment
471 * @param RecentChange $rc
472 * @return string
473 */
474 public function insertComment( $rc ) {
475 if ( $this->isDeleted( $rc, Revision::DELETED_COMMENT ) ) {
476 return ' <span class="history-deleted">' .
477 $this->msg( 'rev-deleted-comment' )->escaped() . '</span>';
478 } else {
479 return Linker::commentBlock( $rc->mAttribs['rc_comment'], $rc->getTitle() );
480 }
481 }
482
483 /**
484 * Check whether to enable recent changes patrol features
485 *
486 * @deprecated since 1.22
487 * @return bool
488 */
489 public static function usePatrol() {
490 global $wgUser;
491
492 wfDeprecated( __METHOD__, '1.22' );
493
494 return $wgUser->useRCPatrol();
495 }
496
497 /**
498 * Returns the string which indicates the number of watching users
499 * @param int $count Number of user watching a page
500 * @return string
501 */
502 protected function numberofWatchingusers( $count ) {
503 $cache = $this->watchingCache;
504 if ( $count > 0 ) {
505 if ( !$cache->has( $count ) ) {
506 $cache->set( $count, $this->msg( 'number_of_watching_users_RCview' )
507 ->numParams( $count )->escaped() );
508 }
509
510 return $cache->get( $count );
511 } else {
512 return '';
513 }
514 }
515
516 /**
517 * Determine if said field of a revision is hidden
518 * @param RCCacheEntry|RecentChange $rc
519 * @param int $field One of DELETED_* bitfield constants
520 * @return bool
521 */
522 public static function isDeleted( $rc, $field ) {
523 return ( $rc->mAttribs['rc_deleted'] & $field ) == $field;
524 }
525
526 /**
527 * Determine if the current user is allowed to view a particular
528 * field of this revision, if it's marked as deleted.
529 * @param RCCacheEntry|RecentChange $rc
530 * @param int $field
531 * @param User $user User object to check, or null to use $wgUser
532 * @return bool
533 */
534 public static function userCan( $rc, $field, User $user = null ) {
535 if ( $rc->mAttribs['rc_type'] == RC_LOG ) {
536 return LogEventsList::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $user );
537 } else {
538 return Revision::userCanBitfield( $rc->mAttribs['rc_deleted'], $field, $user );
539 }
540 }
541
542 /**
543 * @param string $link
544 * @param bool $watched
545 * @return string
546 */
547 protected function maybeWatchedLink( $link, $watched = false ) {
548 if ( $watched ) {
549 return '<strong class="mw-watched">' . $link . '</strong>';
550 } else {
551 return '<span class="mw-rc-unwatched">' . $link . '</span>';
552 }
553 }
554
555 /** Inserts a rollback link
556 *
557 * @param string $s
558 * @param RecentChange $rc
559 */
560 public function insertRollback( &$s, &$rc ) {
561 if ( $rc->mAttribs['rc_type'] == RC_EDIT
562 && $rc->mAttribs['rc_this_oldid']
563 && $rc->mAttribs['rc_cur_id']
564 ) {
565 $page = $rc->getTitle();
566 /** Check for rollback and edit permissions, disallow special pages, and only
567 * show a link on the top-most revision */
568 if ( $this->getUser()->isAllowed( 'rollback' )
569 && $rc->mAttribs['page_latest'] == $rc->mAttribs['rc_this_oldid']
570 ) {
571 $rev = new Revision( array(
572 'title' => $page,
573 'id' => $rc->mAttribs['rc_this_oldid'],
574 'user' => $rc->mAttribs['rc_user'],
575 'user_text' => $rc->mAttribs['rc_user_text'],
576 'deleted' => $rc->mAttribs['rc_deleted']
577 ) );
578 $s .= ' ' . Linker::generateRollback( $rev, $this->getContext() );
579 }
580 }
581 }
582
583 /**
584 * @param RecentChange $rc
585 * @return string
586 * @since 1.26
587 */
588 public function getRollback( RecentChange $rc ) {
589 $s = '';
590 $this->insertRollback( $s, $rc );
591 return $s;
592 }
593
594 /**
595 * @param string $s
596 * @param RecentChange $rc
597 * @param array $classes
598 */
599 public function insertTags( &$s, &$rc, &$classes ) {
600 if ( empty( $rc->mAttribs['ts_tags'] ) ) {
601 return;
602 }
603
604 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
605 $rc->mAttribs['ts_tags'],
606 'changeslist'
607 );
608 $classes = array_merge( $classes, $newClasses );
609 $s .= ' ' . $tagSummary;
610 }
611
612 /**
613 * @param RecentChange $rc
614 * @param array $classes
615 * @return string
616 * @since 1.26
617 */
618 public function getTags( RecentChange $rc, array &$classes ) {
619 $s = '';
620 $this->insertTags( $s, $rc, $classes );
621 return $s;
622 }
623
624 public function insertExtra( &$s, &$rc, &$classes ) {
625 // Empty, used for subclasses to add anything special.
626 }
627
628 protected function showAsUnpatrolled( RecentChange $rc ) {
629 return self::isUnpatrolled( $rc, $this->getUser() );
630 }
631
632 /**
633 * @param object|RecentChange $rc Database row from recentchanges or a RecentChange object
634 * @param User $user
635 * @return bool
636 */
637 public static function isUnpatrolled( $rc, User $user ) {
638 if ( $rc instanceof RecentChange ) {
639 $isPatrolled = $rc->mAttribs['rc_patrolled'];
640 $rcType = $rc->mAttribs['rc_type'];
641 } else {
642 $isPatrolled = $rc->rc_patrolled;
643 $rcType = $rc->rc_type;
644 }
645
646 if ( !$isPatrolled ) {
647 if ( $user->useRCPatrol() ) {
648 return true;
649 }
650 if ( $user->useNPPatrol() && $rcType == RC_NEW ) {
651 return true;
652 }
653 }
654
655 return false;
656 }
657
658 /**
659 * Determines whether a revision is linked to this change; this may not be the case
660 * when the categorization wasn't done by an edit but a conditional parser function
661 *
662 * @since 1.27
663 *
664 * @param RecentChange|RCCacheEntry $rcObj
665 * @return bool
666 */
667 protected function isCategorizationWithoutRevision( $rcObj ) {
668 return intval( $rcObj->getAttribute( 'rc_type' ) ) === RC_CATEGORIZE
669 && intval( $rcObj->getAttribute( 'rc_this_oldid' ) ) === 0;
670 }
671
672 }