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 $dbr = wfGetDB( DB_SLAVE
);
209 if ( $direction == HistoryPage
::DIR_PREV
) {
210 list( $dirs, $oper ) = array( "ASC", ">=" );
211 } else { /* $direction == HistoryPage::DIR_NEXT */
212 list( $dirs, $oper ) = array( "DESC", "<=" );
216 $offsets = array( "rev_timestamp $oper '$offset'" );
221 $page_id = $this->page
->getId();
223 return $dbr->select( 'revision',
224 Revision
::selectFields(),
225 array_merge( array( "rev_page=$page_id" ), $offsets ),
227 array( 'ORDER BY' => "rev_timestamp $dirs",
228 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit )
233 * Output a subscription feed listing recent edits to this page.
235 * @param $type String: feed type
237 function feed( $type ) {
238 global $wgFeedClasses, $wgFeedLimit;
239 if ( !FeedUtils
::checkFeedOutput( $type ) ) {
242 $request = $this->getRequest();
244 $feed = new $wgFeedClasses[$type](
245 $this->getTitle()->getPrefixedText() . ' - ' .
246 wfMsgForContent( 'history-feed-title' ),
247 wfMsgForContent( 'history-feed-description' ),
248 $this->getTitle()->getFullUrl( 'action=history' )
251 // Get a limit on number of feed entries. Provide a sane default
252 // of 10 if none is defined (but limit to $wgFeedLimit max)
253 $limit = $request->getInt( 'limit', 10 );
254 if ( $limit > $wgFeedLimit ||
$limit < 1 ) {
257 $items = $this->fetchRevisions( $limit, 0, HistoryPage
::DIR_NEXT
);
259 // Generate feed elements enclosed between header and footer.
261 if ( $items->numRows() ) {
262 foreach ( $items as $row ) {
263 $feed->outItem( $this->feedItem( $row ) );
266 $feed->outItem( $this->feedEmpty() );
271 function feedEmpty() {
273 wfMsgForContent( 'nohistory' ),
274 $this->getOutput()->parse( wfMsgForContent( 'history-feed-empty' ) ),
275 $this->getTitle()->getFullUrl(),
276 wfTimestamp( TS_MW
),
278 $this->getTitle()->getTalkPage()->getFullUrl()
283 * Generate a FeedItem object from a given revision table row
284 * Borrows Recent Changes' feed generation functions for formatting;
285 * includes a diff to the previous revision (if any).
287 * @param $row Object: database row
290 function feedItem( $row ) {
291 $rev = new Revision( $row );
292 $rev->setTitle( $this->getTitle() );
293 $text = FeedUtils
::formatDiffRow(
295 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
297 $rev->getTimestamp(),
300 if ( $rev->getComment() == '' ) {
302 $title = wfMsgForContent( 'history-feed-item-nocomment',
304 $wgContLang->timeanddate( $rev->getTimestamp() ),
305 $wgContLang->date( $rev->getTimestamp() ),
306 $wgContLang->time( $rev->getTimestamp() )
309 $title = $rev->getUserText() .
310 wfMsgForContent( 'colon-separator' ) .
311 FeedItem
::stripComment( $rev->getComment() );
316 $this->getTitle()->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
317 $rev->getTimestamp(),
319 $this->getTitle()->getTalkPage()->getFullUrl()
327 class HistoryPager
extends ReverseChronologicalPager
{
328 public $lastRow = false, $counter, $historyPage, $buttons, $conds;
329 protected $oldIdChecked;
330 protected $preventClickjacking = false;
334 protected $parentLens;
336 function __construct( $historyPage, $year = '', $month = '', $tagFilter = '', $conds = array() ) {
337 parent
::__construct( $historyPage->getContext() );
338 $this->historyPage
= $historyPage;
339 $this->tagFilter
= $tagFilter;
340 $this->getDateCond( $year, $month );
341 $this->conds
= $conds;
344 // For hook compatibility...
345 function getArticle() {
346 return $this->historyPage
->getArticle();
349 function getSqlComment() {
350 if ( $this->conds
) {
351 return 'history page filtered'; // potentially slow, see CR r58153
353 return 'history page unfiltered';
357 function getQueryInfo() {
359 'tables' => array( 'revision', 'user' ),
360 'fields' => array_merge( Revision
::selectFields(), Revision
::selectUserFields() ),
361 'conds' => array_merge(
362 array( 'rev_page' => $this->getWikiPage()->getId() ),
364 'options' => array( 'USE INDEX' => array( 'revision' => 'page_timestamp' ) ),
365 'join_conds' => array(
366 'user' => Revision
::userJoinCond(),
367 'tag_summary' => array( 'LEFT JOIN', 'ts_rev_id=rev_id' ) ),
369 ChangeTags
::modifyDisplayQuery(
370 $queryInfo['tables'],
371 $queryInfo['fields'],
373 $queryInfo['join_conds'],
374 $queryInfo['options'],
377 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
381 function getIndexField() {
382 return 'rev_timestamp';
385 function formatRow( $row ) {
386 if ( $this->lastRow
) {
387 $latest = ( $this->counter
== 1 && $this->mIsFirst
);
388 $firstInList = $this->counter
== 1;
390 $s = $this->historyLine( $this->lastRow
, $row,
391 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
395 $this->lastRow
= $row;
399 function doBatchLookups() {
400 # Do a link batch query
401 $this->mResult
->seek( 0 );
402 $batch = new LinkBatch();
404 foreach ( $this->mResult
as $row ) {
405 if( $row->rev_parent_id
) {
406 $revIds[] = $row->rev_parent_id
;
408 if( !is_null( $row->user_name
) ) {
409 $batch->add( NS_USER
, $row->user_name
);
410 $batch->add( NS_USER_TALK
, $row->user_name
);
411 } else { # for anons or usernames of imported revisions
412 $batch->add( NS_USER
, $row->rev_user_text
);
413 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
416 $this->parentLens
= $this->getParentLengths( $revIds );
418 $this->mResult
->seek( 0 );
422 * Do a batched query to get the parent revision lengths
423 * @param $revIds array
425 * @TODO: stolen from Contributions, refactor
427 private function getParentLengths( array $revIds ) {
430 return $revLens; // empty
432 wfProfileIn( __METHOD__
);
433 $res = $this->mDb
->select( 'revision',
434 array( 'rev_id', 'rev_len' ),
435 array( 'rev_id' => $revIds ),
437 foreach ( $res as $row ) {
438 $revLens[$row->rev_id
] = $row->rev_len
;
440 wfProfileOut( __METHOD__
);
445 * Creates begin of history list with a submit button
447 * @return string HTML output
449 function getStartBody() {
451 $this->lastRow
= false;
453 $this->oldIdChecked
= 0;
455 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
456 $s = Html
::openElement( 'form', array( 'action' => $wgScript,
457 'id' => 'mw-history-compare' ) ) . "\n";
458 $s .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) . "\n";
459 $s .= Html
::hidden( 'action', 'historysubmit' ) . "\n";
461 // Button container stored in $this->buttons for re-use in getEndBody()
462 $this->buttons
= '<div>';
463 $this->buttons
.= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
464 array( 'class' => 'historysubmit mw-history-compareselectedversions-button' )
465 + Linker
::tooltipAndAccesskeyAttribs( 'compareselectedversions' )
468 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
469 $this->buttons
.= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
471 $this->buttons
.= '</div>';
473 $s .= $this->buttons
;
474 $s .= '<ul id="pagehistory">' . "\n";
478 private function getRevisionButton( $name, $msg ) {
479 $this->preventClickjacking();
480 # Note bug #20966, <button> is non-standard in IE<8
481 $element = Html
::element( 'button',
486 'class' => "historysubmit mw-history-$name-button",
488 $this->msg( $msg )->text()
493 function getEndBody() {
494 if ( $this->lastRow
) {
495 $latest = $this->counter
== 1 && $this->mIsFirst
;
496 $firstInList = $this->counter
== 1;
497 if ( $this->mIsBackwards
) {
498 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
499 if ( $this->mOffset
== '' ) {
505 # The next row is the past-the-end row
506 $next = $this->mPastTheEndRow
;
509 $s = $this->historyLine( $this->lastRow
, $next,
510 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
515 # Add second buttons only if there is more than one rev
516 if ( $this->getNumRows() > 2 ) {
517 $s .= $this->buttons
;
524 * Creates a submit button
526 * @param $message String: text of the submit button, will be escaped
527 * @param $attributes Array: attributes
528 * @return String: HTML output for the submit button
530 function submitButton( $message, $attributes = array() ) {
531 # Disable submit button if history has 1 revision only
532 if ( $this->getNumRows() > 1 ) {
533 return Xml
::submitButton( $message , $attributes );
540 * Returns a row from the history printout.
542 * @todo document some more, and maybe clean up the code (some params redundant?)
544 * @param $row Object: the database row corresponding to the previous line.
545 * @param $next Mixed: the database row corresponding to the next line. (chronologically previous)
546 * @param $notificationtimestamp
547 * @param $latest Boolean: whether this row corresponds to the page's latest revision.
548 * @param $firstInList Boolean: whether this row corresponds to the first displayed on this history page.
549 * @return String: HTML output for the row
551 function historyLine( $row, $next, $notificationtimestamp = false,
552 $latest = false, $firstInList = false )
554 $rev = new Revision( $row );
555 $rev->setTitle( $this->getTitle() );
557 if ( is_object( $next ) ) {
558 $prevRev = new Revision( $next );
559 $prevRev->setTitle( $this->getTitle() );
564 $curlink = $this->curLink( $rev, $latest );
565 $lastlink = $this->lastLink( $rev, $next );
566 $diffButtons = $this->diffButtons( $rev, $firstInList );
567 $histLinks = Html
::rawElement(
569 array( 'class' => 'mw-history-histlinks' ),
570 $this->msg( 'parentheses' )->rawParams( $curlink . $this->historyPage
->message
['pipe-separator'] . $lastlink )->escaped()
572 $s = $histLinks . $diffButtons;
574 $link = $this->revLink( $rev );
578 $user = $this->getUser();
579 // Show checkboxes for each revision
580 if ( $user->isAllowed( 'deleterevision' ) ) {
581 $this->preventClickjacking();
582 // If revision was hidden from sysops, disable the checkbox
583 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
584 $del = Xml
::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
585 // Otherwise, enable the checkbox...
587 $del = Xml
::check( 'showhiderevisions', false,
588 array( 'name' => 'ids[' . $rev->getId() . ']' ) );
590 // User can only view deleted revisions...
591 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
592 // If revision was hidden from sysops, disable the link
593 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
594 $cdel = Linker
::revDeleteLinkDisabled( false );
595 // Otherwise, show the link...
597 $query = array( 'type' => 'revision',
598 'target' => $this->getTitle()->getPrefixedDbkey(), 'ids' => $rev->getId() );
599 $del .= Linker
::revDeleteLink( $query,
600 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), false );
607 $lang = $this->getLanguage();
608 $dirmark = $lang->getDirMark();
612 $s .= " <span class='history-user'>" .
613 Linker
::revUserTools( $rev, true ) . "</span>";
616 if ( $rev->isMinor() ) {
617 $s .= ' ' . ChangesList
::flag( 'minor' );
620 # Size is always public data
621 $prevSize = isset( $this->parentLens
[$row->rev_parent_id
] )
622 ?
$this->parentLens
[$row->rev_parent_id
]
624 $sDiff = ChangesList
::showCharacterDifference( $prevSize, $rev->getSize() );
625 $fSize = Linker
::formatRevisionSize($rev->getSize());
626 $s .= " . . $fSize $sDiff";
628 # Text following the character difference is added just before running hooks
629 $s2 = Linker
::revComment( $rev, false, true );
631 if ( $notificationtimestamp && ( $row->rev_timestamp
>= $notificationtimestamp ) ) {
632 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
637 # Rollback and undo links
639 !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) ) )
641 if ( $latest && !count( $this->getTitle()->getUserPermissionsErrors( 'rollback', $this->getUser() ) ) ) {
642 $this->preventClickjacking();
643 $tools[] = '<span class="mw-rollback-link">' .
644 Linker
::buildRollbackLink( $rev ) . '</span>';
647 if ( !$rev->isDeleted( Revision
::DELETED_TEXT
)
648 && !$prevRev->isDeleted( Revision
::DELETED_TEXT
) )
650 # Create undo tooltip for the first (=latest) line only
651 $undoTooltip = $latest
652 ?
array( 'title' => $this->msg( 'tooltip-undo' )->text() )
654 $undolink = Linker
::linkKnown(
656 $this->msg( 'editundo' )->escaped(),
660 'undoafter' => $prevRev->getId(),
661 'undo' => $rev->getId()
664 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
669 $s2 .= ' '. $this->msg( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped();
673 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow( $row->ts_tags
, 'history' );
674 $classes = array_merge( $classes, $newClasses );
675 if ( $tagSummary !== '' ) {
676 $s2 .= " $tagSummary";
679 # Include separator between character difference and following text
684 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s, &$classes ) );
688 $attribs['class'] = implode( ' ', $classes );
691 return Xml
::tags( 'li', $attribs, $s ) . "\n";
695 * Create a link to view this revision of the page
697 * @param $rev Revision
700 function revLink( $rev ) {
701 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $this->getUser() );
702 $date = htmlspecialchars( $date );
703 if ( $rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
704 $link = Linker
::linkKnown(
708 array( 'oldid' => $rev->getId() )
713 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
714 $link = "<span class=\"history-deleted\">$link</span>";
720 * Create a diff-to-current link for this revision for this page
722 * @param $rev Revision
723 * @param $latest Boolean: this is the latest revision of the page?
726 function curLink( $rev, $latest ) {
727 $cur = $this->historyPage
->message
['cur'];
728 if ( $latest ||
!$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
731 return Linker
::linkKnown(
736 'diff' => $this->getWikiPage()->getLatest(),
737 'oldid' => $rev->getId()
744 * Create a diff-to-previous link for this revision for this page.
746 * @param $prevRev Revision: the previous revision
747 * @param $next Mixed: the newer revision
750 function lastLink( $prevRev, $next ) {
751 $last = $this->historyPage
->message
['last'];
752 # $next may either be a Row, null, or "unkown"
753 $nextRev = is_object( $next ) ?
new Revision( $next ) : $next;
754 if ( is_null( $next ) ) {
755 # Probably no next row
757 } elseif ( $next === 'unknown' ) {
758 # Next row probably exists but is unknown, use an oldid=prev link
759 return Linker
::linkKnown(
764 'diff' => $prevRev->getId(),
768 } elseif ( !$prevRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
769 ||
!$nextRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) )
773 return Linker
::linkKnown(
778 'diff' => $prevRev->getId(),
779 'oldid' => $next->rev_id
786 * Create radio buttons for page history
788 * @param $rev Revision object
789 * @param $firstInList Boolean: is this version the first one?
791 * @return String: HTML output for the radio buttons
793 function diffButtons( $rev, $firstInList ) {
794 if ( $this->getNumRows() > 1 ) {
796 $radio = array( 'type' => 'radio', 'value' => $id );
797 /** @todo: move title texts to javascript */
798 if ( $firstInList ) {
799 $first = Xml
::element( 'input',
800 array_merge( $radio, array(
801 'style' => 'visibility:hidden',
803 'id' => 'mw-oldid-null' ) )
805 $checkmark = array( 'checked' => 'checked' );
807 # Check visibility of old revisions
808 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
809 $radio['disabled'] = 'disabled';
810 $checkmark = array(); // We will check the next possible one
811 } elseif ( !$this->oldIdChecked
) {
812 $checkmark = array( 'checked' => 'checked' );
813 $this->oldIdChecked
= $id;
815 $checkmark = array();
817 $first = Xml
::element( 'input',
818 array_merge( $radio, $checkmark, array(
820 'id' => "mw-oldid-$id" ) ) );
821 $checkmark = array();
823 $second = Xml
::element( 'input',
824 array_merge( $radio, $checkmark, array(
826 'id' => "mw-diff-$id" ) ) );
827 return $first . $second;
834 * This is called if a write operation is possible from the generated HTML
836 function preventClickjacking( $enable = true ) {
837 $this->preventClickjacking
= $enable;
841 * Get the "prevent clickjacking" flag
844 function getPreventClickjacking() {
845 return $this->preventClickjacking
;
850 * Backwards-compatibility alias
852 class HistoryPage
extends HistoryAction
{
853 public function __construct( Page
$article ) { # Just to make it public
854 parent
::__construct( $article );
857 public function history() {