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