Mark protected IndexPager properties also as protected in subclasses
[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 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
362 $title = $this->msg( 'history-feed-item-nocomment',
363 $rev->getUserText(),
364 $contLang->timeanddate( $rev->getTimestamp() ),
365 $contLang->date( $rev->getTimestamp() ),
366 $contLang->time( $rev->getTimestamp() )
367 )->inContentLanguage()->text();
368 } else {
369 $title = $rev->getUserText() .
370 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
371 FeedItem::stripComment( $rev->getComment() );
372 }
373
374 return new FeedItem(
375 $title,
376 $text,
377 $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
378 $rev->getTimestamp(),
379 $rev->getUserText(),
380 $this->getTitle()->getTalkPage()->getFullURL()
381 );
382 }
383 }
384
385 /**
386 * @ingroup Pager
387 * @ingroup Actions
388 */
389 class HistoryPager extends ReverseChronologicalPager {
390 /**
391 * @var bool|stdClass
392 */
393 public $lastRow = false;
394
395 public $counter, $historyPage, $buttons, $conds;
396
397 protected $oldIdChecked;
398
399 protected $preventClickjacking = false;
400 /**
401 * @var array
402 */
403 protected $parentLens;
404
405 /** @var bool Whether to show the tag editing UI */
406 protected $showTagEditUI;
407
408 /** @var string */
409 private $tagFilter;
410
411 /**
412 * @param HistoryAction $historyPage
413 * @param string $year
414 * @param string $month
415 * @param string $tagFilter
416 * @param array $conds
417 */
418 function __construct( $historyPage, $year = '', $month = '', $tagFilter = '', $conds = [] ) {
419 parent::__construct( $historyPage->getContext() );
420 $this->historyPage = $historyPage;
421 $this->tagFilter = $tagFilter;
422 $this->getDateCond( $year, $month );
423 $this->conds = $conds;
424 $this->showTagEditUI = ChangeTags::showTagEditingUI( $this->getUser() );
425 }
426
427 // For hook compatibility...
428 function getArticle() {
429 return $this->historyPage->getArticle();
430 }
431
432 function getSqlComment() {
433 if ( $this->conds ) {
434 return 'history page filtered'; // potentially slow, see CR r58153
435 } else {
436 return 'history page unfiltered';
437 }
438 }
439
440 function getQueryInfo() {
441 $revQuery = Revision::getQueryInfo( [ 'user' ] );
442 $queryInfo = [
443 'tables' => $revQuery['tables'],
444 'fields' => $revQuery['fields'],
445 'conds' => array_merge(
446 [ 'rev_page' => $this->getWikiPage()->getId() ],
447 $this->conds ),
448 'options' => [ 'USE INDEX' => [ 'revision' => 'page_timestamp' ] ],
449 'join_conds' => $revQuery['joins'],
450 ];
451 ChangeTags::modifyDisplayQuery(
452 $queryInfo['tables'],
453 $queryInfo['fields'],
454 $queryInfo['conds'],
455 $queryInfo['join_conds'],
456 $queryInfo['options'],
457 $this->tagFilter
458 );
459
460 // Avoid PHP 7.1 warning of passing $this by reference
461 $historyPager = $this;
462 Hooks::run( 'PageHistoryPager::getQueryInfo', [ &$historyPager, &$queryInfo ] );
463
464 return $queryInfo;
465 }
466
467 function getIndexField() {
468 return 'rev_timestamp';
469 }
470
471 /**
472 * @param stdClass $row
473 * @return string
474 */
475 function formatRow( $row ) {
476 if ( $this->lastRow ) {
477 $latest = ( $this->counter == 1 && $this->mIsFirst );
478 $firstInList = $this->counter == 1;
479 $this->counter++;
480
481 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
482 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
483 : false;
484
485 $s = $this->historyLine(
486 $this->lastRow, $row, $notifTimestamp, $latest, $firstInList );
487 } else {
488 $s = '';
489 }
490 $this->lastRow = $row;
491
492 return $s;
493 }
494
495 protected function doBatchLookups() {
496 if ( !Hooks::run( 'PageHistoryPager::doBatchLookups', [ $this, $this->mResult ] ) ) {
497 return;
498 }
499
500 # Do a link batch query
501 $this->mResult->seek( 0 );
502 $batch = new LinkBatch();
503 $revIds = [];
504 foreach ( $this->mResult as $row ) {
505 if ( $row->rev_parent_id ) {
506 $revIds[] = $row->rev_parent_id;
507 }
508 if ( !is_null( $row->user_name ) ) {
509 $batch->add( NS_USER, $row->user_name );
510 $batch->add( NS_USER_TALK, $row->user_name );
511 } else { # for anons or usernames of imported revisions
512 $batch->add( NS_USER, $row->rev_user_text );
513 $batch->add( NS_USER_TALK, $row->rev_user_text );
514 }
515 }
516 $this->parentLens = Revision::getParentLengths( $this->mDb, $revIds );
517 $batch->execute();
518 $this->mResult->seek( 0 );
519 }
520
521 /**
522 * Creates begin of history list with a submit button
523 *
524 * @return string HTML output
525 */
526 protected function getStartBody() {
527 $this->lastRow = false;
528 $this->counter = 1;
529 $this->oldIdChecked = 0;
530
531 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
532 $s = Html::openElement( 'form', [ 'action' => wfScript(),
533 'id' => 'mw-history-compare' ] ) . "\n";
534 $s .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) . "\n";
535 $s .= Html::hidden( 'action', 'historysubmit' ) . "\n";
536 $s .= Html::hidden( 'type', 'revision' ) . "\n";
537
538 // Button container stored in $this->buttons for re-use in getEndBody()
539 $this->buttons = '<div>';
540 $className = 'historysubmit mw-history-compareselectedversions-button';
541 $attrs = [ 'class' => $className ]
542 + Linker::tooltipAndAccesskeyAttribs( 'compareselectedversions' );
543 $this->buttons .= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
544 $attrs
545 ) . "\n";
546
547 $user = $this->getUser();
548 $actionButtons = '';
549 if ( $user->isAllowed( 'deleterevision' ) ) {
550 $actionButtons .= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
551 }
552 if ( $this->showTagEditUI ) {
553 $actionButtons .= $this->getRevisionButton( 'editchangetags', 'history-edit-tags' );
554 }
555 if ( $actionButtons ) {
556 $this->buttons .= Xml::tags( 'div', [ 'class' =>
557 'mw-history-revisionactions' ], $actionButtons );
558 }
559
560 if ( $user->isAllowed( 'deleterevision' ) || $this->showTagEditUI ) {
561 $this->buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
562 }
563
564 $this->buttons .= '</div>';
565
566 $s .= $this->buttons;
567 $s .= '<ul id="pagehistory">' . "\n";
568
569 return $s;
570 }
571
572 private function getRevisionButton( $name, $msg ) {
573 $this->preventClickjacking();
574 # Note T22966, <button> is non-standard in IE<8
575 $element = Html::element(
576 'button',
577 [
578 'type' => 'submit',
579 'name' => $name,
580 'value' => '1',
581 'class' => "historysubmit mw-history-$name-button",
582 ],
583 $this->msg( $msg )->text()
584 ) . "\n";
585 return $element;
586 }
587
588 protected function getEndBody() {
589 if ( $this->lastRow ) {
590 $latest = $this->counter == 1 && $this->mIsFirst;
591 $firstInList = $this->counter == 1;
592 if ( $this->mIsBackwards ) {
593 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
594 if ( $this->mOffset == '' ) {
595 $next = null;
596 } else {
597 $next = 'unknown';
598 }
599 } else {
600 # The next row is the past-the-end row
601 $next = $this->mPastTheEndRow;
602 }
603 $this->counter++;
604
605 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
606 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
607 : false;
608
609 $s = $this->historyLine(
610 $this->lastRow, $next, $notifTimestamp, $latest, $firstInList );
611 } else {
612 $s = '';
613 }
614 $s .= "</ul>\n";
615 # Add second buttons only if there is more than one rev
616 if ( $this->getNumRows() > 2 ) {
617 $s .= $this->buttons;
618 }
619 $s .= '</form>';
620
621 return $s;
622 }
623
624 /**
625 * Creates a submit button
626 *
627 * @param string $message Text of the submit button, will be escaped
628 * @param array $attributes
629 * @return string HTML output for the submit button
630 */
631 function submitButton( $message, $attributes = [] ) {
632 # Disable submit button if history has 1 revision only
633 if ( $this->getNumRows() > 1 ) {
634 return Html::submitButton( $message, $attributes );
635 } else {
636 return '';
637 }
638 }
639
640 /**
641 * Returns a row from the history printout.
642 *
643 * @todo document some more, and maybe clean up the code (some params redundant?)
644 *
645 * @param stdClass $row The database row corresponding to the previous line.
646 * @param mixed $next The database row corresponding to the next line
647 * (chronologically previous)
648 * @param bool|string $notificationtimestamp
649 * @param bool $latest Whether this row corresponds to the page's latest revision.
650 * @param bool $firstInList Whether this row corresponds to the first
651 * displayed on this history page.
652 * @return string HTML output for the row
653 */
654 function historyLine( $row, $next, $notificationtimestamp = false,
655 $latest = false, $firstInList = false ) {
656 $rev = new Revision( $row, 0, $this->getTitle() );
657
658 if ( is_object( $next ) ) {
659 $prevRev = new Revision( $next, 0, $this->getTitle() );
660 } else {
661 $prevRev = null;
662 }
663
664 $curlink = $this->curLink( $rev, $latest );
665 $lastlink = $this->lastLink( $rev, $next );
666 $curLastlinks = $curlink . $this->historyPage->message['pipe-separator'] . $lastlink;
667 $histLinks = Html::rawElement(
668 'span',
669 [ 'class' => 'mw-history-histlinks' ],
670 $this->msg( 'parentheses' )->rawParams( $curLastlinks )->escaped()
671 );
672
673 $diffButtons = $this->diffButtons( $rev, $firstInList );
674 $s = $histLinks . $diffButtons;
675
676 $link = $this->revLink( $rev );
677 $classes = [];
678
679 $del = '';
680 $user = $this->getUser();
681 $canRevDelete = $user->isAllowed( 'deleterevision' );
682 // Show checkboxes for each revision, to allow for revision deletion and
683 // change tags
684 if ( $canRevDelete || $this->showTagEditUI ) {
685 $this->preventClickjacking();
686 // If revision was hidden from sysops and we don't need the checkbox
687 // for anything else, disable it
688 if ( !$this->showTagEditUI && !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
689 $del = Xml::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
690 // Otherwise, enable the checkbox...
691 } else {
692 $del = Xml::check( 'showhiderevisions', false,
693 [ 'name' => 'ids[' . $rev->getId() . ']' ] );
694 }
695 // User can only view deleted revisions...
696 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
697 // If revision was hidden from sysops, disable the link
698 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
699 $del = Linker::revDeleteLinkDisabled( false );
700 // Otherwise, show the link...
701 } else {
702 $query = [ 'type' => 'revision',
703 'target' => $this->getTitle()->getPrefixedDBkey(), 'ids' => $rev->getId() ];
704 $del .= Linker::revDeleteLink( $query,
705 $rev->isDeleted( Revision::DELETED_RESTRICTED ), false );
706 }
707 }
708 if ( $del ) {
709 $s .= " $del ";
710 }
711
712 $lang = $this->getLanguage();
713 $dirmark = $lang->getDirMark();
714
715 $s .= " $link";
716 $s .= $dirmark;
717 $s .= " <span class='history-user'>" .
718 Linker::revUserTools( $rev, true ) . "</span>";
719 $s .= $dirmark;
720
721 if ( $rev->isMinor() ) {
722 $s .= ' ' . ChangesList::flag( 'minor', $this->getContext() );
723 }
724
725 # Sometimes rev_len isn't populated
726 if ( $rev->getSize() !== null ) {
727 # Size is always public data
728 $prevSize = $this->parentLens[$row->rev_parent_id] ?? 0;
729 $sDiff = ChangesList::showCharacterDifference( $prevSize, $rev->getSize() );
730 $fSize = Linker::formatRevisionSize( $rev->getSize() );
731 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . "$fSize $sDiff";
732 }
733
734 # Text following the character difference is added just before running hooks
735 $s2 = Linker::revComment( $rev, false, true );
736
737 if ( $notificationtimestamp && ( $row->rev_timestamp >= $notificationtimestamp ) ) {
738 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
739 $classes[] = 'mw-history-line-updated';
740 }
741
742 $tools = [];
743
744 # Rollback and undo links
745 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
746 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
747 // Get a rollback link without the brackets
748 $rollbackLink = Linker::generateRollback(
749 $rev,
750 $this->getContext(),
751 [ 'verify', 'noBrackets' ]
752 );
753 if ( $rollbackLink ) {
754 $this->preventClickjacking();
755 $tools[] = $rollbackLink;
756 }
757 }
758
759 if ( !$rev->isDeleted( Revision::DELETED_TEXT )
760 && !$prevRev->isDeleted( Revision::DELETED_TEXT )
761 ) {
762 # Create undo tooltip for the first (=latest) line only
763 $undoTooltip = $latest
764 ? [ 'title' => $this->msg( 'tooltip-undo' )->text() ]
765 : [];
766 $undolink = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
767 $this->getTitle(),
768 $this->msg( 'editundo' )->text(),
769 $undoTooltip,
770 [
771 'action' => 'edit',
772 'undoafter' => $prevRev->getId(),
773 'undo' => $rev->getId()
774 ]
775 );
776 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
777 }
778 }
779 // Allow extension to add their own links here
780 Hooks::run( 'HistoryRevisionTools', [ $rev, &$tools, $prevRev, $user ] );
781
782 if ( $tools ) {
783 $s2 .= ' ' . $this->msg( 'parentheses' )->rawParams( $lang->pipeList( $tools ) )->escaped();
784 }
785
786 # Tags
787 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
788 $row->ts_tags,
789 'history',
790 $this->getContext()
791 );
792 $classes = array_merge( $classes, $newClasses );
793 if ( $tagSummary !== '' ) {
794 $s2 .= " $tagSummary";
795 }
796
797 # Include separator between character difference and following text
798 if ( $s2 !== '' ) {
799 $s .= ' <span class="mw-changeslist-separator">. .</span> ' . $s2;
800 }
801
802 $attribs = [ 'data-mw-revid' => $rev->getId() ];
803
804 Hooks::run( 'PageHistoryLineEnding', [ $this, &$row, &$s, &$classes, &$attribs ] );
805 $attribs = array_filter( $attribs,
806 [ Sanitizer::class, 'isReservedDataAttribute' ],
807 ARRAY_FILTER_USE_KEY
808 );
809
810 if ( $classes ) {
811 $attribs['class'] = implode( ' ', $classes );
812 }
813
814 return Xml::tags( 'li', $attribs, $s ) . "\n";
815 }
816
817 /**
818 * Create a link to view this revision of the page
819 *
820 * @param Revision $rev
821 * @return string
822 */
823 function revLink( $rev ) {
824 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $this->getUser() );
825 if ( $rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
826 $link = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
827 $this->getTitle(),
828 $date,
829 [ 'class' => 'mw-changeslist-date' ],
830 [ 'oldid' => $rev->getId() ]
831 );
832 } else {
833 $link = htmlspecialchars( $date );
834 }
835 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
836 $link = "<span class=\"history-deleted\">$link</span>";
837 }
838
839 return $link;
840 }
841
842 /**
843 * Create a diff-to-current link for this revision for this page
844 *
845 * @param Revision $rev
846 * @param bool $latest This is the latest revision of the page?
847 * @return string
848 */
849 function curLink( $rev, $latest ) {
850 $cur = $this->historyPage->message['cur'];
851 if ( $latest || !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
852 return $cur;
853 } else {
854 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
855 $this->getTitle(),
856 new HtmlArmor( $cur ),
857 [],
858 [
859 'diff' => $this->getWikiPage()->getLatest(),
860 'oldid' => $rev->getId()
861 ]
862 );
863 }
864 }
865
866 /**
867 * Create a diff-to-previous link for this revision for this page.
868 *
869 * @param Revision $prevRev The revision being displayed
870 * @param stdClass|string|null $next The next revision in list (that is
871 * the previous one in chronological order).
872 * May either be a row, "unknown" or null.
873 * @return string
874 */
875 function lastLink( $prevRev, $next ) {
876 $last = $this->historyPage->message['last'];
877
878 if ( $next === null ) {
879 # Probably no next row
880 return $last;
881 }
882
883 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
884 if ( $next === 'unknown' ) {
885 # Next row probably exists but is unknown, use an oldid=prev link
886 return $linkRenderer->makeKnownLink(
887 $this->getTitle(),
888 new HtmlArmor( $last ),
889 [],
890 [
891 'diff' => $prevRev->getId(),
892 'oldid' => 'prev'
893 ]
894 );
895 }
896
897 $nextRev = new Revision( $next );
898
899 if ( !$prevRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
900 || !$nextRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
901 ) {
902 return $last;
903 }
904
905 return $linkRenderer->makeKnownLink(
906 $this->getTitle(),
907 new HtmlArmor( $last ),
908 [],
909 [
910 'diff' => $prevRev->getId(),
911 'oldid' => $next->rev_id
912 ]
913 );
914 }
915
916 /**
917 * Create radio buttons for page history
918 *
919 * @param Revision $rev
920 * @param bool $firstInList Is this version the first one?
921 *
922 * @return string HTML output for the radio buttons
923 */
924 function diffButtons( $rev, $firstInList ) {
925 if ( $this->getNumRows() > 1 ) {
926 $id = $rev->getId();
927 $radio = [ 'type' => 'radio', 'value' => $id ];
928 /** @todo Move title texts to javascript */
929 if ( $firstInList ) {
930 $first = Xml::element( 'input',
931 array_merge( $radio, [
932 'style' => 'visibility:hidden',
933 'name' => 'oldid',
934 'id' => 'mw-oldid-null' ] )
935 );
936 $checkmark = [ 'checked' => 'checked' ];
937 } else {
938 # Check visibility of old revisions
939 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
940 $radio['disabled'] = 'disabled';
941 $checkmark = []; // We will check the next possible one
942 } elseif ( !$this->oldIdChecked ) {
943 $checkmark = [ 'checked' => 'checked' ];
944 $this->oldIdChecked = $id;
945 } else {
946 $checkmark = [];
947 }
948 $first = Xml::element( 'input',
949 array_merge( $radio, $checkmark, [
950 'name' => 'oldid',
951 'id' => "mw-oldid-$id" ] ) );
952 $checkmark = [];
953 }
954 $second = Xml::element( 'input',
955 array_merge( $radio, $checkmark, [
956 'name' => 'diff',
957 'id' => "mw-diff-$id" ] ) );
958
959 return $first . $second;
960 } else {
961 return '';
962 }
963 }
964
965 /**
966 * This is called if a write operation is possible from the generated HTML
967 * @param bool $enable
968 */
969 function preventClickjacking( $enable = true ) {
970 $this->preventClickjacking = $enable;
971 }
972
973 /**
974 * Get the "prevent clickjacking" flag
975 * @return bool
976 */
977 function getPreventClickjacking() {
978 return $this->preventClickjacking;
979 }
980
981 }