5 * Split off from Article.php and Skin.php, 2003-12-22
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 * This class handles printing the history page for an article. In order to
27 * be efficient, it uses timestamps rather than offsets for paging, to avoid
28 * costly LIMIT,offset queries.
30 * Construct it by passing in an Article, and call $h->history() to print the
34 class HistoryAction
extends FormlessAction
{
38 public function getName() {
42 public function requiresWrite() {
46 public function requiresUnblock() {
50 protected function getPageTitle() {
51 return $this->msg( 'history-title', $this->getTitle()->getPrefixedText() )->text();
54 protected function getDescription() {
55 // Creation of a subtitle link pointing to [[Special:Log]]
56 return Linker
::linkKnown(
57 SpecialPage
::getTitleFor( 'Log' ),
58 $this->msg( 'viewpagelogs' )->escaped(),
60 array( 'page' => $this->getTitle()->getPrefixedText() )
65 * Get the Article object we are working on.
68 public function getArticle() {
73 * As we use the same small set of messages in various methods and that
74 * they are called often, we call them once and save them in $this->message
76 private function preCacheMessages() {
77 // Precache various messages
78 if ( !isset( $this->message
) ) {
79 $msgs = array( 'cur', 'last', 'pipe-separator' );
80 foreach ( $msgs as $msg ) {
81 $this->message
[$msg] = $this->msg( $msg )->escaped();
87 * Print the history page for an article.
90 global $wgScript, $wgUseFileCache;
92 $out = $this->getOutput();
93 $request = $this->getRequest();
96 * Allow client caching.
98 if ( $out->checkLastModified( $this->page
->getTouched() ) ) {
99 return; // Client cache fresh and headers sent, nothing more to do.
102 wfProfileIn( __METHOD__
);
104 $this->preCacheMessages();
106 # Fill in the file cache if not set already
107 if ( $wgUseFileCache && HTMLFileCache
::useFileCache( $this->getContext() ) ) {
108 $cache = HTMLFileCache
::newFromTitle( $this->getTitle(), 'history' );
109 if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
110 ob_start( array( &$cache, 'saveToFileCache' ) );
114 // Setup page variables.
115 $out->setFeedAppendQuery( 'action=history' );
116 $out->addModules( array( 'mediawiki.legacy.history', 'mediawiki.action.history' ) );
118 // Handle atom/RSS feeds.
119 $feedType = $request->getVal( 'feed' );
121 $this->feed( $feedType );
122 wfProfileOut( __METHOD__
);
126 // Fail nicely if article doesn't exist.
127 if ( !$this->page
->exists() ) {
128 $out->addWikiMsg( 'nohistory' );
129 # show deletion/move log if there is an entry
130 LogEventsList
::showLogExtract(
132 array( 'delete', 'move' ),
136 'conds' => array( "log_action != 'revision'" ),
137 'showIfEmpty' => false,
138 'msgKey' => array( 'moveddeleted-notice' )
141 wfProfileOut( __METHOD__
);
146 * Add date selector to quickly get to a certain time
148 $year = $request->getInt( 'year' );
149 $month = $request->getInt( 'month' );
150 $tagFilter = $request->getVal( 'tagfilter' );
151 $tagSelector = ChangeTags
::buildTagFilterSelector( $tagFilter );
154 * Option to show only revisions that have been (partially) hidden via RevisionDelete
156 if ( $request->getBool( 'deleted' ) ) {
157 $conds = array( "rev_deleted != '0'" );
161 $checkDeleted = Xml
::checkLabel( $this->msg( 'history-show-deleted' )->text(),
162 'deleted', 'mw-show-deleted-only', $request->getBool( 'deleted' ) ) . "\n";
164 // Add the general form
165 $action = htmlspecialchars( $wgScript );
167 "<form action=\"$action\" method=\"get\" id=\"mw-history-searchform\">" .
169 $this->msg( 'history-fieldset-title' )->text(),
171 array( 'id' => 'mw-history-search' )
173 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBKey() ) . "\n" .
174 Html
::hidden( 'action', 'history' ) . "\n" .
175 Xml
::dateMenu( $year, $month ) . ' ' .
176 ( $tagSelector ?
( implode( ' ', $tagSelector ) . ' ' ) : '' ) .
178 Xml
::submitButton( $this->msg( 'allpagessubmit' )->text() ) . "\n" .
182 wfRunHooks( 'PageHistoryBeforeList', array( &$this->page
) );
184 // Create and output the list.
185 $pager = new HistoryPager( $this, $year, $month, $tagFilter, $conds );
187 $pager->getNavigationBar() .
189 $pager->getNavigationBar()
191 $out->preventClickjacking( $pager->getPreventClickjacking() );
193 wfProfileOut( __METHOD__
);
197 * Fetch an array of revisions, specified by a given limit, offset and
198 * direction. This is now only used by the feeds. It was previously
199 * used by the main UI but that's now handled by the pager.
201 * @param $limit Integer: the limit number of revisions to get
202 * @param $offset Integer
203 * @param $direction Integer: either HistoryPage::DIR_PREV or HistoryPage::DIR_NEXT
204 * @return ResultWrapper
206 function fetchRevisions( $limit, $offset, $direction ) {
207 // Fail if article doesn't exist.
208 if( !$this->getTitle()->exists() ) {
209 return new FakeResultWrapper( array() );
212 $dbr = wfGetDB( DB_SLAVE
);
214 if ( $direction == HistoryPage
::DIR_PREV
) {
215 list( $dirs, $oper ) = array( "ASC", ">=" );
216 } else { /* $direction == HistoryPage::DIR_NEXT */
217 list( $dirs, $oper ) = array( "DESC", "<=" );
221 $offsets = array( "rev_timestamp $oper '$offset'" );
226 $page_id = $this->page
->getId();
228 return $dbr->select( 'revision',
229 Revision
::selectFields(),
230 array_merge( array( "rev_page=$page_id" ), $offsets ),
232 array( 'ORDER BY' => "rev_timestamp $dirs",
233 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit )
238 * Output a subscription feed listing recent edits to this page.
240 * @param $type String: feed type
242 function feed( $type ) {
243 global $wgFeedClasses, $wgFeedLimit;
244 if ( !FeedUtils
::checkFeedOutput( $type ) ) {
247 $request = $this->getRequest();
249 $feed = new $wgFeedClasses[$type](
250 $this->getTitle()->getPrefixedText() . ' - ' .
251 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
252 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
253 $this->getTitle()->getFullUrl( 'action=history' )
256 // Get a limit on number of feed entries. Provide a sane default
257 // of 10 if none is defined (but limit to $wgFeedLimit max)
258 $limit = $request->getInt( 'limit', 10 );
259 if ( $limit > $wgFeedLimit ||
$limit < 1 ) {
262 $items = $this->fetchRevisions( $limit, 0, HistoryPage
::DIR_NEXT
);
264 // Generate feed elements enclosed between header and footer.
266 if ( $items->numRows() ) {
267 foreach ( $items as $row ) {
268 $feed->outItem( $this->feedItem( $row ) );
271 $feed->outItem( $this->feedEmpty() );
276 function feedEmpty() {
278 $this->msg( 'nohistory' )->inContentLanguage()->text(),
279 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
280 $this->getTitle()->getFullUrl(),
281 wfTimestamp( TS_MW
),
283 $this->getTitle()->getTalkPage()->getFullUrl()
288 * Generate a FeedItem object from a given revision table row
289 * Borrows Recent Changes' feed generation functions for formatting;
290 * includes a diff to the previous revision (if any).
292 * @param $row Object: database row
295 function feedItem( $row ) {
296 $rev = new Revision( $row );
297 $rev->setTitle( $this->getTitle() );
298 $text = FeedUtils
::formatDiffRow(
300 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
302 $rev->getTimestamp(),
305 if ( $rev->getComment() == '' ) {
307 $title = $this->msg( 'history-feed-item-nocomment',
309 $wgContLang->timeanddate( $rev->getTimestamp() ),
310 $wgContLang->date( $rev->getTimestamp() ),
311 $wgContLang->time( $rev->getTimestamp() ) )->inContentLanguage()->text();
313 $title = $rev->getUserText() .
314 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
315 FeedItem
::stripComment( $rev->getComment() );
320 $this->getTitle()->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
321 $rev->getTimestamp(),
323 $this->getTitle()->getTalkPage()->getFullUrl()
331 class HistoryPager
extends ReverseChronologicalPager
{
332 public $lastRow = false, $counter, $historyPage, $buttons, $conds;
333 protected $oldIdChecked;
334 protected $preventClickjacking = false;
338 protected $parentLens;
340 function __construct( $historyPage, $year = '', $month = '', $tagFilter = '', $conds = array() ) {
341 parent
::__construct( $historyPage->getContext() );
342 $this->historyPage
= $historyPage;
343 $this->tagFilter
= $tagFilter;
344 $this->getDateCond( $year, $month );
345 $this->conds
= $conds;
348 // For hook compatibility...
349 function getArticle() {
350 return $this->historyPage
->getArticle();
353 function getSqlComment() {
354 if ( $this->conds
) {
355 return 'history page filtered'; // potentially slow, see CR r58153
357 return 'history page unfiltered';
361 function getQueryInfo() {
363 'tables' => array( 'revision', 'user' ),
364 'fields' => array_merge( Revision
::selectFields(), Revision
::selectUserFields() ),
365 'conds' => array_merge(
366 array( 'rev_page' => $this->getWikiPage()->getId() ),
368 'options' => array( 'USE INDEX' => array( 'revision' => 'page_timestamp' ) ),
369 'join_conds' => array(
370 'user' => Revision
::userJoinCond(),
371 'tag_summary' => array( 'LEFT JOIN', 'ts_rev_id=rev_id' ) ),
373 ChangeTags
::modifyDisplayQuery(
374 $queryInfo['tables'],
375 $queryInfo['fields'],
377 $queryInfo['join_conds'],
378 $queryInfo['options'],
381 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
385 function getIndexField() {
386 return 'rev_timestamp';
389 function formatRow( $row ) {
390 if ( $this->lastRow
) {
391 $latest = ( $this->counter
== 1 && $this->mIsFirst
);
392 $firstInList = $this->counter
== 1;
394 $s = $this->historyLine( $this->lastRow
, $row,
395 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
399 $this->lastRow
= $row;
403 function doBatchLookups() {
404 # Do a link batch query
405 $this->mResult
->seek( 0 );
406 $batch = new LinkBatch();
408 foreach ( $this->mResult
as $row ) {
409 if( $row->rev_parent_id
) {
410 $revIds[] = $row->rev_parent_id
;
412 if( !is_null( $row->user_name
) ) {
413 $batch->add( NS_USER
, $row->user_name
);
414 $batch->add( NS_USER_TALK
, $row->user_name
);
415 } else { # for anons or usernames of imported revisions
416 $batch->add( NS_USER
, $row->rev_user_text
);
417 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
420 $this->parentLens
= Revision
::getParentLengths( $this->mDb
, $revIds );
422 $this->mResult
->seek( 0 );
426 * Creates begin of history list with a submit button
428 * @return string HTML output
430 function getStartBody() {
432 $this->lastRow
= false;
434 $this->oldIdChecked
= 0;
436 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
437 $s = Html
::openElement( 'form', array( 'action' => $wgScript,
438 'id' => 'mw-history-compare' ) ) . "\n";
439 $s .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) . "\n";
440 $s .= Html
::hidden( 'action', 'historysubmit' ) . "\n";
442 // Button container stored in $this->buttons for re-use in getEndBody()
443 $this->buttons
= '<div>';
444 $this->buttons
.= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
445 array( 'class' => 'historysubmit mw-history-compareselectedversions-button' )
446 + Linker
::tooltipAndAccesskeyAttribs( 'compareselectedversions' )
449 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
450 $this->buttons
.= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
452 $this->buttons
.= '</div>';
454 $s .= $this->buttons
;
455 $s .= '<ul id="pagehistory">' . "\n";
459 private function getRevisionButton( $name, $msg ) {
460 $this->preventClickjacking();
461 # Note bug #20966, <button> is non-standard in IE<8
462 $element = Html
::element( 'button',
467 'class' => "historysubmit mw-history-$name-button",
469 $this->msg( $msg )->text()
474 function getEndBody() {
475 if ( $this->lastRow
) {
476 $latest = $this->counter
== 1 && $this->mIsFirst
;
477 $firstInList = $this->counter
== 1;
478 if ( $this->mIsBackwards
) {
479 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
480 if ( $this->mOffset
== '' ) {
486 # The next row is the past-the-end row
487 $next = $this->mPastTheEndRow
;
490 $s = $this->historyLine( $this->lastRow
, $next,
491 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
496 # Add second buttons only if there is more than one rev
497 if ( $this->getNumRows() > 2 ) {
498 $s .= $this->buttons
;
505 * Creates a submit button
507 * @param $message String: text of the submit button, will be escaped
508 * @param $attributes Array: attributes
509 * @return String: HTML output for the submit button
511 function submitButton( $message, $attributes = array() ) {
512 # Disable submit button if history has 1 revision only
513 if ( $this->getNumRows() > 1 ) {
514 return Xml
::submitButton( $message , $attributes );
521 * Returns a row from the history printout.
523 * @todo document some more, and maybe clean up the code (some params redundant?)
525 * @param $row Object: the database row corresponding to the previous line.
526 * @param $next Mixed: the database row corresponding to the next line. (chronologically previous)
527 * @param $notificationtimestamp
528 * @param $latest Boolean: whether this row corresponds to the page's latest revision.
529 * @param $firstInList Boolean: whether this row corresponds to the first displayed on this history page.
530 * @return String: HTML output for the row
532 function historyLine( $row, $next, $notificationtimestamp = false,
533 $latest = false, $firstInList = false )
535 $rev = new Revision( $row );
536 $rev->setTitle( $this->getTitle() );
538 if ( is_object( $next ) ) {
539 $prevRev = new Revision( $next );
540 $prevRev->setTitle( $this->getTitle() );
545 $curlink = $this->curLink( $rev, $latest );
546 $lastlink = $this->lastLink( $rev, $next );
547 $diffButtons = $this->diffButtons( $rev, $firstInList );
548 $histLinks = Html
::rawElement(
550 array( 'class' => 'mw-history-histlinks' ),
551 $this->msg( 'parentheses' )->rawParams( $curlink . $this->historyPage
->message
['pipe-separator'] . $lastlink )->escaped()
553 $s = $histLinks . $diffButtons;
555 $link = $this->revLink( $rev );
559 $user = $this->getUser();
560 // Show checkboxes for each revision
561 if ( $user->isAllowed( 'deleterevision' ) ) {
562 $this->preventClickjacking();
563 // If revision was hidden from sysops, disable the checkbox
564 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
565 $del = Xml
::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
566 // Otherwise, enable the checkbox...
568 $del = Xml
::check( 'showhiderevisions', false,
569 array( 'name' => 'ids[' . $rev->getId() . ']' ) );
571 // User can only view deleted revisions...
572 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
573 // If revision was hidden from sysops, disable the link
574 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
575 $cdel = Linker
::revDeleteLinkDisabled( false );
576 // Otherwise, show the link...
578 $query = array( 'type' => 'revision',
579 'target' => $this->getTitle()->getPrefixedDbkey(), 'ids' => $rev->getId() );
580 $del .= Linker
::revDeleteLink( $query,
581 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), false );
588 $lang = $this->getLanguage();
589 $dirmark = $lang->getDirMark();
593 $s .= " <span class='history-user'>" .
594 Linker
::revUserTools( $rev, true ) . "</span>";
597 if ( $rev->isMinor() ) {
598 $s .= ' ' . ChangesList
::flag( 'minor' );
601 # Size is always public data
602 $prevSize = isset( $this->parentLens
[$row->rev_parent_id
] )
603 ?
$this->parentLens
[$row->rev_parent_id
]
605 $sDiff = ChangesList
::showCharacterDifference( $prevSize, $rev->getSize() );
606 $fSize = Linker
::formatRevisionSize($rev->getSize());
607 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . "$fSize $sDiff";
609 # Text following the character difference is added just before running hooks
610 $s2 = Linker
::revComment( $rev, false, true );
612 if ( $notificationtimestamp && ( $row->rev_timestamp
>= $notificationtimestamp ) ) {
613 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
614 $classes[] = 'mw-history-line-updated';
619 # Rollback and undo links
620 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
621 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
622 $this->preventClickjacking();
623 $tools[] = '<span class="mw-rollback-link">' .
624 Linker
::buildRollbackLink( $rev, $this->getContext() ) . '</span>';
627 if ( !$rev->isDeleted( Revision
::DELETED_TEXT
)
628 && !$prevRev->isDeleted( Revision
::DELETED_TEXT
) )
630 # Create undo tooltip for the first (=latest) line only
631 $undoTooltip = $latest
632 ?
array( 'title' => $this->msg( 'tooltip-undo' )->text() )
634 $undolink = Linker
::linkKnown(
636 $this->msg( 'editundo' )->escaped(),
640 'undoafter' => $prevRev->getId(),
641 'undo' => $rev->getId()
644 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
649 $s2 .= ' '. $this->msg( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped();
653 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow( $row->ts_tags
, 'history' );
654 $classes = array_merge( $classes, $newClasses );
655 if ( $tagSummary !== '' ) {
656 $s2 .= " $tagSummary";
659 # Include separator between character difference and following text
661 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . $s2;
664 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s, &$classes ) );
668 $attribs['class'] = implode( ' ', $classes );
671 return Xml
::tags( 'li', $attribs, $s ) . "\n";
675 * Create a link to view this revision of the page
677 * @param $rev Revision
680 function revLink( $rev ) {
681 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $this->getUser() );
682 $date = htmlspecialchars( $date );
683 if ( $rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
684 $link = Linker
::linkKnown(
687 array( 'class' => 'mw-changeslist-date' ),
688 array( 'oldid' => $rev->getId() )
693 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
694 $link = "<span class=\"history-deleted\">$link</span>";
700 * Create a diff-to-current link for this revision for this page
702 * @param $rev Revision
703 * @param $latest Boolean: this is the latest revision of the page?
706 function curLink( $rev, $latest ) {
707 $cur = $this->historyPage
->message
['cur'];
708 if ( $latest ||
!$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
711 return Linker
::linkKnown(
716 'diff' => $this->getWikiPage()->getLatest(),
717 'oldid' => $rev->getId()
724 * Create a diff-to-previous link for this revision for this page.
726 * @param $prevRev Revision: the previous revision
727 * @param $next Mixed: the newer revision
730 function lastLink( $prevRev, $next ) {
731 $last = $this->historyPage
->message
['last'];
732 # $next may either be a Row, null, or "unkown"
733 $nextRev = is_object( $next ) ?
new Revision( $next ) : $next;
734 if ( is_null( $next ) ) {
735 # Probably no next row
737 } elseif ( $next === 'unknown' ) {
738 # Next row probably exists but is unknown, use an oldid=prev link
739 return Linker
::linkKnown(
744 'diff' => $prevRev->getId(),
748 } elseif ( !$prevRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
749 ||
!$nextRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) )
753 return Linker
::linkKnown(
758 'diff' => $prevRev->getId(),
759 'oldid' => $next->rev_id
766 * Create radio buttons for page history
768 * @param $rev Revision object
769 * @param $firstInList Boolean: is this version the first one?
771 * @return String: HTML output for the radio buttons
773 function diffButtons( $rev, $firstInList ) {
774 if ( $this->getNumRows() > 1 ) {
776 $radio = array( 'type' => 'radio', 'value' => $id );
777 /** @todo: move title texts to javascript */
778 if ( $firstInList ) {
779 $first = Xml
::element( 'input',
780 array_merge( $radio, array(
781 'style' => 'visibility:hidden',
783 'id' => 'mw-oldid-null' ) )
785 $checkmark = array( 'checked' => 'checked' );
787 # Check visibility of old revisions
788 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
789 $radio['disabled'] = 'disabled';
790 $checkmark = array(); // We will check the next possible one
791 } elseif ( !$this->oldIdChecked
) {
792 $checkmark = array( 'checked' => 'checked' );
793 $this->oldIdChecked
= $id;
795 $checkmark = array();
797 $first = Xml
::element( 'input',
798 array_merge( $radio, $checkmark, array(
800 'id' => "mw-oldid-$id" ) ) );
801 $checkmark = array();
803 $second = Xml
::element( 'input',
804 array_merge( $radio, $checkmark, array(
806 'id' => "mw-diff-$id" ) ) );
807 return $first . $second;
814 * This is called if a write operation is possible from the generated HTML
816 function preventClickjacking( $enable = true ) {
817 $this->preventClickjacking
= $enable;
821 * Get the "prevent clickjacking" flag
824 function getPreventClickjacking() {
825 return $this->preventClickjacking
;
830 * Backwards-compatibility alias
832 class HistoryPage
extends HistoryAction
{
833 public function __construct( Page
$article ) { # Just to make it public
834 parent
::__construct( $article );
837 public function history() {