Correctly distinguish the latest revision in action=history
[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 = Html::openElement( 'div', [ 'class' => 'mw-history-compareselectedversions' ] );
187 $className = 'historysubmit mw-history-compareselectedversions-button';
188 $attrs = [ 'class' => $className ]
189 + Linker::tooltipAndAccesskeyAttribs( 'compareselectedversions' );
190 $this->buttons .= $this->submitButton( $this->msg( 'compareselectedversions' )->text(),
191 $attrs
192 ) . "\n";
193
194 $user = $this->getUser();
195 $actionButtons = '';
196 if ( $user->isAllowed( 'deleterevision' ) ) {
197 $actionButtons .= $this->getRevisionButton( 'revisiondelete', 'showhideselectedversions' );
198 }
199 if ( $this->showTagEditUI ) {
200 $actionButtons .= $this->getRevisionButton( 'editchangetags', 'history-edit-tags' );
201 }
202 if ( $actionButtons ) {
203 $this->buttons .= Xml::tags( 'div', [ 'class' =>
204 'mw-history-revisionactions' ], $actionButtons );
205 }
206
207 if ( $user->isAllowed( 'deleterevision' ) || $this->showTagEditUI ) {
208 $this->buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
209 }
210
211 $this->buttons .= '</div>';
212
213 $s .= $this->buttons;
214 $s .= '<ul id="pagehistory">' . "\n";
215
216 return $s;
217 }
218
219 private function getRevisionButton( $name, $msg ) {
220 $this->preventClickjacking();
221 # Note T22966, <button> is non-standard in IE<8
222 $element = Html::element(
223 'button',
224 [
225 'type' => 'submit',
226 'name' => $name,
227 'value' => '1',
228 'class' => "historysubmit mw-history-$name-button",
229 ],
230 $this->msg( $msg )->text()
231 ) . "\n";
232 return $element;
233 }
234
235 protected function getEndBody() {
236 if ( $this->lastRow ) {
237 $firstInList = $this->counter == 1;
238 if ( $this->mIsBackwards ) {
239 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
240 if ( $this->mOffset == '' ) {
241 $next = null;
242 } else {
243 $next = 'unknown';
244 }
245 } else {
246 # The next row is the past-the-end row
247 $next = $this->mPastTheEndRow;
248 }
249 $this->counter++;
250
251 $notifTimestamp = $this->getConfig()->get( 'ShowUpdatedMarker' )
252 ? $this->getTitle()->getNotificationTimestamp( $this->getUser() )
253 : false;
254
255 $s = $this->historyLine( $this->lastRow, $next, $notifTimestamp, false, $firstInList );
256 } else {
257 $s = '';
258 }
259 $s .= "</ul>\n";
260 # Add second buttons only if there is more than one rev
261 if ( $this->getNumRows() > 2 ) {
262 $s .= $this->buttons;
263 }
264 $s .= '</form>';
265
266 return $s;
267 }
268
269 /**
270 * Creates a submit button
271 *
272 * @param string $message Text of the submit button, will be escaped
273 * @param array $attributes
274 * @return string HTML output for the submit button
275 */
276 function submitButton( $message, $attributes = [] ) {
277 # Disable submit button if history has 1 revision only
278 if ( $this->getNumRows() > 1 ) {
279 return Html::submitButton( $message, $attributes );
280 } else {
281 return '';
282 }
283 }
284
285 /**
286 * Returns a row from the history printout.
287 *
288 * @todo document some more, and maybe clean up the code (some params redundant?)
289 *
290 * @param stdClass $row The database row corresponding to the previous line.
291 * @param mixed $next The database row corresponding to the next line
292 * (chronologically previous)
293 * @param bool|string $notificationtimestamp
294 * @param bool $dummy Unused.
295 * @param bool $firstInList Whether this row corresponds to the first
296 * displayed on this history page.
297 * @return string HTML output for the row
298 */
299 function historyLine( $row, $next, $notificationtimestamp = false,
300 $dummy = false, $firstInList = false ) {
301 $rev = new Revision( $row, 0, $this->getTitle() );
302
303 if ( is_object( $next ) ) {
304 $prevRev = new Revision( $next, 0, $this->getTitle() );
305 } else {
306 $prevRev = null;
307 }
308
309 $latest = $rev->getId() === $this->getWikiPage()->getLatest();
310 $curlink = $this->curLink( $rev );
311 $lastlink = $this->lastLink( $rev, $next );
312 $curLastlinks = Html::rawElement( 'span', [], $curlink ) .
313 Html::rawElement( 'span', [], $lastlink );
314 $histLinks = Html::rawElement(
315 'span',
316 [ 'class' => 'mw-history-histlinks mw-changeslist-links' ],
317 $curLastlinks
318 );
319
320 $diffButtons = $this->diffButtons( $rev, $firstInList );
321 $s = $histLinks . $diffButtons;
322
323 $link = $this->revLink( $rev );
324 $classes = [];
325
326 $del = '';
327 $user = $this->getUser();
328 $canRevDelete = $user->isAllowed( 'deleterevision' );
329 // Show checkboxes for each revision, to allow for revision deletion and
330 // change tags
331 if ( $canRevDelete || $this->showTagEditUI ) {
332 $this->preventClickjacking();
333 // If revision was hidden from sysops and we don't need the checkbox
334 // for anything else, disable it
335 if ( !$this->showTagEditUI && !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
336 $del = Xml::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
337 // Otherwise, enable the checkbox...
338 } else {
339 $del = Xml::check( 'showhiderevisions', false,
340 [ 'name' => 'ids[' . $rev->getId() . ']' ] );
341 }
342 // User can only view deleted revisions...
343 } elseif ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) {
344 // If revision was hidden from sysops, disable the link
345 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
346 $del = Linker::revDeleteLinkDisabled( false );
347 // Otherwise, show the link...
348 } else {
349 $query = [ 'type' => 'revision',
350 'target' => $this->getTitle()->getPrefixedDBkey(), 'ids' => $rev->getId() ];
351 $del .= Linker::revDeleteLink( $query,
352 $rev->isDeleted( Revision::DELETED_RESTRICTED ), false );
353 }
354 }
355 if ( $del ) {
356 $s .= " $del ";
357 }
358
359 $lang = $this->getLanguage();
360 $dirmark = $lang->getDirMark();
361
362 $s .= " $link";
363 $s .= $dirmark;
364 $s .= " <span class='history-user'>" .
365 Linker::revUserTools( $rev, true, false ) . "</span>";
366 $s .= $dirmark;
367
368 if ( $rev->isMinor() ) {
369 $s .= ' ' . ChangesList::flag( 'minor', $this->getContext() );
370 }
371
372 # Sometimes rev_len isn't populated
373 if ( $rev->getSize() !== null ) {
374 # Size is always public data
375 $prevSize = $this->parentLens[$row->rev_parent_id] ?? 0;
376 $sDiff = ChangesList::showCharacterDifference( $prevSize, $rev->getSize() );
377 $fSize = Linker::formatRevisionSize( $rev->getSize(), false );
378 $s .= ' <span class="mw-changeslist-separator"></span> ' . "$fSize $sDiff";
379 }
380
381 # Text following the character difference is added just before running hooks
382 $s2 = Linker::revComment( $rev, false, true, false );
383
384 if ( $notificationtimestamp && ( $row->rev_timestamp >= $notificationtimestamp ) ) {
385 $s2 .= ' <span class="updatedmarker">' . $this->msg( 'updatedmarker' )->escaped() . '</span>';
386 $classes[] = 'mw-history-line-updated';
387 }
388
389 $tools = [];
390
391 # Rollback and undo links
392 if ( $prevRev && $this->getTitle()->quickUserCan( 'edit', $user ) ) {
393 if ( $latest && $this->getTitle()->quickUserCan( 'rollback', $user ) ) {
394 // Get a rollback link without the brackets
395 $rollbackLink = Linker::generateRollback(
396 $rev,
397 $this->getContext(),
398 [ 'verify', 'noBrackets' ]
399 );
400 if ( $rollbackLink ) {
401 $this->preventClickjacking();
402 $tools[] = $rollbackLink;
403 }
404 }
405
406 if ( !$rev->isDeleted( Revision::DELETED_TEXT )
407 && !$prevRev->isDeleted( Revision::DELETED_TEXT )
408 ) {
409 # Create undo tooltip for the first (=latest) line only
410 $undoTooltip = $latest
411 ? [ 'title' => $this->msg( 'tooltip-undo' )->text() ]
412 : [];
413 $undolink = MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
414 $this->getTitle(),
415 $this->msg( 'editundo' )->text(),
416 $undoTooltip,
417 [
418 'action' => 'edit',
419 'undoafter' => $prevRev->getId(),
420 'undo' => $rev->getId()
421 ]
422 );
423 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
424 }
425 }
426 // Allow extension to add their own links here
427 Hooks::run( 'HistoryRevisionTools', [ $rev, &$tools, $prevRev, $user ] );
428
429 if ( $tools ) {
430 $s2 .= ' ' . Html::openElement( 'span', [ 'class' => 'mw-changeslist-links' ] );
431 foreach ( $tools as $tool ) {
432 $s2 .= Html::rawElement( 'span', [], $tool );
433 }
434 $s2 .= Html::closeElement( 'span' );
435 }
436
437 # Tags
438 list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
439 $row->ts_tags,
440 'history',
441 $this->getContext()
442 );
443 $classes = array_merge( $classes, $newClasses );
444 if ( $tagSummary !== '' ) {
445 $s2 .= " $tagSummary";
446 }
447
448 # Include separator between character difference and following text
449 if ( $s2 !== '' ) {
450 $s .= ' <span class="mw-changeslist-separator"></span> ' . $s2;
451 }
452
453 $attribs = [ 'data-mw-revid' => $rev->getId() ];
454
455 Hooks::run( 'PageHistoryLineEnding', [ $this, &$row, &$s, &$classes, &$attribs ] );
456 $attribs = array_filter( $attribs,
457 [ Sanitizer::class, 'isReservedDataAttribute' ],
458 ARRAY_FILTER_USE_KEY
459 );
460
461 if ( $classes ) {
462 $attribs['class'] = implode( ' ', $classes );
463 }
464
465 return Xml::tags( 'li', $attribs, $s ) . "\n";
466 }
467
468 /**
469 * Create a link to view this revision of the page
470 *
471 * @param Revision $rev
472 * @return string
473 */
474 function revLink( $rev ) {
475 return ChangesList::revDateLink( $rev, $this->getUser(), $this->getLanguage(),
476 $this->getTitle() );
477 }
478
479 /**
480 * Create a diff-to-current link for this revision for this page
481 *
482 * @param Revision $rev
483 * @return string
484 */
485 function curLink( $rev ) {
486 $cur = $this->historyPage->message['cur'];
487 $latest = $this->getWikiPage()->getLatest();
488 if ( $latest === $rev->getId() || !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
489 return $cur;
490 } else {
491 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
492 $this->getTitle(),
493 new HtmlArmor( $cur ),
494 [],
495 [
496 'diff' => $latest,
497 'oldid' => $rev->getId()
498 ]
499 );
500 }
501 }
502
503 /**
504 * Create a diff-to-previous link for this revision for this page.
505 *
506 * @param Revision $prevRev The revision being displayed
507 * @param stdClass|string|null $next The next revision in list (that is
508 * the previous one in chronological order).
509 * May either be a row, "unknown" or null.
510 * @return string
511 */
512 function lastLink( $prevRev, $next ) {
513 $last = $this->historyPage->message['last'];
514
515 if ( $next === null ) {
516 # Probably no next row
517 return $last;
518 }
519
520 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
521 if ( $next === 'unknown' ) {
522 # Next row probably exists but is unknown, use an oldid=prev link
523 return $linkRenderer->makeKnownLink(
524 $this->getTitle(),
525 new HtmlArmor( $last ),
526 [],
527 [
528 'diff' => $prevRev->getId(),
529 'oldid' => 'prev'
530 ]
531 );
532 }
533
534 $nextRev = new Revision( $next, 0, $this->getTitle() );
535
536 if ( !$prevRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
537 || !$nextRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
538 ) {
539 return $last;
540 }
541
542 return $linkRenderer->makeKnownLink(
543 $this->getTitle(),
544 new HtmlArmor( $last ),
545 [],
546 [
547 'diff' => $prevRev->getId(),
548 'oldid' => $next->rev_id
549 ]
550 );
551 }
552
553 /**
554 * Create radio buttons for page history
555 *
556 * @param Revision $rev
557 * @param bool $firstInList Is this version the first one?
558 *
559 * @return string HTML output for the radio buttons
560 */
561 function diffButtons( $rev, $firstInList ) {
562 if ( $this->getNumRows() > 1 ) {
563 $id = $rev->getId();
564 $radio = [ 'type' => 'radio', 'value' => $id ];
565 /** @todo Move title texts to javascript */
566 if ( $firstInList ) {
567 $first = Xml::element( 'input',
568 array_merge( $radio, [
569 'style' => 'visibility:hidden',
570 'name' => 'oldid',
571 'id' => 'mw-oldid-null' ] )
572 );
573 $checkmark = [ 'checked' => 'checked' ];
574 } else {
575 # Check visibility of old revisions
576 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
577 $radio['disabled'] = 'disabled';
578 $checkmark = []; // We will check the next possible one
579 } elseif ( !$this->oldIdChecked ) {
580 $checkmark = [ 'checked' => 'checked' ];
581 $this->oldIdChecked = $id;
582 } else {
583 $checkmark = [];
584 }
585 $first = Xml::element( 'input',
586 array_merge( $radio, $checkmark, [
587 'name' => 'oldid',
588 'id' => "mw-oldid-$id" ] ) );
589 $checkmark = [];
590 }
591 $second = Xml::element( 'input',
592 array_merge( $radio, $checkmark, [
593 'name' => 'diff',
594 'id' => "mw-diff-$id" ] ) );
595
596 return $first . $second;
597 } else {
598 return '';
599 }
600 }
601
602 /**
603 * @inheritDoc
604 */
605 function getDefaultQuery() {
606 parent::getDefaultQuery();
607 unset( $this->mDefaultQuery['date-range-to'] );
608 return $this->mDefaultQuery;
609 }
610
611 /**
612 * This is called if a write operation is possible from the generated HTML
613 * @param bool $enable
614 */
615 function preventClickjacking( $enable = true ) {
616 $this->preventClickjacking = $enable;
617 }
618
619 /**
620 * Get the "prevent clickjacking" flag
621 * @return bool
622 */
623 function getPreventClickjacking() {
624 return $this->preventClickjacking;
625 }
626
627 }