Merge "Type hint against LinkTarget in WatchedItemStore"
[lhc/web/wiklou.git] / includes / actions / pagers / HistoryPager.php
1 <?php
2 /**
3 * Page history pager
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Actions
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Revision\RevisionRecord;
26
27 /**
28 * @ingroup Pager
29 * @ingroup Actions
30 */
31 class HistoryPager extends ReverseChronologicalPager {
32 /**
33 * @var bool|stdClass
34 */
35 public $lastRow = false;
36
37 public $counter, $historyPage, $buttons, $conds;
38
39 protected $oldIdChecked;
40
41 protected $preventClickjacking = false;
42 /**
43 * @var array
44 */
45 protected $parentLens;
46
47 /** @var bool Whether to show the tag editing UI */
48 protected $showTagEditUI;
49
50 /** @var string */
51 private $tagFilter;
52
53 /**
54 * @param HistoryAction $historyPage
55 * @param string $year
56 * @param string $month
57 * @param string $tagFilter
58 * @param array $conds
59 * @param string $day
60 */
61 public function __construct(
62 HistoryAction $historyPage,
63 $year = '',
64 $month = '',
65 $tagFilter = '',
66 array $conds = [],
67 $day = ''
68 ) {
69 parent::__construct( $historyPage->getContext() );
70 $this->historyPage = $historyPage;
71 $this->tagFilter = $tagFilter;
72 $this->getDateCond( $year, $month, $day );
73 $this->conds = $conds;
74 $this->showTagEditUI = ChangeTags::showTagEditingUI( $this->getUser() );
75 }
76
77 // For hook compatibility...
78 function getArticle() {
79 return $this->historyPage->getArticle();
80 }
81
82 function getSqlComment() {
83 if ( $this->conds ) {
84 return 'history page filtered'; // potentially slow, see CR r58153
85 } else {
86 return 'history page unfiltered';
87 }
88 }
89
90 function getQueryInfo() {
91 $revQuery = Revision::getQueryInfo( [ 'user' ] );
92 $queryInfo = [
93 'tables' => $revQuery['tables'],
94 'fields' => $revQuery['fields'],
95 'conds' => array_merge(
96 [ 'rev_page' => $this->getWikiPage()->getId() ],
97 $this->conds ),
98 'options' => [ 'USE INDEX' => [ 'revision' => 'page_timestamp' ] ],
99 'join_conds' => $revQuery['joins'],
100 ];
101 ChangeTags::modifyDisplayQuery(
102 $queryInfo['tables'],
103 $queryInfo['fields'],
104 $queryInfo['conds'],
105 $queryInfo['join_conds'],
106 $queryInfo['options'],
107 $this->tagFilter
108 );
109
110 // Avoid PHP 7.1 warning of passing $this by reference
111 $historyPager = $this;
112 Hooks::run( 'PageHistoryPager::getQueryInfo', [ &$historyPager, &$queryInfo ] );
113
114 return $queryInfo;
115 }
116
117 function getIndexField() {
118 return 'rev_timestamp';
119 }
120
121 /**
122 * @param stdClass $row
123 * @return string
124 */
125 function formatRow( $row ) {
126 if ( $this->lastRow ) {
127 $firstInList = $this->counter == 1;
128 $this->counter++;
129
130 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
131 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
132 : false;
133
134 $s = $this->historyLine( $this->lastRow, $row, $notifTimestamp, false, $firstInList );
135 } else {
136 $s = '';
137 }
138 $this->lastRow = $row;
139
140 return $s;
141 }
142
143 protected function doBatchLookups() {
144 if ( !Hooks::run( 'PageHistoryPager::doBatchLookups', [ $this, $this->mResult ] ) ) {
145 return;
146 }
147
148 # Do a link batch query
149 $this->mResult->seek( 0 );
150 $batch = new LinkBatch();
151 $revIds = [];
152 foreach ( $this->mResult as $row ) {
153 if ( $row->rev_parent_id ) {
154 $revIds[] = $row->rev_parent_id;
155 }
156 if ( $row->user_name !== null ) {
157 $batch->add( NS_USER, $row->user_name );
158 $batch->add( NS_USER_TALK, $row->user_name );
159 } else { # for anons or usernames of imported revisions
160 $batch->add( NS_USER, $row->rev_user_text );
161 $batch->add( NS_USER_TALK, $row->rev_user_text );
162 }
163 }
164 $this->parentLens = Revision::getParentLengths( $this->mDb, $revIds );
165 $batch->execute();
166 $this->mResult->seek( 0 );
167 }
168
169 /**
170 * Creates begin of history list with a submit button
171 *
172 * @return string HTML output
173 */
174 protected function getStartBody() {
175 $this->lastRow = false;
176 $this->counter = 1;
177 $this->oldIdChecked = 0;
178
179 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
180 $s = Html::openElement( 'form', [ 'action' => wfScript(),
181 'id' => 'mw-history-compare' ] ) . "\n";
182 $s .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) . "\n";
183 $s .= Html::hidden( 'action', 'historysubmit' ) . "\n";
184 $s .= Html::hidden( 'type', 'revision' ) . "\n";
185
186 // Button container stored in $this->buttons for re-use in getEndBody()
187 $this->buttons = '';
188 if ( $this->getNumRows() > 0 ) {
189 $this->buttons .= Html::openElement(
190 'div', [ 'class' => 'mw-history-compareselectedversions' ] );
191 $className = 'historysubmit mw-history-compareselectedversions-button';
192 $attrs = [ 'class' => $className ]
193 + Linker::tooltipAndAccesskeyAttribs( 'compareselectedversions' );
194 $this->buttons .= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
195 $attrs
196 ) . "\n";
197
198 $user = $this->getUser();
199 $actionButtons = '';
200 if ( $user->isAllowed( 'deleterevision' ) ) {
201 $actionButtons .= $this->getRevisionButton(
202 'revisiondelete', 'showhideselectedversions' );
203 }
204 if ( $this->showTagEditUI ) {
205 $actionButtons .= $this->getRevisionButton(
206 'editchangetags', 'history-edit-tags' );
207 }
208 if ( $actionButtons ) {
209 $this->buttons .= Xml::tags( 'div', [ 'class' =>
210 'mw-history-revisionactions' ], $actionButtons );
211 }
212
213 if ( $user->isAllowed( 'deleterevision' ) || $this->showTagEditUI ) {
214 $this->buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
215 }
216
217 $this->buttons .= '</div>';
218
219 $s .= $this->buttons;
220 }
221 $s .= '<ul id="pagehistory">' . "\n";
222
223 return $s;
224 }
225
226 private function getRevisionButton( $name, $msg ) {
227 $this->preventClickjacking();
228 # Note T22966, <button> is non-standard in IE<8
229 $element = Html::element(
230 'button',
231 [
232 'type' => 'submit',
233 'name' => $name,
234 'value' => '1',
235 'class' => "historysubmit mw-history-$name-button",
236 ],
237 $this->msg( $msg )->text()
238 ) . "\n";
239 return $element;
240 }
241
242 protected function getEndBody() {
243 if ( $this->lastRow ) {
244 $firstInList = $this->counter == 1;
245 if ( $this->mIsBackwards ) {
246 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
247 if ( $this->mOffset == '' ) {
248 $next = null;
249 } else {
250 $next = 'unknown';
251 }
252 } else {
253 # The next row is the past-the-end row
254 $next = $this->mPastTheEndRow;
255 }
256 $this->counter++;
257
258 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
259 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
260 : false;
261
262 $s = $this->historyLine( $this->lastRow, $next, $notifTimestamp, false, $firstInList );
263 } else {
264 $s = '';
265 }
266 $s .= "</ul>\n";
267 # Add second buttons only if there is more than one rev
268 if ( $this->getNumRows() > 2 ) {
269 $s .= $this->buttons;
270 }
271 $s .= '</form>';
272
273 return $s;
274 }
275
276 /**
277 * Creates a submit button
278 *
279 * @param string $message Text of the submit button, will be escaped
280 * @param array $attributes
281 * @return string HTML output for the submit button
282 */
283 function submitButton( $message, $attributes = [] ) {
284 # Disable submit button if history has 1 revision only
285 if ( $this->getNumRows() > 1 ) {
286 return Html::submitButton( $message, $attributes );
287 } else {
288 return '';
289 }
290 }
291
292 /**
293 * Returns a row from the history printout.
294 *
295 * @todo document some more, and maybe clean up the code (some params redundant?)
296 *
297 * @param stdClass $row The database row corresponding to the previous line.
298 * @param mixed $next The database row corresponding to the next line
299 * (chronologically previous)
300 * @param bool|string $notificationtimestamp
301 * @param bool $dummy Unused.
302 * @param bool $firstInList Whether this row corresponds to the first
303 * displayed on this history page.
304 * @return string HTML output for the row
305 */
306 function historyLine( $row, $next, $notificationtimestamp = false,
307 $dummy = false, $firstInList = false ) {
308 $rev = new Revision( $row, 0, $this->getTitle() );
309
310 if ( is_object( $next ) ) {
311 $prevRev = new Revision( $next, 0, $this->getTitle() );
312 } else {
313 $prevRev = null;
314 }
315
316 $latest = $rev->getId() === $this->getWikiPage()->getLatest();
317 $curlink = $this->curLink( $rev );
318 $lastlink = $this->lastLink( $rev, $next );
319 $curLastlinks = Html::rawElement( 'span', [], $curlink ) .
320 Html::rawElement( 'span', [], $lastlink );
321 $histLinks = Html::rawElement(
322 'span',
323 [ 'class' => 'mw-history-histlinks mw-changeslist-links' ],
324 $curLastlinks
325 );
326
327 $diffButtons = $this->diffButtons( $rev, $firstInList );
328 $s = $histLinks . $diffButtons;
329
330 $link = $this->revLink( $rev );
331 $classes = [];
332
333 $del = '';
334 $user = $this->getUser();
335 $canRevDelete = $user->isAllowed( 'deleterevision' );
336 // Show checkboxes for each revision, to allow for revision deletion and
337 // change tags
338 if ( $canRevDelete || $this->showTagEditUI ) {
339 $this->preventClickjacking();
340 // If revision was hidden from sysops and we don't need the checkbox
341 // for anything else, disable it
342 if ( !$this->showTagEditUI
343 && !$rev->userCan( RevisionRecord::DELETED_RESTRICTED, $user )
344 ) {
345 $del = Xml::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
346 // Otherwise, enable the checkbox...
347 } else {
348 $del = Xml::check( 'showhiderevisions', false,
349 [ 'name' => 'ids[' . $rev->getId() . ']' ] );
350 }
351 // User can only view deleted revisions...
352 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
353 // If revision was hidden from sysops, disable the link
354 if ( !$rev->userCan( RevisionRecord::DELETED_RESTRICTED, $user ) ) {
355 $del = Linker::revDeleteLinkDisabled( false );
356 // Otherwise, show the link...
357 } else {
358 $query = [ 'type' => 'revision',
359 'target' => $this->getTitle()->getPrefixedDBkey(), 'ids' => $rev->getId() ];
360 $del .= Linker::revDeleteLink( $query,
361 $rev->isDeleted( RevisionRecord::DELETED_RESTRICTED ), false );
362 }
363 }
364 if ( $del ) {
365 $s .= " $del ";
366 }
367
368 $lang = $this->getLanguage();
369 $dirmark = $lang->getDirMark();
370
371 $s .= " $link";
372 $s .= $dirmark;
373 $s .= " <span class='history-user'>" .
374 Linker::revUserTools( $rev, true, false ) . "</span>";
375 $s .= $dirmark;
376
377 if ( $rev->isMinor() ) {
378 $s .= ' ' . ChangesList::flag( 'minor', $this->getContext() );
379 }
380
381 # Sometimes rev_len isn't populated
382 if ( $rev->getSize() !== null ) {
383 # Size is always public data
384 $prevSize = $this->parentLens[$row->rev_parent_id] ?? 0;
385 $sDiff = ChangesList::showCharacterDifference( $prevSize, $rev->getSize() );
386 $fSize = Linker::formatRevisionSize( $rev->getSize(), false );
387 $s .= ' <span class="mw-changeslist-separator"></span> ' . "$fSize $sDiff";
388 }
389
390 # Text following the character difference is added just before running hooks
391 $s2 = Linker::revComment( $rev, false, true, false );
392
393 if ( $notificationtimestamp && ( $row->rev_timestamp >= $notificationtimestamp ) ) {
394 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
395 $classes[] = 'mw-history-line-updated';
396 }
397
398 $tools = [];
399
400 # Rollback and undo links
401 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
402 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
403 // Get a rollback link without the brackets
404 $rollbackLink = Linker::generateRollback(
405 $rev,
406 $this->getContext(),
407 [ 'verify', 'noBrackets' ]
408 );
409 if ( $rollbackLink ) {
410 $this->preventClickjacking();
411 $tools[] = $rollbackLink;
412 }
413 }
414
415 if ( !$rev->isDeleted( RevisionRecord::DELETED_TEXT )
416 && !$prevRev->isDeleted( RevisionRecord::DELETED_TEXT )
417 ) {
418 # Create undo tooltip for the first (=latest) line only
419 $undoTooltip = $latest
420 ? [ 'title' => $this->msg( 'tooltip-undo' )->text() ]
421 : [];
422 $undolink = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
423 $this->getTitle(),
424 $this->msg( 'editundo' )->text(),
425 $undoTooltip,
426 [
427 'action' => 'edit',
428 'undoafter' => $prevRev->getId(),
429 'undo' => $rev->getId()
430 ]
431 );
432 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
433 }
434 }
435 // Allow extension to add their own links here
436 Hooks::run( 'HistoryRevisionTools', [ $rev, &$tools, $prevRev, $user ] );
437
438 if ( $tools ) {
439 $s2 .= ' ' . Html::openElement( 'span', [ 'class' => 'mw-changeslist-links' ] );
440 foreach ( $tools as $tool ) {
441 $s2 .= Html::rawElement( 'span', [], $tool );
442 }
443 $s2 .= Html::closeElement( 'span' );
444 }
445
446 # Tags
447 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
448 $row->ts_tags,
449 'history',
450 $this->getContext()
451 );
452 $classes = array_merge( $classes, $newClasses );
453 if ( $tagSummary !== '' ) {
454 $s2 .= " $tagSummary";
455 }
456
457 # Include separator between character difference and following text
458 if ( $s2 !== '' ) {
459 $s .= ' <span class="mw-changeslist-separator"></span> ' . $s2;
460 }
461
462 $attribs = [ 'data-mw-revid' => $rev->getId() ];
463
464 Hooks::run( 'PageHistoryLineEnding', [ $this, &$row, &$s, &$classes, &$attribs ] );
465 $attribs = array_filter( $attribs,
466 [ Sanitizer::class, 'isReservedDataAttribute' ],
467 ARRAY_FILTER_USE_KEY
468 );
469
470 if ( $classes ) {
471 $attribs['class'] = implode( ' ', $classes );
472 }
473
474 return Xml::tags( 'li', $attribs, $s ) . "\n";
475 }
476
477 /**
478 * Create a link to view this revision of the page
479 *
480 * @param Revision $rev
481 * @return string
482 */
483 function revLink( $rev ) {
484 return ChangesList::revDateLink( $rev, $this->getUser(), $this->getLanguage(),
485 $this->getTitle() );
486 }
487
488 /**
489 * Create a diff-to-current link for this revision for this page
490 *
491 * @param Revision $rev
492 * @return string
493 */
494 function curLink( $rev ) {
495 $cur = $this->historyPage->message['cur'];
496 $latest = $this->getWikiPage()->getLatest();
497 if ( $latest === $rev->getId()
498 || !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() )
499 ) {
500 return $cur;
501 } else {
502 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
503 $this->getTitle(),
504 new HtmlArmor( $cur ),
505 [],
506 [
507 'diff' => $latest,
508 'oldid' => $rev->getId()
509 ]
510 );
511 }
512 }
513
514 /**
515 * Create a diff-to-previous link for this revision for this page.
516 *
517 * @param Revision $prevRev The revision being displayed
518 * @param stdClass|string|null $next The next revision in list (that is
519 * the previous one in chronological order).
520 * May either be a row, "unknown" or null.
521 * @return string
522 */
523 function lastLink( $prevRev, $next ) {
524 $last = $this->historyPage->message['last'];
525
526 if ( $next === null ) {
527 # Probably no next row
528 return $last;
529 }
530
531 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
532 if ( $next === 'unknown' ) {
533 # Next row probably exists but is unknown, use an oldid=prev link
534 return $linkRenderer->makeKnownLink(
535 $this->getTitle(),
536 new HtmlArmor( $last ),
537 [],
538 [
539 'diff' => $prevRev->getId(),
540 'oldid' => 'prev'
541 ]
542 );
543 }
544
545 $nextRev = new Revision( $next, 0, $this->getTitle() );
546
547 if ( !$prevRev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() )
548 || !$nextRev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() )
549 ) {
550 return $last;
551 }
552
553 return $linkRenderer->makeKnownLink(
554 $this->getTitle(),
555 new HtmlArmor( $last ),
556 [],
557 [
558 'diff' => $prevRev->getId(),
559 'oldid' => $next->rev_id
560 ]
561 );
562 }
563
564 /**
565 * Create radio buttons for page history
566 *
567 * @param Revision $rev
568 * @param bool $firstInList Is this version the first one?
569 *
570 * @return string HTML output for the radio buttons
571 */
572 function diffButtons( $rev, $firstInList ) {
573 if ( $this->getNumRows() > 1 ) {
574 $id = $rev->getId();
575 $radio = [ 'type' => 'radio', 'value' => $id ];
576 /** @todo Move title texts to javascript */
577 if ( $firstInList ) {
578 $first = Xml::element( 'input',
579 array_merge( $radio, [
580 'style' => 'visibility:hidden',
581 'name' => 'oldid',
582 'id' => 'mw-oldid-null' ] )
583 );
584 $checkmark = [ 'checked' => 'checked' ];
585 } else {
586 # Check visibility of old revisions
587 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() ) ) {
588 $radio['disabled'] = 'disabled';
589 $checkmark = []; // We will check the next possible one
590 } elseif ( !$this->oldIdChecked ) {
591 $checkmark = [ 'checked' => 'checked' ];
592 $this->oldIdChecked = $id;
593 } else {
594 $checkmark = [];
595 }
596 $first = Xml::element( 'input',
597 array_merge( $radio, $checkmark, [
598 'name' => 'oldid',
599 'id' => "mw-oldid-$id" ] ) );
600 $checkmark = [];
601 }
602 $second = Xml::element( 'input',
603 array_merge( $radio, $checkmark, [
604 'name' => 'diff',
605 'id' => "mw-diff-$id" ] ) );
606
607 return $first . $second;
608 } else {
609 return '';
610 }
611 }
612
613 /**
614 * @inheritDoc
615 */
616 function getDefaultQuery() {
617 parent::getDefaultQuery();
618 unset( $this->mDefaultQuery['date-range-to'] );
619 return $this->mDefaultQuery;
620 }
621
622 /**
623 * This is called if a write operation is possible from the generated HTML
624 * @param bool $enable
625 */
626 function preventClickjacking( $enable = true ) {
627 $this->preventClickjacking = $enable;
628 }
629
630 /**
631 * Get the "prevent clickjacking" flag
632 * @return bool
633 */
634 function getPreventClickjacking() {
635 return $this->preventClickjacking;
636 }
637
638 }