Start to improve HTMLDiff.php localization. For the time being, I recommend that...
[mediawiki.git] / includes / PageHistory.php
blob5ea8461d9f8dfa65cea3d91af56f48fbd0f2d664
1 <?php
2 /**
3 * Page history
5 * Split off from Article.php and Skin.php, 2003-12-22
6 * @file
7 */
9 /**
10 * This class handles printing the history page for an article. In order to
11 * be efficient, it uses timestamps rather than offsets for paging, to avoid
12 * costly LIMIT,offset queries.
14 * Construct it by passing in an Article, and call $h->history() to print the
15 * history.
18 class PageHistory {
19 const DIR_PREV = 0;
20 const DIR_NEXT = 1;
22 var $mArticle, $mTitle, $mSkin;
23 var $lastdate;
24 var $linesonpage;
25 var $mNotificationTimestamp;
26 var $mLatestId = null;
28 /**
29 * Construct a new PageHistory.
31 * @param Article $article
32 * @returns nothing
34 function __construct($article) {
35 global $wgUser;
37 $this->mArticle =& $article;
38 $this->mTitle =& $article->mTitle;
39 $this->mNotificationTimestamp = NULL;
40 $this->mSkin = $wgUser->getSkin();
41 $this->preCacheMessages();
44 function getArticle() {
45 return $this->mArticle;
48 function getTitle() {
49 return $this->mTitle;
52 /**
53 * As we use the same small set of messages in various methods and that
54 * they are called often, we call them once and save them in $this->message
56 function preCacheMessages() {
57 // Precache various messages
58 if( !isset( $this->message ) ) {
59 foreach( explode(' ', 'cur last rev-delundel' ) as $msg ) {
60 $this->message[$msg] = wfMsgExt( $msg, array( 'escape') );
65 /**
66 * Print the history page for an article.
68 * @returns nothing
70 function history() {
71 global $wgOut, $wgRequest, $wgTitle, $wgScript;
74 * Allow client caching.
76 if( $wgOut->checkLastModified( $this->mArticle->getTouched() ) )
77 /* Client cache fresh and headers sent, nothing more to do. */
78 return;
80 wfProfileIn( __METHOD__ );
83 * Setup page variables.
85 $wgOut->setPageTitle( wfMsg( 'history-title', $this->mTitle->getPrefixedText() ) );
86 $wgOut->setPageTitleActionText( wfMsg( 'history_short' ) );
87 $wgOut->setArticleFlag( false );
88 $wgOut->setArticleRelated( true );
89 $wgOut->setRobotPolicy( 'noindex,nofollow' );
90 $wgOut->setSyndicated( true );
91 $wgOut->setFeedAppendQuery( 'action=history' );
92 $wgOut->addScriptFile( 'history.js' );
94 $logPage = SpecialPage::getTitleFor( 'Log' );
95 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ), 'page=' . $this->mTitle->getPrefixedUrl() );
96 $wgOut->setSubtitle( $logLink );
98 $feedType = $wgRequest->getVal( 'feed' );
99 if( $feedType ) {
100 wfProfileOut( __METHOD__ );
101 return $this->feed( $feedType );
105 * Fail if article doesn't exist.
107 if( !$this->mTitle->exists() ) {
108 $wgOut->addWikiMsg( 'nohistory' );
109 wfProfileOut( __METHOD__ );
110 return;
114 * "go=first" means to jump to the last (earliest) history page.
115 * This is deprecated, it no longer appears in the user interface
117 if ( $wgRequest->getText("go") == 'first' ) {
118 $limit = $wgRequest->getInt( 'limit', 50 );
119 global $wgFeedLimit;
120 if( $limit > $wgFeedLimit ) {
121 $limit = $wgFeedLimit;
123 $wgOut->redirect( $wgTitle->getLocalURL( "action=history&limit={$limit}&dir=prev" ) );
124 return;
128 * Add date selector to quickly get to a certain time
130 $year = $wgRequest->getInt( 'year' );
131 $month = $wgRequest->getInt( 'month' );
133 $action = htmlspecialchars( $wgScript );
134 $wgOut->addHTML(
135 Xml::fieldset( wfMsg( 'history-search' ), false, array( 'id' => 'mw-history-search' ) ) .
136 "<form action=\"$action\" method=\"get\">" .
137 Xml::hidden( 'title', $this->mTitle->getPrefixedDBKey() ) . "\n" .
138 Xml::hidden( 'action', 'history' ) . "\n" .
139 $this->getDateMenu( $year, $month ) . '&nbsp;' .
140 Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" .
141 '</form></fieldset>'
144 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
147 * Do the list
149 $pager = new PageHistoryPager( $this, $year, $month );
150 $this->linesonpage = $pager->getNumRows();
151 $wgOut->addHTML(
152 $pager->getNavigationBar() .
153 $this->beginHistoryList() .
154 $pager->getBody() .
155 $this->endHistoryList() .
156 $pager->getNavigationBar()
158 wfProfileOut( __METHOD__ );
162 * @return string Formatted HTML
163 * @param int $year
164 * @param int $month
166 private function getDateMenu( $year, $month ) {
167 # Offset overrides year/month selection
168 if( $month && $month !== -1 ) {
169 $encMonth = intval( $month );
170 } else {
171 $encMonth = '';
173 if ( $year ) {
174 $encYear = intval( $year );
175 } else if( $encMonth ) {
176 $thisMonth = intval( gmdate( 'n' ) );
177 $thisYear = intval( gmdate( 'Y' ) );
178 if( intval($encMonth) > $thisMonth ) {
179 $thisYear--;
181 $encYear = $thisYear;
182 } else {
183 $encYear = '';
185 return Xml::label( wfMsg( 'year' ), 'year' ) . ' '.
186 Xml::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) .
187 ' '.
188 Xml::label( wfMsg( 'month' ), 'month' ) . ' '.
189 Xml::monthSelector( $encMonth, -1 );
193 * Creates begin of history list with a submit button
195 * @return string HTML output
197 function beginHistoryList() {
198 global $wgTitle, $wgScript, $wgEnableHtmlDiff;
199 $this->lastdate = '';
200 $s = wfMsgExt( 'histlegend', array( 'parse') );
201 $s .= Xml::openElement( 'form', array( 'action' => $wgScript ) );
202 $s .= Xml::hidden( 'title', $wgTitle->getPrefixedDbKey() );
203 if($wgEnableHtmlDiff){
204 $s .= Xml::hidden( 'htmldiff', 0 , array('id' => 'htmldiff'));
205 $s .= $this->submitButton( wfMsg( 'visualcomparison'),
206 array(
207 'id' => 'submithtmldiff1',
208 'class' => 'historysubmit',
209 'accesskey' => wfMsg( 'accesskey-visualcomparison' ),
210 'title' => wfMsg( 'tooltip-compareselectedversions' ),
213 $s .= $this->submitButton( wfMsg( 'wikicodecomparison'),
214 array(
215 'id' => 'submitsourcediff1',
216 'class' => 'historysubmit',
217 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
218 'title' => wfMsg( 'tooltip-compareselectedversions' ),
221 }else{
222 $s .= $this->submitButton( wfMsg( 'compareselectedversions'),
223 array(
224 'class' => 'historysubmit',
225 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
226 'title' => wfMsg( 'tooltip-compareselectedversions' ),
230 $s .= '<ul id="pagehistory">' . "\n";
231 return $s;
235 * Creates end of history list with a submit button
237 * @return string HTML output
239 function endHistoryList() {
240 global $wgEnableHtmlDiff;
241 $s = '</ul>';
242 if($wgEnableHtmlDiff){
243 $s .= $this->submitButton( wfMsg( 'visualcomparison'),
244 array(
245 'id' => 'submithtmldiff2',
246 'class' => 'historysubmit',
247 'accesskey' => wfMsg( 'accesskey-visualcomparison' ),
248 'title' => wfMsg( 'tooltip-compareselectedversions' ),
251 $s .= $this->submitButton( wfMsg( 'wikicodecomparison'),
252 array(
253 'id' => 'submitsourcediff2',
254 'class' => 'historysubmit',
255 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
256 'title' => wfMsg( 'tooltip-compareselectedversions' ),
259 }else{
260 $s .= $this->submitButton( wfMsg( 'compareselectedversions'),
261 array(
262 'class' => 'historysubmit',
263 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
264 'title' => wfMsg( 'tooltip-compareselectedversions' ),
268 $s .= '</form>';
269 return $s;
273 * Creates a submit button
275 * @param array $attributes attributes
276 * @return string HTML output for the submit button
278 function submitButton($message, $attributes = array() ) {
279 # Disable submit button if history has 1 revision only
280 if ( $this->linesonpage > 1 ) {
281 return Xml::submitButton( $message , $attributes );
282 } else {
283 return '';
288 * Returns a row from the history printout.
290 * @todo document some more, and maybe clean up the code (some params redundant?)
292 * @param Row $row The database row corresponding to the previous line.
293 * @param mixed $next The database row corresponding to the next line.
294 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
295 * @param $notificationtimestamp
296 * @param bool $latest Whether this row corresponds to the page's latest revision.
297 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
298 * @return string HTML output for the row
300 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
301 global $wgUser, $wgLang;
302 $rev = new Revision( $row );
303 $rev->setTitle( $this->mTitle );
305 $s = '';
306 $curlink = $this->curLink( $rev, $latest );
307 $lastlink = $this->lastLink( $rev, $next, $counter );
308 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
309 $link = $this->revLink( $rev );
311 $s .= "($curlink) ($lastlink) $arbitrary";
313 if( $wgUser->isAllowed( 'deleterevision' ) ) {
314 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
315 if( $firstInList ) {
316 // We don't currently handle well changing the top revision's settings
317 $del = $this->message['rev-delundel'];
318 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
319 // If revision was hidden from sysops
320 $del = $this->message['rev-delundel'];
321 } else {
322 $del = $this->mSkin->makeKnownLinkObj( $revdel,
323 $this->message['rev-delundel'],
324 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
325 '&oldid=' . urlencode( $rev->getId() ) );
326 // Bolden oversighted content
327 if( $rev->isDeleted( Revision::DELETED_RESTRICTED ) )
328 $del = "<strong>$del</strong>";
330 $s .= " <tt>(<small>$del</small>)</tt> ";
333 $s .= " $link";
334 $s .= " <span class='history-user'>" . $this->mSkin->revUserTools( $rev, true ) . "</span>";
336 if( $row->rev_minor_edit ) {
337 $s .= ' ' . Xml::element( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
340 if ( !is_null( $size = $rev->getSize() ) && $rev->userCan( Revision::DELETED_TEXT ) ) {
341 $s .= ' ' . $this->mSkin->formatRevisionSize( $size );
344 $s .= $this->mSkin->revComment( $rev, false, true );
346 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
347 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
349 #add blurb about text having been deleted
350 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
351 $s .= ' <tt>' . wfMsgHtml( 'deletedrev' ) . '</tt>';
354 $tools = array();
356 if ( !is_null( $next ) && is_object( $next ) ) {
357 if( !$this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser )
358 && !$this->mTitle->getUserPermissionsErrors( 'edit', $wgUser )
359 && $latest ) {
360 $tools[] = '<span class="mw-rollback-link">'
361 . $this->mSkin->buildRollbackLink( $rev )
362 . '</span>';
365 if( $this->mTitle->quickUserCan( 'edit' ) &&
366 !$rev->isDeleted( Revision::DELETED_TEXT ) &&
367 !$next->rev_deleted & Revision::DELETED_TEXT ) {
368 $undolink = $this->mSkin->makeKnownLinkObj(
369 $this->mTitle,
370 wfMsgHtml( 'editundo' ),
371 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
373 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
377 if( $tools ) {
378 $s .= ' (' . implode( ' | ', $tools ) . ')';
381 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s ) );
383 return "<li>$s</li>\n";
387 * Create a link to view this revision of the page
388 * @param Revision $rev
389 * @returns string
391 function revLink( $rev ) {
392 global $wgLang;
393 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
394 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
395 $link = $this->mSkin->makeKnownLinkObj(
396 $this->mTitle, $date, "oldid=" . $rev->getId() );
397 } else {
398 $link = $date;
400 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
401 return '<span class="history-deleted">' . $link . '</span>';
403 return $link;
407 * Create a diff-to-current link for this revision for this page
408 * @param Revision $rev
409 * @param Bool $latest, this is the latest revision of the page?
410 * @returns string
412 function curLink( $rev, $latest ) {
413 $cur = $this->message['cur'];
414 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
415 return $cur;
416 } else {
417 return $this->mSkin->makeKnownLinkObj(
418 $this->mTitle, $cur,
419 'diff=' . $this->getLatestID() .
420 "&oldid=" . $rev->getId() );
425 * Create a diff-to-previous link for this revision for this page.
426 * @param Revision $prevRev, the previous revision
427 * @param mixed $next, the newer revision
428 * @param int $counter, what row on the history list this is
429 * @returns string
431 function lastLink( $prevRev, $next, $counter ) {
432 $last = $this->message['last'];
433 # $next may either be a Row, null, or "unkown"
434 $nextRev = is_object($next) ? new Revision( $next ) : $next;
435 if( is_null($next) ) {
436 # Probably no next row
437 return $last;
438 } elseif( $next === 'unknown' ) {
439 # Next row probably exists but is unknown, use an oldid=prev link
440 return $this->mSkin->makeKnownLinkObj(
441 $this->mTitle,
442 $last,
443 "diff=" . $prevRev->getId() . "&oldid=prev" );
444 } elseif( !$prevRev->userCan(Revision::DELETED_TEXT) || !$nextRev->userCan(Revision::DELETED_TEXT) ) {
445 return $last;
446 } else {
447 return $this->mSkin->makeKnownLinkObj(
448 $this->mTitle,
449 $last,
450 "diff=" . $prevRev->getId() . "&oldid={$next->rev_id}"
454 "tabindex={$counter}"*/ );
459 * Create radio buttons for page history
461 * @param object $rev Revision
462 * @param bool $firstInList Is this version the first one?
463 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
464 * @return string HTML output for the radio buttons
466 function diffButtons( $rev, $firstInList, $counter ) {
467 if( $this->linesonpage > 1) {
468 $radio = array(
469 'type' => 'radio',
470 'value' => $rev->getId(),
473 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
474 $radio['disabled'] = 'disabled';
477 /** @todo: move title texts to javascript */
478 if ( $firstInList ) {
479 $first = Xml::element( 'input', array_merge(
480 $radio,
481 array(
482 'style' => 'visibility:hidden',
483 'name' => 'oldid' ) ) );
484 $checkmark = array( 'checked' => 'checked' );
485 } else {
486 if( $counter == 2 ) {
487 $checkmark = array( 'checked' => 'checked' );
488 } else {
489 $checkmark = array();
491 $first = Xml::element( 'input', array_merge(
492 $radio,
493 $checkmark,
494 array( 'name' => 'oldid' ) ) );
495 $checkmark = array();
497 $second = Xml::element( 'input', array_merge(
498 $radio,
499 $checkmark,
500 array( 'name' => 'diff' ) ) );
501 return $first . $second;
502 } else {
503 return '';
507 /** @todo document */
508 function getLatestId() {
509 if( is_null( $this->mLatestId ) ) {
510 $id = $this->mTitle->getArticleID();
511 $db = wfGetDB( DB_SLAVE );
512 $this->mLatestId = $db->selectField( 'page',
513 "page_latest",
514 array( 'page_id' => $id ),
515 __METHOD__ );
517 return $this->mLatestId;
521 * Fetch an array of revisions, specified by a given limit, offset and
522 * direction. This is now only used by the feeds. It was previously
523 * used by the main UI but that's now handled by the pager.
525 function fetchRevisions($limit, $offset, $direction) {
526 $dbr = wfGetDB( DB_SLAVE );
528 if ($direction == PageHistory::DIR_PREV)
529 list($dirs, $oper) = array("ASC", ">=");
530 else /* $direction == PageHistory::DIR_NEXT */
531 list($dirs, $oper) = array("DESC", "<=");
533 if ($offset)
534 $offsets = array("rev_timestamp $oper '$offset'");
535 else
536 $offsets = array();
538 $page_id = $this->mTitle->getArticleID();
540 return $dbr->select(
541 'revision',
542 Revision::selectFields(),
543 array_merge(array("rev_page=$page_id"), $offsets),
544 __METHOD__,
545 array('ORDER BY' => "rev_timestamp $dirs",
546 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
550 /** @todo document */
551 function getNotificationTimestamp() {
552 global $wgUser, $wgShowUpdatedMarker;
554 if ($this->mNotificationTimestamp !== NULL)
555 return $this->mNotificationTimestamp;
557 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
558 return $this->mNotificationTimestamp = false;
560 $dbr = wfGetDB(DB_SLAVE);
562 $this->mNotificationTimestamp = $dbr->selectField(
563 'watchlist',
564 'wl_notificationtimestamp',
565 array( 'wl_namespace' => $this->mTitle->getNamespace(),
566 'wl_title' => $this->mTitle->getDBkey(),
567 'wl_user' => $wgUser->getId()
569 __METHOD__ );
571 // Don't use the special value reserved for telling whether the field is filled
572 if ( is_null( $this->mNotificationTimestamp ) ) {
573 $this->mNotificationTimestamp = false;
576 return $this->mNotificationTimestamp;
580 * Output a subscription feed listing recent edits to this page.
581 * @param string $type
583 function feed( $type ) {
584 global $wgFeedClasses, $wgRequest, $wgFeedLimit;
585 if ( !FeedUtils::checkFeedOutput($type) ) {
586 return;
589 $feed = new $wgFeedClasses[$type](
590 $this->mTitle->getPrefixedText() . ' - ' .
591 wfMsgForContent( 'history-feed-title' ),
592 wfMsgForContent( 'history-feed-description' ),
593 $this->mTitle->getFullUrl( 'action=history' ) );
595 // Get a limit on number of feed entries. Provide a sane default
596 // of 10 if none is defined (but limit to $wgFeedLimit max)
597 $limit = $wgRequest->getInt( 'limit', 10 );
598 if( $limit > $wgFeedLimit || $limit < 1 ) {
599 $limit = 10;
601 $items = $this->fetchRevisions($limit, 0, PageHistory::DIR_NEXT);
603 $feed->outHeader();
604 if( $items ) {
605 foreach( $items as $row ) {
606 $feed->outItem( $this->feedItem( $row ) );
608 } else {
609 $feed->outItem( $this->feedEmpty() );
611 $feed->outFooter();
614 function feedEmpty() {
615 global $wgOut;
616 return new FeedItem(
617 wfMsgForContent( 'nohistory' ),
618 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
619 $this->mTitle->getFullUrl(),
620 wfTimestamp( TS_MW ),
622 $this->mTitle->getTalkPage()->getFullUrl() );
626 * Generate a FeedItem object from a given revision table row
627 * Borrows Recent Changes' feed generation functions for formatting;
628 * includes a diff to the previous revision (if any).
630 * @param $row
631 * @return FeedItem
633 function feedItem( $row ) {
634 $rev = new Revision( $row );
635 $rev->setTitle( $this->mTitle );
636 $text = FeedUtils::formatDiffRow( $this->mTitle,
637 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
638 $rev->getId(),
639 $rev->getTimestamp(),
640 $rev->getComment() );
642 if( $rev->getComment() == '' ) {
643 global $wgContLang;
644 $title = wfMsgForContent( 'history-feed-item-nocomment',
645 $rev->getUserText(),
646 $wgContLang->timeanddate( $rev->getTimestamp() ) );
647 } else {
648 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
651 return new FeedItem(
652 $title,
653 $text,
654 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
655 $rev->getTimestamp(),
656 $rev->getUserText(),
657 $this->mTitle->getTalkPage()->getFullUrl() );
661 * Quickie hack... strip out wikilinks to more legible form from the comment.
663 function stripComment( $text ) {
664 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
670 * @ingroup Pager
672 class PageHistoryPager extends ReverseChronologicalPager {
673 public $mLastRow = false, $mPageHistory;
675 function __construct( $pageHistory, $year='', $month='' ) {
676 parent::__construct();
677 $this->mPageHistory = $pageHistory;
678 $this->getDateCond( $year, $month );
681 function getQueryInfo() {
682 $queryInfo = array(
683 'tables' => array('revision'),
684 'fields' => Revision::selectFields(),
685 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
686 'options' => array( 'USE INDEX' => array('revision' => 'page_timestamp') )
688 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
689 return $queryInfo;
692 function getIndexField() {
693 return 'rev_timestamp';
696 function formatRow( $row ) {
697 if ( $this->mLastRow ) {
698 $latest = $this->mCounter == 1 && $this->mIsFirst;
699 $firstInList = $this->mCounter == 1;
700 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
701 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
702 } else {
703 $s = '';
705 $this->mLastRow = $row;
706 return $s;
709 function getStartBody() {
710 $this->mLastRow = false;
711 $this->mCounter = 1;
712 return '';
715 function getEndBody() {
716 if ( $this->mLastRow ) {
717 $latest = $this->mCounter == 1 && $this->mIsFirst;
718 $firstInList = $this->mCounter == 1;
719 if ( $this->mIsBackwards ) {
720 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
721 if ( $this->mOffset == '' ) {
722 $next = null;
723 } else {
724 $next = 'unknown';
726 } else {
727 # The next row is the past-the-end row
728 $next = $this->mPastTheEndRow;
730 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
731 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
732 } else {
733 $s = '';
735 return $s;