Merge "ChangesList: HTML escape the timestamp"
[lhc/web/wiklou.git] / includes / actions / HistoryAction.php
1 <?php
2 /**
3 * Page history
4 *
5 * Split off from Article.php and Skin.php, 2003-12-22
6 *
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.
11 *
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.
16 *
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
21 *
22 * @file
23 * @ingroup Actions
24 */
25
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\ResultWrapper;
28 use Wikimedia\Rdbms\FakeResultWrapper;
29
30 /**
31 * This class handles printing the history page for an article. In order to
32 * be efficient, it uses timestamps rather than offsets for paging, to avoid
33 * costly LIMIT,offset queries.
34 *
35 * Construct it by passing in an Article, and call $h->history() to print the
36 * history.
37 *
38 * @ingroup Actions
39 */
40 class HistoryAction extends FormlessAction {
41 const DIR_PREV = 0;
42 const DIR_NEXT = 1;
43
44 /** @var array Array of message keys and strings */
45 public $message;
46
47 public function getName() {
48 return 'history';
49 }
50
51 public function requiresWrite() {
52 return false;
53 }
54
55 public function requiresUnblock() {
56 return false;
57 }
58
59 protected function getPageTitle() {
60 return $this->msg( 'history-title', $this->getTitle()->getPrefixedText() )->text();
61 }
62
63 protected function getDescription() {
64 // Creation of a subtitle link pointing to [[Special:Log]]
65 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
66 $subtitle = $linkRenderer->makeKnownLink(
67 SpecialPage::getTitleFor( 'Log' ),
68 $this->msg( 'viewpagelogs' )->text(),
69 [],
70 [ 'page' => $this->getTitle()->getPrefixedText() ]
71 );
72
73 $links = [];
74 // Allow extensions to add more links
75 Hooks::run( 'HistoryPageToolLinks', [ $this->getContext(), $linkRenderer, &$links ] );
76 if ( $links ) {
77 $subtitle .= ''
78 . $this->msg( 'word-separator' )->escaped()
79 . $this->msg( 'parentheses' )
80 ->rawParams( $this->getLanguage()->pipeList( $links ) )
81 ->escaped();
82 }
83 return $subtitle;
84 }
85
86 /**
87 * @return WikiPage|Article|ImagePage|CategoryPage|Page The Article object we are working on.
88 */
89 public function getArticle() {
90 return $this->page;
91 }
92
93 /**
94 * As we use the same small set of messages in various methods and that
95 * they are called often, we call them once and save them in $this->message
96 */
97 private function preCacheMessages() {
98 // Precache various messages
99 if ( !isset( $this->message ) ) {
100 $msgs = [ 'cur', 'last', 'pipe-separator' ];
101 foreach ( $msgs as $msg ) {
102 $this->message[$msg] = $this->msg( $msg )->escaped();
103 }
104 }
105 }
106
107 /**
108 * Print the history page for an article.
109 */
110 function onView() {
111 $out = $this->getOutput();
112 $request = $this->getRequest();
113
114 /**
115 * Allow client caching.
116 */
117 if ( $out->checkLastModified( $this->page->getTouched() ) ) {
118 return; // Client cache fresh and headers sent, nothing more to do.
119 }
120
121 $this->preCacheMessages();
122 $config = $this->context->getConfig();
123
124 # Fill in the file cache if not set already
125 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
126 $cache = new HTMLFileCache( $this->getTitle(), 'history' );
127 if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
128 ob_start( [ &$cache, 'saveToFileCache' ] );
129 }
130 }
131
132 // Setup page variables.
133 $out->setFeedAppendQuery( 'action=history' );
134 $out->addModules( 'mediawiki.action.history' );
135 $out->addModuleStyles( [
136 'mediawiki.action.history.styles',
137 'mediawiki.special.changeslist',
138 ] );
139 if ( $config->get( 'UseMediaWikiUIEverywhere' ) ) {
140 $out = $this->getOutput();
141 $out->addModuleStyles( [
142 'mediawiki.ui.input',
143 'mediawiki.ui.checkbox',
144 ] );
145 }
146
147 // Handle atom/RSS feeds.
148 $feedType = $request->getVal( 'feed' );
149 if ( $feedType ) {
150 $this->feed( $feedType );
151
152 return;
153 }
154
155 $this->addHelpLink( '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Page_history', true );
156
157 // Fail nicely if article doesn't exist.
158 if ( !$this->page->exists() ) {
159 global $wgSend404Code;
160 if ( $wgSend404Code ) {
161 $out->setStatusCode( 404 );
162 }
163 $out->addWikiMsg( 'nohistory' );
164
165 $dbr = wfGetDB( DB_REPLICA );
166
167 # show deletion/move log if there is an entry
168 LogEventsList::showLogExtract(
169 $out,
170 [ 'delete', 'move', 'protect' ],
171 $this->getTitle(),
172 '',
173 [ 'lim' => 10,
174 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
175 'showIfEmpty' => false,
176 'msgKey' => [ 'moveddeleted-notice' ]
177 ]
178 );
179
180 return;
181 }
182
183 /**
184 * Add date selector to quickly get to a certain time
185 */
186 $year = $request->getInt( 'year' );
187 $month = $request->getInt( 'month' );
188 $tagFilter = $request->getVal( 'tagfilter' );
189 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter, false, $this->getContext() );
190
191 /**
192 * Option to show only revisions that have been (partially) hidden via RevisionDelete
193 */
194 if ( $request->getBool( 'deleted' ) ) {
195 $conds = [ 'rev_deleted != 0' ];
196 } else {
197 $conds = [];
198 }
199 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
200 $checkDeleted = Xml::checkLabel( $this->msg( 'history-show-deleted' )->text(),
201 'deleted', 'mw-show-deleted-only', $request->getBool( 'deleted' ) ) . "\n";
202 } else {
203 $checkDeleted = '';
204 }
205
206 // Add the general form
207 $action = htmlspecialchars( wfScript() );
208 $content = Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) . "\n";
209 $content .= Html::hidden( 'action', 'history' ) . "\n";
210 $content .= Xml::dateMenu(
211 ( $year == null ? MWTimestamp::getLocalInstance()->format( 'Y' ) : $year ),
212 $month
213 ) . "\u{00A0}";
214 $content .= $tagSelector ? ( implode( "\u{00A0}", $tagSelector ) . "\u{00A0}" ) : '';
215 $content .= $checkDeleted . Html::submitButton(
216 $this->msg( 'historyaction-submit' )->text(),
217 [],
218 [ 'mw-ui-progressive' ]
219 );
220 $out->addHTML(
221 "<form action=\"$action\" method=\"get\" id=\"mw-history-searchform\">" .
222 Xml::fieldset(
223 $this->msg( 'history-fieldset-title' )->text(),
224 $content,
225 [ 'id' => 'mw-history-search' ]
226 ) .
227 '</form>'
228 );
229
230 Hooks::run( 'PageHistoryBeforeList', [ &$this->page, $this->getContext() ] );
231
232 // Create and output the list.
233 $pager = new HistoryPager( $this, $year, $month, $tagFilter, $conds );
234 $out->addHTML(
235 $pager->getNavigationBar() .
236 $pager->getBody() .
237 $pager->getNavigationBar()
238 );
239 $out->preventClickjacking( $pager->getPreventClickjacking() );
240 }
241
242 /**
243 * Fetch an array of revisions, specified by a given limit, offset and
244 * direction. This is now only used by the feeds. It was previously
245 * used by the main UI but that's now handled by the pager.
246 *
247 * @param int $limit The limit number of revisions to get
248 * @param int $offset
249 * @param int $direction Either self::DIR_PREV or self::DIR_NEXT
250 * @return ResultWrapper
251 */
252 function fetchRevisions( $limit, $offset, $direction ) {
253 // Fail if article doesn't exist.
254 if ( !$this->getTitle()->exists() ) {
255 return new FakeResultWrapper( [] );
256 }
257
258 $dbr = wfGetDB( DB_REPLICA );
259
260 if ( $direction === self::DIR_PREV ) {
261 list( $dirs, $oper ) = [ "ASC", ">=" ];
262 } else { /* $direction === self::DIR_NEXT */
263 list( $dirs, $oper ) = [ "DESC", "<=" ];
264 }
265
266 if ( $offset ) {
267 $offsets = [ "rev_timestamp $oper " . $dbr->addQuotes( $dbr->timestamp( $offset ) ) ];
268 } else {
269 $offsets = [];
270 }
271
272 $page_id = $this->page->getId();
273
274 $revQuery = Revision::getQueryInfo();
275 return $dbr->select(
276 $revQuery['tables'],
277 $revQuery['fields'],
278 array_merge( [ 'rev_page' => $page_id ], $offsets ),
279 __METHOD__,
280 [
281 'ORDER BY' => "rev_timestamp $dirs",
282 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
283 'LIMIT' => $limit
284 ],
285 $revQuery['joins']
286 );
287 }
288
289 /**
290 * Output a subscription feed listing recent edits to this page.
291 *
292 * @param string $type Feed type
293 */
294 function feed( $type ) {
295 if ( !FeedUtils::checkFeedOutput( $type ) ) {
296 return;
297 }
298 $request = $this->getRequest();
299
300 $feedClasses = $this->context->getConfig()->get( 'FeedClasses' );
301 /** @var RSSFeed|AtomFeed $feed */
302 $feed = new $feedClasses[$type](
303 $this->getTitle()->getPrefixedText() . ' - ' .
304 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
305 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
306 $this->getTitle()->getFullURL( 'action=history' )
307 );
308
309 // Get a limit on number of feed entries. Provide a sane default
310 // of 10 if none is defined (but limit to $wgFeedLimit max)
311 $limit = $request->getInt( 'limit', 10 );
312 $limit = min(
313 max( $limit, 1 ),
314 $this->context->getConfig()->get( 'FeedLimit' )
315 );
316
317 $items = $this->fetchRevisions( $limit, 0, self::DIR_NEXT );
318
319 // Generate feed elements enclosed between header and footer.
320 $feed->outHeader();
321 if ( $items->numRows() ) {
322 foreach ( $items as $row ) {
323 $feed->outItem( $this->feedItem( $row ) );
324 }
325 } else {
326 $feed->outItem( $this->feedEmpty() );
327 }
328 $feed->outFooter();
329 }
330
331 function feedEmpty() {
332 return new FeedItem(
333 $this->msg( 'nohistory' )->inContentLanguage()->text(),
334 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
335 $this->getTitle()->getFullURL(),
336 wfTimestamp( TS_MW ),
337 '',
338 $this->getTitle()->getTalkPage()->getFullURL()
339 );
340 }
341
342 /**
343 * Generate a FeedItem object from a given revision table row
344 * Borrows Recent Changes' feed generation functions for formatting;
345 * includes a diff to the previous revision (if any).
346 *
347 * @param stdClass|array $row Database row
348 * @return FeedItem
349 */
350 function feedItem( $row ) {
351 $rev = new Revision( $row, 0, $this->getTitle() );
352
353 $text = FeedUtils::formatDiffRow(
354 $this->getTitle(),
355 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
356 $rev->getId(),
357 $rev->getTimestamp(),
358 $rev->getComment()
359 );
360 if ( $rev->getComment() == '' ) {
361 global $wgContLang;
362 $title = $this->msg( 'history-feed-item-nocomment',
363 $rev->getUserText(),
364 $wgContLang->timeanddate( $rev->getTimestamp() ),
365 $wgContLang->date( $rev->getTimestamp() ),
366 $wgContLang->time( $rev->getTimestamp() ) )->inContentLanguage()->text();
367 } else {
368 $title = $rev->getUserText() .
369 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
370 FeedItem::stripComment( $rev->getComment() );
371 }
372
373 return new FeedItem(
374 $title,
375 $text,
376 $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
377 $rev->getTimestamp(),
378 $rev->getUserText(),
379 $this->getTitle()->getTalkPage()->getFullURL()
380 );
381 }
382 }
383
384 /**
385 * @ingroup Pager
386 * @ingroup Actions
387 */
388 class HistoryPager extends ReverseChronologicalPager {
389 /**
390 * @var bool|stdClass
391 */
392 public $lastRow = false;
393
394 public $counter, $historyPage, $buttons, $conds;
395
396 protected $oldIdChecked;
397
398 protected $preventClickjacking = false;
399 /**
400 * @var array
401 */
402 protected $parentLens;
403
404 /** @var bool Whether to show the tag editing UI */
405 protected $showTagEditUI;
406
407 /** @var string */
408 private $tagFilter;
409
410 /**
411 * @param HistoryAction $historyPage
412 * @param string $year
413 * @param string $month
414 * @param string $tagFilter
415 * @param array $conds
416 */
417 function __construct( $historyPage, $year = '', $month = '', $tagFilter = '', $conds = [] ) {
418 parent::__construct( $historyPage->getContext() );
419 $this->historyPage = $historyPage;
420 $this->tagFilter = $tagFilter;
421 $this->getDateCond( $year, $month );
422 $this->conds = $conds;
423 $this->showTagEditUI = ChangeTags::showTagEditingUI( $this->getUser() );
424 }
425
426 // For hook compatibility...
427 function getArticle() {
428 return $this->historyPage->getArticle();
429 }
430
431 function getSqlComment() {
432 if ( $this->conds ) {
433 return 'history page filtered'; // potentially slow, see CR r58153
434 } else {
435 return 'history page unfiltered';
436 }
437 }
438
439 function getQueryInfo() {
440 $revQuery = Revision::getQueryInfo( [ 'user' ] );
441 $queryInfo = [
442 'tables' => $revQuery['tables'],
443 'fields' => $revQuery['fields'],
444 'conds' => array_merge(
445 [ 'rev_page' => $this->getWikiPage()->getId() ],
446 $this->conds ),
447 'options' => [ 'USE INDEX' => [ 'revision' => 'page_timestamp' ] ],
448 'join_conds' => $revQuery['joins'],
449 ];
450 ChangeTags::modifyDisplayQuery(
451 $queryInfo['tables'],
452 $queryInfo['fields'],
453 $queryInfo['conds'],
454 $queryInfo['join_conds'],
455 $queryInfo['options'],
456 $this->tagFilter
457 );
458
459 // Avoid PHP 7.1 warning of passing $this by reference
460 $historyPager = $this;
461 Hooks::run( 'PageHistoryPager::getQueryInfo', [ &$historyPager, &$queryInfo ] );
462
463 return $queryInfo;
464 }
465
466 function getIndexField() {
467 return 'rev_timestamp';
468 }
469
470 /**
471 * @param stdClass $row
472 * @return string
473 */
474 function formatRow( $row ) {
475 if ( $this->lastRow ) {
476 $latest = ( $this->counter == 1 && $this->mIsFirst );
477 $firstInList = $this->counter == 1;
478 $this->counter++;
479
480 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
481 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
482 : false;
483
484 $s = $this->historyLine(
485 $this->lastRow, $row, $notifTimestamp, $latest, $firstInList );
486 } else {
487 $s = '';
488 }
489 $this->lastRow = $row;
490
491 return $s;
492 }
493
494 function doBatchLookups() {
495 if ( !Hooks::run( 'PageHistoryPager::doBatchLookups', [ $this, $this->mResult ] ) ) {
496 return;
497 }
498
499 # Do a link batch query
500 $this->mResult->seek( 0 );
501 $batch = new LinkBatch();
502 $revIds = [];
503 foreach ( $this->mResult as $row ) {
504 if ( $row->rev_parent_id ) {
505 $revIds[] = $row->rev_parent_id;
506 }
507 if ( !is_null( $row->user_name ) ) {
508 $batch->add( NS_USER, $row->user_name );
509 $batch->add( NS_USER_TALK, $row->user_name );
510 } else { # for anons or usernames of imported revisions
511 $batch->add( NS_USER, $row->rev_user_text );
512 $batch->add( NS_USER_TALK, $row->rev_user_text );
513 }
514 }
515 $this->parentLens = Revision::getParentLengths( $this->mDb, $revIds );
516 $batch->execute();
517 $this->mResult->seek( 0 );
518 }
519
520 /**
521 * Creates begin of history list with a submit button
522 *
523 * @return string HTML output
524 */
525 function getStartBody() {
526 $this->lastRow = false;
527 $this->counter = 1;
528 $this->oldIdChecked = 0;
529
530 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
531 $s = Html::openElement( 'form', [ 'action' => wfScript(),
532 'id' => 'mw-history-compare' ] ) . "\n";
533 $s .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) . "\n";
534 $s .= Html::hidden( 'action', 'historysubmit' ) . "\n";
535 $s .= Html::hidden( 'type', 'revision' ) . "\n";
536
537 // Button container stored in $this->buttons for re-use in getEndBody()
538 $this->buttons = '<div>';
539 $className = 'historysubmit mw-history-compareselectedversions-button';
540 $attrs = [ 'class' => $className ]
541 + Linker::tooltipAndAccesskeyAttribs( 'compareselectedversions' );
542 $this->buttons .= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
543 $attrs
544 ) . "\n";
545
546 $user = $this->getUser();
547 $actionButtons = '';
548 if ( $user->isAllowed( 'deleterevision' ) ) {
549 $actionButtons .= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
550 }
551 if ( $this->showTagEditUI ) {
552 $actionButtons .= $this->getRevisionButton( 'editchangetags', 'history-edit-tags' );
553 }
554 if ( $actionButtons ) {
555 $this->buttons .= Xml::tags( 'div', [ 'class' =>
556 'mw-history-revisionactions' ], $actionButtons );
557 }
558
559 if ( $user->isAllowed( 'deleterevision' ) || $this->showTagEditUI ) {
560 $this->buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
561 }
562
563 $this->buttons .= '</div>';
564
565 $s .= $this->buttons;
566 $s .= '<ul id="pagehistory">' . "\n";
567
568 return $s;
569 }
570
571 private function getRevisionButton( $name, $msg ) {
572 $this->preventClickjacking();
573 # Note bug #20966, <button> is non-standard in IE<8
574 $element = Html::element(
575 'button',
576 [
577 'type' => 'submit',
578 'name' => $name,
579 'value' => '1',
580 'class' => "historysubmit mw-history-$name-button",
581 ],
582 $this->msg( $msg )->text()
583 ) . "\n";
584 return $element;
585 }
586
587 function getEndBody() {
588 if ( $this->lastRow ) {
589 $latest = $this->counter == 1 && $this->mIsFirst;
590 $firstInList = $this->counter == 1;
591 if ( $this->mIsBackwards ) {
592 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
593 if ( $this->mOffset == '' ) {
594 $next = null;
595 } else {
596 $next = 'unknown';
597 }
598 } else {
599 # The next row is the past-the-end row
600 $next = $this->mPastTheEndRow;
601 }
602 $this->counter++;
603
604 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
605 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
606 : false;
607
608 $s = $this->historyLine(
609 $this->lastRow, $next, $notifTimestamp, $latest, $firstInList );
610 } else {
611 $s = '';
612 }
613 $s .= "</ul>\n";
614 # Add second buttons only if there is more than one rev
615 if ( $this->getNumRows() > 2 ) {
616 $s .= $this->buttons;
617 }
618 $s .= '</form>';
619
620 return $s;
621 }
622
623 /**
624 * Creates a submit button
625 *
626 * @param string $message Text of the submit button, will be escaped
627 * @param array $attributes
628 * @return string HTML output for the submit button
629 */
630 function submitButton( $message, $attributes = [] ) {
631 # Disable submit button if history has 1 revision only
632 if ( $this->getNumRows() > 1 ) {
633 return Html::submitButton( $message, $attributes );
634 } else {
635 return '';
636 }
637 }
638
639 /**
640 * Returns a row from the history printout.
641 *
642 * @todo document some more, and maybe clean up the code (some params redundant?)
643 *
644 * @param stdClass $row The database row corresponding to the previous line.
645 * @param mixed $next The database row corresponding to the next line
646 * (chronologically previous)
647 * @param bool|string $notificationtimestamp
648 * @param bool $latest Whether this row corresponds to the page's latest revision.
649 * @param bool $firstInList Whether this row corresponds to the first
650 * displayed on this history page.
651 * @return string HTML output for the row
652 */
653 function historyLine( $row, $next, $notificationtimestamp = false,
654 $latest = false, $firstInList = false ) {
655 $rev = new Revision( $row, 0, $this->getTitle() );
656
657 if ( is_object( $next ) ) {
658 $prevRev = new Revision( $next, 0, $this->getTitle() );
659 } else {
660 $prevRev = null;
661 }
662
663 $curlink = $this->curLink( $rev, $latest );
664 $lastlink = $this->lastLink( $rev, $next );
665 $curLastlinks = $curlink . $this->historyPage->message['pipe-separator'] . $lastlink;
666 $histLinks = Html::rawElement(
667 'span',
668 [ 'class' => 'mw-history-histlinks' ],
669 $this->msg( 'parentheses' )->rawParams( $curLastlinks )->escaped()
670 );
671
672 $diffButtons = $this->diffButtons( $rev, $firstInList );
673 $s = $histLinks . $diffButtons;
674
675 $link = $this->revLink( $rev );
676 $classes = [];
677
678 $del = '';
679 $user = $this->getUser();
680 $canRevDelete = $user->isAllowed( 'deleterevision' );
681 // Show checkboxes for each revision, to allow for revision deletion and
682 // change tags
683 if ( $canRevDelete || $this->showTagEditUI ) {
684 $this->preventClickjacking();
685 // If revision was hidden from sysops and we don't need the checkbox
686 // for anything else, disable it
687 if ( !$this->showTagEditUI && !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
688 $del = Xml::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
689 // Otherwise, enable the checkbox...
690 } else {
691 $del = Xml::check( 'showhiderevisions', false,
692 [ 'name' => 'ids[' . $rev->getId() . ']' ] );
693 }
694 // User can only view deleted revisions...
695 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
696 // If revision was hidden from sysops, disable the link
697 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
698 $del = Linker::revDeleteLinkDisabled( false );
699 // Otherwise, show the link...
700 } else {
701 $query = [ 'type' => 'revision',
702 'target' => $this->getTitle()->getPrefixedDBkey(), 'ids' => $rev->getId() ];
703 $del .= Linker::revDeleteLink( $query,
704 $rev->isDeleted( Revision::DELETED_RESTRICTED ), false );
705 }
706 }
707 if ( $del ) {
708 $s .= " $del ";
709 }
710
711 $lang = $this->getLanguage();
712 $dirmark = $lang->getDirMark();
713
714 $s .= " $link";
715 $s .= $dirmark;
716 $s .= " <span class='history-user'>" .
717 Linker::revUserTools( $rev, true ) . "</span>";
718 $s .= $dirmark;
719
720 if ( $rev->isMinor() ) {
721 $s .= ' ' . ChangesList::flag( 'minor', $this->getContext() );
722 }
723
724 # Sometimes rev_len isn't populated
725 if ( $rev->getSize() !== null ) {
726 # Size is always public data
727 $prevSize = $this->parentLens[$row->rev_parent_id] ?? 0;
728 $sDiff = ChangesList::showCharacterDifference( $prevSize, $rev->getSize() );
729 $fSize = Linker::formatRevisionSize( $rev->getSize() );
730 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . "$fSize $sDiff";
731 }
732
733 # Text following the character difference is added just before running hooks
734 $s2 = Linker::revComment( $rev, false, true );
735
736 if ( $notificationtimestamp && ( $row->rev_timestamp >= $notificationtimestamp ) ) {
737 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
738 $classes[] = 'mw-history-line-updated';
739 }
740
741 $tools = [];
742
743 # Rollback and undo links
744 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
745 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
746 // Get a rollback link without the brackets
747 $rollbackLink = Linker::generateRollback(
748 $rev,
749 $this->getContext(),
750 [ 'verify', 'noBrackets' ]
751 );
752 if ( $rollbackLink ) {
753 $this->preventClickjacking();
754 $tools[] = $rollbackLink;
755 }
756 }
757
758 if ( !$rev->isDeleted( Revision::DELETED_TEXT )
759 && !$prevRev->isDeleted( Revision::DELETED_TEXT )
760 ) {
761 # Create undo tooltip for the first (=latest) line only
762 $undoTooltip = $latest
763 ? [ 'title' => $this->msg( 'tooltip-undo' )->text() ]
764 : [];
765 $undolink = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
766 $this->getTitle(),
767 $this->msg( 'editundo' )->text(),
768 $undoTooltip,
769 [
770 'action' => 'edit',
771 'undoafter' => $prevRev->getId(),
772 'undo' => $rev->getId()
773 ]
774 );
775 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
776 }
777 }
778 // Allow extension to add their own links here
779 Hooks::run( 'HistoryRevisionTools', [ $rev, &$tools, $prevRev, $user ] );
780
781 if ( $tools ) {
782 $s2 .= ' ' . $this->msg( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped();
783 }
784
785 # Tags
786 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
787 $row->ts_tags,
788 'history',
789 $this->getContext()
790 );
791 $classes = array_merge( $classes, $newClasses );
792 if ( $tagSummary !== '' ) {
793 $s2 .= " $tagSummary";
794 }
795
796 # Include separator between character difference and following text
797 if ( $s2 !== '' ) {
798 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . $s2;
799 }
800
801 $attribs = [ 'data-mw-revid' => $rev->getId() ];
802
803 Hooks::run( 'PageHistoryLineEnding', [ $this, &$row, &$s, &$classes, &$attribs ] );
804 $attribs = array_filter( $attribs,
805 [ Sanitizer::class, 'isReservedDataAttribute' ],
806 ARRAY_FILTER_USE_KEY
807 );
808
809 if ( $classes ) {
810 $attribs['class'] = implode( ' ', $classes );
811 }
812
813 return Xml::tags( 'li', $attribs, $s ) . "\n";
814 }
815
816 /**
817 * Create a link to view this revision of the page
818 *
819 * @param Revision $rev
820 * @return string
821 */
822 function revLink( $rev ) {
823 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $this->getUser() );
824 if ( $rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
825 $link = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
826 $this->getTitle(),
827 $date,
828 [ 'class' => 'mw-changeslist-date' ],
829 [ 'oldid' => $rev->getId() ]
830 );
831 } else {
832 $link = htmlspecialchars( $date );
833 }
834 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
835 $link = "<span class=\"history-deleted\">$link</span>";
836 }
837
838 return $link;
839 }
840
841 /**
842 * Create a diff-to-current link for this revision for this page
843 *
844 * @param Revision $rev
845 * @param bool $latest This is the latest revision of the page?
846 * @return string
847 */
848 function curLink( $rev, $latest ) {
849 $cur = $this->historyPage->message['cur'];
850 if ( $latest || !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
851 return $cur;
852 } else {
853 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
854 $this->getTitle(),
855 new HtmlArmor( $cur ),
856 [],
857 [
858 'diff' => $this->getWikiPage()->getLatest(),
859 'oldid' => $rev->getId()
860 ]
861 );
862 }
863 }
864
865 /**
866 * Create a diff-to-previous link for this revision for this page.
867 *
868 * @param Revision $prevRev The revision being displayed
869 * @param stdClass|string|null $next The next revision in list (that is
870 * the previous one in chronological order).
871 * May either be a row, "unknown" or null.
872 * @return string
873 */
874 function lastLink( $prevRev, $next ) {
875 $last = $this->historyPage->message['last'];
876
877 if ( $next === null ) {
878 # Probably no next row
879 return $last;
880 }
881
882 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
883 if ( $next === 'unknown' ) {
884 # Next row probably exists but is unknown, use an oldid=prev link
885 return $linkRenderer->makeKnownLink(
886 $this->getTitle(),
887 new HtmlArmor( $last ),
888 [],
889 [
890 'diff' => $prevRev->getId(),
891 'oldid' => 'prev'
892 ]
893 );
894 }
895
896 $nextRev = new Revision( $next );
897
898 if ( !$prevRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
899 || !$nextRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
900 ) {
901 return $last;
902 }
903
904 return $linkRenderer->makeKnownLink(
905 $this->getTitle(),
906 new HtmlArmor( $last ),
907 [],
908 [
909 'diff' => $prevRev->getId(),
910 'oldid' => $next->rev_id
911 ]
912 );
913 }
914
915 /**
916 * Create radio buttons for page history
917 *
918 * @param Revision $rev
919 * @param bool $firstInList Is this version the first one?
920 *
921 * @return string HTML output for the radio buttons
922 */
923 function diffButtons( $rev, $firstInList ) {
924 if ( $this->getNumRows() > 1 ) {
925 $id = $rev->getId();
926 $radio = [ 'type' => 'radio', 'value' => $id ];
927 /** @todo Move title texts to javascript */
928 if ( $firstInList ) {
929 $first = Xml::element( 'input',
930 array_merge( $radio, [
931 'style' => 'visibility:hidden',
932 'name' => 'oldid',
933 'id' => 'mw-oldid-null' ] )
934 );
935 $checkmark = [ 'checked' => 'checked' ];
936 } else {
937 # Check visibility of old revisions
938 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
939 $radio['disabled'] = 'disabled';
940 $checkmark = []; // We will check the next possible one
941 } elseif ( !$this->oldIdChecked ) {
942 $checkmark = [ 'checked' => 'checked' ];
943 $this->oldIdChecked = $id;
944 } else {
945 $checkmark = [];
946 }
947 $first = Xml::element( 'input',
948 array_merge( $radio, $checkmark, [
949 'name' => 'oldid',
950 'id' => "mw-oldid-$id" ] ) );
951 $checkmark = [];
952 }
953 $second = Xml::element( 'input',
954 array_merge( $radio, $checkmark, [
955 'name' => 'diff',
956 'id' => "mw-diff-$id" ] ) );
957
958 return $first . $second;
959 } else {
960 return '';
961 }
962 }
963
964 /**
965 * This is called if a write operation is possible from the generated HTML
966 * @param bool $enable
967 */
968 function preventClickjacking( $enable = true ) {
969 $this->preventClickjacking = $enable;
970 }
971
972 /**
973 * Get the "prevent clickjacking" flag
974 * @return bool
975 */
976 function getPreventClickjacking() {
977 return $this->preventClickjacking;
978 }
979
980 }