Make a note about the reserved word problem.
[mediawiki.git] / includes / PageHistory.php
blobd81e7ff73252b556ef80e71ab5f23124d977758b
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 $bits = $bits + array( 'disabled' => 'disabled' );
170 return Xml::submitButton( wfMsg( 'compareselectedversions' ),
171 $bits + array(
172 'class' => 'historysubmit',
173 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
174 'title' => wfMsg( 'tooltip-compareselectedversions' ),
180 * Returns a row from the history printout.
182 * @todo document some more, and maybe clean up the code (some params redundant?)
184 * @param object $row The database row corresponding to the line (or is it the previous line?).
185 * @param object $next The database row corresponding to the next line (or is it this one?).
186 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
187 * @param $notificationtimestamp
188 * @param bool $latest Whether this row corresponds to the page's latest revision.
189 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
190 * @return string HTML output for the row
192 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
193 global $wgUser, $wgLang;
194 $rev = new Revision( $row );
195 $rev->setTitle( $this->mTitle );
197 $s = '<li>';
198 $curlink = $this->curLink( $rev, $latest );
199 $lastlink = $this->lastLink( $rev, $next, $counter );
200 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
201 $link = $this->revLink( $rev );
203 $user = $this->mSkin->userLink( $rev->getUser(), $rev->getUserText() )
204 . $this->mSkin->userToolLinks( $rev->getUser(), $rev->getUserText() );
206 $s .= "($curlink) ($lastlink) $arbitrary";
208 if( $wgUser->isAllowed( 'deleterevision' ) ) {
209 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
210 if( $firstInList ) {
211 // We don't currently handle well changing the top revision's settings
212 $del = wfMsgHtml( 'rev-delundel' );
213 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
214 // If revision was hidden from sysops
215 $del = wfMsgHtml( 'rev-delundel' );
216 } else {
217 $del = $this->mSkin->makeKnownLinkObj( $revdel,
218 wfMsg( 'rev-delundel' ),
219 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
220 '&oldid=' . urlencode( $rev->getId() ) );
222 $s .= " (<small>$del</small>) ";
225 $s .= " $link";
226 #getUser is safe, but this avoids making the invalid untargeted contribs links
227 if( $row->rev_deleted & Revision::DELETED_USER ) {
228 $user = '<span class="history-deleted">' . wfMsg('rev-deleted-user') . '</span>';
230 $s .= " <span class='history-user'>$user</span>";
232 if( $row->rev_minor_edit ) {
233 $s .= ' ' . wfElement( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
236 if ( !is_null( $size = $rev->getSize() ) ) {
237 if ( $size == 0 )
238 $stxt = wfMsgHtml( 'historyempty' );
239 else
240 $stxt = wfMsgExt( 'historysize', array( 'parsemag' ), $wgLang->formatNum( $size ) );
241 $s .= " <span class=\"history-size\">$stxt</span>";
244 #getComment is safe, but this is better formatted
245 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
246 $s .= " <span class=\"history-deleted\"><span class=\"comment\">" .
247 wfMsgHtml( 'rev-deleted-comment' ) . "</span></span>";
248 } else {
249 $s .= $this->mSkin->revComment( $rev );
252 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
253 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
255 #add blurb about text having been deleted
256 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
257 $s .= ' ' . wfMsgHtml( 'deletedrev' );
260 $tools = array();
262 if ( !is_null( $next ) && is_object( $next ) ) {
263 if( $wgUser->isAllowed( 'rollback' ) && $latest ) {
264 $tools[] = '<span class="mw-rollback-link">'
265 . $this->mSkin->buildRollbackLink( $rev )
266 . '</span>';
269 $undolink = $this->mSkin->makeKnownLinkObj(
270 $this->mTitle,
271 wfMsgHtml( 'editundo' ),
272 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
274 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
277 if( $tools ) {
278 $s .= ' (' . implode( ' | ', $tools ) . ')';
281 wfRunHooks( 'PageHistoryLineEnding', array( &$row , &$s ) );
283 $s .= "</li>\n";
285 return $s;
288 /** @todo document */
289 function revLink( $rev ) {
290 global $wgLang;
291 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
292 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
293 $link = $this->mSkin->makeKnownLinkObj(
294 $this->mTitle, $date, "oldid=" . $rev->getId() );
295 } else {
296 $link = $date;
298 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
299 return '<span class="history-deleted">' . $link . '</span>';
301 return $link;
304 /** @todo document */
305 function curLink( $rev, $latest ) {
306 $cur = wfMsgExt( 'cur', array( 'escape') );
307 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
308 return $cur;
309 } else {
310 return $this->mSkin->makeKnownLinkObj(
311 $this->mTitle, $cur,
312 'diff=' . $this->getLatestID() .
313 "&oldid=" . $rev->getId() );
317 /** @todo document */
318 function lastLink( $rev, $next, $counter ) {
319 $last = wfMsgExt( 'last', array( 'escape' ) );
320 if ( is_null( $next ) ) {
321 # Probably no next row
322 return $last;
323 } elseif ( $next === 'unknown' ) {
324 # Next row probably exists but is unknown, use an oldid=prev link
325 return $this->mSkin->makeKnownLinkObj(
326 $this->mTitle,
327 $last,
328 "diff=" . $rev->getId() . "&oldid=prev" );
329 } elseif( !$rev->userCan( Revision::DELETED_TEXT ) ) {
330 return $last;
331 } else {
332 return $this->mSkin->makeKnownLinkObj(
333 $this->mTitle,
334 $last,
335 "diff=" . $rev->getId() . "&oldid={$next->rev_id}"
339 "tabindex={$counter}"*/ );
344 * Create radio buttons for page history
346 * @param object $rev Revision
347 * @param bool $firstInList Is this version the first one?
348 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
349 * @return string HTML output for the radio buttons
351 function diffButtons( $rev, $firstInList, $counter ) {
352 if( $this->linesonpage > 1) {
353 $radio = array(
354 'type' => 'radio',
355 'value' => $rev->getId(),
358 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
359 $radio['disabled'] = 'disabled';
362 /** @todo: move title texts to javascript */
363 if ( $firstInList ) {
364 $first = Xml::element( 'input', array_merge(
365 $radio,
366 array(
367 'style' => 'visibility:hidden',
368 'name' => 'oldid' ) ) );
369 $checkmark = array( 'checked' => 'checked' );
370 } else {
371 if( $counter == 2 ) {
372 $checkmark = array( 'checked' => 'checked' );
373 } else {
374 $checkmark = array();
376 $first = Xml::element( 'input', array_merge(
377 $radio,
378 $checkmark,
379 array( 'name' => 'oldid' ) ) );
380 $checkmark = array();
382 $second = Xml::element( 'input', array_merge(
383 $radio,
384 $checkmark,
385 array( 'name' => 'diff' ) ) );
386 return $first . $second;
387 } else {
388 return '';
392 /** @todo document */
393 function getLatestId() {
394 if( is_null( $this->mLatestId ) ) {
395 $id = $this->mTitle->getArticleID();
396 $db = wfGetDB(DB_SLAVE);
397 $this->mLatestId = $db->selectField( 'page',
398 "page_latest",
399 array( 'page_id' => $id ),
400 'PageHistory::getLatestID' );
402 return $this->mLatestId;
406 * Fetch an array of revisions, specified by a given limit, offset and
407 * direction. This is now only used by the feeds. It was previously
408 * used by the main UI but that's now handled by the pager.
410 function fetchRevisions($limit, $offset, $direction) {
411 $fname = 'PageHistory::fetchRevisions';
413 $dbr = wfGetDB( DB_SLAVE );
415 if ($direction == PageHistory::DIR_PREV)
416 list($dirs, $oper) = array("ASC", ">=");
417 else /* $direction == PageHistory::DIR_NEXT */
418 list($dirs, $oper) = array("DESC", "<=");
420 if ($offset)
421 $offsets = array("rev_timestamp $oper '$offset'");
422 else
423 $offsets = array();
425 $page_id = $this->mTitle->getArticleID();
427 $res = $dbr->select(
428 'revision',
429 Revision::selectFields(),
430 array_merge(array("rev_page=$page_id"), $offsets),
431 $fname,
432 array('ORDER BY' => "rev_timestamp $dirs",
433 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
436 $result = array();
437 while (($obj = $dbr->fetchObject($res)) != NULL)
438 $result[] = $obj;
440 return $result;
443 /** @todo document */
444 function getNotificationTimestamp() {
445 global $wgUser, $wgShowUpdatedMarker;
446 $fname = 'PageHistory::getNotficationTimestamp';
448 if ($this->mNotificationTimestamp !== NULL)
449 return $this->mNotificationTimestamp;
451 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
452 return $this->mNotificationTimestamp = false;
454 $dbr = wfGetDB(DB_SLAVE);
456 $this->mNotificationTimestamp = $dbr->selectField(
457 'watchlist',
458 'wl_notificationtimestamp',
459 array( 'wl_namespace' => $this->mTitle->getNamespace(),
460 'wl_title' => $this->mTitle->getDBkey(),
461 'wl_user' => $wgUser->getID()
463 $fname);
465 // Don't use the special value reserved for telling whether the field is filled
466 if ( is_null( $this->mNotificationTimestamp ) ) {
467 $this->mNotificationTimestamp = false;
470 return $this->mNotificationTimestamp;
474 * Output a subscription feed listing recent edits to this page.
475 * @param string $type
477 function feed( $type ) {
478 require_once 'SpecialRecentchanges.php';
480 global $wgFeedClasses;
481 if( !isset( $wgFeedClasses[$type] ) ) {
482 global $wgOut;
483 $wgOut->addWikiText( wfMsg( 'feed-invalid' ) );
484 return;
487 $feed = new $wgFeedClasses[$type](
488 $this->mTitle->getPrefixedText() . ' - ' .
489 wfMsgForContent( 'history-feed-title' ),
490 wfMsgForContent( 'history-feed-description' ),
491 $this->mTitle->getFullUrl( 'action=history' ) );
493 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
494 $feed->outHeader();
495 if( $items ) {
496 foreach( $items as $row ) {
497 $feed->outItem( $this->feedItem( $row ) );
499 } else {
500 $feed->outItem( $this->feedEmpty() );
502 $feed->outFooter();
505 function feedEmpty() {
506 global $wgOut;
507 return new FeedItem(
508 wfMsgForContent( 'nohistory' ),
509 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
510 $this->mTitle->getFullUrl(),
511 wfTimestamp( TS_MW ),
513 $this->mTitle->getTalkPage()->getFullUrl() );
517 * Generate a FeedItem object from a given revision table row
518 * Borrows Recent Changes' feed generation functions for formatting;
519 * includes a diff to the previous revision (if any).
521 * @param $row
522 * @return FeedItem
524 function feedItem( $row ) {
525 $rev = new Revision( $row );
526 $rev->setTitle( $this->mTitle );
527 $text = rcFormatDiffRow( $this->mTitle,
528 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
529 $rev->getId(),
530 $rev->getTimestamp(),
531 $rev->getComment() );
533 if( $rev->getComment() == '' ) {
534 global $wgContLang;
535 $title = wfMsgForContent( 'history-feed-item-nocomment',
536 $rev->getUserText(),
537 $wgContLang->timeanddate( $rev->getTimestamp() ) );
538 } else {
539 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
542 return new FeedItem(
543 $title,
544 $text,
545 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
546 $rev->getTimestamp(),
547 $rev->getUserText(),
548 $this->mTitle->getTalkPage()->getFullUrl() );
552 * Quickie hack... strip out wikilinks to more legible form from the comment.
554 function stripComment( $text ) {
555 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
561 * @addtogroup Pager
563 class PageHistoryPager extends ReverseChronologicalPager {
564 public $mLastRow = false, $mPageHistory;
566 function __construct( $pageHistory ) {
567 parent::__construct();
568 $this->mPageHistory = $pageHistory;
571 function getQueryInfo() {
572 return array(
573 'tables' => 'revision',
574 'fields' => Revision::selectFields(),
575 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
576 'options' => array( 'USE INDEX' => 'page_timestamp' )
580 function getIndexField() {
581 return 'rev_timestamp';
584 function formatRow( $row ) {
585 if ( $this->mLastRow ) {
586 $latest = $this->mCounter == 1 && $this->mOffset == '';
587 $firstInList = $this->mCounter == 1;
588 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
589 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
590 } else {
591 $s = '';
593 $this->mLastRow = $row;
594 return $s;
597 function getStartBody() {
598 $this->mLastRow = false;
599 $this->mCounter = 1;
600 return '';
603 function getEndBody() {
604 if ( $this->mLastRow ) {
605 $latest = $this->mCounter == 1 && $this->mOffset == 0;
606 $firstInList = $this->mCounter == 1;
607 if ( $this->mIsBackwards ) {
608 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
609 if ( $this->mOffset == '' ) {
610 $next = null;
611 } else {
612 $next = 'unknown';
614 } else {
615 # The next row is the past-the-end row
616 $next = $this->mPastTheEndRow;
618 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
619 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
620 } else {
621 $s = '';
623 return $s;