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 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
162 $checkDeleted = Xml
::checkLabel( $this->msg( 'history-show-deleted' )->text(),
163 'deleted', 'mw-show-deleted-only', $request->getBool( 'deleted' ) ) . "\n";
168 // Add the general form
169 $action = htmlspecialchars( $wgScript );
171 "<form action=\"$action\" method=\"get\" id=\"mw-history-searchform\">" .
173 $this->msg( 'history-fieldset-title' )->text(),
175 array( 'id' => 'mw-history-search' )
177 Html
::hidden( 'title', $this->getTitle()->getPrefixedDBKey() ) . "\n" .
178 Html
::hidden( 'action', 'history' ) . "\n" .
179 Xml
::dateMenu( $year, $month ) . ' ' .
180 ( $tagSelector ?
( implode( ' ', $tagSelector ) . ' ' ) : '' ) .
182 Xml
::submitButton( $this->msg( 'allpagessubmit' )->text() ) . "\n" .
186 wfRunHooks( 'PageHistoryBeforeList', array( &$this->page
) );
188 // Create and output the list.
189 $pager = new HistoryPager( $this, $year, $month, $tagFilter, $conds );
191 $pager->getNavigationBar() .
193 $pager->getNavigationBar()
195 $out->preventClickjacking( $pager->getPreventClickjacking() );
197 wfProfileOut( __METHOD__
);
201 * Fetch an array of revisions, specified by a given limit, offset and
202 * direction. This is now only used by the feeds. It was previously
203 * used by the main UI but that's now handled by the pager.
205 * @param $limit Integer: the limit number of revisions to get
206 * @param $offset Integer
207 * @param $direction Integer: either HistoryPage::DIR_PREV or HistoryPage::DIR_NEXT
208 * @return ResultWrapper
210 function fetchRevisions( $limit, $offset, $direction ) {
211 // Fail if article doesn't exist.
212 if( !$this->getTitle()->exists() ) {
213 return new FakeResultWrapper( array() );
216 $dbr = wfGetDB( DB_SLAVE
);
218 if ( $direction == HistoryPage
::DIR_PREV
) {
219 list( $dirs, $oper ) = array( "ASC", ">=" );
220 } else { /* $direction == HistoryPage::DIR_NEXT */
221 list( $dirs, $oper ) = array( "DESC", "<=" );
225 $offsets = array( "rev_timestamp $oper '$offset'" );
230 $page_id = $this->page
->getId();
232 return $dbr->select( 'revision',
233 Revision
::selectFields(),
234 array_merge( array( "rev_page=$page_id" ), $offsets ),
236 array( 'ORDER BY' => "rev_timestamp $dirs",
237 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit )
242 * Output a subscription feed listing recent edits to this page.
244 * @param $type String: feed type
246 function feed( $type ) {
247 global $wgFeedClasses, $wgFeedLimit;
248 if ( !FeedUtils
::checkFeedOutput( $type ) ) {
251 $request = $this->getRequest();
253 $feed = new $wgFeedClasses[$type](
254 $this->getTitle()->getPrefixedText() . ' - ' .
255 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
256 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
257 $this->getTitle()->getFullUrl( 'action=history' )
260 // Get a limit on number of feed entries. Provide a sane default
261 // of 10 if none is defined (but limit to $wgFeedLimit max)
262 $limit = $request->getInt( 'limit', 10 );
263 if ( $limit > $wgFeedLimit ||
$limit < 1 ) {
266 $items = $this->fetchRevisions( $limit, 0, HistoryPage
::DIR_NEXT
);
268 // Generate feed elements enclosed between header and footer.
270 if ( $items->numRows() ) {
271 foreach ( $items as $row ) {
272 $feed->outItem( $this->feedItem( $row ) );
275 $feed->outItem( $this->feedEmpty() );
280 function feedEmpty() {
282 $this->msg( 'nohistory' )->inContentLanguage()->text(),
283 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
284 $this->getTitle()->getFullUrl(),
285 wfTimestamp( TS_MW
),
287 $this->getTitle()->getTalkPage()->getFullUrl()
292 * Generate a FeedItem object from a given revision table row
293 * Borrows Recent Changes' feed generation functions for formatting;
294 * includes a diff to the previous revision (if any).
296 * @param $row Object: database row
299 function feedItem( $row ) {
300 $rev = new Revision( $row );
301 $rev->setTitle( $this->getTitle() );
302 $text = FeedUtils
::formatDiffRow(
304 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
306 $rev->getTimestamp(),
309 if ( $rev->getComment() == '' ) {
311 $title = $this->msg( 'history-feed-item-nocomment',
313 $wgContLang->timeanddate( $rev->getTimestamp() ),
314 $wgContLang->date( $rev->getTimestamp() ),
315 $wgContLang->time( $rev->getTimestamp() ) )->inContentLanguage()->text();
317 $title = $rev->getUserText() .
318 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
319 FeedItem
::stripComment( $rev->getComment() );
324 $this->getTitle()->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
325 $rev->getTimestamp(),
327 $this->getTitle()->getTalkPage()->getFullUrl()
335 class HistoryPager
extends ReverseChronologicalPager
{
336 public $lastRow = false, $counter, $historyPage, $buttons, $conds;
337 protected $oldIdChecked;
338 protected $preventClickjacking = false;
342 protected $parentLens;
344 function __construct( $historyPage, $year = '', $month = '', $tagFilter = '', $conds = array() ) {
345 parent
::__construct( $historyPage->getContext() );
346 $this->historyPage
= $historyPage;
347 $this->tagFilter
= $tagFilter;
348 $this->getDateCond( $year, $month );
349 $this->conds
= $conds;
352 // For hook compatibility...
353 function getArticle() {
354 return $this->historyPage
->getArticle();
357 function getSqlComment() {
358 if ( $this->conds
) {
359 return 'history page filtered'; // potentially slow, see CR r58153
361 return 'history page unfiltered';
365 function getQueryInfo() {
367 'tables' => array( 'revision', 'user' ),
368 'fields' => array_merge( Revision
::selectFields(), Revision
::selectUserFields() ),
369 'conds' => array_merge(
370 array( 'rev_page' => $this->getWikiPage()->getId() ),
372 'options' => array( 'USE INDEX' => array( 'revision' => 'page_timestamp' ) ),
373 'join_conds' => array(
374 'user' => Revision
::userJoinCond(),
375 'tag_summary' => array( 'LEFT JOIN', 'ts_rev_id=rev_id' ) ),
377 ChangeTags
::modifyDisplayQuery(
378 $queryInfo['tables'],
379 $queryInfo['fields'],
381 $queryInfo['join_conds'],
382 $queryInfo['options'],
385 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
389 function getIndexField() {
390 return 'rev_timestamp';
393 function formatRow( $row ) {
394 if ( $this->lastRow
) {
395 $latest = ( $this->counter
== 1 && $this->mIsFirst
);
396 $firstInList = $this->counter
== 1;
398 $s = $this->historyLine( $this->lastRow
, $row,
399 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
403 $this->lastRow
= $row;
407 function doBatchLookups() {
408 # Do a link batch query
409 $this->mResult
->seek( 0 );
410 $batch = new LinkBatch();
412 foreach ( $this->mResult
as $row ) {
413 if( $row->rev_parent_id
) {
414 $revIds[] = $row->rev_parent_id
;
416 if( !is_null( $row->user_name
) ) {
417 $batch->add( NS_USER
, $row->user_name
);
418 $batch->add( NS_USER_TALK
, $row->user_name
);
419 } else { # for anons or usernames of imported revisions
420 $batch->add( NS_USER
, $row->rev_user_text
);
421 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
424 $this->parentLens
= Revision
::getParentLengths( $this->mDb
, $revIds );
426 $this->mResult
->seek( 0 );
430 * Creates begin of history list with a submit button
432 * @return string HTML output
434 function getStartBody() {
436 $this->lastRow
= false;
438 $this->oldIdChecked
= 0;
440 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
441 $s = Html
::openElement( 'form', array( 'action' => $wgScript,
442 'id' => 'mw-history-compare' ) ) . "\n";
443 $s .= Html
::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) . "\n";
444 $s .= Html
::hidden( 'action', 'historysubmit' ) . "\n";
446 // Button container stored in $this->buttons for re-use in getEndBody()
447 $this->buttons
= '<div>';
448 $this->buttons
.= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
449 array( 'class' => 'historysubmit mw-history-compareselectedversions-button' )
450 + Linker
::tooltipAndAccesskeyAttribs( 'compareselectedversions' )
453 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
454 $this->buttons
.= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
456 $this->buttons
.= '</div>';
458 $s .= $this->buttons
;
459 $s .= '<ul id="pagehistory">' . "\n";
463 private function getRevisionButton( $name, $msg ) {
464 $this->preventClickjacking();
465 # Note bug #20966, <button> is non-standard in IE<8
466 $element = Html
::element( 'button',
471 'class' => "historysubmit mw-history-$name-button",
473 $this->msg( $msg )->text()
478 function getEndBody() {
479 if ( $this->lastRow
) {
480 $latest = $this->counter
== 1 && $this->mIsFirst
;
481 $firstInList = $this->counter
== 1;
482 if ( $this->mIsBackwards
) {
483 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
484 if ( $this->mOffset
== '' ) {
490 # The next row is the past-the-end row
491 $next = $this->mPastTheEndRow
;
494 $s = $this->historyLine( $this->lastRow
, $next,
495 $this->getTitle()->getNotificationTimestamp( $this->getUser() ), $latest, $firstInList );
500 # Add second buttons only if there is more than one rev
501 if ( $this->getNumRows() > 2 ) {
502 $s .= $this->buttons
;
509 * Creates a submit button
511 * @param $message String: text of the submit button, will be escaped
512 * @param $attributes Array: attributes
513 * @return String: HTML output for the submit button
515 function submitButton( $message, $attributes = array() ) {
516 # Disable submit button if history has 1 revision only
517 if ( $this->getNumRows() > 1 ) {
518 return Xml
::submitButton( $message , $attributes );
525 * Returns a row from the history printout.
527 * @todo document some more, and maybe clean up the code (some params redundant?)
529 * @param $row Object: the database row corresponding to the previous line.
530 * @param $next Mixed: the database row corresponding to the next line. (chronologically previous)
531 * @param $notificationtimestamp
532 * @param $latest Boolean: whether this row corresponds to the page's latest revision.
533 * @param $firstInList Boolean: whether this row corresponds to the first displayed on this history page.
534 * @return String: HTML output for the row
536 function historyLine( $row, $next, $notificationtimestamp = false,
537 $latest = false, $firstInList = false )
539 $rev = new Revision( $row );
540 $rev->setTitle( $this->getTitle() );
542 if ( is_object( $next ) ) {
543 $prevRev = new Revision( $next );
544 $prevRev->setTitle( $this->getTitle() );
549 $curlink = $this->curLink( $rev, $latest );
550 $lastlink = $this->lastLink( $rev, $next );
551 $diffButtons = $this->diffButtons( $rev, $firstInList );
552 $histLinks = Html
::rawElement(
554 array( 'class' => 'mw-history-histlinks' ),
555 $this->msg( 'parentheses' )->rawParams( $curlink . $this->historyPage
->message
['pipe-separator'] . $lastlink )->escaped()
557 $s = $histLinks . $diffButtons;
559 $link = $this->revLink( $rev );
563 $user = $this->getUser();
564 // Show checkboxes for each revision
565 if ( $user->isAllowed( 'deleterevision' ) ) {
566 $this->preventClickjacking();
567 // If revision was hidden from sysops, disable the checkbox
568 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
569 $del = Xml
::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
570 // Otherwise, enable the checkbox...
572 $del = Xml
::check( 'showhiderevisions', false,
573 array( 'name' => 'ids[' . $rev->getId() . ']' ) );
575 // User can only view deleted revisions...
576 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
577 // If revision was hidden from sysops, disable the link
578 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
579 $del = Linker
::revDeleteLinkDisabled( false );
580 // Otherwise, show the link...
582 $query = array( 'type' => 'revision',
583 'target' => $this->getTitle()->getPrefixedDbkey(), 'ids' => $rev->getId() );
584 $del .= Linker
::revDeleteLink( $query,
585 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), false );
592 $lang = $this->getLanguage();
593 $dirmark = $lang->getDirMark();
597 $s .= " <span class='history-user'>" .
598 Linker
::revUserTools( $rev, true ) . "</span>";
601 if ( $rev->isMinor() ) {
602 $s .= ' ' . ChangesList
::flag( 'minor' );
605 # Size is always public data
606 $prevSize = isset( $this->parentLens
[$row->rev_parent_id
] )
607 ?
$this->parentLens
[$row->rev_parent_id
]
609 $sDiff = ChangesList
::showCharacterDifference( $prevSize, $rev->getSize() );
610 $fSize = Linker
::formatRevisionSize($rev->getSize());
611 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . "$fSize $sDiff";
613 # Text following the character difference is added just before running hooks
614 $s2 = Linker
::revComment( $rev, false, true );
616 if ( $notificationtimestamp && ( $row->rev_timestamp
>= $notificationtimestamp ) ) {
617 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
618 $classes[] = 'mw-history-line-updated';
623 # Rollback and undo links
624 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
625 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
626 $this->preventClickjacking();
627 $tools[] = '<span class="mw-rollback-link">' .
628 Linker
::buildRollbackLink( $rev, $this->getContext() ) . '</span>';
631 if ( !$rev->isDeleted( Revision
::DELETED_TEXT
)
632 && !$prevRev->isDeleted( Revision
::DELETED_TEXT
) )
634 # Create undo tooltip for the first (=latest) line only
635 $undoTooltip = $latest
636 ?
array( 'title' => $this->msg( 'tooltip-undo' )->text() )
638 $undolink = Linker
::linkKnown(
640 $this->msg( 'editundo' )->escaped(),
644 'undoafter' => $prevRev->getId(),
645 'undo' => $rev->getId()
648 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
653 $s2 .= ' '. $this->msg( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped();
657 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow( $row->ts_tags
, 'history' );
658 $classes = array_merge( $classes, $newClasses );
659 if ( $tagSummary !== '' ) {
660 $s2 .= " $tagSummary";
663 # Include separator between character difference and following text
665 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . $s2;
668 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s, &$classes ) );
672 $attribs['class'] = implode( ' ', $classes );
675 return Xml
::tags( 'li', $attribs, $s ) . "\n";
679 * Create a link to view this revision of the page
681 * @param $rev Revision
684 function revLink( $rev ) {
685 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $this->getUser() );
686 $date = htmlspecialchars( $date );
687 if ( $rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
688 $link = Linker
::linkKnown(
691 array( 'class' => 'mw-changeslist-date' ),
692 array( 'oldid' => $rev->getId() )
697 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
698 $link = "<span class=\"history-deleted\">$link</span>";
704 * Create a diff-to-current link for this revision for this page
706 * @param $rev Revision
707 * @param $latest Boolean: this is the latest revision of the page?
710 function curLink( $rev, $latest ) {
711 $cur = $this->historyPage
->message
['cur'];
712 if ( $latest ||
!$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
715 return Linker
::linkKnown(
720 'diff' => $this->getWikiPage()->getLatest(),
721 'oldid' => $rev->getId()
728 * Create a diff-to-previous link for this revision for this page.
730 * @param $prevRev Revision: the previous revision
731 * @param $next Mixed: the newer revision
734 function lastLink( $prevRev, $next ) {
735 $last = $this->historyPage
->message
['last'];
736 # $next may either be a Row, null, or "unkown"
737 $nextRev = is_object( $next ) ?
new Revision( $next ) : $next;
738 if ( is_null( $next ) ) {
739 # Probably no next row
741 } elseif ( $next === 'unknown' ) {
742 # Next row probably exists but is unknown, use an oldid=prev link
743 return Linker
::linkKnown(
748 'diff' => $prevRev->getId(),
752 } elseif ( !$prevRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
753 ||
!$nextRev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) )
757 return Linker
::linkKnown(
762 'diff' => $prevRev->getId(),
763 'oldid' => $next->rev_id
770 * Create radio buttons for page history
772 * @param $rev Revision object
773 * @param $firstInList Boolean: is this version the first one?
775 * @return String: HTML output for the radio buttons
777 function diffButtons( $rev, $firstInList ) {
778 if ( $this->getNumRows() > 1 ) {
780 $radio = array( 'type' => 'radio', 'value' => $id );
781 /** @todo: move title texts to javascript */
782 if ( $firstInList ) {
783 $first = Xml
::element( 'input',
784 array_merge( $radio, array(
785 'style' => 'visibility:hidden',
787 'id' => 'mw-oldid-null' ) )
789 $checkmark = array( 'checked' => 'checked' );
791 # Check visibility of old revisions
792 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
793 $radio['disabled'] = 'disabled';
794 $checkmark = array(); // We will check the next possible one
795 } elseif ( !$this->oldIdChecked
) {
796 $checkmark = array( 'checked' => 'checked' );
797 $this->oldIdChecked
= $id;
799 $checkmark = array();
801 $first = Xml
::element( 'input',
802 array_merge( $radio, $checkmark, array(
804 'id' => "mw-oldid-$id" ) ) );
805 $checkmark = array();
807 $second = Xml
::element( 'input',
808 array_merge( $radio, $checkmark, array(
810 'id' => "mw-diff-$id" ) ) );
811 return $first . $second;
818 * This is called if a write operation is possible from the generated HTML
820 function preventClickjacking( $enable = true ) {
821 $this->preventClickjacking
= $enable;
825 * Get the "prevent clickjacking" flag
828 function getPreventClickjacking() {
829 return $this->preventClickjacking
;
834 * Backwards-compatibility alias
836 class HistoryPage
extends HistoryAction
{
837 public function __construct( Page
$article ) { # Just to make it public
838 parent
::__construct( $article );
841 public function history() {