Find variant link of categories, to fix some strange bugs in Chinese Wikipedia.
[mediawiki.git] / includes / PageHistory.php
blobb3b9fc5dab1fa909d457113bd578f90f7593c76b
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 $mLatestId = null;
27 /**
28 * Construct a new PageHistory.
30 * @param Article $article
31 * @returns nothing
33 function __construct( $article ) {
34 global $wgUser;
35 $this->mArticle =& $article;
36 $this->mTitle =& $article->mTitle;
37 $this->mSkin = $wgUser->getSkin();
38 $this->preCacheMessages();
41 function getArticle() {
42 return $this->mArticle;
45 function getTitle() {
46 return $this->mTitle;
49 /**
50 * As we use the same small set of messages in various methods and that
51 * they are called often, we call them once and save them in $this->message
53 function preCacheMessages() {
54 // Precache various messages
55 if( !isset( $this->message ) ) {
56 foreach( explode(' ', 'cur last rev-delundel' ) as $msg ) {
57 $this->message[$msg] = wfMsgExt( $msg, array( 'escape') );
62 /**
63 * Print the history page for an article.
65 * @returns nothing
67 function history() {
68 global $wgOut, $wgRequest, $wgTitle, $wgScript;
71 * Allow client caching.
73 if( $wgOut->checkLastModified( $this->mArticle->getTouched() ) )
74 return; // Client cache fresh and headers sent, nothing more to do.
76 wfProfileIn( __METHOD__ );
79 * Setup page variables.
81 $wgOut->setPageTitle( wfMsg( 'history-title', $this->mTitle->getPrefixedText() ) );
82 $wgOut->setPageTitleActionText( wfMsg( 'history_short' ) );
83 $wgOut->setArticleFlag( false );
84 $wgOut->setArticleRelated( true );
85 $wgOut->setRobotPolicy( 'noindex,nofollow' );
86 $wgOut->setSyndicated( true );
87 $wgOut->setFeedAppendQuery( 'action=history' );
88 $wgOut->addScriptFile( 'history.js' );
90 $logPage = SpecialPage::getTitleFor( 'Log' );
91 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ),
92 'page=' . $this->mTitle->getPrefixedUrl() );
93 $wgOut->setSubtitle( $logLink );
95 $feedType = $wgRequest->getVal( 'feed' );
96 if( $feedType ) {
97 wfProfileOut( __METHOD__ );
98 return $this->feed( $feedType );
102 * Fail if article doesn't exist.
104 if( !$this->mTitle->exists() ) {
105 $wgOut->addWikiMsg( 'nohistory' );
106 wfProfileOut( __METHOD__ );
107 return;
111 * Add date selector to quickly get to a certain time
113 $year = $wgRequest->getInt( 'year' );
114 $month = $wgRequest->getInt( 'month' );
116 $action = htmlspecialchars( $wgScript );
117 $wgOut->addHTML(
118 "<form action=\"$action\" method=\"get\" id=\"mw-history-searchform\">" .
119 Xml::fieldset( wfMsg( 'history-fieldset-title' ), false, array( 'id' => 'mw-history-search' ) ) .
120 Xml::hidden( 'title', $this->mTitle->getPrefixedDBKey() ) . "\n" .
121 Xml::hidden( 'action', 'history' ) . "\n" .
122 $this->getDateMenu( $year, $month ) . '&nbsp;' .
123 Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" .
124 '</fieldset></form>'
127 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
130 * Do the list
132 $pager = new PageHistoryPager( $this, $year, $month );
133 $this->linesonpage = $pager->getNumRows();
134 $wgOut->addHTML(
135 $pager->getNavigationBar() .
136 $this->beginHistoryList() .
137 $pager->getBody() .
138 $this->endHistoryList() .
139 $pager->getNavigationBar()
142 wfProfileOut( __METHOD__ );
146 * @return string Formatted HTML
147 * @param int $year
148 * @param int $month
150 private function getDateMenu( $year, $month ) {
151 # Offset overrides year/month selection
152 if( $month && $month !== -1 ) {
153 $encMonth = intval( $month );
154 } else {
155 $encMonth = '';
157 if( $year ) {
158 $encYear = intval( $year );
159 } else if( $encMonth ) {
160 $thisMonth = intval( gmdate( 'n' ) );
161 $thisYear = intval( gmdate( 'Y' ) );
162 if( intval($encMonth) > $thisMonth ) {
163 $thisYear--;
165 $encYear = $thisYear;
166 } else {
167 $encYear = '';
169 return Xml::label( wfMsg( 'year' ), 'year' ) . ' '.
170 Xml::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) .
171 ' '.
172 Xml::label( wfMsg( 'month' ), 'month' ) . ' '.
173 Xml::monthSelector( $encMonth, -1 );
177 * Creates begin of history list with a submit button
179 * @return string HTML output
181 function beginHistoryList() {
182 global $wgTitle, $wgScript, $wgEnableHtmlDiff;
183 $this->lastdate = '';
184 $s = wfMsgExt( 'histlegend', array( 'parse') );
185 $s .= Xml::openElement( 'form', array( 'action' => $wgScript, 'id' => 'mw-history-compare' ) );
186 $s .= Xml::hidden( 'title', $wgTitle->getPrefixedDbKey() );
187 if( $wgEnableHtmlDiff ) {
188 $s .= $this->submitButton( wfMsg( 'visualcomparison'),
189 array(
190 'name' => 'htmldiff',
191 'class' => 'historysubmit',
192 'accesskey' => wfMsg( 'accesskey-visualcomparison' ),
193 'title' => wfMsg( 'tooltip-compareselectedversions' ),
196 $s .= $this->submitButton( wfMsg( 'wikicodecomparison'),
197 array(
198 'class' => 'historysubmit',
199 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
200 'title' => wfMsg( 'tooltip-compareselectedversions' ),
203 } else {
204 $s .= $this->submitButton( wfMsg( 'compareselectedversions'),
205 array(
206 'class' => 'historysubmit',
207 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
208 'title' => wfMsg( 'tooltip-compareselectedversions' ),
212 $s .= '<ul id="pagehistory">' . "\n";
213 return $s;
217 * Creates end of history list with a submit button
219 * @return string HTML output
221 function endHistoryList() {
222 global $wgEnableHtmlDiff;
223 $s = '</ul>';
224 if( $wgEnableHtmlDiff ) {
225 $s .= $this->submitButton( wfMsg( 'visualcomparison'),
226 array(
227 'name' => 'htmldiff',
228 'class' => 'historysubmit',
229 'accesskey' => wfMsg( 'accesskey-visualcomparison' ),
230 'title' => wfMsg( 'tooltip-compareselectedversions' ),
233 $s .= $this->submitButton( wfMsg( 'wikicodecomparison'),
234 array(
235 'class' => 'historysubmit',
236 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
237 'title' => wfMsg( 'tooltip-compareselectedversions' ),
240 } else {
241 $s .= $this->submitButton( wfMsg( 'compareselectedversions'),
242 array(
243 'class' => 'historysubmit',
244 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
245 'title' => wfMsg( 'tooltip-compareselectedversions' ),
249 $s .= '</form>';
250 return $s;
254 * Creates a submit button
256 * @param array $attributes attributes
257 * @return string HTML output for the submit button
259 function submitButton($message, $attributes = array() ) {
260 # Disable submit button if history has 1 revision only
261 if( $this->linesonpage > 1 ) {
262 return Xml::submitButton( $message , $attributes );
263 } else {
264 return '';
269 * Returns a row from the history printout.
271 * @todo document some more, and maybe clean up the code (some params redundant?)
273 * @param Row $row The database row corresponding to the previous line.
274 * @param mixed $next The database row corresponding to the next line.
275 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
276 * @param $notificationtimestamp
277 * @param bool $latest Whether this row corresponds to the page's latest revision.
278 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
279 * @return string HTML output for the row
281 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
282 global $wgUser, $wgLang;
283 $rev = new Revision( $row );
284 $rev->setTitle( $this->mTitle );
286 $curlink = $this->curLink( $rev, $latest );
287 $lastlink = $this->lastLink( $rev, $next, $counter );
288 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
289 $link = $this->revLink( $rev );
291 $s = "($curlink) ($lastlink) $arbitrary";
293 if( $wgUser->isAllowed( 'deleterevision' ) ) {
294 if( $firstInList ) {
295 // We don't currently handle well changing the top revision's settings
296 $del = Xml::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.$this->message['rev-delundel'].')' );
297 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
298 // If revision was hidden from sysops
299 $del = Xml::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.$this->message['rev-delundel'].')' );
300 } else {
301 $query = array( 'target' => $this->mTitle->getPrefixedDbkey(),
302 'oldid' => $rev->getId()
304 $del = $this->mSkin->revDeleteLink( $query, $rev->isDeleted( Revision::DELETED_RESTRICTED ) );
306 $s .= " $del ";
309 $s .= " $link";
310 $s .= " <span class='history-user'>" . $this->mSkin->revUserTools( $rev, true ) . "</span>";
312 if( $row->rev_minor_edit ) {
313 $s .= ' ' . Xml::element( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
316 if( !is_null( $size = $rev->getSize() ) && $rev->userCan( Revision::DELETED_TEXT ) ) {
317 $s .= ' ' . $this->mSkin->formatRevisionSize( $size );
320 $s .= $this->mSkin->revComment( $rev, false, true );
322 if( $notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp) ) {
323 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
325 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
326 $s .= ' <tt>' . wfMsgHtml( 'deletedrev' ) . '</tt>';
329 $tools = array();
331 if( !is_null( $next ) && is_object( $next ) ) {
332 if( $latest && $this->mTitle->userCan( 'rollback' ) && $this->mTitle->userCan( 'edit' ) ) {
333 $tools[] = '<span class="mw-rollback-link">'.$this->mSkin->buildRollbackLink( $rev ).'</span>';
336 if( $this->mTitle->quickUserCan( 'edit' ) && !$rev->isDeleted( Revision::DELETED_TEXT ) &&
337 !$next->rev_deleted & Revision::DELETED_TEXT )
339 # Create undo tooltip for the first (=latest) line only
340 $undoTooltip = $latest
341 ? array( 'title' => wfMsg( 'tooltip-undo' ) )
342 : array();
343 $undolink = $this->mSkin->link(
344 $this->mTitle,
345 wfMsgHtml( 'editundo' ),
346 $undoTooltip,
347 array( 'action' => 'edit', 'undoafter' => $next->rev_id, 'undo' => $rev->getId() ),
348 array( 'known', 'noclasses' )
350 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
354 if( $tools ) {
355 $s .= ' (' . implode( ' | ', $tools ) . ')';
358 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s ) );
360 return "<li>$s</li>\n";
364 * Create a link to view this revision of the page
365 * @param Revision $rev
366 * @returns string
368 function revLink( $rev ) {
369 global $wgLang;
370 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
371 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
372 $link = $this->mSkin->makeKnownLinkObj(
373 $this->mTitle, $date, "oldid=" . $rev->getId() );
374 } else {
375 $link = $date;
377 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
378 return '<span class="history-deleted">' . $link . '</span>';
380 return $link;
384 * Create a diff-to-current link for this revision for this page
385 * @param Revision $rev
386 * @param Bool $latest, this is the latest revision of the page?
387 * @returns string
389 function curLink( $rev, $latest ) {
390 $cur = $this->message['cur'];
391 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
392 return $cur;
393 } else {
394 return $this->mSkin->makeKnownLinkObj( $this->mTitle, $cur,
395 'diff=' . $this->mTitle->getLatestRevID() . "&oldid=" . $rev->getId() );
400 * Create a diff-to-previous link for this revision for this page.
401 * @param Revision $prevRev, the previous revision
402 * @param mixed $next, the newer revision
403 * @param int $counter, what row on the history list this is
404 * @returns string
406 function lastLink( $prevRev, $next, $counter ) {
407 $last = $this->message['last'];
408 # $next may either be a Row, null, or "unkown"
409 $nextRev = is_object($next) ? new Revision( $next ) : $next;
410 if( is_null($next) ) {
411 # Probably no next row
412 return $last;
413 } elseif( $next === 'unknown' ) {
414 # Next row probably exists but is unknown, use an oldid=prev link
415 return $this->mSkin->makeKnownLinkObj( $this->mTitle, $last,
416 "diff=" . $prevRev->getId() . "&oldid=prev" );
417 } elseif( !$prevRev->userCan(Revision::DELETED_TEXT) || !$nextRev->userCan(Revision::DELETED_TEXT) ) {
418 return $last;
419 } else {
420 return $this->mSkin->makeKnownLinkObj( $this->mTitle, $last,
421 "diff=" . $prevRev->getId() . "&oldid={$next->rev_id}" );
426 * Create radio buttons for page history
428 * @param object $rev Revision
429 * @param bool $firstInList Is this version the first one?
430 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
431 * @return string HTML output for the radio buttons
433 function diffButtons( $rev, $firstInList, $counter ) {
434 if( $this->linesonpage > 1) {
435 $radio = array(
436 'type' => 'radio',
437 'value' => $rev->getId(),
440 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
441 $radio['disabled'] = 'disabled';
444 /** @todo: move title texts to javascript */
445 if( $firstInList ) {
446 $first = Xml::element( 'input', array_merge(
447 $radio,
448 array(
449 'style' => 'visibility:hidden',
450 'name' => 'oldid' ) ) );
451 $checkmark = array( 'checked' => 'checked' );
452 } else {
453 if( $counter == 2 ) {
454 $checkmark = array( 'checked' => 'checked' );
455 } else {
456 $checkmark = array();
458 $first = Xml::element( 'input', array_merge(
459 $radio,
460 $checkmark,
461 array( 'name' => 'oldid' ) ) );
462 $checkmark = array();
464 $second = Xml::element( 'input', array_merge(
465 $radio,
466 $checkmark,
467 array( 'name' => 'diff' ) ) );
468 return $first . $second;
469 } else {
470 return '';
475 * Fetch an array of revisions, specified by a given limit, offset and
476 * direction. This is now only used by the feeds. It was previously
477 * used by the main UI but that's now handled by the pager.
479 function fetchRevisions($limit, $offset, $direction) {
480 $dbr = wfGetDB( DB_SLAVE );
482 if( $direction == PageHistory::DIR_PREV )
483 list($dirs, $oper) = array("ASC", ">=");
484 else /* $direction == PageHistory::DIR_NEXT */
485 list($dirs, $oper) = array("DESC", "<=");
487 if( $offset )
488 $offsets = array("rev_timestamp $oper '$offset'");
489 else
490 $offsets = array();
492 $page_id = $this->mTitle->getArticleID();
494 return $dbr->select( 'revision',
495 Revision::selectFields(),
496 array_merge(array("rev_page=$page_id"), $offsets),
497 __METHOD__,
498 array( 'ORDER BY' => "rev_timestamp $dirs",
499 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
504 * Output a subscription feed listing recent edits to this page.
505 * @param string $type
507 function feed( $type ) {
508 global $wgFeedClasses, $wgRequest, $wgFeedLimit;
509 if( !FeedUtils::checkFeedOutput($type) ) {
510 return;
513 $feed = new $wgFeedClasses[$type](
514 $this->mTitle->getPrefixedText() . ' - ' .
515 wfMsgForContent( 'history-feed-title' ),
516 wfMsgForContent( 'history-feed-description' ),
517 $this->mTitle->getFullUrl( 'action=history' ) );
519 // Get a limit on number of feed entries. Provide a sane default
520 // of 10 if none is defined (but limit to $wgFeedLimit max)
521 $limit = $wgRequest->getInt( 'limit', 10 );
522 if( $limit > $wgFeedLimit || $limit < 1 ) {
523 $limit = 10;
525 $items = $this->fetchRevisions($limit, 0, PageHistory::DIR_NEXT);
527 $feed->outHeader();
528 if( $items ) {
529 foreach( $items as $row ) {
530 $feed->outItem( $this->feedItem( $row ) );
532 } else {
533 $feed->outItem( $this->feedEmpty() );
535 $feed->outFooter();
538 function feedEmpty() {
539 global $wgOut;
540 return new FeedItem(
541 wfMsgForContent( 'nohistory' ),
542 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
543 $this->mTitle->getFullUrl(),
544 wfTimestamp( TS_MW ),
546 $this->mTitle->getTalkPage()->getFullUrl() );
550 * Generate a FeedItem object from a given revision table row
551 * Borrows Recent Changes' feed generation functions for formatting;
552 * includes a diff to the previous revision (if any).
554 * @param $row
555 * @return FeedItem
557 function feedItem( $row ) {
558 $rev = new Revision( $row );
559 $rev->setTitle( $this->mTitle );
560 $text = FeedUtils::formatDiffRow( $this->mTitle,
561 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
562 $rev->getId(),
563 $rev->getTimestamp(),
564 $rev->getComment() );
566 if( $rev->getComment() == '' ) {
567 global $wgContLang;
568 $title = wfMsgForContent( 'history-feed-item-nocomment',
569 $rev->getUserText(),
570 $wgContLang->timeanddate( $rev->getTimestamp() ) );
571 } else {
572 $title = $rev->getUserText() . wfMsgForContent( 'colon-separator' ) . FeedItem::stripComment( $rev->getComment() );
575 return new FeedItem(
576 $title,
577 $text,
578 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
579 $rev->getTimestamp(),
580 $rev->getUserText(),
581 $this->mTitle->getTalkPage()->getFullUrl() );
587 * @ingroup Pager
589 class PageHistoryPager extends ReverseChronologicalPager {
590 public $mLastRow = false, $mPageHistory, $mTitle;
592 function __construct( $pageHistory, $year='', $month='' ) {
593 parent::__construct();
594 $this->mPageHistory = $pageHistory;
595 $this->mTitle =& $this->mPageHistory->mTitle;
596 $this->getDateCond( $year, $month );
599 function getQueryInfo() {
600 $queryInfo = array(
601 'tables' => array('revision'),
602 'fields' => Revision::selectFields(),
603 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
604 'options' => array( 'USE INDEX' => array('revision' => 'page_timestamp') )
606 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
607 return $queryInfo;
610 function getIndexField() {
611 return 'rev_timestamp';
614 function formatRow( $row ) {
615 if( $this->mLastRow ) {
616 $latest = $this->mCounter == 1 && $this->mIsFirst;
617 $firstInList = $this->mCounter == 1;
618 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
619 $this->mTitle->getNotificationTimestamp(), $latest, $firstInList );
620 } else {
621 $s = '';
623 $this->mLastRow = $row;
624 return $s;
627 function getStartBody() {
628 $this->mLastRow = false;
629 $this->mCounter = 1;
630 return '';
633 function getEndBody() {
634 if( $this->mLastRow ) {
635 $latest = $this->mCounter == 1 && $this->mIsFirst;
636 $firstInList = $this->mCounter == 1;
637 if( $this->mIsBackwards ) {
638 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
639 if( $this->mOffset == '' ) {
640 $next = null;
641 } else {
642 $next = 'unknown';
644 } else {
645 # The next row is the past-the-end row
646 $next = $this->mPastTheEndRow;
648 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
649 $this->mTitle->getNotificationTimestamp(), $latest, $firstInList );
650 } else {
651 $s = '';
653 return $s;