* (bug 12584) Don't reset cl_timestamp when auto-updating sort key on move
[mediawiki.git] / includes / PageHistory.php
blob9d8466528d48c12fae6956a52d2fb57413f8ad1b
1 <?php
2 /**
3 * Page history
5 * Split off from Article.php and Skin.php, 2003-12-22
6 */
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.
13 * Construct it by passing in an Article, and call $h->history() to print the
14 * history.
17 class PageHistory {
18 const DIR_PREV = 0;
19 const DIR_NEXT = 1;
21 var $mArticle, $mTitle, $mSkin;
22 var $lastdate;
23 var $linesonpage;
24 var $mNotificationTimestamp;
25 var $mLatestId = null;
27 /**
28 * Construct a new PageHistory.
30 * @param Article $article
31 * @returns nothing
33 function __construct($article) {
34 global $wgUser;
36 $this->mArticle =& $article;
37 $this->mTitle =& $article->mTitle;
38 $this->mNotificationTimestamp = NULL;
39 $this->mSkin = $wgUser->getSkin();
42 /**
43 * Print the history page for an article.
45 * @returns nothing
47 function history() {
48 global $wgOut, $wgRequest, $wgTitle;
51 * Allow client caching.
54 if( $wgOut->checkLastModified( $this->mArticle->getTimestamp() ) )
55 /* Client cache fresh and headers sent, nothing more to do. */
56 return;
58 $fname = 'PageHistory::history';
59 wfProfileIn( $fname );
62 * Setup page variables.
64 $wgOut->setPageTitle( wfMsg( 'history-title', $this->mTitle->getPrefixedText() ) );
65 $wgOut->setPageTitleActionText( wfMsg( 'history_short' ) );
66 $wgOut->setArticleFlag( false );
67 $wgOut->setArticleRelated( true );
68 $wgOut->setRobotpolicy( 'noindex,nofollow' );
69 $wgOut->setSyndicated( true );
71 $logPage = SpecialPage::getTitleFor( 'Log' );
72 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ), 'page=' . $this->mTitle->getPrefixedUrl() );
73 $wgOut->setSubtitle( $logLink );
75 $feedType = $wgRequest->getVal( 'feed' );
76 if( $feedType ) {
77 wfProfileOut( $fname );
78 return $this->feed( $feedType );
82 * Fail if article doesn't exist.
84 if( !$this->mTitle->exists() ) {
85 $wgOut->addWikiText( wfMsg( 'nohistory' ) );
86 wfProfileOut( $fname );
87 return;
91 * "go=first" means to jump to the last (earliest) history page.
92 * This is deprecated, it no longer appears in the user interface
94 if ( $wgRequest->getText("go") == 'first' ) {
95 $limit = $wgRequest->getInt( 'limit', 50 );
96 $wgOut->redirect( $wgTitle->getLocalURL( "action=history&limit={$limit}&dir=prev" ) );
97 return;
100 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
102 /**
103 * Do the list
105 $pager = new PageHistoryPager( $this );
106 $this->linesonpage = $pager->getNumRows();
107 $wgOut->addHTML(
108 $pager->getNavigationBar() .
109 $this->beginHistoryList() .
110 $pager->getBody() .
111 $this->endHistoryList() .
112 $pager->getNavigationBar()
114 wfProfileOut( $fname );
118 * Creates begin of history list with a submit button
120 * @return string HTML output
122 function beginHistoryList() {
123 global $wgTitle;
124 $this->lastdate = '';
125 $s = wfMsgExt( 'histlegend', array( 'parse') );
126 $s .= '<form action="' . $wgTitle->escapeLocalURL( '-' ) . '" method="get">';
127 $prefixedkey = htmlspecialchars($wgTitle->getPrefixedDbKey());
129 // The following line is SUPPOSED to have double-quotes around the
130 // $prefixedkey variable, because htmlspecialchars() doesn't escape
131 // single-quotes.
133 // On at least two occasions people have changed it to single-quotes,
134 // which creates invalid HTML and incorrect display of the resulting
135 // link.
137 // Please do not break this a third time. Thank you for your kind
138 // consideration and cooperation.
140 $s .= "<input type='hidden' name='title' value=\"{$prefixedkey}\" />\n";
142 $s .= $this->submitButton();
143 $s .= '<ul id="pagehistory">' . "\n";
144 return $s;
148 * Creates end of history list with a submit button
150 * @return string HTML output
152 function endHistoryList() {
153 $s = '</ul>';
154 $s .= $this->submitButton( array( 'id' => 'historysubmit' ) );
155 $s .= '</form>';
156 return $s;
160 * Creates a submit button
162 * @param array $bits optional CSS ID
163 * @return string HTML output for the submit button
165 function submitButton( $bits = array() ) {
166 # Disable submit button if history has 1 revision only
167 if ( $this->linesonpage > 1 ) {
168 return Xml::submitButton( wfMsg( 'compareselectedversions' ),
169 $bits + array(
170 'class' => 'historysubmit',
171 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
172 'title' => wfMsg( 'tooltip-compareselectedversions' ),
175 } else {
176 return '';
181 * Returns a row from the history printout.
183 * @todo document some more, and maybe clean up the code (some params redundant?)
185 * @param object $row The database row corresponding to the line (or is it the previous line?).
186 * @param object $next The database row corresponding to the next line (or is it this one?).
187 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
188 * @param $notificationtimestamp
189 * @param bool $latest Whether this row corresponds to the page's latest revision.
190 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
191 * @return string HTML output for the row
193 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
194 global $wgUser, $wgLang;
195 $rev = new Revision( $row );
196 $rev->setTitle( $this->mTitle );
198 $s = '<li>';
199 $curlink = $this->curLink( $rev, $latest );
200 $lastlink = $this->lastLink( $rev, $next, $counter );
201 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
202 $link = $this->revLink( $rev );
204 $user = $this->mSkin->userLink( $rev->getUser(), $rev->getUserText() )
205 . $this->mSkin->userToolLinks( $rev->getUser(), $rev->getUserText() );
207 $s .= "($curlink) ($lastlink) $arbitrary";
209 if( $wgUser->isAllowed( 'deleterevision' ) ) {
210 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
211 if( $firstInList ) {
212 // We don't currently handle well changing the top revision's settings
213 $del = wfMsgHtml( 'rev-delundel' );
214 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
215 // If revision was hidden from sysops
216 $del = wfMsgHtml( 'rev-delundel' );
217 } else {
218 $del = $this->mSkin->makeKnownLinkObj( $revdel,
219 wfMsg( 'rev-delundel' ),
220 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
221 '&oldid=' . urlencode( $rev->getId() ) );
223 $s .= " (<small>$del</small>) ";
226 $s .= " $link";
227 #getUser is safe, but this avoids making the invalid untargeted contribs links
228 if( $row->rev_deleted & Revision::DELETED_USER ) {
229 $user = '<span class="history-deleted">' . wfMsg('rev-deleted-user') . '</span>';
231 $s .= " <span class='history-user'>$user</span>";
233 if( $row->rev_minor_edit ) {
234 $s .= ' ' . wfElement( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
237 if ( !is_null( $size = $rev->getSize() ) ) {
238 if ( $size == 0 )
239 $stxt = wfMsgHtml( 'historyempty' );
240 else
241 $stxt = wfMsgExt( 'historysize', array( 'parsemag' ), $wgLang->formatNum( $size ) );
242 $s .= " <span class=\"history-size\">$stxt</span>";
245 #getComment is safe, but this is better formatted
246 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
247 $s .= " <span class=\"history-deleted\"><span class=\"comment\">" .
248 wfMsgHtml( 'rev-deleted-comment' ) . "</span></span>";
249 } else {
250 $s .= $this->mSkin->revComment( $rev );
253 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
254 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
256 #add blurb about text having been deleted
257 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
258 $s .= ' ' . wfMsgHtml( 'deletedrev' );
261 $tools = array();
263 if ( !is_null( $next ) && is_object( $next ) ) {
264 if( $wgUser->isAllowed( 'rollback' ) && $latest ) {
265 $tools[] = '<span class="mw-rollback-link">'
266 . $this->mSkin->buildRollbackLink( $rev )
267 . '</span>';
270 if( $this->mTitle->quickUserCan( 'edit' ) ) {
271 $undolink = $this->mSkin->makeKnownLinkObj(
272 $this->mTitle,
273 wfMsgHtml( 'editundo' ),
274 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
276 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
280 if( $tools ) {
281 $s .= ' (' . implode( ' | ', $tools ) . ')';
284 wfRunHooks( 'PageHistoryLineEnding', array( &$row , &$s ) );
286 $s .= "</li>\n";
288 return $s;
291 /** @todo document */
292 function revLink( $rev ) {
293 global $wgLang;
294 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
295 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
296 $link = $this->mSkin->makeKnownLinkObj(
297 $this->mTitle, $date, "oldid=" . $rev->getId() );
298 } else {
299 $link = $date;
301 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
302 return '<span class="history-deleted">' . $link . '</span>';
304 return $link;
307 /** @todo document */
308 function curLink( $rev, $latest ) {
309 $cur = wfMsgExt( 'cur', array( 'escape') );
310 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
311 return $cur;
312 } else {
313 return $this->mSkin->makeKnownLinkObj(
314 $this->mTitle, $cur,
315 'diff=' . $this->getLatestID() .
316 "&oldid=" . $rev->getId() );
320 /** @todo document */
321 function lastLink( $rev, $next, $counter ) {
322 $last = wfMsgExt( 'last', array( 'escape' ) );
323 if ( is_null( $next ) ) {
324 # Probably no next row
325 return $last;
326 } elseif ( $next === 'unknown' ) {
327 # Next row probably exists but is unknown, use an oldid=prev link
328 return $this->mSkin->makeKnownLinkObj(
329 $this->mTitle,
330 $last,
331 "diff=" . $rev->getId() . "&oldid=prev" );
332 } elseif( !$rev->userCan( Revision::DELETED_TEXT ) ) {
333 return $last;
334 } else {
335 return $this->mSkin->makeKnownLinkObj(
336 $this->mTitle,
337 $last,
338 "diff=" . $rev->getId() . "&oldid={$next->rev_id}"
342 "tabindex={$counter}"*/ );
347 * Create radio buttons for page history
349 * @param object $rev Revision
350 * @param bool $firstInList Is this version the first one?
351 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
352 * @return string HTML output for the radio buttons
354 function diffButtons( $rev, $firstInList, $counter ) {
355 if( $this->linesonpage > 1) {
356 $radio = array(
357 'type' => 'radio',
358 'value' => $rev->getId(),
361 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
362 $radio['disabled'] = 'disabled';
365 /** @todo: move title texts to javascript */
366 if ( $firstInList ) {
367 $first = Xml::element( 'input', array_merge(
368 $radio,
369 array(
370 'style' => 'visibility:hidden',
371 'name' => 'oldid' ) ) );
372 $checkmark = array( 'checked' => 'checked' );
373 } else {
374 if( $counter == 2 ) {
375 $checkmark = array( 'checked' => 'checked' );
376 } else {
377 $checkmark = array();
379 $first = Xml::element( 'input', array_merge(
380 $radio,
381 $checkmark,
382 array( 'name' => 'oldid' ) ) );
383 $checkmark = array();
385 $second = Xml::element( 'input', array_merge(
386 $radio,
387 $checkmark,
388 array( 'name' => 'diff' ) ) );
389 return $first . $second;
390 } else {
391 return '';
395 /** @todo document */
396 function getLatestId() {
397 if( is_null( $this->mLatestId ) ) {
398 $id = $this->mTitle->getArticleID();
399 $db = wfGetDB(DB_SLAVE);
400 $this->mLatestId = $db->selectField( 'page',
401 "page_latest",
402 array( 'page_id' => $id ),
403 'PageHistory::getLatestID' );
405 return $this->mLatestId;
409 * Fetch an array of revisions, specified by a given limit, offset and
410 * direction. This is now only used by the feeds. It was previously
411 * used by the main UI but that's now handled by the pager.
413 function fetchRevisions($limit, $offset, $direction) {
414 $fname = 'PageHistory::fetchRevisions';
416 $dbr = wfGetDB( DB_SLAVE );
418 if ($direction == PageHistory::DIR_PREV)
419 list($dirs, $oper) = array("ASC", ">=");
420 else /* $direction == PageHistory::DIR_NEXT */
421 list($dirs, $oper) = array("DESC", "<=");
423 if ($offset)
424 $offsets = array("rev_timestamp $oper '$offset'");
425 else
426 $offsets = array();
428 $page_id = $this->mTitle->getArticleID();
430 $res = $dbr->select(
431 'revision',
432 Revision::selectFields(),
433 array_merge(array("rev_page=$page_id"), $offsets),
434 $fname,
435 array('ORDER BY' => "rev_timestamp $dirs",
436 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
439 $result = array();
440 while (($obj = $dbr->fetchObject($res)) != NULL)
441 $result[] = $obj;
443 return $result;
446 /** @todo document */
447 function getNotificationTimestamp() {
448 global $wgUser, $wgShowUpdatedMarker;
449 $fname = 'PageHistory::getNotficationTimestamp';
451 if ($this->mNotificationTimestamp !== NULL)
452 return $this->mNotificationTimestamp;
454 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
455 return $this->mNotificationTimestamp = false;
457 $dbr = wfGetDB(DB_SLAVE);
459 $this->mNotificationTimestamp = $dbr->selectField(
460 'watchlist',
461 'wl_notificationtimestamp',
462 array( 'wl_namespace' => $this->mTitle->getNamespace(),
463 'wl_title' => $this->mTitle->getDBkey(),
464 'wl_user' => $wgUser->getID()
466 $fname);
468 // Don't use the special value reserved for telling whether the field is filled
469 if ( is_null( $this->mNotificationTimestamp ) ) {
470 $this->mNotificationTimestamp = false;
473 return $this->mNotificationTimestamp;
477 * Output a subscription feed listing recent edits to this page.
478 * @param string $type
480 function feed( $type ) {
481 require_once 'SpecialRecentchanges.php';
483 global $wgFeedClasses;
484 if( !isset( $wgFeedClasses[$type] ) ) {
485 global $wgOut;
486 $wgOut->addWikiText( wfMsg( 'feed-invalid' ) );
487 return;
490 $feed = new $wgFeedClasses[$type](
491 $this->mTitle->getPrefixedText() . ' - ' .
492 wfMsgForContent( 'history-feed-title' ),
493 wfMsgForContent( 'history-feed-description' ),
494 $this->mTitle->getFullUrl( 'action=history' ) );
496 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
497 $feed->outHeader();
498 if( $items ) {
499 foreach( $items as $row ) {
500 $feed->outItem( $this->feedItem( $row ) );
502 } else {
503 $feed->outItem( $this->feedEmpty() );
505 $feed->outFooter();
508 function feedEmpty() {
509 global $wgOut;
510 return new FeedItem(
511 wfMsgForContent( 'nohistory' ),
512 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
513 $this->mTitle->getFullUrl(),
514 wfTimestamp( TS_MW ),
516 $this->mTitle->getTalkPage()->getFullUrl() );
520 * Generate a FeedItem object from a given revision table row
521 * Borrows Recent Changes' feed generation functions for formatting;
522 * includes a diff to the previous revision (if any).
524 * @param $row
525 * @return FeedItem
527 function feedItem( $row ) {
528 $rev = new Revision( $row );
529 $rev->setTitle( $this->mTitle );
530 $text = rcFormatDiffRow( $this->mTitle,
531 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
532 $rev->getId(),
533 $rev->getTimestamp(),
534 $rev->getComment() );
536 if( $rev->getComment() == '' ) {
537 global $wgContLang;
538 $title = wfMsgForContent( 'history-feed-item-nocomment',
539 $rev->getUserText(),
540 $wgContLang->timeanddate( $rev->getTimestamp() ) );
541 } else {
542 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
545 return new FeedItem(
546 $title,
547 $text,
548 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
549 $rev->getTimestamp(),
550 $rev->getUserText(),
551 $this->mTitle->getTalkPage()->getFullUrl() );
555 * Quickie hack... strip out wikilinks to more legible form from the comment.
557 function stripComment( $text ) {
558 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
564 * @addtogroup Pager
566 class PageHistoryPager extends ReverseChronologicalPager {
567 public $mLastRow = false, $mPageHistory;
569 function __construct( $pageHistory ) {
570 parent::__construct();
571 $this->mPageHistory = $pageHistory;
574 function getQueryInfo() {
575 return array(
576 'tables' => 'revision',
577 'fields' => Revision::selectFields(),
578 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
579 'options' => array( 'USE INDEX' => 'page_timestamp' )
583 function getIndexField() {
584 return 'rev_timestamp';
587 function formatRow( $row ) {
588 if ( $this->mLastRow ) {
589 $latest = $this->mCounter == 1 && $this->mOffset == '';
590 $firstInList = $this->mCounter == 1;
591 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
592 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
593 } else {
594 $s = '';
596 $this->mLastRow = $row;
597 return $s;
600 function getStartBody() {
601 $this->mLastRow = false;
602 $this->mCounter = 1;
603 return '';
606 function getEndBody() {
607 if ( $this->mLastRow ) {
608 $latest = $this->mCounter == 1 && $this->mOffset == 0;
609 $firstInList = $this->mCounter == 1;
610 if ( $this->mIsBackwards ) {
611 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
612 if ( $this->mOffset == '' ) {
613 $next = null;
614 } else {
615 $next = 'unknown';
617 } else {
618 # The next row is the past-the-end row
619 $next = $this->mPastTheEndRow;
621 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
622 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
623 } else {
624 $s = '';
626 return $s;