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