Don't show tools on history view when no revisions can be shown
[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 $latest = ( $this->counter == 1 && $this->mIsFirst );
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(
135 $this->lastRow, $row, $notifTimestamp, $latest, $firstInList );
136 } else {
137 $s = '';
138 }
139 $this->lastRow = $row;
140
141 return $s;
142 }
143
144 protected function doBatchLookups() {
145 if ( !Hooks::run( 'PageHistoryPager::doBatchLookups', [ $this, $this->mResult ] ) ) {
146 return;
147 }
148
149 # Do a link batch query
150 $this->mResult->seek( 0 );
151 $batch = new LinkBatch();
152 $revIds = [];
153 foreach ( $this->mResult as $row ) {
154 if ( $row->rev_parent_id ) {
155 $revIds[] = $row->rev_parent_id;
156 }
157 if ( $row->user_name !== null ) {
158 $batch->add( NS_USER, $row->user_name );
159 $batch->add( NS_USER_TALK, $row->user_name );
160 } else { # for anons or usernames of imported revisions
161 $batch->add( NS_USER, $row->rev_user_text );
162 $batch->add( NS_USER_TALK, $row->rev_user_text );
163 }
164 }
165 $this->parentLens = Revision::getParentLengths( $this->mDb, $revIds );
166 $batch->execute();
167 $this->mResult->seek( 0 );
168 }
169
170 /**
171 * Creates begin of history list with a submit button
172 *
173 * @return string HTML output
174 */
175 protected function getStartBody() {
176 $this->lastRow = false;
177 $this->counter = 1;
178 $this->oldIdChecked = 0;
179
180 $this->getOutput()->wrapWikiMsg( "<div class='mw-history-legend'>\n$1\n</div>", 'histlegend' );
181 $s = Html::openElement( 'form', [ 'action' => wfScript(),
182 'id' => 'mw-history-compare' ] ) . "\n";
183 $s .= Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) . "\n";
184 $s .= Html::hidden( 'action', 'historysubmit' ) . "\n";
185 $s .= Html::hidden( 'type', 'revision' ) . "\n";
186
187 // Button container stored in $this->buttons for re-use in getEndBody()
188 $this->buttons = '';
189 if ( $this->getNumRows() > 0 ) {
190 $this->buttons .= Html::openElement(
191 'div', [ 'class' => 'mw-history-compareselectedversions' ] );
192 $className = 'historysubmit mw-history-compareselectedversions-button';
193 $attrs = [ 'class' => $className ]
194 + Linker::tooltipAndAccesskeyAttribs( 'compareselectedversions' );
195 $this->buttons .= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
196 $attrs
197 ) . "\n";
198
199 $user = $this->getUser();
200 $actionButtons = '';
201 if ( $user->isAllowed( 'deleterevision' ) ) {
202 $actionButtons .= $this->getRevisionButton(
203 'revisiondelete', 'showhideselectedversions' );
204 }
205 if ( $this->showTagEditUI ) {
206 $actionButtons .= $this->getRevisionButton(
207 'editchangetags', 'history-edit-tags' );
208 }
209 if ( $actionButtons ) {
210 $this->buttons .= Xml::tags( 'div', [ 'class' =>
211 'mw-history-revisionactions' ], $actionButtons );
212 }
213
214 if ( $user->isAllowed( 'deleterevision' ) || $this->showTagEditUI ) {
215 $this->buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
216 }
217
218 $this->buttons .= '</div>';
219
220 $s .= $this->buttons;
221 }
222 $s .= '<ul id="pagehistory">' . "\n";
223
224 return $s;
225 }
226
227 private function getRevisionButton( $name, $msg ) {
228 $this->preventClickjacking();
229 # Note T22966, <button> is non-standard in IE<8
230 $element = Html::element(
231 'button',
232 [
233 'type' => 'submit',
234 'name' => $name,
235 'value' => '1',
236 'class' => "historysubmit mw-history-$name-button",
237 ],
238 $this->msg( $msg )->text()
239 ) . "\n";
240 return $element;
241 }
242
243 protected function getEndBody() {
244 if ( $this->lastRow ) {
245 $latest = $this->counter == 1 && $this->mIsFirst;
246 $firstInList = $this->counter == 1;
247 if ( $this->mIsBackwards ) {
248 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
249 if ( $this->mOffset == '' ) {
250 $next = null;
251 } else {
252 $next = 'unknown';
253 }
254 } else {
255 # The next row is the past-the-end row
256 $next = $this->mPastTheEndRow;
257 }
258 $this->counter++;
259
260 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
261 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
262 : false;
263
264 $s = $this->historyLine(
265 $this->lastRow, $next, $notifTimestamp, $latest, $firstInList );
266 } else {
267 $s = '';
268 }
269 $s .= "</ul>\n";
270 # Add second buttons only if there is more than one rev
271 if ( $this->getNumRows() > 2 ) {
272 $s .= $this->buttons;
273 }
274 $s .= '</form>';
275
276 return $s;
277 }
278
279 /**
280 * Creates a submit button
281 *
282 * @param string $message Text of the submit button, will be escaped
283 * @param array $attributes
284 * @return string HTML output for the submit button
285 */
286 function submitButton( $message, $attributes = [] ) {
287 # Disable submit button if history has 1 revision only
288 if ( $this->getNumRows() > 1 ) {
289 return Html::submitButton( $message, $attributes );
290 } else {
291 return '';
292 }
293 }
294
295 /**
296 * Returns a row from the history printout.
297 *
298 * @todo document some more, and maybe clean up the code (some params redundant?)
299 *
300 * @param stdClass $row The database row corresponding to the previous line.
301 * @param mixed $next The database row corresponding to the next line
302 * (chronologically previous)
303 * @param bool|string $notificationtimestamp
304 * @param bool $latest Whether this row corresponds to the page's latest revision.
305 * @param bool $firstInList Whether this row corresponds to the first
306 * displayed on this history page.
307 * @return string HTML output for the row
308 */
309 function historyLine( $row, $next, $notificationtimestamp = false,
310 $latest = false, $firstInList = false ) {
311 $rev = new Revision( $row, 0, $this->getTitle() );
312
313 if ( is_object( $next ) ) {
314 $prevRev = new Revision( $next, 0, $this->getTitle() );
315 } else {
316 $prevRev = null;
317 }
318
319 $curlink = $this->curLink( $rev, $latest );
320 $lastlink = $this->lastLink( $rev, $next );
321 $curLastlinks = Html::rawElement( 'span', [], $curlink ) .
322 Html::rawElement( 'span', [], $lastlink );
323 $histLinks = Html::rawElement(
324 'span',
325 [ 'class' => 'mw-history-histlinks mw-changeslist-links' ],
326 $curLastlinks
327 );
328
329 $diffButtons = $this->diffButtons( $rev, $firstInList );
330 $s = $histLinks . $diffButtons;
331
332 $link = $this->revLink( $rev );
333 $classes = [];
334
335 $del = '';
336 $user = $this->getUser();
337 $canRevDelete = $user->isAllowed( 'deleterevision' );
338 // Show checkboxes for each revision, to allow for revision deletion and
339 // change tags
340 if ( $canRevDelete || $this->showTagEditUI ) {
341 $this->preventClickjacking();
342 // If revision was hidden from sysops and we don't need the checkbox
343 // for anything else, disable it
344 if ( !$this->showTagEditUI && !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
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( Revision::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( Revision::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( Revision::DELETED_TEXT )
416 && !$prevRev->isDeleted( Revision::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 * @param bool $latest This is the latest revision of the page?
493 * @return string
494 */
495 function curLink( $rev, $latest ) {
496 $cur = $this->historyPage->message['cur'];
497 if ( $latest || !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
498 return $cur;
499 } else {
500 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
501 $this->getTitle(),
502 new HtmlArmor( $cur ),
503 [],
504 [
505 'diff' => $this->getWikiPage()->getLatest(),
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( Revision::DELETED_TEXT, $this->getUser() )
546 || !$nextRev->userCan( Revision::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( Revision::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 }