]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/ChangesList.php
MediaWiki 1.16.0
[autoinstalls/mediawiki.git] / includes / ChangesList.php
1 <?php
2
3 /**
4  * @todo document
5  */
6 class RCCacheEntry extends RecentChange {
7         var $secureName, $link;
8         var $curlink , $difflink, $lastlink, $usertalklink, $versionlink;
9         var $userlink, $timestamp, $watched;
10
11         static function newFromParent( $rc ) {
12                 $rc2 = new RCCacheEntry;
13                 $rc2->mAttribs = $rc->mAttribs;
14                 $rc2->mExtra = $rc->mExtra;
15                 return $rc2;
16         }
17 }
18
19 /**
20  * Class to show various lists of changes:
21  * - what links here
22  * - related changes
23  * - recent changes
24  */
25 class ChangesList {
26         # Called by history lists and recent changes
27         public $skin;
28         protected $watchlist = false;
29
30         /**
31         * Changeslist contructor
32         * @param $skin Skin
33         */
34         public function __construct( $skin ) {
35                 $this->skin = $skin;
36                 $this->preCacheMessages();
37         }
38
39         /**
40          * Fetch an appropriate changes list class for the specified user
41          * Some users might want to use an enhanced list format, for instance
42          *
43          * @param $user User to fetch the list class for
44          * @return ChangesList derivative
45          */
46         public static function newFromUser( &$user ) {
47                 $sk = $user->getSkin();
48                 $list = null;
49                 if( wfRunHooks( 'FetchChangesList', array( &$user, &$sk, &$list ) ) ) {
50                         return $user->getOption( 'usenewrc' ) ?
51                                 new EnhancedChangesList( $sk ) : new OldChangesList( $sk );
52                 } else {
53                         return $list;
54                 }
55         }
56         
57         /**
58          * Sets the list to use a <li class="watchlist-(namespace)-(page)"> tag
59          * @param $value Boolean
60          */
61         public function setWatchlistDivs( $value = true ) {
62                 $this->watchlist = $value;
63         }
64
65         /**
66          * As we use the same small set of messages in various methods and that
67          * they are called often, we call them once and save them in $this->message
68          */
69         private function preCacheMessages() {
70                 if( !isset( $this->message ) ) {
71                         foreach ( explode( ' ', 'cur diff hist last blocklink history ' .
72                         'semicolon-separator pipe-separator' ) as $msg ) {
73                                 $this->message[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) );
74                         }
75                 }
76         }
77
78
79         /**
80          * Returns the appropriate flags for new page, minor change and patrolling
81          * @param $new Boolean
82          * @param $minor Boolean
83          * @param $patrolled Boolean
84          * @param $nothing String to use for empty space
85          * @param $bot Boolean
86          * @return String
87          */
88         protected function recentChangesFlags( $new, $minor, $patrolled, $nothing = '&nbsp;', $bot = false ) {
89                 $f = $new ? self::flag( 'newpage' ) : $nothing;
90                 $f .= $minor ? self::flag( 'minor' ) : $nothing;
91                 $f .= $bot ? self::flag( 'bot' ) : $nothing;
92                 $f .= $patrolled ? self::flag( 'unpatrolled' ) : $nothing;
93                 return $f;
94         }
95
96         /**
97          * Provide the <abbr> element appropriate to a given abbreviated flag,
98          * namely the flag indicating a new page, a minor edit, a bot edit, or an
99          * unpatrolled edit.  By default in English it will contain "N", "m", "b",
100          * "!" respectively, plus it will have an appropriate title and class.
101          *
102          * @param $key String: 'newpage', 'unpatrolled', 'minor', or 'bot'
103          * @return String: Raw HTML
104          */
105         public static function flag( $key ) {
106                 static $messages = null;
107                 if ( is_null( $messages ) ) {
108                         foreach ( explode( ' ', 'minoreditletter boteditletter newpageletter ' .
109                         'unpatrolledletter recentchanges-label-minor recentchanges-label-bot ' .
110                         'recentchanges-label-newpage recentchanges-label-unpatrolled' ) as $msg ) {
111                                 $messages[$msg] = wfMsgExt( $msg, 'escapenoentities' );
112                         }
113                 }
114                 # Inconsistent naming, bleh
115                 if ( $key == 'newpage' || $key == 'unpatrolled' ) {
116                         $key2 = $key;
117                 } else {
118                         $key2 = $key . 'edit';
119                 }
120                 return "<abbr class=\"$key\" title=\""
121                         . $messages["recentchanges-label-$key"] . "\">"
122                         . $messages["${key2}letter"]
123                         . '</abbr>';
124         }
125
126         /**
127          * Some explanatory wrapper text for the given flag, to be used in a legend
128          * explaining what the flags mean.  For instance, "N - new page".  See
129          * also flag().
130          *
131          * @param $key String: 'newpage', 'unpatrolled', 'minor', or 'bot'
132          * @return String: Raw HTML
133          */
134         private static function flagLine( $key ) {
135                 return wfMsgExt( "recentchanges-legend-$key", array( 'escapenoentities',
136                         'replaceafter' ), self::flag( $key ) );
137         }
138
139         /**
140          * A handy legend to tell users what the little "m", "b", and so on mean.
141          *
142          * @return String: Raw HTML
143          */
144         public static function flagLegend() {
145                 global $wgGroupPermissions, $wgLang;
146
147                 $flags = array( self::flagLine( 'newpage' ),
148                         self::flagLine( 'minor' ) );
149
150                 # Don't show info on bot edits unless there's a bot group of some kind
151                 foreach ( $wgGroupPermissions as $rights ) {
152                         if ( isset( $rights['bot'] ) && $rights['bot'] ) {
153                                 $flags[] = self::flagLine( 'bot' );
154                                 break;
155                         }
156                 }
157
158                 if ( self::usePatrol() ) {
159                         $flags[] = self::flagLine( 'unpatrolled' );
160                 }
161
162                 return '<div class="mw-rc-label-legend">' .
163                         wfMsgExt( 'recentchanges-label-legend', 'parseinline',
164                         $wgLang->commaList( $flags ) ) . '</div>';
165         }
166
167         /**
168          * Returns text for the start of the tabular part of RC
169          * @return String
170          */
171         public function beginRecentChangesList() {
172                 $this->rc_cache = array();
173                 $this->rcMoveIndex = 0;
174                 $this->rcCacheIndex = 0;
175                 $this->lastdate = '';
176                 $this->rclistOpen = false;
177                 return '';
178         }
179         
180         /**
181          * Show formatted char difference
182          * @param $old Integer: bytes
183          * @param $new Integer: bytes
184          * @returns String
185          */
186         public static function showCharacterDifference( $old, $new ) {
187                 global $wgRCChangedSizeThreshold, $wgLang, $wgMiserMode;
188                 $szdiff = $new - $old;
189
190                 $code = $wgLang->getCode();
191                 static $fastCharDiff = array();
192                 if ( !isset($fastCharDiff[$code]) ) {
193                         $fastCharDiff[$code] = $wgMiserMode || wfMsgNoTrans( 'rc-change-size' ) === '$1';
194                 }
195                         
196                 $formatedSize = $wgLang->formatNum($szdiff);
197
198                 if ( !$fastCharDiff[$code] ) {
199                         $formatedSize = wfMsgExt( 'rc-change-size', array( 'parsemag', 'escape' ), $formatedSize );
200                 }
201                         
202                 if( abs( $szdiff ) > abs( $wgRCChangedSizeThreshold ) ) {
203                         $tag = 'strong';
204                 } else {
205                     $tag = 'span';
206                 }
207                 if( $szdiff === 0 ) {
208                         return "<$tag class='mw-plusminus-null'>($formatedSize)</$tag>";
209                 } elseif( $szdiff > 0 ) {
210                         return "<$tag class='mw-plusminus-pos'>(+$formatedSize)</$tag>";
211             } else {
212                         return "<$tag class='mw-plusminus-neg'>($formatedSize)</$tag>";
213                 }
214         }
215
216         /**
217          * Returns text for the end of RC
218          * @return String
219          */
220         public function endRecentChangesList() {
221                 if( $this->rclistOpen ) {
222                         return "</ul>\n";
223                 } else {
224                         return '';
225                 }
226         }
227
228         public function insertMove( &$s, $rc ) {
229                 # Diff
230                 $s .= '(' . $this->message['diff'] . ') (';
231                 # Hist
232                 $s .= $this->skin->link(
233                         $rc->getMovedToTitle(),
234                         $this->message['hist'],
235                         array(),
236                         array( 'action' => 'history' ),
237                         array( 'known', 'noclasses' )
238                 ) . ') . . ';
239                 # "[[x]] moved to [[y]]"
240                 $msg = ( $rc->mAttribs['rc_type'] == RC_MOVE ) ? '1movedto2' : '1movedto2_redir';
241                 $s .= wfMsg(
242                         $msg,
243                         $this->skin->link(
244                                 $rc->getTitle(),
245                                 null,
246                                 array(),
247                                 array( 'redirect' => 'no' ),
248                                 array( 'known', 'noclasses' )
249                         ),
250                         $this->skin->link(
251                                 $rc->getMovedToTitle(),
252                                 null,
253                                 array(),
254                                 array(),
255                                 array( 'known', 'noclasses' )
256                         )
257                 );
258         }
259
260         public function insertDateHeader( &$s, $rc_timestamp ) {
261                 global $wgLang;
262                 # Make date header if necessary
263                 $date = $wgLang->date( $rc_timestamp, true, true );
264                 if( $date != $this->lastdate ) {
265                         if( $this->lastdate != '' ) {
266                                 $s .= "</ul>\n";
267                         }
268                         $s .= Xml::element( 'h4', null, $date ) . "\n<ul class=\"special\">";
269                         $this->lastdate = $date;
270                         $this->rclistOpen = true;
271                 }
272         }
273
274         public function insertLog( &$s, $title, $logtype ) {
275                 $logname = LogPage::logName( $logtype );
276                 $s .= '(' . $this->skin->link(
277                         $title,
278                         $logname,
279                         array(),
280                         array(),
281                         array( 'known', 'noclasses' )
282                 ) . ')';
283         }
284
285         public function insertDiffHist( &$s, &$rc, $unpatrolled ) {
286                 # Diff link
287                 if( $rc->mAttribs['rc_type'] == RC_NEW || $rc->mAttribs['rc_type'] == RC_LOG ) {
288                         $diffLink = $this->message['diff'];
289                 } else if( !self::userCan($rc,Revision::DELETED_TEXT) ) {
290                         $diffLink = $this->message['diff'];
291                 } else {
292                         $query = array(
293                                 'curid' => $rc->mAttribs['rc_cur_id'],
294                                 'diff'  => $rc->mAttribs['rc_this_oldid'],
295                                 'oldid' => $rc->mAttribs['rc_last_oldid']
296                         );
297
298                         if( $unpatrolled ) {
299                                 $query['rcid'] = $rc->mAttribs['rc_id'];
300                         };
301
302                         $diffLink = $this->skin->link(
303                                 $rc->getTitle(),
304                                 $this->message['diff'],
305                                 array( 'tabindex' => $rc->counter ),
306                                 $query,
307                                 array( 'known', 'noclasses' )
308                         );
309                 }
310                 $s .= '(' . $diffLink . $this->message['pipe-separator'];
311                 # History link
312                 $s .= $this->skin->link(
313                         $rc->getTitle(),
314                         $this->message['hist'],
315                         array(),
316                         array(
317                                 'curid' => $rc->mAttribs['rc_cur_id'],
318                                 'action' => 'history'
319                         ),
320                         array( 'known', 'noclasses' )
321                 );
322                 $s .= ') . . ';
323         }
324
325         public function insertArticleLink( &$s, &$rc, $unpatrolled, $watched ) {
326                 global $wgContLang;
327                 # If it's a new article, there is no diff link, but if it hasn't been
328                 # patrolled yet, we need to give users a way to do so
329                 $params = array();
330
331                 if ( $unpatrolled && $rc->mAttribs['rc_type'] == RC_NEW ) {
332                         $params['rcid'] = $rc->mAttribs['rc_id'];
333                 }
334
335                 if( $this->isDeleted($rc,Revision::DELETED_TEXT) ) {
336                         $articlelink = $this->skin->link(
337                                 $rc->getTitle(),
338                                 null,
339                                 array(),
340                                 $params,
341                                 array( 'known', 'noclasses' )
342                         );
343                         $articlelink = '<span class="history-deleted">' . $articlelink . '</span>';
344                 } else {
345                         $articlelink = ' '. $this->skin->link(
346                                 $rc->getTitle(),
347                                 null,
348                                 array(),
349                                 $params,
350                                 array( 'known', 'noclasses' )
351                         );
352                 }
353                 # Bolden pages watched by this user
354                 if( $watched ) {
355                         $articlelink = "<strong class=\"mw-watched\">{$articlelink}</strong>";
356                 }
357                 # RTL/LTR marker
358                 $articlelink .= $wgContLang->getDirMark();
359
360                 wfRunHooks( 'ChangesListInsertArticleLink',
361                         array(&$this, &$articlelink, &$s, &$rc, $unpatrolled, $watched) );
362
363                 $s .= " $articlelink";
364         }
365
366         public function insertTimestamp( &$s, $rc ) {
367                 global $wgLang;
368                 $s .= $this->message['semicolon-separator'] . 
369                         $wgLang->time( $rc->mAttribs['rc_timestamp'], true, true ) . ' . . ';
370         }
371
372         /** Insert links to user page, user talk page and eventually a blocking link */
373         public function insertUserRelatedLinks( &$s, &$rc ) {
374                 if( $this->isDeleted( $rc, Revision::DELETED_USER ) ) {
375                    $s .= ' <span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
376                 } else {
377                   $s .= $this->skin->userLink( $rc->mAttribs['rc_user'], $rc->mAttribs['rc_user_text'] );
378                   $s .= $this->skin->userToolLinks( $rc->mAttribs['rc_user'], $rc->mAttribs['rc_user_text'] );
379                 }
380         }
381
382         /** insert a formatted action */
383         public function insertAction( &$s, &$rc ) {
384                 if( $rc->mAttribs['rc_type'] == RC_LOG ) {
385                         if( $this->isDeleted( $rc, LogPage::DELETED_ACTION ) ) {
386                                 $s .= ' <span class="history-deleted">' . wfMsgHtml( 'rev-deleted-event' ) . '</span>';
387                         } else {
388                                 $s .= ' '.LogPage::actionText( $rc->mAttribs['rc_log_type'], $rc->mAttribs['rc_log_action'],
389                                         $rc->getTitle(), $this->skin, LogPage::extractParams( $rc->mAttribs['rc_params'] ), true, true );
390                         }
391                 }
392         }
393
394         /** insert a formatted comment */
395         public function insertComment( &$s, &$rc ) {
396                 if( $rc->mAttribs['rc_type'] != RC_MOVE && $rc->mAttribs['rc_type'] != RC_MOVE_OVER_REDIRECT ) {
397                         if( $this->isDeleted( $rc, Revision::DELETED_COMMENT ) ) {
398                                 $s .= ' <span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
399                         } else {
400                                 $s .= $this->skin->commentBlock( $rc->mAttribs['rc_comment'], $rc->getTitle() );
401                         }
402                 }
403         }
404
405         /**
406          * Check whether to enable recent changes patrol features
407          * @return Boolean
408          */
409         public static function usePatrol() {
410                 global $wgUser;
411                 return $wgUser->useRCPatrol();
412         }
413
414         /**
415          * Returns the string which indicates the number of watching users
416          */
417         protected function numberofWatchingusers( $count ) {
418                 global $wgLang;
419                 static $cache = array();
420                 if( $count > 0 ) {
421                         if( !isset( $cache[$count] ) ) {
422                                 $cache[$count] = wfMsgExt( 'number_of_watching_users_RCview',
423                                         array('parsemag', 'escape' ), $wgLang->formatNum( $count ) );
424                         }
425                         return $cache[$count];
426                 } else {
427                         return '';
428                 }
429         }
430
431         /**
432          * Determine if said field of a revision is hidden
433          * @param $rc RCCacheEntry
434          * @param $field Integer: one of DELETED_* bitfield constants
435          * @return Boolean
436          */
437         public static function isDeleted( $rc, $field ) {
438                 return ( $rc->mAttribs['rc_deleted'] & $field ) == $field;
439         }
440
441         /**
442          * Determine if the current user is allowed to view a particular
443          * field of this revision, if it's marked as deleted.
444          * @param $rc RCCacheEntry
445          * @param $field Integer
446          * @return Boolean
447          */
448         public static function userCan( $rc, $field ) {
449                 if( $rc->mAttribs['rc_type'] == RC_LOG ) {
450                         return LogEventsList::userCanBitfield( $rc->mAttribs['rc_deleted'], $field );
451                 } else {
452                         return Revision::userCanBitfield( $rc->mAttribs['rc_deleted'], $field );
453                 }
454         }
455
456         protected function maybeWatchedLink( $link, $watched = false ) {
457                 if( $watched ) {
458                         return '<strong class="mw-watched">' . $link . '</strong>';
459                 } else {
460                         return '<span class="mw-rc-unwatched">' . $link . '</span>';
461                 }
462         }
463         
464         /** Inserts a rollback link */
465         public function insertRollback( &$s, &$rc ) {
466                 global $wgUser;
467                 if( !$rc->mAttribs['rc_new'] && $rc->mAttribs['rc_this_oldid'] && $rc->mAttribs['rc_cur_id'] ) {
468                         $page = $rc->getTitle();
469                         /** Check for rollback and edit permissions, disallow special pages, and only
470                           * show a link on the top-most revision */
471                         if ($wgUser->isAllowed('rollback') && $rc->mAttribs['page_latest'] == $rc->mAttribs['rc_this_oldid'] )
472                         {
473                                 $rev = new Revision( array(
474                                         'id'        => $rc->mAttribs['rc_this_oldid'],
475                                         'user'      => $rc->mAttribs['rc_user'],
476                                         'user_text' => $rc->mAttribs['rc_user_text'],
477                                         'deleted'   => $rc->mAttribs['rc_deleted']
478                                 ) );
479                                 $rev->setTitle( $page );
480                                 $s .= ' '.$this->skin->generateRollback( $rev );
481                         }
482                 }
483         }
484
485         public function insertTags( &$s, &$rc, &$classes ) {
486                 if ( empty($rc->mAttribs['ts_tags']) )
487                         return;
488                         
489                 list($tagSummary, $newClasses) = ChangeTags::formatSummaryRow( $rc->mAttribs['ts_tags'], 'changeslist' );
490                 $classes = array_merge( $classes, $newClasses );
491                 $s .= ' ' . $tagSummary;
492         }
493
494         public function insertExtra( &$s, &$rc, &$classes ) {
495                 ## Empty, used for subclassers to add anything special.
496         }
497 }
498
499
500 /**
501  * Generate a list of changes using the good old system (no javascript)
502  */
503 class OldChangesList extends ChangesList {
504         /**
505          * Format a line using the old system (aka without any javascript).
506          */
507         public function recentChangesLine( &$rc, $watched = false, $linenumber = null ) {
508                 global $wgLang, $wgRCShowChangedSize, $wgUser;
509                 wfProfileIn( __METHOD__ );
510                 # Should patrol-related stuff be shown?
511                 $unpatrolled = $wgUser->useRCPatrol() && !$rc->mAttribs['rc_patrolled'];
512
513                 $dateheader = ''; // $s now contains only <li>...</li>, for hooks' convenience.
514                 $this->insertDateHeader( $dateheader, $rc->mAttribs['rc_timestamp'] );
515
516                 $s = '';
517                 $classes = array();
518                 // use mw-line-even/mw-line-odd class only if linenumber is given (feature from bug 14468)
519                 if( $linenumber ) {
520                         if( $linenumber & 1 ) {
521                                 $classes[] = 'mw-line-odd';
522                         }
523                         else {
524                                 $classes[] = 'mw-line-even';
525                         }
526                 }
527
528                 // Moved pages
529                 if( $rc->mAttribs['rc_type'] == RC_MOVE || $rc->mAttribs['rc_type'] == RC_MOVE_OVER_REDIRECT ) {
530                         $this->insertMove( $s, $rc );
531                 // Log entries
532                 } elseif( $rc->mAttribs['rc_log_type'] ) {
533                         $logtitle = Title::newFromText( 'Log/'.$rc->mAttribs['rc_log_type'], NS_SPECIAL );
534                         $this->insertLog( $s, $logtitle, $rc->mAttribs['rc_log_type'] );
535                 // Log entries (old format) or log targets, and special pages
536                 } elseif( $rc->mAttribs['rc_namespace'] == NS_SPECIAL ) {
537                         list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $rc->mAttribs['rc_title'] );
538                         if( $name == 'Log' ) {
539                                 $this->insertLog( $s, $rc->getTitle(), $subpage );
540                         }
541                 // Regular entries
542                 } else {
543                         $this->insertDiffHist( $s, $rc, $unpatrolled );
544                         # M, N, b and ! (minor, new, bot and unpatrolled)
545                         $s .= $this->recentChangesFlags( $rc->mAttribs['rc_new'], $rc->mAttribs['rc_minor'],
546                                 $unpatrolled, '', $rc->mAttribs['rc_bot'] );
547                         $this->insertArticleLink( $s, $rc, $unpatrolled, $watched );
548                 }
549                 # Edit/log timestamp
550                 $this->insertTimestamp( $s, $rc );
551                 # Bytes added or removed
552                 if( $wgRCShowChangedSize ) {
553                         $cd = $rc->getCharacterDifference();
554                         if( $cd != '' ) {
555                                 $s .= "$cd  . . ";
556                         }
557                 }
558                 # User tool links
559                 $this->insertUserRelatedLinks( $s, $rc );
560                 # Log action text (if any)
561                 $this->insertAction( $s, $rc );
562                 # Edit or log comment
563                 $this->insertComment( $s, $rc );
564                 # Tags
565                 $this->insertTags( $s, $rc, $classes );
566                 # Rollback
567                 $this->insertRollback( $s, $rc );
568                 # For subclasses
569                 $this->insertExtra( $s, $rc, $classes );
570                 
571                 # How many users watch this page
572                 if( $rc->numberofWatchingusers > 0 ) {
573                         $s .= ' ' . wfMsgExt( 'number_of_watching_users_RCview', 
574                                 array( 'parsemag', 'escape' ), $wgLang->formatNum( $rc->numberofWatchingusers ) );
575                 }
576                 
577                 if( $this->watchlist ) {
578                         $classes[] = Sanitizer::escapeClass( 'watchlist-'.$rc->mAttribs['rc_namespace'].'-'.$rc->mAttribs['rc_title'] );
579                 }
580                 
581                 wfRunHooks( 'OldChangesListRecentChangesLine', array(&$this, &$s, $rc) );
582
583                 wfProfileOut( __METHOD__ );
584                 return "$dateheader<li class=\"".implode( ' ', $classes )."\">".$s."</li>\n";
585         }
586 }
587
588
589 /**
590  * Generate a list of changes using an Enhanced system (uses javascript).
591  */
592 class EnhancedChangesList extends ChangesList {
593         /**
594          * Add the JavaScript file for enhanced changeslist
595          * @return String
596          */
597         public function beginRecentChangesList() {
598                 global $wgStylePath, $wgStyleVersion;
599                 $this->rc_cache = array();
600                 $this->rcMoveIndex = 0;
601                 $this->rcCacheIndex = 0;
602                 $this->lastdate = '';
603                 $this->rclistOpen = false;
604                 $script = Html::linkedScript( $wgStylePath . "/common/enhancedchanges.js?$wgStyleVersion" );
605                 return $script;
606         }
607         /**
608          * Format a line for enhanced recentchange (aka with javascript and block of lines).
609          */
610         public function recentChangesLine( &$baseRC, $watched = false ) {
611                 global $wgLang, $wgUser;
612                 
613                 wfProfileIn( __METHOD__ );
614
615                 # Create a specialised object
616                 $rc = RCCacheEntry::newFromParent( $baseRC );
617
618                 # Extract fields from DB into the function scope (rc_xxxx variables)
619                 // FIXME: Would be good to replace this extract() call with something
620                 // that explicitly initializes variables.
621                 extract( $rc->mAttribs );
622                 $curIdEq = array( 'curid' => $rc_cur_id );
623
624                 # If it's a new day, add the headline and flush the cache
625                 $date = $wgLang->date( $rc_timestamp, true );
626                 $ret = '';
627                 if( $date != $this->lastdate ) {
628                         # Process current cache
629                         $ret = $this->recentChangesBlock();
630                         $this->rc_cache = array();
631                         $ret .= Xml::element( 'h4', null, $date );
632                         $this->lastdate = $date;
633                 }
634
635                 # Should patrol-related stuff be shown?
636                 if( $wgUser->useRCPatrol() ) {
637                         $rc->unpatrolled = !$rc_patrolled;
638                 } else {
639                         $rc->unpatrolled = false;
640                 }
641
642                 $showdifflinks = true;
643                 # Make article link
644                 // Page moves
645                 if( $rc_type == RC_MOVE || $rc_type == RC_MOVE_OVER_REDIRECT ) {
646                         $msg = ( $rc_type == RC_MOVE ) ? "1movedto2" : "1movedto2_redir";
647                         $clink = wfMsg( $msg, $this->skin->linkKnown( $rc->getTitle(), null,
648                                 array(), array( 'redirect' => 'no' ) ),
649                                 $this->skin->linkKnown( $rc->getMovedToTitle() ) );
650                 // New unpatrolled pages
651                 } else if( $rc->unpatrolled && $rc_type == RC_NEW ) {
652                         $clink = $this->skin->linkKnown( $rc->getTitle(), null, array(),
653                                 array( 'rcid' => $rc_id ) );
654                 // Log entries
655                 } else if( $rc_type == RC_LOG ) {
656                         if( $rc_log_type ) {
657                                 $logtitle = SpecialPage::getTitleFor( 'Log', $rc_log_type );
658                                 $clink = '(' . $this->skin->linkKnown( $logtitle, 
659                                         LogPage::logName($rc_log_type) ) . ')';
660                         } else {
661                                 $clink = $this->skin->link( $rc->getTitle() );
662                         }
663                         $watched = false;
664                 // Log entries (old format) and special pages
665                 } elseif( $rc_namespace == NS_SPECIAL ) {
666                         list( $specialName, $logtype ) = SpecialPage::resolveAliasWithSubpage( $rc_title );
667                         if ( $specialName == 'Log' ) {
668                                 # Log updates, etc
669                                 $logname = LogPage::logName( $logtype );
670                                 $clink = '(' . $this->skin->linkKnown( $rc->getTitle(), $logname ) . ')';
671                         } else {
672                                 wfDebug( "Unexpected special page in recentchanges\n" );
673                                 $clink = '';
674                         }
675                 // Edits
676                 } else {
677                         $clink = $this->skin->linkKnown( $rc->getTitle() );
678                 }
679
680                 # Don't show unusable diff links
681                 if ( !ChangesList::userCan($rc,Revision::DELETED_TEXT) ) {
682                         $showdifflinks = false;
683                 }
684
685                 $time = $wgLang->time( $rc_timestamp, true, true );
686                 $rc->watched = $watched;
687                 $rc->link = $clink;
688                 $rc->timestamp = $time;
689                 $rc->numberofWatchingusers = $baseRC->numberofWatchingusers;
690
691                 # Make "cur" and "diff" links.  Do not use link(), it is too slow if
692                 # called too many times (50% of CPU time on RecentChanges!).
693                 if( $rc->unpatrolled ) {
694                         $rcIdQuery = array( 'rcid' => $rc_id );
695                 } else {
696                         $rcIdQuery = array();
697                 }
698                 $querycur = $curIdEq + array( 'diff' => '0', 'oldid' => $rc_this_oldid );
699                 $querydiff = $curIdEq + array( 'diff' => $rc_this_oldid, 'oldid' =>
700                         $rc_last_oldid ) + $rcIdQuery;
701
702                 if( !$showdifflinks ) {
703                         $curLink = $this->message['cur'];
704                         $diffLink = $this->message['diff'];
705                 } else if( in_array( $rc_type, array(RC_NEW,RC_LOG,RC_MOVE,RC_MOVE_OVER_REDIRECT) ) ) {
706                         if ( $rc_type != RC_NEW ) {
707                                 $curLink = $this->message['cur'];
708                         } else {
709                                 $curUrl = htmlspecialchars( $rc->getTitle()->getLinkUrl( $querycur ) );
710                                 $curLink = "<a href=\"$curUrl\" tabindex=\"{$baseRC->counter}\">{$this->message['cur']}</a>";
711                         }
712                         $diffLink = $this->message['diff'];
713                 } else {
714                         $diffUrl = htmlspecialchars( $rc->getTitle()->getLinkUrl( $querydiff ) );
715                         $curUrl = htmlspecialchars( $rc->getTitle()->getLinkUrl( $querycur ) );
716                         $diffLink = "<a href=\"$diffUrl\" tabindex=\"{$baseRC->counter}\">{$this->message['diff']}</a>";
717                         $curLink = "<a href=\"$curUrl\" tabindex=\"{$baseRC->counter}\">{$this->message['cur']}</a>";
718                 }
719
720                 # Make "last" link
721                 if( !$showdifflinks || !$rc_last_oldid ) {
722                         $lastLink = $this->message['last'];
723                 } else if( $rc_type == RC_LOG || $rc_type == RC_MOVE || $rc_type == RC_MOVE_OVER_REDIRECT ) {
724                         $lastLink = $this->message['last'];
725                 } else {
726                         $lastLink = $this->skin->linkKnown( $rc->getTitle(), $this->message['last'],
727                                 array(), $curIdEq + array('diff' => $rc_this_oldid, 'oldid' => $rc_last_oldid) + $rcIdQuery );
728                 }
729
730                 # Make user links
731                 if( $this->isDeleted($rc,Revision::DELETED_USER) ) {
732                         $rc->userlink = ' <span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
733                 } else {
734                         $rc->userlink = $this->skin->userLink( $rc_user, $rc_user_text );
735                         $rc->usertalklink = $this->skin->userToolLinks( $rc_user, $rc_user_text );
736                 }
737
738                 $rc->lastlink = $lastLink;
739                 $rc->curlink  = $curLink;
740                 $rc->difflink = $diffLink;
741
742                 # Put accumulated information into the cache, for later display
743                 # Page moves go on their own line
744                 $title = $rc->getTitle();
745                 $secureName = $title->getPrefixedDBkey();
746                 if( $rc_type == RC_MOVE || $rc_type == RC_MOVE_OVER_REDIRECT ) {
747                         # Use an @ character to prevent collision with page names
748                         $this->rc_cache['@@' . ($this->rcMoveIndex++)] = array($rc);
749                 } else {
750                         # Logs are grouped by type
751                         if( $rc_type == RC_LOG ){
752                                 $secureName = SpecialPage::getTitleFor( 'Log', $rc_log_type )->getPrefixedDBkey();
753                         }
754                         if( !isset( $this->rc_cache[$secureName] ) ) {
755                                 $this->rc_cache[$secureName] = array();
756                         }
757
758                         array_push( $this->rc_cache[$secureName], $rc );
759                 }
760
761                 wfProfileOut( __METHOD__ );
762
763                 return $ret;
764         }
765
766         /**
767          * Enhanced RC group
768          */
769         protected function recentChangesBlockGroup( $block ) {
770                 global $wgLang, $wgContLang, $wgRCShowChangedSize;
771
772                 wfProfileIn( __METHOD__ );
773
774                 $r = '<table class="mw-enhanced-rc"><tr>';
775
776                 # Collate list of users
777                 $userlinks = array();
778                 # Other properties
779                 $unpatrolled = false;
780                 $isnew = false;
781                 $curId = $currentRevision = 0;
782                 # Some catalyst variables...
783                 $namehidden = true;
784                 $allLogs = true;
785                 foreach( $block as $rcObj ) {
786                         $oldid = $rcObj->mAttribs['rc_last_oldid'];
787                         if( $rcObj->mAttribs['rc_new'] ) {
788                                 $isnew = true;
789                         }
790                         // If all log actions to this page were hidden, then don't
791                         // give the name of the affected page for this block!
792                         if( !$this->isDeleted( $rcObj, LogPage::DELETED_ACTION ) ) {
793                                 $namehidden = false;
794                         }
795                         $u = $rcObj->userlink;
796                         if( !isset( $userlinks[$u] ) ) {
797                                 $userlinks[$u] = 0;
798                         }
799                         if( $rcObj->unpatrolled ) {
800                                 $unpatrolled = true;
801                         }
802                         if( $rcObj->mAttribs['rc_type'] != RC_LOG ) {
803                                 $allLogs = false;
804                         }
805                         # Get the latest entry with a page_id and oldid
806                         # since logs may not have these.
807                         if( !$curId && $rcObj->mAttribs['rc_cur_id'] ) {
808                                 $curId = $rcObj->mAttribs['rc_cur_id'];
809                         }
810                         if( !$currentRevision && $rcObj->mAttribs['rc_this_oldid'] ) {
811                                 $currentRevision = $rcObj->mAttribs['rc_this_oldid'];
812                         }
813
814                         $bot = $rcObj->mAttribs['rc_bot'];
815                         $userlinks[$u]++;
816                 }
817
818                 # Sort the list and convert to text
819                 krsort( $userlinks );
820                 asort( $userlinks );
821                 $users = array();
822                 foreach( $userlinks as $userlink => $count) {
823                         $text = $userlink;
824                         $text .= $wgContLang->getDirMark();
825                         if( $count > 1 ) {
826                                 $text .= ' (' . $wgLang->formatNum( $count ) . '×)';
827                         }
828                         array_push( $users, $text );
829                 }
830
831                 $users = ' <span class="changedby">[' . 
832                         implode( $this->message['semicolon-separator'], $users ) . ']</span>';
833
834                 # ID for JS visibility toggle
835                 $jsid = $this->rcCacheIndex;
836                 # onclick handler to toggle hidden/expanded
837                 $toggleLink = "onclick='toggleVisibility($jsid); return false'";
838                 # Title for <a> tags
839                 $expandTitle = htmlspecialchars( wfMsg( 'rc-enhanced-expand' ) );
840                 $closeTitle = htmlspecialchars( wfMsg( 'rc-enhanced-hide' ) );
841
842                 $tl = "<span id='mw-rc-openarrow-$jsid' class='mw-changeslist-expanded' style='visibility:hidden'><a href='#' $toggleLink title='$expandTitle'>" . $this->sideArrow() . "</a></span>";
843                 $tl .= "<span id='mw-rc-closearrow-$jsid' class='mw-changeslist-hidden' style='display:none'><a href='#' $toggleLink title='$closeTitle'>" . $this->downArrow() . "</a></span>";
844                 $r .= '<td class="mw-enhanced-rc">'.$tl.'&nbsp;';
845
846                 # Main line
847                 $r .= $this->recentChangesFlags( $isnew, false, $unpatrolled, '&nbsp;', $bot );
848
849                 # Timestamp
850                 $r .= '&nbsp;'.$block[0]->timestamp.'&nbsp;</td><td style="padding:0px;">';
851
852                 # Article link
853                 if( $namehidden ) {
854                         $r .= ' <span class="history-deleted">' . wfMsgHtml( 'rev-deleted-event' ) . '</span>';
855                 } else if( $allLogs ) {
856                         $r .= $this->maybeWatchedLink( $block[0]->link, $block[0]->watched );
857                 } else {
858                         $this->insertArticleLink( $r, $block[0], $block[0]->unpatrolled, $block[0]->watched );
859                 }
860
861                 $r .= $wgContLang->getDirMark();
862
863                 $queryParams['curid'] = $curId;
864                 # Changes message
865                 $n = count($block);
866                 static $nchanges = array();
867                 if ( !isset( $nchanges[$n] ) ) {
868                         $nchanges[$n] = wfMsgExt( 'nchanges', array( 'parsemag', 'escape' ), $wgLang->formatNum( $n ) );
869                 }
870                 # Total change link
871                 $r .= ' ';
872                 if( !$allLogs ) {
873                         $r .= '(';
874                         if( !ChangesList::userCan( $rcObj, Revision::DELETED_TEXT ) ) {
875                                 $r .= $nchanges[$n];
876                         } else if( $isnew ) {
877                                 $r .= $nchanges[$n];
878                         } else {
879                                 $params = $queryParams;
880                                 $params['diff'] = $currentRevision;
881                                 $params['oldid'] = $oldid;
882                                 
883                                 $r .= $this->skin->link(
884                                         $block[0]->getTitle(),
885                                         $nchanges[$n],
886                                         array(),
887                                         $params,
888                                         array( 'known', 'noclasses' )
889                                 );
890                         }
891                 }
892
893                 # History
894                 if( $allLogs ) {
895                         // don't show history link for logs
896                 } else if( $namehidden || !$block[0]->getTitle()->exists() ) {
897                         $r .= $this->message['pipe-separator'] . $this->message['hist'] . ')';
898                 } else {
899                         $params = $queryParams;
900                         $params['action'] = 'history';
901
902                         $r .= $this->message['pipe-separator'] .
903                                 $this->skin->link(
904                                         $block[0]->getTitle(),
905                                         $this->message['hist'],
906                                         array(),
907                                         $params,
908                                         array( 'known', 'noclasses' )
909                                 ) . ')';
910                 }
911                 $r .= ' . . ';
912
913                 # Character difference (does not apply if only log items)
914                 if( $wgRCShowChangedSize && !$allLogs ) {
915                         $last = 0;
916                         $first = count($block) - 1;
917                         # Some events (like logs) have an "empty" size, so we need to skip those...
918                         while( $last < $first && $block[$last]->mAttribs['rc_new_len'] === null ) {
919                                 $last++;
920                         }
921                         while( $first > $last && $block[$first]->mAttribs['rc_old_len'] === null ) {
922                                 $first--;
923                         }
924                         # Get net change
925                         $chardiff = $rcObj->getCharacterDifference( $block[$first]->mAttribs['rc_old_len'],
926                                 $block[$last]->mAttribs['rc_new_len'] );
927
928                         if( $chardiff == '' ) {
929                                 $r .= ' ';
930                         } else {
931                                 $r .= ' ' . $chardiff. ' . . ';
932                         }
933                 }
934
935                 $r .= $users;
936                 $r .= $this->numberofWatchingusers($block[0]->numberofWatchingusers);
937
938                 $r .= "</td></tr></table>\n";
939
940                 # Sub-entries
941                 $r .= '<div id="mw-rc-subentries-'.$jsid.'" class="mw-changeslist-hidden">';
942                 $r .= '<table class="mw-enhanced-rc">';
943                 foreach( $block as $rcObj ) {
944                         # Extract fields from DB into the function scope (rc_xxxx variables)
945                         // FIXME: Would be good to replace this extract() call with something
946                         // that explicitly initializes variables.
947                         # Classes to apply -- TODO implement
948                         $classes = array();
949                         extract( $rcObj->mAttribs );
950
951                         #$r .= '<tr><td valign="top">'.$this->spacerArrow();
952                         $r .= '<tr><td style="vertical-align:top;font-family:monospace; padding:0px;">';
953                         $r .= $this->spacerIndent() . $this->spacerIndent();
954                         $r .= $this->recentChangesFlags( $rc_new, $rc_minor, $rcObj->unpatrolled, '&nbsp;', $rc_bot );
955                         $r .= '&nbsp;</td><td style="vertical-align:top; padding:0px;"><span style="font-family:monospace">';
956
957                         $params = $queryParams;
958
959                         if( $rc_this_oldid != 0 ) {
960                                 $params['oldid'] = $rc_this_oldid;
961                         }
962
963                         # Log timestamp
964                         if( $rc_type == RC_LOG ) {
965                                 $link = $rcObj->timestamp;
966                         # Revision link
967                         } else if( !ChangesList::userCan($rcObj,Revision::DELETED_TEXT) ) {
968                                 $link = '<span class="history-deleted">'.$rcObj->timestamp.'</span> ';
969                         } else {
970                                 if ( $rcObj->unpatrolled && $rc_type == RC_NEW) {
971                                         $params['rcid'] = $rcObj->mAttribs['rc_id'];
972                                 }
973
974                                 $link = $this->skin->link(
975                                                 $rcObj->getTitle(),
976                                                 $rcObj->timestamp,
977                                                 array(),
978                                                 $params,
979                                                 array( 'known', 'noclasses' )
980                                         );
981                                 if( $this->isDeleted($rcObj,Revision::DELETED_TEXT) )
982                                         $link = '<span class="history-deleted">'.$link.'</span> ';
983                         }
984                         $r .= $link . '</span>';
985
986                         if ( !$rc_type == RC_LOG || $rc_type == RC_NEW ) {
987                                 $r .= ' (';
988                                 $r .= $rcObj->curlink;
989                                 $r .= $this->message['pipe-separator'];
990                                 $r .= $rcObj->lastlink;
991                                 $r .= ')';
992                         }
993                         $r .= ' . . ';
994
995                         # Character diff
996                         if( $wgRCShowChangedSize ) {
997                                 $r .= ( $rcObj->getCharacterDifference() == '' ? '' : $rcObj->getCharacterDifference() . ' . . ' ) ;
998                         }
999                         # User links
1000                         $r .= $rcObj->userlink;
1001                         $r .= $rcObj->usertalklink;
1002                         // log action
1003                         $this->insertAction( $r, $rcObj );
1004                         // log comment
1005                         $this->insertComment( $r, $rcObj );
1006                         # Rollback
1007                         $this->insertRollback( $r, $rcObj );
1008                         # Tags
1009                         $this->insertTags( $r, $rcObj, $classes );
1010
1011                         $r .= "</td></tr>\n";
1012                 }
1013                 $r .= "</table></div>\n";
1014
1015                 $this->rcCacheIndex++;
1016
1017                 wfProfileOut( __METHOD__ );
1018
1019                 return $r;
1020         }
1021
1022         /**
1023          * Generate HTML for an arrow or placeholder graphic
1024          * @param $dir String: one of '', 'd', 'l', 'r'
1025          * @param $alt String: text
1026          * @param $title String: text
1027          * @return String: HTML <img> tag
1028          */
1029         protected function arrow( $dir, $alt='', $title='' ) {
1030                 global $wgStylePath;
1031                 $encUrl = htmlspecialchars( $wgStylePath . '/common/images/Arr_' . $dir . '.png' );
1032                 $encAlt = htmlspecialchars( $alt );
1033                 $encTitle = htmlspecialchars( $title );
1034                 return "<img src=\"$encUrl\" width=\"12\" height=\"12\" alt=\"$encAlt\" title=\"$encTitle\" />";
1035         }
1036
1037         /**
1038          * Generate HTML for a right- or left-facing arrow,
1039          * depending on language direction.
1040          * @return String: HTML <img> tag
1041          */
1042         protected function sideArrow() {
1043                 global $wgContLang;
1044                 $dir = $wgContLang->isRTL() ? 'l' : 'r';
1045                 return $this->arrow( $dir, '+', wfMsg( 'rc-enhanced-expand' ) );
1046         }
1047
1048         /**
1049          * Generate HTML for a down-facing arrow
1050          * depending on language direction.
1051          * @return String: HTML <img> tag
1052          */
1053         protected function downArrow() {
1054                 return $this->arrow( 'd', '-', wfMsg( 'rc-enhanced-hide' ) );
1055         }
1056
1057         /**
1058          * Generate HTML for a spacer image
1059          * @return String: HTML <img> tag
1060          */
1061         protected function spacerArrow() {
1062                 return $this->arrow( '', codepointToUtf8( 0xa0 ) ); // non-breaking space
1063         }
1064
1065         /**
1066          * Add a set of spaces
1067          * @return String: HTML <td> tag
1068          */
1069         protected function spacerIndent() {
1070                 return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1071         }
1072
1073         /**
1074          * Enhanced RC ungrouped line.
1075          * @return String: a HTML formated line (generated using $r)
1076          */
1077         protected function recentChangesBlockLine( $rcObj ) {
1078                 global $wgRCShowChangedSize;
1079
1080                 wfProfileIn( __METHOD__ );
1081
1082                 # Extract fields from DB into the function scope (rc_xxxx variables)
1083                 // FIXME: Would be good to replace this extract() call with something
1084                 // that explicitly initializes variables.
1085                 $classes = array(); // TODO implement
1086                 extract( $rcObj->mAttribs );
1087                 $query['curid'] = $rc_cur_id;
1088
1089                 $r = '<table class="mw-enhanced-rc"><tr>';
1090                 $r .= '<td class="mw-enhanced-rc">' . $this->spacerArrow() . '&nbsp;';
1091                 # Flag and Timestamp
1092                 if( $rc_type == RC_MOVE || $rc_type == RC_MOVE_OVER_REDIRECT ) {
1093                         $r .= '&nbsp;&nbsp;&nbsp;&nbsp;'; // 4 flags -> 4 spaces
1094                 } else {
1095                         $r .= $this->recentChangesFlags( $rc_type == RC_NEW, $rc_minor, $rcObj->unpatrolled, '&nbsp;', $rc_bot );
1096                 }
1097                 $r .= '&nbsp;'.$rcObj->timestamp.'&nbsp;</td><td style="padding:0px;">';
1098                 # Article or log link
1099                 if( $rc_log_type ) {
1100                         $logtitle = Title::newFromText( "Log/$rc_log_type", NS_SPECIAL );
1101                         $logname = LogPage::logName( $rc_log_type );
1102                         $r .= '(' . $this->skin->link(
1103                                 $logtitle,
1104                                 $logname,
1105                                 array(),
1106                                 array(),
1107                                 array( 'known', 'noclasses' )
1108                         ) . ')';
1109                 } else {
1110                         $this->insertArticleLink( $r, $rcObj, $rcObj->unpatrolled, $rcObj->watched );
1111                 }
1112                 # Diff and hist links
1113                 if ( $rc_type != RC_LOG ) {
1114                         $r .= ' ('. $rcObj->difflink . $this->message['pipe-separator'];
1115                         $query['action'] = 'history';
1116                         $r .= $this->skin->link(
1117                                 $rcObj->getTitle(),
1118                                 $this->message['hist'],
1119                                 array(),
1120                                 $query,
1121                                 array( 'known', 'noclasses' )
1122                         ) . ')';
1123                 }
1124                 $r .= ' . . ';
1125                 # Character diff
1126                 if( $wgRCShowChangedSize && ($cd = $rcObj->getCharacterDifference()) ) {
1127                         $r .= "$cd . . ";
1128                 }
1129                 # User/talk
1130                 $r .= ' '.$rcObj->userlink . $rcObj->usertalklink;
1131                 # Log action (if any)
1132                 if( $rc_log_type ) {
1133                         if( $this->isDeleted($rcObj,LogPage::DELETED_ACTION) ) {
1134                                 $r .= ' <span class="history-deleted">' . wfMsgHtml('rev-deleted-event') . '</span>';
1135                         } else {
1136                                 $r .= ' ' . LogPage::actionText( $rc_log_type, $rc_log_action, $rcObj->getTitle(), 
1137                                         $this->skin, LogPage::extractParams($rc_params), true, true );
1138                         }
1139                 }
1140                 $this->insertComment( $r, $rcObj );
1141                 $this->insertRollback( $r, $rcObj );
1142                 # Tags
1143                 $this->insertTags( $r, $rcObj, $classes );
1144                 # Show how many people are watching this if enabled
1145                 $r .= $this->numberofWatchingusers($rcObj->numberofWatchingusers);
1146
1147                 $r .= "</td></tr></table>\n";
1148
1149                 wfProfileOut( __METHOD__ );
1150
1151                 return $r;
1152         }
1153
1154         /**
1155          * If enhanced RC is in use, this function takes the previously cached
1156          * RC lines, arranges them, and outputs the HTML
1157          */
1158         protected function recentChangesBlock() {
1159                 if( count ( $this->rc_cache ) == 0 ) {
1160                         return '';
1161                 }
1162
1163                 wfProfileIn( __METHOD__ );
1164
1165                 $blockOut = '';
1166                 foreach( $this->rc_cache as $block ) {
1167                         if( count( $block ) < 2 ) {
1168                                 $blockOut .= $this->recentChangesBlockLine( array_shift( $block ) );
1169                         } else {
1170                                 $blockOut .= $this->recentChangesBlockGroup( $block );
1171                         }
1172                 }
1173
1174                 wfProfileOut( __METHOD__ );
1175
1176                 return '<div>'.$blockOut.'</div>';
1177         }
1178
1179         /**
1180          * Returns text for the end of RC
1181          * If enhanced RC is in use, returns pretty much all the text
1182          */
1183         public function endRecentChangesList() {
1184                 return $this->recentChangesBlock() . parent::endRecentChangesList();
1185         }
1186
1187 }