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