Merge "Title: Title::getSubpage should not lose the interwiki prefix"
[lhc/web/wiklou.git] / includes / actions / HistoryAction.php
1 <?php
2 /**
3 * Page history
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Actions
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\IResultWrapper;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27
28 /**
29 * This class handles printing the history page for an article. In order to
30 * be efficient, it uses timestamps rather than offsets for paging, to avoid
31 * costly LIMIT,offset queries.
32 *
33 * Construct it by passing in an Article, and call $h->history() to print the
34 * history.
35 *
36 * @ingroup Actions
37 */
38 class HistoryAction extends FormlessAction {
39 const DIR_PREV = 0;
40 const DIR_NEXT = 1;
41
42 /** @var array Array of message keys and strings */
43 public $message;
44
45 public function getName() {
46 return 'history';
47 }
48
49 public function requiresWrite() {
50 return false;
51 }
52
53 public function requiresUnblock() {
54 return false;
55 }
56
57 protected function getPageTitle() {
58 return $this->msg( 'history-title', $this->getTitle()->getPrefixedText() )->text();
59 }
60
61 protected function getDescription() {
62 // Creation of a subtitle link pointing to [[Special:Log]]
63 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
64 $subtitle = $linkRenderer->makeKnownLink(
65 SpecialPage::getTitleFor( 'Log' ),
66 $this->msg( 'viewpagelogs' )->text(),
67 [],
68 [ 'page' => $this->getTitle()->getPrefixedText() ]
69 );
70
71 $links = [];
72 // Allow extensions to add more links
73 Hooks::run( 'HistoryPageToolLinks', [ $this->getContext(), $linkRenderer, &$links ] );
74 if ( $links ) {
75 $subtitle .= ''
76 . $this->msg( 'word-separator' )->escaped()
77 . $this->msg( 'parentheses' )
78 ->rawParams( $this->getLanguage()->pipeList( $links ) )
79 ->escaped();
80 }
81 return Html::rawElement( 'div', [ 'class' => 'mw-history-subtitle' ], $subtitle );
82 }
83
84 /**
85 * @return WikiPage|Article|ImagePage|CategoryPage|Page The Article object we are working on.
86 */
87 public function getArticle() {
88 return $this->page;
89 }
90
91 /**
92 * As we use the same small set of messages in various methods and that
93 * they are called often, we call them once and save them in $this->message
94 */
95 private function preCacheMessages() {
96 // Precache various messages
97 if ( !isset( $this->message ) ) {
98 $msgs = [ 'cur', 'last', 'pipe-separator' ];
99 foreach ( $msgs as $msg ) {
100 $this->message[$msg] = $this->msg( $msg )->escaped();
101 }
102 }
103 }
104
105 /**
106 * @param WebRequest $request
107 * @return string
108 */
109 private function getTimestampFromRequest( WebRequest $request ) {
110 // Backwards compatibility checks for URIs with only year and/or month.
111 $year = $request->getInt( 'year' );
112 $month = $request->getInt( 'month' );
113 $day = null;
114 if ( $year !== 0 || $month !== 0 ) {
115 if ( $year === 0 ) {
116 $year = MWTimestamp::getLocalInstance()->format( 'Y' );
117 }
118 if ( $month < 1 || $month > 12 ) {
119 // month is invalid so treat as December (all months)
120 $month = 12;
121 }
122 // month is valid so check day
123 $day = cal_days_in_month( CAL_GREGORIAN, $month, $year );
124
125 // Left pad the months and days
126 $month = str_pad( $month, 2, "0", STR_PAD_LEFT );
127 $day = str_pad( $day, 2, "0", STR_PAD_LEFT );
128 }
129
130 $before = $request->getVal( 'date-range-to' );
131 if ( $before ) {
132 $parts = explode( '-', $before );
133 $year = $parts[0];
134 // check date input is valid
135 if ( count( $parts ) === 3 ) {
136 $month = $parts[1];
137 $day = $parts[2];
138 }
139 }
140 return $year && $month && $day ? $year . '-' . $month . '-' . $day : '';
141 }
142
143 /**
144 * Print the history page for an article.
145 * @return string|null
146 */
147 function onView() {
148 $out = $this->getOutput();
149 $request = $this->getRequest();
150
151 // Allow client-side HTTP caching of the history page.
152 // But, always ignore this cache if the (logged-in) user has this page on their watchlist
153 // and has one or more unseen revisions. Otherwise, we might be showing stale update markers.
154 // The Last-Modified for the history page does not change when user's markers are cleared,
155 // so going from "some unseen" to "all seen" would not clear the cache.
156 // But, when all of the revisions are marked as seen, then only way for new unseen revision
157 // markers to appear, is for the page to be edited, which updates page_touched/Last-Modified.
158 if (
159 !$this->hasUnseenRevisionMarkers() &&
160 $out->checkLastModified( $this->page->getTouched() )
161 ) {
162 return null; // Client cache fresh and headers sent, nothing more to do.
163 }
164
165 $this->preCacheMessages();
166 $config = $this->context->getConfig();
167
168 # Fill in the file cache if not set already
169 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
170 $cache = new HTMLFileCache( $this->getTitle(), 'history' );
171 if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
172 ob_start( [ &$cache, 'saveToFileCache' ] );
173 }
174 }
175
176 // Setup page variables.
177 $out->setFeedAppendQuery( 'action=history' );
178 $out->addModules( 'mediawiki.action.history' );
179 $out->addModuleStyles( [
180 'mediawiki.interface.helpers.styles',
181 'mediawiki.action.history.styles',
182 'mediawiki.special.changeslist',
183 ] );
184 if ( $config->get( 'UseMediaWikiUIEverywhere' ) ) {
185 $out = $this->getOutput();
186 $out->addModuleStyles( [
187 'mediawiki.ui.input',
188 'mediawiki.ui.checkbox',
189 ] );
190 }
191
192 // Handle atom/RSS feeds.
193 $feedType = $request->getRawVal( 'feed' );
194 if ( $feedType !== null ) {
195 $this->feed( $feedType );
196 return null;
197 }
198
199 $this->addHelpLink(
200 'https://meta.wikimedia.org/wiki/Special:MyLanguage/Help:Page_history',
201 true
202 );
203
204 // Fail nicely if article doesn't exist.
205 if ( !$this->page->exists() ) {
206 global $wgSend404Code;
207 if ( $wgSend404Code ) {
208 $out->setStatusCode( 404 );
209 }
210 $out->addWikiMsg( 'nohistory' );
211
212 $dbr = wfGetDB( DB_REPLICA );
213
214 # show deletion/move log if there is an entry
215 LogEventsList::showLogExtract(
216 $out,
217 [ 'delete', 'move', 'protect' ],
218 $this->getTitle(),
219 '',
220 [ 'lim' => 10,
221 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
222 'showIfEmpty' => false,
223 'msgKey' => [ 'moveddeleted-notice' ]
224 ]
225 );
226
227 return null;
228 }
229
230 $ts = $this->getTimestampFromRequest( $request );
231 $tagFilter = $request->getVal( 'tagfilter' );
232
233 /**
234 * Option to show only revisions that have been (partially) hidden via RevisionDelete
235 */
236 if ( $request->getBool( 'deleted' ) ) {
237 $conds = [ 'rev_deleted != 0' ];
238 } else {
239 $conds = [];
240 }
241
242 // Add the general form.
243 $fields = [
244 [
245 'name' => 'title',
246 'type' => 'hidden',
247 'default' => $this->getTitle()->getPrefixedDBkey(),
248 ],
249 [
250 'name' => 'action',
251 'type' => 'hidden',
252 'default' => 'history',
253 ],
254 [
255 'type' => 'date',
256 'default' => $ts,
257 'label' => $this->msg( 'date-range-to' )->text(),
258 'name' => 'date-range-to',
259 ],
260 [
261 'label-raw' => $this->msg( 'tag-filter' )->parse(),
262 'type' => 'tagfilter',
263 'id' => 'tagfilter',
264 'name' => 'tagfilter',
265 'value' => $tagFilter,
266 ]
267 ];
268 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
269 $fields[] = [
270 'type' => 'check',
271 'label' => $this->msg( 'history-show-deleted' )->text(),
272 'default' => $request->getBool( 'deleted' ),
273 'name' => 'deleted',
274 ];
275 }
276
277 $out->enableOOUI();
278 $htmlForm = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
279 $htmlForm
280 ->setMethod( 'get' )
281 ->setAction( wfScript() )
282 ->setCollapsibleOptions( true )
283 ->setId( 'mw-history-searchform' )
284 ->setSubmitText( $this->msg( 'historyaction-submit' )->text() )
285 ->setWrapperAttributes( [ 'id' => 'mw-history-search' ] )
286 ->setWrapperLegend( $this->msg( 'history-fieldset-title' )->text() );
287 $htmlForm->loadData();
288
289 $out->addHTML( $htmlForm->getHTML( false ) );
290
291 Hooks::run( 'PageHistoryBeforeList', [ &$this->page, $this->getContext() ] );
292
293 // Create and output the list.
294 $dateComponents = explode( '-', $ts );
295 if ( count( $dateComponents ) > 1 ) {
296 $y = $dateComponents[0];
297 $m = $dateComponents[1];
298 $d = $dateComponents[2];
299 } else {
300 $y = '';
301 $m = '';
302 $d = '';
303 }
304 $pager = new HistoryPager( $this, $y, $m, $tagFilter, $conds, $d );
305 $out->addHTML(
306 $pager->getNavigationBar() .
307 $pager->getBody() .
308 $pager->getNavigationBar()
309 );
310 $out->preventClickjacking( $pager->getPreventClickjacking() );
311
312 return null;
313 }
314
315 /**
316 * @return bool Page is watched by and has unseen revision for the user
317 */
318 private function hasUnseenRevisionMarkers() {
319 return (
320 $this->getContext()->getConfig()->get( 'ShowUpdatedMarker' ) &&
321 $this->getTitle()->getNotificationTimestamp( $this->getUser() )
322 );
323 }
324
325 /**
326 * Fetch an array of revisions, specified by a given limit, offset and
327 * direction. This is now only used by the feeds. It was previously
328 * used by the main UI but that's now handled by the pager.
329 *
330 * @param int $limit The limit number of revisions to get
331 * @param int $offset
332 * @param int $direction Either self::DIR_PREV or self::DIR_NEXT
333 * @return IResultWrapper
334 */
335 function fetchRevisions( $limit, $offset, $direction ) {
336 // Fail if article doesn't exist.
337 if ( !$this->getTitle()->exists() ) {
338 return new FakeResultWrapper( [] );
339 }
340
341 $dbr = wfGetDB( DB_REPLICA );
342
343 if ( $direction === self::DIR_PREV ) {
344 list( $dirs, $oper ) = [ "ASC", ">=" ];
345 } else { /* $direction === self::DIR_NEXT */
346 list( $dirs, $oper ) = [ "DESC", "<=" ];
347 }
348
349 if ( $offset ) {
350 $offsets = [ "rev_timestamp $oper " . $dbr->addQuotes( $dbr->timestamp( $offset ) ) ];
351 } else {
352 $offsets = [];
353 }
354
355 $page_id = $this->page->getId();
356
357 $revQuery = Revision::getQueryInfo();
358 return $dbr->select(
359 $revQuery['tables'],
360 $revQuery['fields'],
361 array_merge( [ 'rev_page' => $page_id ], $offsets ),
362 __METHOD__,
363 [
364 'ORDER BY' => "rev_timestamp $dirs",
365 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
366 'LIMIT' => $limit
367 ],
368 $revQuery['joins']
369 );
370 }
371
372 /**
373 * Output a subscription feed listing recent edits to this page.
374 *
375 * @param string $type Feed type
376 */
377 function feed( $type ) {
378 if ( !FeedUtils::checkFeedOutput( $type ) ) {
379 return;
380 }
381 $request = $this->getRequest();
382
383 $feedClasses = $this->context->getConfig()->get( 'FeedClasses' );
384 /** @var RSSFeed|AtomFeed $feed */
385 $feed = new $feedClasses[$type](
386 $this->getTitle()->getPrefixedText() . ' - ' .
387 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
388 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
389 $this->getTitle()->getFullURL( 'action=history' )
390 );
391
392 // Get a limit on number of feed entries. Provide a sane default
393 // of 10 if none is defined (but limit to $wgFeedLimit max)
394 $limit = $request->getInt( 'limit', 10 );
395 $limit = min(
396 max( $limit, 1 ),
397 $this->context->getConfig()->get( 'FeedLimit' )
398 );
399
400 $items = $this->fetchRevisions( $limit, 0, self::DIR_NEXT );
401
402 // Generate feed elements enclosed between header and footer.
403 $feed->outHeader();
404 if ( $items->numRows() ) {
405 foreach ( $items as $row ) {
406 $feed->outItem( $this->feedItem( $row ) );
407 }
408 } else {
409 $feed->outItem( $this->feedEmpty() );
410 }
411 $feed->outFooter();
412 }
413
414 function feedEmpty() {
415 return new FeedItem(
416 $this->msg( 'nohistory' )->inContentLanguage()->text(),
417 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
418 $this->getTitle()->getFullURL(),
419 wfTimestamp( TS_MW ),
420 '',
421 $this->getTitle()->getTalkPage()->getFullURL()
422 );
423 }
424
425 /**
426 * Generate a FeedItem object from a given revision table row
427 * Borrows Recent Changes' feed generation functions for formatting;
428 * includes a diff to the previous revision (if any).
429 *
430 * @param stdClass|array $row Database row
431 * @return FeedItem
432 */
433 function feedItem( $row ) {
434 $rev = new Revision( $row, 0, $this->getTitle() );
435
436 $text = FeedUtils::formatDiffRow(
437 $this->getTitle(),
438 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
439 $rev->getId(),
440 $rev->getTimestamp(),
441 $rev->getComment()
442 );
443 if ( $rev->getComment() == '' ) {
444 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
445 $title = $this->msg( 'history-feed-item-nocomment',
446 $rev->getUserText(),
447 $contLang->timeanddate( $rev->getTimestamp() ),
448 $contLang->date( $rev->getTimestamp() ),
449 $contLang->time( $rev->getTimestamp() )
450 )->inContentLanguage()->text();
451 } else {
452 $title = $rev->getUserText() .
453 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
454 FeedItem::stripComment( $rev->getComment() );
455 }
456
457 return new FeedItem(
458 $title,
459 $text,
460 $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
461 $rev->getTimestamp(),
462 $rev->getUserText(),
463 $this->getTitle()->getTalkPage()->getFullURL()
464 );
465 }
466 }