5ef6e77b31337599cc9085a44cca31ecc8dace0f
[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 && !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
343 $del = Xml::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
344 // Otherwise, enable the checkbox...
345 } else {
346 $del = Xml::check( 'showhiderevisions', false,
347 [ 'name' => 'ids[' . $rev->getId() . ']' ] );
348 }
349 // User can only view deleted revisions...
350 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
351 // If revision was hidden from sysops, disable the link
352 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
353 $del = Linker::revDeleteLinkDisabled( false );
354 // Otherwise, show the link...
355 } else {
356 $query = [ 'type' => 'revision',
357 'target' => $this->getTitle()->getPrefixedDBkey(), 'ids' => $rev->getId() ];
358 $del .= Linker::revDeleteLink( $query,
359 $rev->isDeleted( Revision::DELETED_RESTRICTED ), false );
360 }
361 }
362 if ( $del ) {
363 $s .= " $del ";
364 }
365
366 $lang = $this->getLanguage();
367 $dirmark = $lang->getDirMark();
368
369 $s .= " $link";
370 $s .= $dirmark;
371 $s .= " <span class='history-user'>" .
372 Linker::revUserTools( $rev, true, false ) . "</span>";
373 $s .= $dirmark;
374
375 if ( $rev->isMinor() ) {
376 $s .= ' ' . ChangesList::flag( 'minor', $this->getContext() );
377 }
378
379 # Sometimes rev_len isn't populated
380 if ( $rev->getSize() !== null ) {
381 # Size is always public data
382 $prevSize = $this->parentLens[$row->rev_parent_id] ?? 0;
383 $sDiff = ChangesList::showCharacterDifference( $prevSize, $rev->getSize() );
384 $fSize = Linker::formatRevisionSize( $rev->getSize(), false );
385 $s .= ' <span class="mw-changeslist-separator"></span> ' . "$fSize $sDiff";
386 }
387
388 # Text following the character difference is added just before running hooks
389 $s2 = Linker::revComment( $rev, false, true, false );
390
391 if ( $notificationtimestamp && ( $row->rev_timestamp >= $notificationtimestamp ) ) {
392 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
393 $classes[] = 'mw-history-line-updated';
394 }
395
396 $tools = [];
397
398 # Rollback and undo links
399 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
400 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
401 // Get a rollback link without the brackets
402 $rollbackLink = Linker::generateRollback(
403 $rev,
404 $this->getContext(),
405 [ 'verify', 'noBrackets' ]
406 );
407 if ( $rollbackLink ) {
408 $this->preventClickjacking();
409 $tools[] = $rollbackLink;
410 }
411 }
412
413 if ( !$rev->isDeleted( RevisionRecord::DELETED_TEXT )
414 && !$prevRev->isDeleted( RevisionRecord::DELETED_TEXT )
415 ) {
416 # Create undo tooltip for the first (=latest) line only
417 $undoTooltip = $latest
418 ? [ 'title' => $this->msg( 'tooltip-undo' )->text() ]
419 : [];
420 $undolink = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
421 $this->getTitle(),
422 $this->msg( 'editundo' )->text(),
423 $undoTooltip,
424 [
425 'action' => 'edit',
426 'undoafter' => $prevRev->getId(),
427 'undo' => $rev->getId()
428 ]
429 );
430 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
431 }
432 }
433 // Allow extension to add their own links here
434 Hooks::run( 'HistoryRevisionTools', [ $rev, &$tools, $prevRev, $user ] );
435
436 if ( $tools ) {
437 $s2 .= ' ' . Html::openElement( 'span', [ 'class' => 'mw-changeslist-links' ] );
438 foreach ( $tools as $tool ) {
439 $s2 .= Html::rawElement( 'span', [], $tool );
440 }
441 $s2 .= Html::closeElement( 'span' );
442 }
443
444 # Tags
445 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
446 $row->ts_tags,
447 'history',
448 $this->getContext()
449 );
450 $classes = array_merge( $classes, $newClasses );
451 if ( $tagSummary !== '' ) {
452 $s2 .= " $tagSummary";
453 }
454
455 # Include separator between character difference and following text
456 if ( $s2 !== '' ) {
457 $s .= ' <span class="mw-changeslist-separator"></span> ' . $s2;
458 }
459
460 $attribs = [ 'data-mw-revid' => $rev->getId() ];
461
462 Hooks::run( 'PageHistoryLineEnding', [ $this, &$row, &$s, &$classes, &$attribs ] );
463 $attribs = array_filter( $attribs,
464 [ Sanitizer::class, 'isReservedDataAttribute' ],
465 ARRAY_FILTER_USE_KEY
466 );
467
468 if ( $classes ) {
469 $attribs['class'] = implode( ' ', $classes );
470 }
471
472 return Xml::tags( 'li', $attribs, $s ) . "\n";
473 }
474
475 /**
476 * Create a link to view this revision of the page
477 *
478 * @param Revision $rev
479 * @return string
480 */
481 function revLink( $rev ) {
482 return ChangesList::revDateLink( $rev, $this->getUser(), $this->getLanguage(),
483 $this->getTitle() );
484 }
485
486 /**
487 * Create a diff-to-current link for this revision for this page
488 *
489 * @param Revision $rev
490 * @return string
491 */
492 function curLink( $rev ) {
493 $cur = $this->historyPage->message['cur'];
494 $latest = $this->getWikiPage()->getLatest();
495 if ( $latest === $rev->getId()
496 || !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() )
497 ) {
498 return $cur;
499 } else {
500 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
501 $this->getTitle(),
502 new HtmlArmor( $cur ),
503 [],
504 [
505 'diff' => $latest,
506 'oldid' => $rev->getId()
507 ]
508 );
509 }
510 }
511
512 /**
513 * Create a diff-to-previous link for this revision for this page.
514 *
515 * @param Revision $prevRev The revision being displayed
516 * @param stdClass|string|null $next The next revision in list (that is
517 * the previous one in chronological order).
518 * May either be a row, "unknown" or null.
519 * @return string
520 */
521 function lastLink( $prevRev, $next ) {
522 $last = $this->historyPage->message['last'];
523
524 if ( $next === null ) {
525 # Probably no next row
526 return $last;
527 }
528
529 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
530 if ( $next === 'unknown' ) {
531 # Next row probably exists but is unknown, use an oldid=prev link
532 return $linkRenderer->makeKnownLink(
533 $this->getTitle(),
534 new HtmlArmor( $last ),
535 [],
536 [
537 'diff' => $prevRev->getId(),
538 'oldid' => 'prev'
539 ]
540 );
541 }
542
543 $nextRev = new Revision( $next, 0, $this->getTitle() );
544
545 if ( !$prevRev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() )
546 || !$nextRev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() )
547 ) {
548 return $last;
549 }
550
551 return $linkRenderer->makeKnownLink(
552 $this->getTitle(),
553 new HtmlArmor( $last ),
554 [],
555 [
556 'diff' => $prevRev->getId(),
557 'oldid' => $next->rev_id
558 ]
559 );
560 }
561
562 /**
563 * Create radio buttons for page history
564 *
565 * @param Revision $rev
566 * @param bool $firstInList Is this version the first one?
567 *
568 * @return string HTML output for the radio buttons
569 */
570 function diffButtons( $rev, $firstInList ) {
571 if ( $this->getNumRows() > 1 ) {
572 $id = $rev->getId();
573 $radio = [ 'type' => 'radio', 'value' => $id ];
574 /** @todo Move title texts to javascript */
575 if ( $firstInList ) {
576 $first = Xml::element( 'input',
577 array_merge( $radio, [
578 'style' => 'visibility:hidden',
579 'name' => 'oldid',
580 'id' => 'mw-oldid-null' ] )
581 );
582 $checkmark = [ 'checked' => 'checked' ];
583 } else {
584 # Check visibility of old revisions
585 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() ) ) {
586 $radio['disabled'] = 'disabled';
587 $checkmark = []; // We will check the next possible one
588 } elseif ( !$this->oldIdChecked ) {
589 $checkmark = [ 'checked' => 'checked' ];
590 $this->oldIdChecked = $id;
591 } else {
592 $checkmark = [];
593 }
594 $first = Xml::element( 'input',
595 array_merge( $radio, $checkmark, [
596 'name' => 'oldid',
597 'id' => "mw-oldid-$id" ] ) );
598 $checkmark = [];
599 }
600 $second = Xml::element( 'input',
601 array_merge( $radio, $checkmark, [
602 'name' => 'diff',
603 'id' => "mw-diff-$id" ] ) );
604
605 return $first . $second;
606 } else {
607 return '';
608 }
609 }
610
611 /**
612 * @inheritDoc
613 */
614 function getDefaultQuery() {
615 parent::getDefaultQuery();
616 unset( $this->mDefaultQuery['date-range-to'] );
617 return $this->mDefaultQuery;
618 }
619
620 /**
621 * This is called if a write operation is possible from the generated HTML
622 * @param bool $enable
623 */
624 function preventClickjacking( $enable = true ) {
625 $this->preventClickjacking = $enable;
626 }
627
628 /**
629 * Get the "prevent clickjacking" flag
630 * @return bool
631 */
632 function getPreventClickjacking() {
633 return $this->preventClickjacking;
634 }
635
636 }