5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Feed\AtomFeed
;
25 use MediaWiki\Feed\FeedItem
;
26 use MediaWiki\Feed\FeedUtils
;
27 use MediaWiki\Feed\RSSFeed
;
28 use MediaWiki\Html\Html
;
29 use MediaWiki\HTMLForm\HTMLForm
;
30 use MediaWiki\MainConfigNames
;
31 use MediaWiki\MediaWikiServices
;
32 use MediaWiki\Pager\HistoryPager
;
33 use MediaWiki\Request\WebRequest
;
34 use MediaWiki\SpecialPage\SpecialPage
;
35 use MediaWiki\Utils\MWTimestamp
;
36 use Wikimedia\Rdbms\FakeResultWrapper
;
37 use Wikimedia\Rdbms\IResultWrapper
;
40 * This class handles printing the history page for an article. In order to
41 * be efficient, it uses timestamps rather than offsets for paging, to avoid
42 * costly LIMIT,offset queries.
44 * Construct it by passing in an Article, and call $h->history() to print the
49 class HistoryAction
extends FormlessAction
{
50 private const DIR_PREV
= 0;
51 private const DIR_NEXT
= 1;
53 /** @var array Array of message keys and strings */
56 public function getName() {
60 public function requiresWrite() {
64 public function requiresUnblock() {
68 protected function getPageTitle() {
69 return $this->msg( 'history-title' )->plaintextParams( $this->getTitle()->getPrefixedText() );
72 protected function getDescription() {
73 // Creation of a subtitle link pointing to [[Special:Log]]
74 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
75 $subtitle = $linkRenderer->makeKnownLink(
76 SpecialPage
::getTitleFor( 'Log' ),
77 $this->msg( 'viewpagelogs' )->text(),
79 [ 'page' => $this->getTitle()->getPrefixedText() ]
83 // Allow extensions to add more links
84 $this->getHookRunner()->onHistoryPageToolLinks( $this->getContext(), $linkRenderer, $links );
87 . $this->msg( 'word-separator' )->escaped()
88 . $this->msg( 'parentheses' )
89 ->rawParams( $this->getLanguage()->pipeList( $links ) )
92 return Html
::rawElement( 'div', [ 'class' => 'mw-history-subtitle' ], $subtitle );
96 * As we use the same small set of messages in various methods and that
97 * they are called often, we call them once and save them in $this->message
99 private function preCacheMessages() {
100 // Precache various messages
101 // @phan-suppress-next-line MediaWikiNoIssetIfDefined False positives when documented as nullable
102 if ( !isset( $this->message
) ) {
105 'cur', 'tooltip-cur', 'last', 'tooltip-last', 'pipe-separator',
106 'changeslist-nocomment', 'updatedmarker',
108 foreach ( $msgs as $msg ) {
109 $this->message
[$msg] = $this->msg( $msg )->escaped();
115 * @param WebRequest $request
118 private function getTimestampFromRequest( WebRequest
$request ) {
119 // Backwards compatibility checks for URIs with only year and/or month.
120 $year = $request->getInt( 'year' );
121 $month = $request->getInt( 'month' );
123 if ( $year !== 0 ||
$month !== 0 ) {
125 $year = MWTimestamp
::getLocalInstance()->format( 'Y' );
127 if ( $month < 1 ||
$month > 12 ) {
128 // month is invalid so treat as December (all months)
131 // month is valid so check day
132 $day = cal_days_in_month( CAL_GREGORIAN
, $month, $year );
134 // Left pad the months and days
135 $month = str_pad( (string)$month, 2, "0", STR_PAD_LEFT
);
136 $day = str_pad( (string)$day, 2, "0", STR_PAD_LEFT
);
139 $before = $request->getVal( 'date-range-to' );
141 $parts = explode( '-', $before );
143 // check date input is valid
144 if ( count( $parts ) === 3 ) {
149 return $year && $month && $day ?
$year . '-' . $month . '-' . $day : '';
153 * Print the history page for an article.
154 * @return string|null
156 public function onView() {
157 $out = $this->getOutput();
158 $request = $this->getRequest();
159 $config = $this->context
->getConfig();
160 $services = MediaWikiServices
::getInstance();
162 // Allow client-side HTTP caching of the history page.
163 // But, always ignore this cache if the (logged-in) user has this page on their watchlist
164 // and has one or more unseen revisions. Otherwise, we might be showing stale update markers.
165 // The Last-Modified for the history page does not change when user's markers are cleared,
166 // so going from "some unseen" to "all seen" would not clear the cache.
167 // But, when all of the revisions are marked as seen, then only way for new unseen revision
168 // markers to appear, is for the page to be edited, which updates page_touched/Last-Modified.
169 $watchlistManager = $services->getWatchlistManager();
170 $hasUnseenRevisionMarkers = $config->get( MainConfigNames
::ShowUpdatedMarker
) &&
171 $watchlistManager->getTitleNotificationTimestamp(
176 !$hasUnseenRevisionMarkers &&
177 $out->checkLastModified( $this->getWikiPage()->getTouched() )
179 return null; // Client cache fresh and headers sent, nothing more to do.
182 $this->preCacheMessages();
184 # Fill in the file cache if not set already
185 if ( HTMLFileCache
::useFileCache( $this->getContext() ) ) {
186 $cache = new HTMLFileCache( $this->getTitle(), 'history' );
187 if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
188 ob_start( [ &$cache, 'saveToFileCache' ] );
192 // Setup page variables.
193 $out->setFeedAppendQuery( 'action=history' );
194 $out->addModules( 'mediawiki.action.history' );
195 $out->addModuleStyles( [
196 'mediawiki.interface.helpers.styles',
197 'mediawiki.action.history.styles',
198 'mediawiki.special.changeslist',
201 // Handle atom/RSS feeds.
202 $feedType = $request->getRawVal( 'feed' );
203 if ( $feedType !== null ) {
204 $this->feed( $feedType );
209 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:History',
213 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
214 // Fail nicely if article doesn't exist.
215 if ( !$this->getWikiPage()->exists() ) {
216 $send404Code = $config->get( MainConfigNames
::Send404Code
);
217 if ( $send404Code ) {
218 $out->setStatusCode( 404 );
220 $out->addWikiMsg( 'nohistory' );
222 # show deletion/move log if there is an entry
223 LogEventsList
::showLogExtract(
225 [ 'delete', 'move', 'protect', 'merge' ],
229 'conds' => [ $dbr->expr( 'log_action', '!=', 'revision' ) ],
230 'showIfEmpty' => false,
231 'msgKey' => [ 'moveddeleted-notice' ]
238 $ts = $this->getTimestampFromRequest( $request );
239 $tagFilter = $request->getVal( 'tagfilter' );
242 * Option to show only revisions that have been (partially) hidden via RevisionDelete
244 if ( $request->getBool( 'deleted' ) ) {
245 $conds = [ $dbr->expr( 'rev_deleted', '!=', 0 ) ];
250 // Add the general form.
255 'default' => 'history',
260 'label' => $this->msg( 'date-range-to' )->text(),
261 'name' => 'date-range-to',
264 'label-message' => 'tag-filter',
265 'type' => 'tagfilter',
267 'name' => 'tagfilter',
268 'value' => $tagFilter,
272 'name' => 'tagInvert',
273 'label-message' => 'invert',
274 'hide-if' => [ '===', 'tagfilter', '' ],
277 if ( $this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
278 $fields['deleted'] = [
280 'label' => $this->msg( 'history-show-deleted' )->text(),
281 'default' => $request->getBool( 'deleted' ),
287 $htmlForm = HTMLForm
::factory( 'ooui', $fields, $this->getContext() );
290 ->setAction( wfScript() )
291 ->setCollapsibleOptions( true )
292 ->setId( 'mw-history-searchform' )
293 ->setSubmitTextMsg( 'historyaction-submit' )
294 ->setWrapperAttributes( [ 'id' => 'mw-history-search' ] )
295 ->setWrapperLegendMsg( 'history-fieldset-title' )
298 $out->addHTML( $htmlForm->getHTML( false ) );
300 $this->getHookRunner()->onPageHistoryBeforeList(
305 // Create and output the list.
306 $dateComponents = explode( '-', $ts );
307 if ( count( $dateComponents ) > 1 ) {
308 $y = (int)$dateComponents[0];
309 $m = (int)$dateComponents[1];
310 $d = (int)$dateComponents[2];
316 $pager = new HistoryPager(
322 $request->getCheck( 'tagInvert' ),
324 $services->getLinkBatchFactory(),
326 $services->getCommentFormatter(),
327 $services->getHookContainer(),
328 $services->getChangeTagsStore()
331 $pager->getNavigationBar() .
333 $pager->getNavigationBar()
335 $out->getMetadata()->setPreventClickjacking( $pager->getPreventClickjacking() );
341 * Fetch an array of revisions, specified by a given limit, offset and
342 * direction. This is now only used by the feeds. It was previously
343 * used by the main UI but that's now handled by the pager.
345 * @param int $limit The limit number of revisions to get
347 * @param int $direction Either self::DIR_PREV or self::DIR_NEXT
348 * @return IResultWrapper
350 private function fetchRevisions( $limit, $offset, $direction ) {
351 // Fail if article doesn't exist.
352 if ( !$this->getTitle()->exists() ) {
353 return new FakeResultWrapper( [] );
356 $dbr = MediaWikiServices
::getInstance()->getConnectionProvider()->getReplicaDatabase();
358 if ( $direction === self
::DIR_PREV
) {
359 [ $dirs, $oper ] = [ "ASC", ">=" ];
360 } else { /* $direction === self::DIR_NEXT */
361 [ $dirs, $oper ] = [ "DESC", "<=" ];
364 $queryBuilder = MediaWikiServices
::getInstance()->getRevisionStore()->newSelectQueryBuilder( $dbr )
366 ->where( [ 'rev_page' => $this->getWikiPage()->getId() ] )
367 ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
368 ->orderBy( [ 'rev_timestamp' ], $dirs )
371 $queryBuilder->andWhere( $dbr->expr( 'rev_timestamp', $oper, $dbr->timestamp( $offset ) ) );
374 return $queryBuilder->caller( __METHOD__
)->fetchResultSet();
378 * Output a subscription feed listing recent edits to this page.
380 * @param string $type Feed type
382 private function feed( $type ) {
383 if ( !FeedUtils
::checkFeedOutput( $type, $this->getOutput() ) ) {
386 $request = $this->getRequest();
388 $feedClasses = $this->context
->getConfig()->get( MainConfigNames
::FeedClasses
);
389 /** @var RSSFeed|AtomFeed $feed */
390 $feed = new $feedClasses[$type](
391 $this->getTitle()->getPrefixedText() . ' - ' .
392 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
393 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
394 $this->getTitle()->getFullURL( 'action=history' )
397 // Get a limit on number of feed entries. Provide a sensible default
398 // of 10 if none is defined (but limit to $wgFeedLimit max)
399 $limit = $request->getInt( 'limit', 10 );
402 $this->context
->getConfig()->get( MainConfigNames
::FeedLimit
)
405 $items = $this->fetchRevisions( $limit, 0, self
::DIR_NEXT
);
408 $formattedComments = MediaWikiServices
::getInstance()->getRowCommentFormatter()
409 ->formatRows( $items, 'rev_comment' );
411 // Generate feed elements enclosed between header and footer.
413 if ( $items->numRows() ) {
414 foreach ( $items as $i => $row ) {
415 $feed->outItem( $this->feedItem( $row, $formattedComments[$i] ) );
418 $feed->outItem( $this->feedEmpty() );
423 private function feedEmpty() {
425 $this->msg( 'nohistory' )->inContentLanguage()->text(),
426 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
427 $this->getTitle()->getFullURL(),
428 wfTimestamp( TS_MW
),
430 $this->getTitle()->getTalkPage()->getFullURL()
435 * Generate a MediaWiki\Feed\FeedItem object from a given revision table row
436 * Borrows Recent Changes' feed generation functions for formatting;
437 * includes a diff to the previous revision (if any).
439 * @param stdClass|array $row Database row
440 * @param string $formattedComment The comment in HTML format
443 private function feedItem( $row, $formattedComment ) {
444 $revisionStore = MediaWikiServices
::getInstance()->getRevisionStore();
445 $rev = $revisionStore->newRevisionFromRow( $row, 0, $this->getTitle() );
446 $prevRev = $revisionStore->getPreviousRevision( $rev );
447 $revComment = $rev->getComment() === null ?
null : $rev->getComment()->text
;
448 $text = FeedUtils
::formatDiffRow2(
450 $prevRev ?
$prevRev->getId() : false,
452 $rev->getTimestamp(),
455 $revUserText = $rev->getUser() ?
$rev->getUser()->getName() : '';
456 if ( $revComment == '' ) {
457 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
458 $title = $this->msg( 'history-feed-item-nocomment',
460 $contLang->timeanddate( $rev->getTimestamp() ),
461 $contLang->date( $rev->getTimestamp() ),
462 $contLang->time( $rev->getTimestamp() )
463 )->inContentLanguage()->text();
465 $title = $revUserText .
466 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
467 FeedItem
::stripComment( $revComment );
473 $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
474 $rev->getTimestamp(),
476 $this->getTitle()->getTalkPage()->getFullURL()