Don't spew () when tools group is empty (as on last line where there can be no undo...
[lhc/web/wiklou.git] / includes / PageHistory.php
1 <?php
2 /**
3 * Page history
4 *
5 * Split off from Article.php and Skin.php, 2003-12-22
6 */
7
8 /**
9 * This class handles printing the history page for an article. In order to
10 * be efficient, it uses timestamps rather than offsets for paging, to avoid
11 * costly LIMIT,offset queries.
12 *
13 * Construct it by passing in an Article, and call $h->history() to print the
14 * history.
15 *
16 */
17 class PageHistory {
18 const DIR_PREV = 0;
19 const DIR_NEXT = 1;
20
21 var $mArticle, $mTitle, $mSkin;
22 var $lastdate;
23 var $linesonpage;
24 var $mNotificationTimestamp;
25 var $mLatestId = null;
26
27 /**
28 * Construct a new PageHistory.
29 *
30 * @param Article $article
31 * @returns nothing
32 */
33 function __construct($article) {
34 global $wgUser;
35
36 $this->mArticle =& $article;
37 $this->mTitle =& $article->mTitle;
38 $this->mNotificationTimestamp = NULL;
39 $this->mSkin = $wgUser->getSkin();
40 }
41
42 /**
43 * Print the history page for an article.
44 *
45 * @returns nothing
46 */
47 function history() {
48 global $wgOut, $wgRequest, $wgTitle;
49
50 /*
51 * Allow client caching.
52 */
53
54 if( $wgOut->checkLastModified( $this->mArticle->getTimestamp() ) )
55 /* Client cache fresh and headers sent, nothing more to do. */
56 return;
57
58 $fname = 'PageHistory::history';
59 wfProfileIn( $fname );
60
61 /*
62 * Setup page variables.
63 */
64 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
65 $wgOut->setArticleFlag( false );
66 $wgOut->setArticleRelated( true );
67 $wgOut->setRobotpolicy( 'noindex,nofollow' );
68 $wgOut->setSyndicated( true );
69
70 $logPage = SpecialPage::getTitleFor( 'Log' );
71 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ), 'page=' . $this->mTitle->getPrefixedUrl() );
72
73 $subtitle = wfMsgHtml( 'revhistory' ) . '<br />' . $logLink;
74 $wgOut->setSubtitle( $subtitle );
75
76 $feedType = $wgRequest->getVal( 'feed' );
77 if( $feedType ) {
78 wfProfileOut( $fname );
79 return $this->feed( $feedType );
80 }
81
82 /*
83 * Fail if article doesn't exist.
84 */
85 if( !$this->mTitle->exists() ) {
86 $wgOut->addWikiText( wfMsg( 'nohistory' ) );
87 wfProfileOut( $fname );
88 return;
89 }
90
91
92 /*
93 * "go=first" means to jump to the last (earliest) history page.
94 * This is deprecated, it no longer appears in the user interface
95 */
96 if ( $wgRequest->getText("go") == 'first' ) {
97 $limit = $wgRequest->getInt( 'limit', 50 );
98 $wgOut->redirect( $wgTitle->getLocalURL( "action=history&limit={$limit}&dir=prev" ) );
99 return;
100 }
101
102 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
103
104 /**
105 * Do the list
106 */
107 $pager = new PageHistoryPager( $this );
108 $this->linesonpage = $pager->getNumRows();
109 $wgOut->addHTML(
110 $pager->getNavigationBar() .
111 $this->beginHistoryList() .
112 $pager->getBody() .
113 $this->endHistoryList() .
114 $pager->getNavigationBar()
115 );
116 wfProfileOut( $fname );
117 }
118
119 /** @todo document */
120 function beginHistoryList() {
121 global $wgTitle;
122 $this->lastdate = '';
123 $s = wfMsgExt( 'histlegend', array( 'parse') );
124 $s .= '<form action="' . $wgTitle->escapeLocalURL( '-' ) . '" method="get">';
125 $prefixedkey = htmlspecialchars($wgTitle->getPrefixedDbKey());
126
127 // The following line is SUPPOSED to have double-quotes around the
128 // $prefixedkey variable, because htmlspecialchars() doesn't escape
129 // single-quotes.
130 //
131 // On at least two occasions people have changed it to single-quotes,
132 // which creates invalid HTML and incorrect display of the resulting
133 // link.
134 //
135 // Please do not break this a third time. Thank you for your kind
136 // consideration and cooperation.
137 //
138 $s .= "<input type='hidden' name='title' value=\"{$prefixedkey}\" />\n";
139
140 $s .= $this->submitButton();
141 $s .= '<ul id="pagehistory">' . "\n";
142 return $s;
143 }
144
145 /** @todo document */
146 function endHistoryList() {
147 $s = '</ul>';
148 $s .= $this->submitButton( array( 'id' => 'historysubmit' ) );
149 $s .= '</form>';
150 return $s;
151 }
152
153 /** @todo document */
154 function submitButton( $bits = array() ) {
155 return ( $this->linesonpage > 0 )
156 ? wfElement( 'input', array_merge( $bits,
157 array(
158 'class' => 'historysubmit',
159 'type' => 'submit',
160 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
161 'title' => wfMsg( 'tooltip-compareselectedversions' ).' ['.wfMsg( 'accesskey-compareselectedversions' ).']',
162 'value' => wfMsg( 'compareselectedversions' ),
163 ) ) )
164 : '';
165 }
166
167 /**
168 * Returns a row from the history printout.
169 *
170 * @todo document some more, and maybe clean up the code (some params redundant?)
171 *
172 * @param object $row The database row corresponding to the line (or is it the previous line?).
173 * @param object $next The database row corresponding to the next line (or is it this one?).
174 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
175 * @param $notificationtimestamp
176 * @param bool $latest Whether this row corresponds to the page's latest revision.
177 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
178 * @return string HTML output for the row
179 */
180 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
181 global $wgUser, $wgLang;
182 $rev = new Revision( $row );
183 $rev->setTitle( $this->mTitle );
184
185 $s = '<li>';
186 $curlink = $this->curLink( $rev, $latest );
187 $lastlink = $this->lastLink( $rev, $next, $counter );
188 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
189 $link = $this->revLink( $rev );
190
191 $user = $this->mSkin->userLink( $rev->getUser(), $rev->getUserText() )
192 . $this->mSkin->userToolLinks( $rev->getUser(), $rev->getUserText() );
193
194 $s .= "($curlink) ($lastlink) $arbitrary";
195
196 if( $wgUser->isAllowed( 'deleterevision' ) ) {
197 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
198 if( $firstInList ) {
199 // We don't currently handle well changing the top revision's settings
200 $del = wfMsgHtml( 'rev-delundel' );
201 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
202 // If revision was hidden from sysops
203 $del = wfMsgHtml( 'rev-delundel' );
204 } else {
205 $del = $this->mSkin->makeKnownLinkObj( $revdel,
206 wfMsg( 'rev-delundel' ),
207 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
208 '&oldid=' . urlencode( $rev->getId() ) );
209 }
210 $s .= " (<small>$del</small>) ";
211 }
212
213 $s .= " $link";
214 #getUser is safe, but this avoids making the invalid untargeted contribs links
215 if( $row->rev_deleted & Revision::DELETED_USER ) {
216 $user = '<span class="history-deleted">' . wfMsg('rev-deleted-user') . '</span>';
217 }
218 $s .= " <span class='history-user'>$user</span>";
219
220 if( $row->rev_minor_edit ) {
221 $s .= ' ' . wfElement( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
222 }
223
224 if (!is_null($size = $rev->getSize())) {
225 if ($size == 0)
226 $stxt = wfMsgHtml('historyempty');
227 else
228 $stxt = wfMsgHtml('historysize', $wgLang->formatNum( $size ) );
229 $s .= " <span class=\"history-size\">$stxt</span>";
230 }
231
232 #getComment is safe, but this is better formatted
233 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
234 $s .= " <span class=\"history-deleted\"><span class=\"comment\">" .
235 wfMsgHtml( 'rev-deleted-comment' ) . "</span></span>";
236 } else {
237 $s .= $this->mSkin->revComment( $rev );
238 }
239
240 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
241 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
242 }
243 #add blurb about text having been deleted
244 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
245 $s .= ' ' . wfMsgHtml( 'deletedrev' );
246 }
247
248 $tools = array();
249
250 if( $wgUser->isAllowed( 'rollback' ) && $latest ) {
251 $tools[] = '<span class="mw-rollback-link">'
252 . $this->mSkin->buildRollbackLink( $rev )
253 . '</span>';
254 }
255
256 if ( !is_null( $next ) ) {
257 $undolink = $this->mSkin->makeKnownLinkObj(
258 $this->mTitle,
259 wfMsgHtml( 'editundo' ),
260 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
261 );
262 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
263 }
264
265 if( $tools ) {
266 $s .= ' (' . implode( ' | ', $tools ) . ')';
267 }
268
269 wfRunHooks( 'PageHistoryLineEnding', array( &$row , &$s ) );
270
271 $s .= "</li>\n";
272
273 return $s;
274 }
275
276 /** @todo document */
277 function revLink( $rev ) {
278 global $wgLang;
279 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
280 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
281 $link = $this->mSkin->makeKnownLinkObj(
282 $this->mTitle, $date, "oldid=" . $rev->getId() );
283 } else {
284 $link = $date;
285 }
286 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
287 return '<span class="history-deleted">' . $link . '</span>';
288 }
289 return $link;
290 }
291
292 /** @todo document */
293 function curLink( $rev, $latest ) {
294 $cur = wfMsgExt( 'cur', array( 'escape') );
295 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
296 return $cur;
297 } else {
298 return $this->mSkin->makeKnownLinkObj(
299 $this->mTitle, $cur,
300 'diff=' . $this->getLatestID() .
301 "&oldid=" . $rev->getId() );
302 }
303 }
304
305 /** @todo document */
306 function lastLink( $rev, $next, $counter ) {
307 $last = wfMsgExt( 'last', array( 'escape' ) );
308 if ( is_null( $next ) ) {
309 # Probably no next row
310 return $last;
311 } elseif ( $next === 'unknown' ) {
312 # Next row probably exists but is unknown, use an oldid=prev link
313 return $this->mSkin->makeKnownLinkObj(
314 $this->mTitle,
315 $last,
316 "diff=" . $rev->getId() . "&oldid=prev" );
317 } elseif( !$rev->userCan( Revision::DELETED_TEXT ) ) {
318 return $last;
319 } else {
320 return $this->mSkin->makeKnownLinkObj(
321 $this->mTitle,
322 $last,
323 "diff=" . $rev->getId() . "&oldid={$next->rev_id}"
324 /*,
325 '',
326 '',
327 "tabindex={$counter}"*/ );
328 }
329 }
330
331 /** @todo document */
332 function diffButtons( $rev, $firstInList, $counter ) {
333 if( $this->linesonpage > 1) {
334 $radio = array(
335 'type' => 'radio',
336 'value' => $rev->getId(),
337 # do we really need to flood this on every item?
338 # 'title' => wfMsgHtml( 'selectolderversionfordiff' )
339 );
340
341 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
342 $radio['disabled'] = 'disabled';
343 }
344
345 /** @todo: move title texts to javascript */
346 if ( $firstInList ) {
347 $first = wfElement( 'input', array_merge(
348 $radio,
349 array(
350 'style' => 'visibility:hidden',
351 'name' => 'oldid' ) ) );
352 $checkmark = array( 'checked' => 'checked' );
353 } else {
354 if( $counter == 2 ) {
355 $checkmark = array( 'checked' => 'checked' );
356 } else {
357 $checkmark = array();
358 }
359 $first = wfElement( 'input', array_merge(
360 $radio,
361 $checkmark,
362 array( 'name' => 'oldid' ) ) );
363 $checkmark = array();
364 }
365 $second = wfElement( 'input', array_merge(
366 $radio,
367 $checkmark,
368 array( 'name' => 'diff' ) ) );
369 return $first . $second;
370 } else {
371 return '';
372 }
373 }
374
375 /** @todo document */
376 function getLatestId() {
377 if( is_null( $this->mLatestId ) ) {
378 $id = $this->mTitle->getArticleID();
379 $db = wfGetDB(DB_SLAVE);
380 $this->mLatestId = $db->selectField( 'page',
381 "page_latest",
382 array( 'page_id' => $id ),
383 'PageHistory::getLatestID' );
384 }
385 return $this->mLatestId;
386 }
387
388 /**
389 * Fetch an array of revisions, specified by a given limit, offset and
390 * direction. This is now only used by the feeds. It was previously
391 * used by the main UI but that's now handled by the pager.
392 */
393 function fetchRevisions($limit, $offset, $direction) {
394 $fname = 'PageHistory::fetchRevisions';
395
396 $dbr = wfGetDB( DB_SLAVE );
397
398 if ($direction == PageHistory::DIR_PREV)
399 list($dirs, $oper) = array("ASC", ">=");
400 else /* $direction == PageHistory::DIR_NEXT */
401 list($dirs, $oper) = array("DESC", "<=");
402
403 if ($offset)
404 $offsets = array("rev_timestamp $oper '$offset'");
405 else
406 $offsets = array();
407
408 $page_id = $this->mTitle->getArticleID();
409
410 $res = $dbr->select(
411 'revision',
412 Revision::selectFields(),
413 array_merge(array("rev_page=$page_id"), $offsets),
414 $fname,
415 array('ORDER BY' => "rev_timestamp $dirs",
416 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
417 );
418
419 $result = array();
420 while (($obj = $dbr->fetchObject($res)) != NULL)
421 $result[] = $obj;
422
423 return $result;
424 }
425
426 /** @todo document */
427 function getNotificationTimestamp() {
428 global $wgUser, $wgShowUpdatedMarker;
429 $fname = 'PageHistory::getNotficationTimestamp';
430
431 if ($this->mNotificationTimestamp !== NULL)
432 return $this->mNotificationTimestamp;
433
434 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
435 return $this->mNotificationTimestamp = false;
436
437 $dbr = wfGetDB(DB_SLAVE);
438
439 $this->mNotificationTimestamp = $dbr->selectField(
440 'watchlist',
441 'wl_notificationtimestamp',
442 array( 'wl_namespace' => $this->mTitle->getNamespace(),
443 'wl_title' => $this->mTitle->getDBkey(),
444 'wl_user' => $wgUser->getID()
445 ),
446 $fname);
447
448 // Don't use the special value reserved for telling whether the field is filled
449 if ( is_null( $this->mNotificationTimestamp ) ) {
450 $this->mNotificationTimestamp = false;
451 }
452
453 return $this->mNotificationTimestamp;
454 }
455
456 /**
457 * Output a subscription feed listing recent edits to this page.
458 * @param string $type
459 */
460 function feed( $type ) {
461 require_once 'SpecialRecentchanges.php';
462
463 global $wgFeedClasses;
464 if( !isset( $wgFeedClasses[$type] ) ) {
465 global $wgOut;
466 $wgOut->addWikiText( wfMsg( 'feed-invalid' ) );
467 return;
468 }
469
470 $feed = new $wgFeedClasses[$type](
471 $this->mTitle->getPrefixedText() . ' - ' .
472 wfMsgForContent( 'history-feed-title' ),
473 wfMsgForContent( 'history-feed-description' ),
474 $this->mTitle->getFullUrl( 'action=history' ) );
475
476 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
477 $feed->outHeader();
478 if( $items ) {
479 foreach( $items as $row ) {
480 $feed->outItem( $this->feedItem( $row ) );
481 }
482 } else {
483 $feed->outItem( $this->feedEmpty() );
484 }
485 $feed->outFooter();
486 }
487
488 function feedEmpty() {
489 global $wgOut;
490 return new FeedItem(
491 wfMsgForContent( 'nohistory' ),
492 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
493 $this->mTitle->getFullUrl(),
494 wfTimestamp( TS_MW ),
495 '',
496 $this->mTitle->getTalkPage()->getFullUrl() );
497 }
498
499 /**
500 * Generate a FeedItem object from a given revision table row
501 * Borrows Recent Changes' feed generation functions for formatting;
502 * includes a diff to the previous revision (if any).
503 *
504 * @param $row
505 * @return FeedItem
506 */
507 function feedItem( $row ) {
508 $rev = new Revision( $row );
509 $rev->setTitle( $this->mTitle );
510 $text = rcFormatDiffRow( $this->mTitle,
511 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
512 $rev->getId(),
513 $rev->getTimestamp(),
514 $rev->getComment() );
515
516 if( $rev->getComment() == '' ) {
517 global $wgContLang;
518 $title = wfMsgForContent( 'history-feed-item-nocomment',
519 $rev->getUserText(),
520 $wgContLang->timeanddate( $rev->getTimestamp() ) );
521 } else {
522 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
523 }
524
525 return new FeedItem(
526 $title,
527 $text,
528 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
529 $rev->getTimestamp(),
530 $rev->getUserText(),
531 $this->mTitle->getTalkPage()->getFullUrl() );
532 }
533
534 /**
535 * Quickie hack... strip out wikilinks to more legible form from the comment.
536 */
537 function stripComment( $text ) {
538 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
539 }
540 }
541
542
543 /**
544 * @addtogroup Pager
545 */
546 class PageHistoryPager extends ReverseChronologicalPager {
547 public $mLastRow = false, $mPageHistory;
548
549 function __construct( $pageHistory ) {
550 parent::__construct();
551 $this->mPageHistory = $pageHistory;
552 }
553
554 function getQueryInfo() {
555 return array(
556 'tables' => 'revision',
557 'fields' => Revision::selectFields(),
558 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
559 'options' => array( 'USE INDEX' => 'page_timestamp' )
560 );
561 }
562
563 function getIndexField() {
564 return 'rev_timestamp';
565 }
566
567 function formatRow( $row ) {
568 if ( $this->mLastRow ) {
569 $latest = $this->mCounter == 1 && $this->mOffset == '';
570 $firstInList = $this->mCounter == 1;
571 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
572 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
573 } else {
574 $s = '';
575 }
576 $this->mLastRow = $row;
577 return $s;
578 }
579
580 function getStartBody() {
581 $this->mLastRow = false;
582 $this->mCounter = 1;
583 return '';
584 }
585
586 function getEndBody() {
587 if ( $this->mLastRow ) {
588 $latest = $this->mCounter == 1 && $this->mOffset == 0;
589 $firstInList = $this->mCounter == 1;
590 if ( $this->mIsBackwards ) {
591 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
592 if ( $this->mOffset == '' ) {
593 $next = null;
594 } else {
595 $next = 'unknown';
596 }
597 } else {
598 # The next row is the past-the-end row
599 $next = $this->mPastTheEndRow;
600 }
601 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
602 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
603 } else {
604 $s = '';
605 }
606 return $s;
607 }
608 }
609
610
611