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