Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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 /**
152 * Allow client caching.
153 */
154 if ( $out->checkLastModified( $this->page->getTouched() ) ) {
155 return null; // Client cache fresh and headers sent, nothing more to do.
156 }
157
158 $this->preCacheMessages();
159 $config = $this->context->getConfig();
160
161 # Fill in the file cache if not set already
162 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
163 $cache = new HTMLFileCache( $this->getTitle(), 'history' );
164 if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
165 ob_start( [ &$cache, 'saveToFileCache' ] );
166 }
167 }
168
169 // Setup page variables.
170 $out->setFeedAppendQuery( 'action=history' );
171 $out->addModules( 'mediawiki.action.history' );
172 $out->addModuleStyles( [
173 'mediawiki.interface.helpers.styles',
174 'mediawiki.action.history.styles',
175 'mediawiki.special.changeslist',
176 ] );
177 if ( $config->get( 'UseMediaWikiUIEverywhere' ) ) {
178 $out = $this->getOutput();
179 $out->addModuleStyles( [
180 'mediawiki.ui.input',
181 'mediawiki.ui.checkbox',
182 ] );
183 }
184
185 // Handle atom/RSS feeds.
186 $feedType = $request->getRawVal( 'feed' );
187 if ( $feedType !== null ) {
188 $this->feed( $feedType );
189 return null;
190 }
191
192 $this->addHelpLink(
193 'https://meta.wikimedia.org/wiki/Special:MyLanguage/Help:Page_history',
194 true
195 );
196
197 // Fail nicely if article doesn't exist.
198 if ( !$this->page->exists() ) {
199 global $wgSend404Code;
200 if ( $wgSend404Code ) {
201 $out->setStatusCode( 404 );
202 }
203 $out->addWikiMsg( 'nohistory' );
204
205 $dbr = wfGetDB( DB_REPLICA );
206
207 # show deletion/move log if there is an entry
208 LogEventsList::showLogExtract(
209 $out,
210 [ 'delete', 'move', 'protect' ],
211 $this->getTitle(),
212 '',
213 [ 'lim' => 10,
214 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
215 'showIfEmpty' => false,
216 'msgKey' => [ 'moveddeleted-notice' ]
217 ]
218 );
219
220 return null;
221 }
222
223 $ts = $this->getTimestampFromRequest( $request );
224 $tagFilter = $request->getVal( 'tagfilter' );
225
226 /**
227 * Option to show only revisions that have been (partially) hidden via RevisionDelete
228 */
229 if ( $request->getBool( 'deleted' ) ) {
230 $conds = [ 'rev_deleted != 0' ];
231 } else {
232 $conds = [];
233 }
234
235 // Add the general form.
236 $fields = [
237 [
238 'name' => 'title',
239 'type' => 'hidden',
240 'default' => $this->getTitle()->getPrefixedDBkey(),
241 ],
242 [
243 'name' => 'action',
244 'type' => 'hidden',
245 'default' => 'history',
246 ],
247 [
248 'type' => 'date',
249 'default' => $ts,
250 'label' => $this->msg( 'date-range-to' )->text(),
251 'name' => 'date-range-to',
252 ],
253 [
254 'label-raw' => $this->msg( 'tag-filter' )->parse(),
255 'type' => 'tagfilter',
256 'id' => 'tagfilter',
257 'name' => 'tagfilter',
258 'value' => $tagFilter,
259 ]
260 ];
261 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
262 $fields[] = [
263 'type' => 'check',
264 'label' => $this->msg( 'history-show-deleted' )->text(),
265 'default' => $request->getBool( 'deleted' ),
266 'name' => 'deleted',
267 ];
268 }
269
270 $out->enableOOUI();
271 $htmlForm = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
272 $htmlForm
273 ->setMethod( 'get' )
274 ->setAction( wfScript() )
275 ->setCollapsibleOptions( true )
276 ->setId( 'mw-history-searchform' )
277 ->setSubmitText( $this->msg( 'historyaction-submit' )->text() )
278 ->setWrapperAttributes( [ 'id' => 'mw-history-search' ] )
279 ->setWrapperLegend( $this->msg( 'history-fieldset-title' )->text() );
280 $htmlForm->loadData();
281
282 $out->addHTML( $htmlForm->getHTML( false ) );
283
284 Hooks::run( 'PageHistoryBeforeList', [ &$this->page, $this->getContext() ] );
285
286 // Create and output the list.
287 $dateComponents = explode( '-', $ts );
288 if ( count( $dateComponents ) > 1 ) {
289 $y = $dateComponents[0];
290 $m = $dateComponents[1];
291 $d = $dateComponents[2];
292 } else {
293 $y = '';
294 $m = '';
295 $d = '';
296 }
297 $pager = new HistoryPager( $this, $y, $m, $tagFilter, $conds, $d );
298 $out->addHTML(
299 $pager->getNavigationBar() .
300 $pager->getBody() .
301 $pager->getNavigationBar()
302 );
303 $out->preventClickjacking( $pager->getPreventClickjacking() );
304
305 return null;
306 }
307
308 /**
309 * Fetch an array of revisions, specified by a given limit, offset and
310 * direction. This is now only used by the feeds. It was previously
311 * used by the main UI but that's now handled by the pager.
312 *
313 * @param int $limit The limit number of revisions to get
314 * @param int $offset
315 * @param int $direction Either self::DIR_PREV or self::DIR_NEXT
316 * @return IResultWrapper
317 */
318 function fetchRevisions( $limit, $offset, $direction ) {
319 // Fail if article doesn't exist.
320 if ( !$this->getTitle()->exists() ) {
321 return new FakeResultWrapper( [] );
322 }
323
324 $dbr = wfGetDB( DB_REPLICA );
325
326 if ( $direction === self::DIR_PREV ) {
327 list( $dirs, $oper ) = [ "ASC", ">=" ];
328 } else { /* $direction === self::DIR_NEXT */
329 list( $dirs, $oper ) = [ "DESC", "<=" ];
330 }
331
332 if ( $offset ) {
333 $offsets = [ "rev_timestamp $oper " . $dbr->addQuotes( $dbr->timestamp( $offset ) ) ];
334 } else {
335 $offsets = [];
336 }
337
338 $page_id = $this->page->getId();
339
340 $revQuery = Revision::getQueryInfo();
341 return $dbr->select(
342 $revQuery['tables'],
343 $revQuery['fields'],
344 array_merge( [ 'rev_page' => $page_id ], $offsets ),
345 __METHOD__,
346 [
347 'ORDER BY' => "rev_timestamp $dirs",
348 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
349 'LIMIT' => $limit
350 ],
351 $revQuery['joins']
352 );
353 }
354
355 /**
356 * Output a subscription feed listing recent edits to this page.
357 *
358 * @param string $type Feed type
359 */
360 function feed( $type ) {
361 if ( !FeedUtils::checkFeedOutput( $type ) ) {
362 return;
363 }
364 $request = $this->getRequest();
365
366 $feedClasses = $this->context->getConfig()->get( 'FeedClasses' );
367 /** @var RSSFeed|AtomFeed $feed */
368 $feed = new $feedClasses[$type](
369 $this->getTitle()->getPrefixedText() . ' - ' .
370 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
371 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
372 $this->getTitle()->getFullURL( 'action=history' )
373 );
374
375 // Get a limit on number of feed entries. Provide a sane default
376 // of 10 if none is defined (but limit to $wgFeedLimit max)
377 $limit = $request->getInt( 'limit', 10 );
378 $limit = min(
379 max( $limit, 1 ),
380 $this->context->getConfig()->get( 'FeedLimit' )
381 );
382
383 $items = $this->fetchRevisions( $limit, 0, self::DIR_NEXT );
384
385 // Generate feed elements enclosed between header and footer.
386 $feed->outHeader();
387 if ( $items->numRows() ) {
388 foreach ( $items as $row ) {
389 $feed->outItem( $this->feedItem( $row ) );
390 }
391 } else {
392 $feed->outItem( $this->feedEmpty() );
393 }
394 $feed->outFooter();
395 }
396
397 function feedEmpty() {
398 return new FeedItem(
399 $this->msg( 'nohistory' )->inContentLanguage()->text(),
400 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
401 $this->getTitle()->getFullURL(),
402 wfTimestamp( TS_MW ),
403 '',
404 $this->getTitle()->getTalkPage()->getFullURL()
405 );
406 }
407
408 /**
409 * Generate a FeedItem object from a given revision table row
410 * Borrows Recent Changes' feed generation functions for formatting;
411 * includes a diff to the previous revision (if any).
412 *
413 * @param stdClass|array $row Database row
414 * @return FeedItem
415 */
416 function feedItem( $row ) {
417 $rev = new Revision( $row, 0, $this->getTitle() );
418
419 $text = FeedUtils::formatDiffRow(
420 $this->getTitle(),
421 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
422 $rev->getId(),
423 $rev->getTimestamp(),
424 $rev->getComment()
425 );
426 if ( $rev->getComment() == '' ) {
427 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
428 $title = $this->msg( 'history-feed-item-nocomment',
429 $rev->getUserText(),
430 $contLang->timeanddate( $rev->getTimestamp() ),
431 $contLang->date( $rev->getTimestamp() ),
432 $contLang->time( $rev->getTimestamp() )
433 )->inContentLanguage()->text();
434 } else {
435 $title = $rev->getUserText() .
436 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
437 FeedItem::stripComment( $rev->getComment() );
438 }
439
440 return new FeedItem(
441 $title,
442 $text,
443 $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
444 $rev->getTimestamp(),
445 $rev->getUserText(),
446 $this->getTitle()->getTalkPage()->getFullURL()
447 );
448 }
449 }