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