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