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 wfMsgForContent( 'history-feed-title' ),
252 wfMsgForContent( 'history-feed-description' ),
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 wfMsgForContent( 'nohistory' ),
279 $this->getOutput()->parse( wfMsgForContent( 'history-feed-empty' ) ),
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 = wfMsgForContent( 'history-feed-item-nocomment',
309 $wgContLang->timeanddate( $rev->getTimestamp() ),
310 $wgContLang->date( $rev->getTimestamp() ),
311 $wgContLang->time( $rev->getTimestamp() )
314 $title = $rev->getUserText() .
315 wfMsgForContent( 'colon-separator' ) .
316 FeedItem
::stripComment( $rev->getComment() );
321 $this->getTitle()->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
322 $rev->getTimestamp(),
324 $this->getTitle()->getTalkPage()->getFullUrl()
332 class HistoryPager
extends ReverseChronologicalPager
{
333 public $lastRow = false, $counter, $historyPage, $buttons, $conds;
334 protected $oldIdChecked;
335 protected $preventClickjacking = false;
339 protected $parentLens;
341 function __construct( $historyPage, $year = '', $month = '', $tagFilter = '', $conds = array() ) {
342 parent
::__construct( $historyPage->getContext() );
343 $this->historyPage
= $historyPage;
344 $this->tagFilter
= $tagFilter;
345 $this->getDateCond( $year, $month );
346 $this->conds
= $conds;
349 // For hook compatibility...
350 function getArticle() {
351 return $this->historyPage
->getArticle();
354 function getSqlComment() {
355 if ( $this->conds
) {
356 return 'history page filtered'; // potentially slow, see CR r58153
358 return 'history page unfiltered';
362 function getQueryInfo() {
364 'tables' => array( 'revision', 'user' ),
365 'fields' => array_merge( Revision
::selectFields(), Revision
::selectUserFields() ),
366 'conds' => array_merge(
367 array( 'rev_page' => $this->getWikiPage()->getId() ),
369 'options' => array( 'USE INDEX' => array( 'revision' => 'page_timestamp' ) ),
370 'join_conds' => array(
371 'user' => Revision
::userJoinCond(),
372 'tag_summary' => array( 'LEFT JOIN', 'ts_rev_id=rev_id' ) ),
374 ChangeTags
::modifyDisplayQuery(
375 $queryInfo['tables'],
376 $queryInfo['fields'],
378 $queryInfo['join_conds'],
379 $queryInfo['options'],
382 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
386 function getIndexField() {
387 return 'rev_timestamp';
390 function formatRow( $row ) {
391 if ( $this->lastRow
) {
392 $latest = ( $this->counter
== 1 && $this->mIsFirst
);
393 $firstInList = $this->counter
== 1;
395 $s = $this->historyLine( $this->lastRow
, $row,
396 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
400 $this->lastRow
= $row;
404 function doBatchLookups() {
405 # Do a link batch query
406 $this->mResult
->seek( 0 );
407 $batch = new LinkBatch();
409 foreach ( $this->mResult
as $row ) {
410 if( $row->rev_parent_id
) {
411 $revIds[] = $row->rev_parent_id
;
413 if( !is_null( $row->user_name
) ) {
414 $batch->add( NS_USER
, $row->user_name
);
415 $batch->add( NS_USER_TALK
, $row->user_name
);
416 } else { # for anons or usernames of imported revisions
417 $batch->add( NS_USER
, $row->rev_user_text
);
418 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
421 $this->parentLens
= $this->getParentLengths( $revIds );
423 $this->mResult
->seek( 0 );
427 * Do a batched query to get the parent revision lengths
428 * @param $revIds array
430 * @TODO: stolen from Contributions, refactor
432 private function getParentLengths( array $revIds ) {
435 return $revLens; // empty
437 wfProfileIn( __METHOD__
);
438 $res = $this->mDb
->select( 'revision',
439 array( 'rev_id', 'rev_len' ),
440 array( 'rev_id' => $revIds ),
442 foreach ( $res as $row ) {
443 $revLens[$row->rev_id
] = $row->rev_len
;
445 wfProfileOut( __METHOD__
);
450 * Creates begin of history list with a submit button
452 * @return string HTML output
454 function getStartBody() {
456 $this->lastRow
= false;
458 $this->oldIdChecked
= 0;
460 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
461 $s = Html
::openElement( 'form', array( 'action' => $wgScript,
462 'id' => 'mw-history-compare' ) ) . "\n";
463 $s .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) . "\n";
464 $s .= Html
::hidden( 'action', 'historysubmit' ) . "\n";
466 // Button container stored in $this->buttons for re-use in getEndBody()
467 $this->buttons
= '<div>';
468 $this->buttons
.= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
469 array( 'class' => 'historysubmit mw-history-compareselectedversions-button' )
470 + Linker
::tooltipAndAccesskeyAttribs( 'compareselectedversions' )
473 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
474 $this->buttons
.= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
476 $this->buttons
.= '</div>';
478 $s .= $this->buttons
;
479 $s .= '<ul id="pagehistory">' . "\n";
483 private function getRevisionButton( $name, $msg ) {
484 $this->preventClickjacking();
485 # Note bug #20966, <button> is non-standard in IE<8
486 $element = Html
::element( 'button',
491 'class' => "historysubmit mw-history-$name-button",
493 $this->msg( $msg )->text()
498 function getEndBody() {
499 if ( $this->lastRow
) {
500 $latest = $this->counter
== 1 && $this->mIsFirst
;
501 $firstInList = $this->counter
== 1;
502 if ( $this->mIsBackwards
) {
503 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
504 if ( $this->mOffset
== '' ) {
510 # The next row is the past-the-end row
511 $next = $this->mPastTheEndRow
;
514 $s = $this->historyLine( $this->lastRow
, $next,
515 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
520 # Add second buttons only if there is more than one rev
521 if ( $this->getNumRows() > 2 ) {
522 $s .= $this->buttons
;
529 * Creates a submit button
531 * @param $message String: text of the submit button, will be escaped
532 * @param $attributes Array: attributes
533 * @return String: HTML output for the submit button
535 function submitButton( $message, $attributes = array() ) {
536 # Disable submit button if history has 1 revision only
537 if ( $this->getNumRows() > 1 ) {
538 return Xml
::submitButton( $message , $attributes );
545 * Returns a row from the history printout.
547 * @todo document some more, and maybe clean up the code (some params redundant?)
549 * @param $row Object: the database row corresponding to the previous line.
550 * @param $next Mixed: the database row corresponding to the next line. (chronologically previous)
551 * @param $notificationtimestamp
552 * @param $latest Boolean: whether this row corresponds to the page's latest revision.
553 * @param $firstInList Boolean: whether this row corresponds to the first displayed on this history page.
554 * @return String: HTML output for the row
556 function historyLine( $row, $next, $notificationtimestamp = false,
557 $latest = false, $firstInList = false )
559 $rev = new Revision( $row );
560 $rev->setTitle( $this->getTitle() );
562 if ( is_object( $next ) ) {
563 $prevRev = new Revision( $next );
564 $prevRev->setTitle( $this->getTitle() );
569 $curlink = $this->curLink( $rev, $latest );
570 $lastlink = $this->lastLink( $rev, $next );
571 $diffButtons = $this->diffButtons( $rev, $firstInList );
572 $histLinks = Html
::rawElement(
574 array( 'class' => 'mw-history-histlinks' ),
575 $this->msg( 'parentheses' )->rawParams( $curlink . $this->historyPage
->message
['pipe-separator'] . $lastlink )->escaped()
577 $s = $histLinks . $diffButtons;
579 $link = $this->revLink( $rev );
583 $user = $this->getUser();
584 // Show checkboxes for each revision
585 if ( $user->isAllowed( 'deleterevision' ) ) {
586 $this->preventClickjacking();
587 // If revision was hidden from sysops, disable the checkbox
588 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
589 $del = Xml
::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
590 // Otherwise, enable the checkbox...
592 $del = Xml
::check( 'showhiderevisions', false,
593 array( 'name' => 'ids[' . $rev->getId() . ']' ) );
595 // User can only view deleted revisions...
596 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
597 // If revision was hidden from sysops, disable the link
598 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
599 $cdel = Linker
::revDeleteLinkDisabled( false );
600 // Otherwise, show the link...
602 $query = array( 'type' => 'revision',
603 'target' => $this->getTitle()->getPrefixedDbkey(), 'ids' => $rev->getId() );
604 $del .= Linker
::revDeleteLink( $query,
605 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), false );
612 $lang = $this->getLanguage();
613 $dirmark = $lang->getDirMark();
617 $s .= " <span class='history-user'>" .
618 Linker
::revUserTools( $rev, true ) . "</span>";
621 if ( $rev->isMinor() ) {
622 $s .= ' ' . ChangesList
::flag( 'minor' );
625 # Size is always public data
626 $prevSize = isset( $this->parentLens
[$row->rev_parent_id
] )
627 ?
$this->parentLens
[$row->rev_parent_id
]
629 $sDiff = ChangesList
::showCharacterDifference( $prevSize, $rev->getSize() );
630 $fSize = Linker
::formatRevisionSize($rev->getSize());
631 $s .= " . . $fSize $sDiff";
633 # Text following the character difference is added just before running hooks
634 $s2 = Linker
::revComment( $rev, false, true );
636 if ( $notificationtimestamp && ( $row->rev_timestamp
>= $notificationtimestamp ) ) {
637 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
642 # Rollback and undo links
644 !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) ) )
646 if ( $latest && !count( $this->getTitle()->getUserPermissionsErrors( 'rollback', $this->getUser() ) ) ) {
647 $this->preventClickjacking();
648 $tools[] = '<span class="mw-rollback-link">' .
649 Linker
::buildRollbackLink( $rev ) . '</span>';
652 if ( !$rev->isDeleted( Revision
::DELETED_TEXT
)
653 && !$prevRev->isDeleted( Revision
::DELETED_TEXT
) )
655 # Create undo tooltip for the first (=latest) line only
656 $undoTooltip = $latest
657 ?
array( 'title' => $this->msg( 'tooltip-undo' )->text() )
659 $undolink = Linker
::linkKnown(
661 $this->msg( 'editundo' )->escaped(),
665 'undoafter' => $prevRev->getId(),
666 'undo' => $rev->getId()
669 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
674 $s2 .= ' '. $this->msg( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped();
678 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow( $row->ts_tags
, 'history' );
679 $classes = array_merge( $classes, $newClasses );
680 if ( $tagSummary !== '' ) {
681 $s2 .= " $tagSummary";
684 # Include separator between character difference and following text
689 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s, &$classes ) );
693 $attribs['class'] = implode( ' ', $classes );
696 return Xml
::tags( 'li', $attribs, $s ) . "\n";
700 * Create a link to view this revision of the page
702 * @param $rev Revision
705 function revLink( $rev ) {
706 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $this->getUser() );
707 $date = htmlspecialchars( $date );
708 if ( $rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
709 $link = Linker
::linkKnown(
713 array( 'oldid' => $rev->getId() )
718 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
719 $link = "<span class=\"history-deleted\">$link</span>";
725 * Create a diff-to-current link for this revision for this page
727 * @param $rev Revision
728 * @param $latest Boolean: this is the latest revision of the page?
731 function curLink( $rev, $latest ) {
732 $cur = $this->historyPage
->message
['cur'];
733 if ( $latest ||
!$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
736 return Linker
::linkKnown(
741 'diff' => $this->getWikiPage()->getLatest(),
742 'oldid' => $rev->getId()
749 * Create a diff-to-previous link for this revision for this page.
751 * @param $prevRev Revision: the previous revision
752 * @param $next Mixed: the newer revision
755 function lastLink( $prevRev, $next ) {
756 $last = $this->historyPage
->message
['last'];
757 # $next may either be a Row, null, or "unkown"
758 $nextRev = is_object( $next ) ?
new Revision( $next ) : $next;
759 if ( is_null( $next ) ) {
760 # Probably no next row
762 } elseif ( $next === 'unknown' ) {
763 # Next row probably exists but is unknown, use an oldid=prev link
764 return Linker
::linkKnown(
769 'diff' => $prevRev->getId(),
773 } elseif ( !$prevRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
774 ||
!$nextRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) )
778 return Linker
::linkKnown(
783 'diff' => $prevRev->getId(),
784 'oldid' => $next->rev_id
791 * Create radio buttons for page history
793 * @param $rev Revision object
794 * @param $firstInList Boolean: is this version the first one?
796 * @return String: HTML output for the radio buttons
798 function diffButtons( $rev, $firstInList ) {
799 if ( $this->getNumRows() > 1 ) {
801 $radio = array( 'type' => 'radio', 'value' => $id );
802 /** @todo: move title texts to javascript */
803 if ( $firstInList ) {
804 $first = Xml
::element( 'input',
805 array_merge( $radio, array(
806 'style' => 'visibility:hidden',
808 'id' => 'mw-oldid-null' ) )
810 $checkmark = array( 'checked' => 'checked' );
812 # Check visibility of old revisions
813 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
814 $radio['disabled'] = 'disabled';
815 $checkmark = array(); // We will check the next possible one
816 } elseif ( !$this->oldIdChecked
) {
817 $checkmark = array( 'checked' => 'checked' );
818 $this->oldIdChecked
= $id;
820 $checkmark = array();
822 $first = Xml
::element( 'input',
823 array_merge( $radio, $checkmark, array(
825 'id' => "mw-oldid-$id" ) ) );
826 $checkmark = array();
828 $second = Xml
::element( 'input',
829 array_merge( $radio, $checkmark, array(
831 'id' => "mw-diff-$id" ) ) );
832 return $first . $second;
839 * This is called if a write operation is possible from the generated HTML
841 function preventClickjacking( $enable = true ) {
842 $this->preventClickjacking
= $enable;
846 * Get the "prevent clickjacking" flag
849 function getPreventClickjacking() {
850 return $this->preventClickjacking
;
855 * Backwards-compatibility alias
857 class HistoryPage
extends HistoryAction
{
858 public function __construct( Page
$article ) { # Just to make it public
859 parent
::__construct( $article );
862 public function history() {