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