Merge "Allow partially blocked users to tag unrelated revisions"
[lhc/web/wiklou.git] / includes / specials / SpecialUndelete.php
1 <?php
2 /**
3 * Implements Special:Undelete
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 SpecialPage
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Revision\RevisionRecord;
26 use MediaWiki\Storage\NameTableAccessException;
27 use Wikimedia\Rdbms\IResultWrapper;
28
29 /**
30 * Special page allowing users with the appropriate permissions to view
31 * and restore deleted content.
32 *
33 * @ingroup SpecialPage
34 */
35 class SpecialUndelete extends SpecialPage {
36 private $mAction;
37 private $mTarget;
38 private $mTimestamp;
39 private $mRestore;
40 private $mRevdel;
41 private $mInvert;
42 private $mFilename;
43 private $mTargetTimestamp;
44 private $mAllowed;
45 private $mCanView;
46 private $mComment;
47 private $mToken;
48 /** @var bool|null */
49 private $mPreview;
50 /** @var bool|null */
51 private $mDiff;
52 /** @var bool|null */
53 private $mDiffOnly;
54 /** @var bool|null */
55 private $mUnsuppress;
56 /** @var int[]|null */
57 private $mFileVersions;
58
59 /** @var Title */
60 private $mTargetObj;
61 /**
62 * @var string Search prefix
63 */
64 private $mSearchPrefix;
65
66 function __construct() {
67 parent::__construct( 'Undelete', 'deletedhistory' );
68 }
69
70 public function doesWrites() {
71 return true;
72 }
73
74 function loadRequest( $par ) {
75 $request = $this->getRequest();
76 $user = $this->getUser();
77
78 $this->mAction = $request->getVal( 'action' );
79 if ( $par !== null && $par !== '' ) {
80 $this->mTarget = $par;
81 } else {
82 $this->mTarget = $request->getVal( 'target' );
83 }
84
85 $this->mTargetObj = null;
86
87 if ( $this->mTarget !== null && $this->mTarget !== '' ) {
88 $this->mTargetObj = Title::newFromText( $this->mTarget );
89 }
90
91 $this->mSearchPrefix = $request->getText( 'prefix' );
92 $time = $request->getVal( 'timestamp' );
93 $this->mTimestamp = $time ? wfTimestamp( TS_MW, $time ) : '';
94 $this->mFilename = $request->getVal( 'file' );
95
96 $posted = $request->wasPosted() &&
97 $user->matchEditToken( $request->getVal( 'wpEditToken' ) );
98 $this->mRestore = $request->getCheck( 'restore' ) && $posted;
99 $this->mRevdel = $request->getCheck( 'revdel' ) && $posted;
100 $this->mInvert = $request->getCheck( 'invert' ) && $posted;
101 $this->mPreview = $request->getCheck( 'preview' ) && $posted;
102 $this->mDiff = $request->getCheck( 'diff' );
103 $this->mDiffOnly = $request->getBool( 'diffonly', $this->getUser()->getOption( 'diffonly' ) );
104 $this->mComment = $request->getText( 'wpComment' );
105 $this->mUnsuppress = $request->getVal( 'wpUnsuppress' ) && $user->isAllowed( 'suppressrevision' );
106 $this->mToken = $request->getVal( 'token' );
107
108 $block = $user->getBlock();
109 if ( $this->isAllowed( 'undelete' ) && !( $block && $block->isSitewide() ) ) {
110 $this->mAllowed = true; // user can restore
111 $this->mCanView = true; // user can view content
112 } elseif ( $this->isAllowed( 'deletedtext' ) ) {
113 $this->mAllowed = false; // user cannot restore
114 $this->mCanView = true; // user can view content
115 $this->mRestore = false;
116 } else { // user can only view the list of revisions
117 $this->mAllowed = false;
118 $this->mCanView = false;
119 $this->mTimestamp = '';
120 $this->mRestore = false;
121 }
122
123 if ( $this->mRestore || $this->mInvert ) {
124 $timestamps = [];
125 $this->mFileVersions = [];
126 foreach ( $request->getValues() as $key => $val ) {
127 $matches = [];
128 if ( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
129 array_push( $timestamps, $matches[1] );
130 }
131
132 if ( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
133 $this->mFileVersions[] = intval( $matches[1] );
134 }
135 }
136 rsort( $timestamps );
137 $this->mTargetTimestamp = $timestamps;
138 }
139 }
140
141 /**
142 * Checks whether a user is allowed the permission for the
143 * specific title if one is set.
144 *
145 * @param string $permission
146 * @param User|null $user
147 * @return bool
148 */
149 protected function isAllowed( $permission, User $user = null ) {
150 $user = $user ?: $this->getUser();
151 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
152
153 if ( $this->mTargetObj !== null ) {
154 return $permissionManager->userCan( $permission, $user, $this->mTargetObj );
155 } else {
156 return $user->isAllowed( $permission );
157 }
158 }
159
160 function userCanExecute( User $user ) {
161 return $this->isAllowed( $this->mRestriction, $user );
162 }
163
164 function execute( $par ) {
165 $this->useTransactionalTimeLimit();
166
167 $user = $this->getUser();
168
169 $this->setHeaders();
170 $this->outputHeader();
171 $this->addHelpLink( 'Help:Deletion_and_undeletion' );
172
173 $this->loadRequest( $par );
174 $this->checkPermissions(); // Needs to be after mTargetObj is set
175
176 $out = $this->getOutput();
177
178 if ( is_null( $this->mTargetObj ) ) {
179 $out->addWikiMsg( 'undelete-header' );
180
181 # Not all users can just browse every deleted page from the list
182 if ( $user->isAllowed( 'browsearchive' ) ) {
183 $this->showSearchForm();
184 }
185
186 return;
187 }
188
189 $this->addHelpLink( 'Help:Undelete' );
190 if ( $this->mAllowed ) {
191 $out->setPageTitle( $this->msg( 'undeletepage' ) );
192 } else {
193 $out->setPageTitle( $this->msg( 'viewdeletedpage' ) );
194 }
195
196 $this->getSkin()->setRelevantTitle( $this->mTargetObj );
197
198 if ( $this->mTimestamp !== '' ) {
199 $this->showRevision( $this->mTimestamp );
200 } elseif ( $this->mFilename !== null && $this->mTargetObj->inNamespace( NS_FILE ) ) {
201 $file = new ArchivedFile( $this->mTargetObj, 0, $this->mFilename );
202 // Check if user is allowed to see this file
203 if ( !$file->exists() ) {
204 $out->addWikiMsg( 'filedelete-nofile', $this->mFilename );
205 } elseif ( !$file->userCan( File::DELETED_FILE, $user ) ) {
206 if ( $file->isDeleted( File::DELETED_RESTRICTED ) ) {
207 throw new PermissionsError( 'suppressrevision' );
208 } else {
209 throw new PermissionsError( 'deletedtext' );
210 }
211 } elseif ( !$user->matchEditToken( $this->mToken, $this->mFilename ) ) {
212 $this->showFileConfirmationForm( $this->mFilename );
213 } else {
214 $this->showFile( $this->mFilename );
215 }
216 } elseif ( $this->mAction === 'submit' ) {
217 if ( $this->mRestore ) {
218 $this->undelete();
219 } elseif ( $this->mRevdel ) {
220 $this->redirectToRevDel();
221 }
222
223 } else {
224 $this->showHistory();
225 }
226 }
227
228 /**
229 * Convert submitted form data to format expected by RevisionDelete and
230 * redirect the request
231 */
232 private function redirectToRevDel() {
233 $archive = new PageArchive( $this->mTargetObj );
234
235 $revisions = [];
236
237 foreach ( $this->getRequest()->getValues() as $key => $val ) {
238 $matches = [];
239 if ( preg_match( "/^ts(\d{14})$/", $key, $matches ) ) {
240 $revisions[$archive->getRevision( $matches[1] )->getId()] = 1;
241 }
242 }
243
244 $query = [
245 'type' => 'revision',
246 'ids' => $revisions,
247 'target' => $this->mTargetObj->getPrefixedText()
248 ];
249 $url = SpecialPage::getTitleFor( 'Revisiondelete' )->getFullURL( $query );
250 $this->getOutput()->redirect( $url );
251 }
252
253 function showSearchForm() {
254 $out = $this->getOutput();
255 $out->setPageTitle( $this->msg( 'undelete-search-title' ) );
256 $fuzzySearch = $this->getRequest()->getVal( 'fuzzy', true );
257
258 $out->enableOOUI();
259
260 $fields = [];
261 $fields[] = new OOUI\ActionFieldLayout(
262 new OOUI\TextInputWidget( [
263 'name' => 'prefix',
264 'inputId' => 'prefix',
265 'infusable' => true,
266 'value' => $this->mSearchPrefix,
267 'autofocus' => true,
268 ] ),
269 new OOUI\ButtonInputWidget( [
270 'label' => $this->msg( 'undelete-search-submit' )->text(),
271 'flags' => [ 'primary', 'progressive' ],
272 'inputId' => 'searchUndelete',
273 'type' => 'submit',
274 ] ),
275 [
276 'label' => new OOUI\HtmlSnippet(
277 $this->msg(
278 $fuzzySearch ? 'undelete-search-full' : 'undelete-search-prefix'
279 )->parse()
280 ),
281 'align' => 'left',
282 ]
283 );
284
285 $fieldset = new OOUI\FieldsetLayout( [
286 'label' => $this->msg( 'undelete-search-box' )->text(),
287 'items' => $fields,
288 ] );
289
290 $form = new OOUI\FormLayout( [
291 'method' => 'get',
292 'action' => wfScript(),
293 ] );
294
295 $form->appendContent(
296 $fieldset,
297 new OOUI\HtmlSnippet(
298 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
299 Html::hidden( 'fuzzy', $fuzzySearch )
300 )
301 );
302
303 $out->addHTML(
304 new OOUI\PanelLayout( [
305 'expanded' => false,
306 'padded' => true,
307 'framed' => true,
308 'content' => $form,
309 ] )
310 );
311
312 # List undeletable articles
313 if ( $this->mSearchPrefix ) {
314 // For now, we enable search engine match only when specifically asked to
315 // by using fuzzy=1 parameter.
316 if ( $fuzzySearch ) {
317 $result = PageArchive::listPagesBySearch( $this->mSearchPrefix );
318 } else {
319 $result = PageArchive::listPagesByPrefix( $this->mSearchPrefix );
320 }
321 $this->showList( $result );
322 }
323 }
324
325 /**
326 * Generic list of deleted pages
327 *
328 * @param IResultWrapper $result
329 * @return bool
330 */
331 private function showList( $result ) {
332 $out = $this->getOutput();
333
334 if ( $result->numRows() == 0 ) {
335 $out->addWikiMsg( 'undelete-no-results' );
336
337 return false;
338 }
339
340 $out->addWikiMsg( 'undeletepagetext', $this->getLanguage()->formatNum( $result->numRows() ) );
341
342 $linkRenderer = $this->getLinkRenderer();
343 $undelete = $this->getPageTitle();
344 $out->addHTML( "<ul id='undeleteResultsList'>\n" );
345 foreach ( $result as $row ) {
346 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
347 if ( $title !== null ) {
348 $item = $linkRenderer->makeKnownLink(
349 $undelete,
350 $title->getPrefixedText(),
351 [],
352 [ 'target' => $title->getPrefixedText() ]
353 );
354 } else {
355 // The title is no longer valid, show as text
356 $item = Html::element(
357 'span',
358 [ 'class' => 'mw-invalidtitle' ],
359 Linker::getInvalidTitleDescription(
360 $this->getContext(),
361 $row->ar_namespace,
362 $row->ar_title
363 )
364 );
365 }
366 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count )->parse();
367 $out->addHTML(
368 Html::rawElement(
369 'li',
370 [ 'class' => 'undeleteResult' ],
371 "{$item} ({$revs})"
372 )
373 );
374 }
375 $result->free();
376 $out->addHTML( "</ul>\n" );
377
378 return true;
379 }
380
381 private function showRevision( $timestamp ) {
382 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
383 return;
384 }
385
386 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
387 if ( !Hooks::run( 'UndeleteForm::showRevision', [ &$archive, $this->mTargetObj ] ) ) {
388 return;
389 }
390 $rev = $archive->getRevision( $timestamp );
391
392 $out = $this->getOutput();
393 $user = $this->getUser();
394
395 if ( !$rev ) {
396 $out->addWikiMsg( 'undeleterevision-missing' );
397
398 return;
399 }
400
401 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
402 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
403 $out->wrapWikiMsg(
404 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
405 $rev->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ?
406 'rev-suppressed-text-permission' : 'rev-deleted-text-permission'
407 );
408
409 return;
410 }
411
412 $out->wrapWikiMsg(
413 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
414 $rev->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ?
415 'rev-suppressed-text-view' : 'rev-deleted-text-view'
416 );
417 $out->addHTML( '<br />' );
418 // and we are allowed to see...
419 }
420
421 if ( $this->mDiff ) {
422 $previousRev = $archive->getPreviousRevision( $timestamp );
423 if ( $previousRev ) {
424 $this->showDiff( $previousRev, $rev );
425 if ( $this->mDiffOnly ) {
426 return;
427 }
428
429 $out->addHTML( '<hr />' );
430 } else {
431 $out->addWikiMsg( 'undelete-nodiff' );
432 }
433 }
434
435 $link = $this->getLinkRenderer()->makeKnownLink(
436 $this->getPageTitle( $this->mTargetObj->getPrefixedDBkey() ),
437 $this->mTargetObj->getPrefixedText()
438 );
439
440 $lang = $this->getLanguage();
441
442 // date and time are separate parameters to facilitate localisation.
443 // $time is kept for backward compat reasons.
444 $time = $lang->userTimeAndDate( $timestamp, $user );
445 $d = $lang->userDate( $timestamp, $user );
446 $t = $lang->userTime( $timestamp, $user );
447 $userLink = Linker::revUserTools( $rev );
448
449 $content = $rev->getContent( RevisionRecord::FOR_THIS_USER, $user );
450
451 // TODO: MCR: this will have to become something like $hasTextSlots and $hasNonTextSlots
452 $isText = ( $content instanceof TextContent );
453
454 if ( $this->mPreview || $isText ) {
455 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
456 } else {
457 $openDiv = '<div id="mw-undelete-revision">';
458 }
459 $out->addHTML( $openDiv );
460
461 // Revision delete links
462 if ( !$this->mDiff ) {
463 $revdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
464 if ( $revdel ) {
465 $out->addHTML( "$revdel " );
466 }
467 }
468
469 $out->addWikiMsg(
470 'undelete-revision',
471 Message::rawParam( $link ), $time,
472 Message::rawParam( $userLink ), $d, $t
473 );
474 $out->addHTML( '</div>' );
475
476 if ( !Hooks::run( 'UndeleteShowRevision', [ $this->mTargetObj, $rev ] ) ) {
477 return;
478 }
479
480 if ( $this->mPreview || !$isText ) {
481 // NOTE: non-text content has no source view, so always use rendered preview
482
483 $popts = $out->parserOptions();
484 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
485
486 $rendered = $renderer->getRenderedRevision(
487 $rev->getRevisionRecord(),
488 $popts,
489 $user,
490 [ 'audience' => RevisionRecord::FOR_THIS_USER ]
491 );
492
493 // Fail hard if the audience check fails, since we already checked
494 // at the beginning of this method.
495 $pout = $rendered->getRevisionParserOutput();
496
497 $out->addParserOutput( $pout, [
498 'enableSectionEditLinks' => false,
499 ] );
500 }
501
502 $out->enableOOUI();
503 $buttonFields = [];
504
505 if ( $isText ) {
506 '@phan-var TextContent $content';
507 // TODO: MCR: make this work for multiple slots
508 // source view for textual content
509 $sourceView = Xml::element( 'textarea', [
510 'readonly' => 'readonly',
511 'cols' => 80,
512 'rows' => 25
513 ], $content->getText() . "\n" );
514
515 $buttonFields[] = new OOUI\ButtonInputWidget( [
516 'type' => 'submit',
517 'name' => 'preview',
518 'label' => $this->msg( 'showpreview' )->text()
519 ] );
520 } else {
521 $sourceView = '';
522 }
523
524 $buttonFields[] = new OOUI\ButtonInputWidget( [
525 'name' => 'diff',
526 'type' => 'submit',
527 'label' => $this->msg( 'showdiff' )->text()
528 ] );
529
530 $out->addHTML(
531 $sourceView .
532 Xml::openElement( 'div', [
533 'style' => 'clear: both' ] ) .
534 Xml::openElement( 'form', [
535 'method' => 'post',
536 'action' => $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] ) ] ) .
537 Xml::element( 'input', [
538 'type' => 'hidden',
539 'name' => 'target',
540 'value' => $this->mTargetObj->getPrefixedDBkey() ] ) .
541 Xml::element( 'input', [
542 'type' => 'hidden',
543 'name' => 'timestamp',
544 'value' => $timestamp ] ) .
545 Xml::element( 'input', [
546 'type' => 'hidden',
547 'name' => 'wpEditToken',
548 'value' => $user->getEditToken() ] ) .
549 new OOUI\FieldLayout(
550 new OOUI\Widget( [
551 'content' => new OOUI\HorizontalLayout( [
552 'items' => $buttonFields
553 ] )
554 ] )
555 ) .
556 Xml::closeElement( 'form' ) .
557 Xml::closeElement( 'div' )
558 );
559 }
560
561 /**
562 * Build a diff display between this and the previous either deleted
563 * or non-deleted edit.
564 *
565 * @param Revision $previousRev
566 * @param Revision $currentRev
567 */
568 function showDiff( $previousRev, $currentRev ) {
569 $diffContext = clone $this->getContext();
570 $diffContext->setTitle( $currentRev->getTitle() );
571 $diffContext->setWikiPage( WikiPage::factory( $currentRev->getTitle() ) );
572
573 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
574 $diffEngine->setRevisions( $previousRev->getRevisionRecord(), $currentRev->getRevisionRecord() );
575 $diffEngine->showDiffStyle();
576 $formattedDiff = $diffEngine->getDiff(
577 $this->diffHeader( $previousRev, 'o' ),
578 $this->diffHeader( $currentRev, 'n' )
579 );
580
581 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
582 }
583
584 /**
585 * @param Revision $rev
586 * @param string $prefix
587 * @return string
588 */
589 private function diffHeader( $rev, $prefix ) {
590 $isDeleted = !( $rev->getId() && $rev->getTitle() );
591 if ( $isDeleted ) {
592 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
593 $targetPage = $this->getPageTitle();
594 $targetQuery = [
595 'target' => $this->mTargetObj->getPrefixedText(),
596 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
597 ];
598 } else {
599 /// @todo FIXME: getId() may return non-zero for deleted revs...
600 $targetPage = $rev->getTitle();
601 $targetQuery = [ 'oldid' => $rev->getId() ];
602 }
603
604 // Add show/hide deletion links if available
605 $user = $this->getUser();
606 $lang = $this->getLanguage();
607 $rdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
608
609 if ( $rdel ) {
610 $rdel = " $rdel";
611 }
612
613 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
614
615 $tagIds = wfGetDB( DB_REPLICA )->selectFieldValues(
616 'change_tag',
617 'ct_tag_id',
618 [ 'ct_rev_id' => $rev->getId() ],
619 __METHOD__
620 );
621 $tags = [];
622 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
623 foreach ( $tagIds as $tagId ) {
624 try {
625 $tags[] = $changeTagDefStore->getName( (int)$tagId );
626 } catch ( NameTableAccessException $exception ) {
627 continue;
628 }
629 }
630 $tags = implode( ',', $tags );
631 $tagSummary = ChangeTags::formatSummaryRow( $tags, 'deleteddiff', $this->getContext() );
632
633 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
634 // and partially #showDiffPage, but worse
635 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
636 $this->getLinkRenderer()->makeLink(
637 $targetPage,
638 $this->msg(
639 'revisionasof',
640 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
641 $lang->userDate( $rev->getTimestamp(), $user ),
642 $lang->userTime( $rev->getTimestamp(), $user )
643 )->text(),
644 [],
645 $targetQuery
646 ) .
647 '</strong></div>' .
648 '<div id="mw-diff-' . $prefix . 'title2">' .
649 Linker::revUserTools( $rev ) . '<br />' .
650 '</div>' .
651 '<div id="mw-diff-' . $prefix . 'title3">' .
652 $minor . Linker::revComment( $rev ) . $rdel . '<br />' .
653 '</div>' .
654 '<div id="mw-diff-' . $prefix . 'title5">' .
655 $tagSummary[0] . '<br />' .
656 '</div>';
657 }
658
659 /**
660 * Show a form confirming whether a tokenless user really wants to see a file
661 * @param string $key
662 */
663 private function showFileConfirmationForm( $key ) {
664 $out = $this->getOutput();
665 $lang = $this->getLanguage();
666 $user = $this->getUser();
667 $file = new ArchivedFile( $this->mTargetObj, 0, $this->mFilename );
668 $out->addWikiMsg( 'undelete-show-file-confirm',
669 $this->mTargetObj->getText(),
670 $lang->userDate( $file->getTimestamp(), $user ),
671 $lang->userTime( $file->getTimestamp(), $user ) );
672 $out->addHTML(
673 Xml::openElement( 'form', [
674 'method' => 'POST',
675 'action' => $this->getPageTitle()->getLocalURL( [
676 'target' => $this->mTarget,
677 'file' => $key,
678 'token' => $user->getEditToken( $key ),
679 ] ),
680 ]
681 ) .
682 Xml::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
683 '</form>'
684 );
685 }
686
687 /**
688 * Show a deleted file version requested by the visitor.
689 * @param string $key
690 */
691 private function showFile( $key ) {
692 $this->getOutput()->disable();
693
694 # We mustn't allow the output to be CDN cached, otherwise
695 # if an admin previews a deleted image, and it's cached, then
696 # a user without appropriate permissions can toddle off and
697 # nab the image, and CDN will serve it
698 $response = $this->getRequest()->response();
699 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
700 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
701 $response->header( 'Pragma: no-cache' );
702
703 $repo = RepoGroup::singleton()->getLocalRepo();
704 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
705 $repo->streamFileWithStatus( $path );
706 }
707
708 protected function showHistory() {
709 $this->checkReadOnly();
710
711 $out = $this->getOutput();
712 if ( $this->mAllowed ) {
713 $out->addModules( 'mediawiki.special.undelete' );
714 }
715 $out->wrapWikiMsg(
716 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
717 [ 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj->getPrefixedText() ) ]
718 );
719
720 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
721 Hooks::run( 'UndeleteForm::showHistory', [ &$archive, $this->mTargetObj ] );
722
723 $out->addHTML( '<div class="mw-undelete-history">' );
724 if ( $this->mAllowed ) {
725 $out->addWikiMsg( 'undeletehistory' );
726 $out->addWikiMsg( 'undeleterevdel' );
727 } else {
728 $out->addWikiMsg( 'undeletehistorynoadmin' );
729 }
730 $out->addHTML( '</div>' );
731
732 # List all stored revisions
733 $revisions = $archive->listRevisions();
734 $files = $archive->listFiles();
735
736 $haveRevisions = $revisions && $revisions->numRows() > 0;
737 $haveFiles = $files && $files->numRows() > 0;
738
739 # Batch existence check on user and talk pages
740 if ( $haveRevisions ) {
741 $batch = new LinkBatch();
742 foreach ( $revisions as $row ) {
743 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
744 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
745 }
746 $batch->execute();
747 $revisions->seek( 0 );
748 }
749 if ( $haveFiles ) {
750 $batch = new LinkBatch();
751 foreach ( $files as $row ) {
752 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
753 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
754 }
755 $batch->execute();
756 $files->seek( 0 );
757 }
758
759 if ( $this->mAllowed ) {
760 $out->enableOOUI();
761
762 $action = $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] );
763 # Start the form here
764 $form = new OOUI\FormLayout( [
765 'method' => 'post',
766 'action' => $action,
767 'id' => 'undelete',
768 ] );
769 }
770
771 # Show relevant lines from the deletion log:
772 $deleteLogPage = new LogPage( 'delete' );
773 $out->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
774 LogEventsList::showLogExtract( $out, 'delete', $this->mTargetObj );
775 # Show relevant lines from the suppression log:
776 $suppressLogPage = new LogPage( 'suppress' );
777 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
778 $out->addHTML( Xml::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
779 LogEventsList::showLogExtract( $out, 'suppress', $this->mTargetObj );
780 }
781
782 if ( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
783 $fields = [];
784 $fields[] = new OOUI\Layout( [
785 'content' => new OOUI\HtmlSnippet( $this->msg( 'undeleteextrahelp' )->parseAsBlock() )
786 ] );
787
788 $fields[] = new OOUI\FieldLayout(
789 new OOUI\TextInputWidget( [
790 'name' => 'wpComment',
791 'inputId' => 'wpComment',
792 'infusable' => true,
793 'value' => $this->mComment,
794 'autofocus' => true,
795 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
796 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
797 // Unicode codepoints.
798 'maxLength' => CommentStore::COMMENT_CHARACTER_LIMIT,
799 ] ),
800 [
801 'label' => $this->msg( 'undeletecomment' )->text(),
802 'align' => 'top',
803 ]
804 );
805
806 $fields[] = new OOUI\FieldLayout(
807 new OOUI\Widget( [
808 'content' => new OOUI\HorizontalLayout( [
809 'items' => [
810 new OOUI\ButtonInputWidget( [
811 'name' => 'restore',
812 'inputId' => 'mw-undelete-submit',
813 'value' => '1',
814 'label' => $this->msg( 'undeletebtn' )->text(),
815 'flags' => [ 'primary', 'progressive' ],
816 'type' => 'submit',
817 ] ),
818 new OOUI\ButtonInputWidget( [
819 'name' => 'invert',
820 'inputId' => 'mw-undelete-invert',
821 'value' => '1',
822 'label' => $this->msg( 'undeleteinvert' )->text()
823 ] ),
824 ]
825 ] )
826 ] )
827 );
828
829 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
830 $fields[] = new OOUI\FieldLayout(
831 new OOUI\CheckboxInputWidget( [
832 'name' => 'wpUnsuppress',
833 'inputId' => 'mw-undelete-unsuppress',
834 'value' => '1',
835 ] ),
836 [
837 'label' => $this->msg( 'revdelete-unsuppress' )->text(),
838 'align' => 'inline',
839 ]
840 );
841 }
842
843 $fieldset = new OOUI\FieldsetLayout( [
844 'label' => $this->msg( 'undelete-fieldset-title' )->text(),
845 'id' => 'mw-undelete-table',
846 'items' => $fields,
847 ] );
848
849 $form->appendContent(
850 new OOUI\PanelLayout( [
851 'expanded' => false,
852 'padded' => true,
853 'framed' => true,
854 'content' => $fieldset,
855 ] ),
856 new OOUI\HtmlSnippet(
857 Html::hidden( 'target', $this->mTarget ) .
858 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() )
859 )
860 );
861 }
862
863 $history = '';
864 $history .= Xml::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n";
865
866 if ( $haveRevisions ) {
867 # Show the page's stored (deleted) history
868
869 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
870 $history .= Html::element(
871 'button',
872 [
873 'name' => 'revdel',
874 'type' => 'submit',
875 'class' => 'deleterevision-log-submit mw-log-deleterevision-button'
876 ],
877 $this->msg( 'showhideselectedversions' )->text()
878 ) . "\n";
879 }
880
881 $history .= '<ul class="mw-undelete-revlist">';
882 $remaining = $revisions->numRows();
883 $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
884
885 foreach ( $revisions as $row ) {
886 $remaining--;
887 $history .= $this->formatRevisionRow( $row, $earliestLiveTime, $remaining );
888 }
889 $revisions->free();
890 $history .= '</ul>';
891 } else {
892 $out->addWikiMsg( 'nohistory' );
893 }
894
895 if ( $haveFiles ) {
896 $history .= Xml::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n";
897 $history .= '<ul class="mw-undelete-revlist">';
898 foreach ( $files as $row ) {
899 $history .= $this->formatFileRow( $row );
900 }
901 $files->free();
902 $history .= '</ul>';
903 }
904
905 if ( $this->mAllowed ) {
906 # Slip in the hidden controls here
907 $misc = Html::hidden( 'target', $this->mTarget );
908 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
909 $history .= $misc;
910
911 $form->appendContent( new OOUI\HtmlSnippet( $history ) );
912 $out->addHTML( $form );
913 } else {
914 $out->addHTML( $history );
915 }
916
917 return true;
918 }
919
920 protected function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
921 $rev = Revision::newFromArchiveRow( $row,
922 [
923 'title' => $this->mTargetObj
924 ] );
925
926 $revTextSize = '';
927 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
928 // Build checkboxen...
929 if ( $this->mAllowed ) {
930 if ( $this->mInvert ) {
931 if ( in_array( $ts, $this->mTargetTimestamp ) ) {
932 $checkBox = Xml::check( "ts$ts" );
933 } else {
934 $checkBox = Xml::check( "ts$ts", true );
935 }
936 } else {
937 $checkBox = Xml::check( "ts$ts" );
938 }
939 } else {
940 $checkBox = '';
941 }
942
943 // Build page & diff links...
944 $user = $this->getUser();
945 if ( $this->mCanView ) {
946 $titleObj = $this->getPageTitle();
947 # Last link
948 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() ) ) {
949 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
950 $last = $this->msg( 'diff' )->escaped();
951 } elseif ( $remaining > 0 || ( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
952 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
953 $last = $this->getLinkRenderer()->makeKnownLink(
954 $titleObj,
955 $this->msg( 'diff' )->text(),
956 [],
957 [
958 'target' => $this->mTargetObj->getPrefixedText(),
959 'timestamp' => $ts,
960 'diff' => 'prev'
961 ]
962 );
963 } else {
964 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
965 $last = $this->msg( 'diff' )->escaped();
966 }
967 } else {
968 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
969 $last = $this->msg( 'diff' )->escaped();
970 }
971
972 // User links
973 $userLink = Linker::revUserTools( $rev );
974
975 // Minor edit
976 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
977
978 // Revision text size
979 $size = $row->ar_len;
980 if ( !is_null( $size ) ) {
981 $revTextSize = Linker::formatRevisionSize( $size );
982 }
983
984 // Edit summary
985 $comment = Linker::revComment( $rev );
986
987 // Tags
988 $attribs = [];
989 list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow(
990 $row->ts_tags,
991 'deletedhistory',
992 $this->getContext()
993 );
994 if ( $classes ) {
995 $attribs['class'] = implode( ' ', $classes );
996 }
997
998 $revisionRow = $this->msg( 'undelete-revision-row2' )
999 ->rawParams(
1000 $checkBox,
1001 $last,
1002 $pageLink,
1003 $userLink,
1004 $minor,
1005 $revTextSize,
1006 $comment,
1007 $tagSummary
1008 )
1009 ->escaped();
1010
1011 return Xml::tags( 'li', $attribs, $revisionRow ) . "\n";
1012 }
1013
1014 private function formatFileRow( $row ) {
1015 $file = ArchivedFile::newFromRow( $row );
1016 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
1017 $user = $this->getUser();
1018
1019 $checkBox = '';
1020 if ( $this->mCanView && $row->fa_storage_key ) {
1021 if ( $this->mAllowed ) {
1022 $checkBox = Xml::check( 'fileid' . $row->fa_id );
1023 }
1024 $key = urlencode( $row->fa_storage_key );
1025 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
1026 } else {
1027 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1028 }
1029 $userLink = $this->getFileUser( $file );
1030 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width, $row->fa_height )->text();
1031 $bytes = $this->msg( 'parentheses' )
1032 ->plaintextParams( $this->msg( 'nbytes' )->numParams( $row->fa_size )->text() )
1033 ->plain();
1034 $data = htmlspecialchars( $data . ' ' . $bytes );
1035 $comment = $this->getFileComment( $file );
1036
1037 // Add show/hide deletion links if available
1038 $canHide = $this->isAllowed( 'deleterevision' );
1039 if ( $canHide || ( $file->getVisibility() && $this->isAllowed( 'deletedhistory' ) ) ) {
1040 if ( !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1041 // Revision was hidden from sysops
1042 $revdlink = Linker::revDeleteLinkDisabled( $canHide );
1043 } else {
1044 $query = [
1045 'type' => 'filearchive',
1046 'target' => $this->mTargetObj->getPrefixedDBkey(),
1047 'ids' => $row->fa_id
1048 ];
1049 $revdlink = Linker::revDeleteLink( $query,
1050 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1051 }
1052 } else {
1053 $revdlink = '';
1054 }
1055
1056 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1057 }
1058
1059 /**
1060 * Fetch revision text link if it's available to all users
1061 *
1062 * @param Revision $rev
1063 * @param Title $titleObj
1064 * @param string $ts Timestamp
1065 * @return string
1066 */
1067 function getPageLink( $rev, $titleObj, $ts ) {
1068 $user = $this->getUser();
1069 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1070
1071 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
1072 return '<span class="history-deleted">' . $time . '</span>';
1073 }
1074
1075 $link = $this->getLinkRenderer()->makeKnownLink(
1076 $titleObj,
1077 $time,
1078 [],
1079 [
1080 'target' => $this->mTargetObj->getPrefixedText(),
1081 'timestamp' => $ts
1082 ]
1083 );
1084
1085 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
1086 $link = '<span class="history-deleted">' . $link . '</span>';
1087 }
1088
1089 return $link;
1090 }
1091
1092 /**
1093 * Fetch image view link if it's available to all users
1094 *
1095 * @param File|ArchivedFile $file
1096 * @param Title $titleObj
1097 * @param string $ts A timestamp
1098 * @param string $key A storage key
1099 *
1100 * @return string HTML fragment
1101 */
1102 function getFileLink( $file, $titleObj, $ts, $key ) {
1103 $user = $this->getUser();
1104 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1105
1106 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1107 return '<span class="history-deleted">' . htmlspecialchars( $time ) . '</span>';
1108 }
1109
1110 $link = $this->getLinkRenderer()->makeKnownLink(
1111 $titleObj,
1112 $time,
1113 [],
1114 [
1115 'target' => $this->mTargetObj->getPrefixedText(),
1116 'file' => $key,
1117 'token' => $user->getEditToken( $key )
1118 ]
1119 );
1120
1121 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1122 $link = '<span class="history-deleted">' . $link . '</span>';
1123 }
1124
1125 return $link;
1126 }
1127
1128 /**
1129 * Fetch file's user id if it's available to this user
1130 *
1131 * @param File|ArchivedFile $file
1132 * @return string HTML fragment
1133 */
1134 function getFileUser( $file ) {
1135 if ( !$file->userCan( File::DELETED_USER, $this->getUser() ) ) {
1136 return '<span class="history-deleted">' .
1137 $this->msg( 'rev-deleted-user' )->escaped() .
1138 '</span>';
1139 }
1140
1141 $link = Linker::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1142 Linker::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1143
1144 if ( $file->isDeleted( File::DELETED_USER ) ) {
1145 $link = '<span class="history-deleted">' . $link . '</span>';
1146 }
1147
1148 return $link;
1149 }
1150
1151 /**
1152 * Fetch file upload comment if it's available to this user
1153 *
1154 * @param File|ArchivedFile $file
1155 * @return string HTML fragment
1156 */
1157 function getFileComment( $file ) {
1158 if ( !$file->userCan( File::DELETED_COMMENT, $this->getUser() ) ) {
1159 return '<span class="history-deleted"><span class="comment">' .
1160 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1161 }
1162
1163 $link = Linker::commentBlock( $file->getRawDescription() );
1164
1165 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1166 $link = '<span class="history-deleted">' . $link . '</span>';
1167 }
1168
1169 return $link;
1170 }
1171
1172 function undelete() {
1173 if ( $this->getConfig()->get( 'UploadMaintenance' )
1174 && $this->mTargetObj->getNamespace() == NS_FILE
1175 ) {
1176 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1177 }
1178
1179 $this->checkReadOnly();
1180
1181 $out = $this->getOutput();
1182 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1183 Hooks::run( 'UndeleteForm::undelete', [ &$archive, $this->mTargetObj ] );
1184 $ok = $archive->undelete(
1185 $this->mTargetTimestamp,
1186 $this->mComment,
1187 $this->mFileVersions,
1188 $this->mUnsuppress,
1189 $this->getUser()
1190 );
1191
1192 if ( is_array( $ok ) ) {
1193 if ( $ok[1] ) { // Undeleted file count
1194 Hooks::run( 'FileUndeleteComplete', [
1195 $this->mTargetObj, $this->mFileVersions,
1196 $this->getUser(), $this->mComment ] );
1197 }
1198
1199 $link = $this->getLinkRenderer()->makeKnownLink( $this->mTargetObj );
1200 $out->addWikiMsg( 'undeletedpage', Message::rawParam( $link ) );
1201 } else {
1202 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1203 }
1204
1205 // Show revision undeletion warnings and errors
1206 $status = $archive->getRevisionStatus();
1207 if ( $status && !$status->isGood() ) {
1208 $out->wrapWikiTextAsInterface(
1209 'error',
1210 '<div id="mw-error-cannotundelete">' .
1211 $status->getWikiText(
1212 'cannotundelete',
1213 'cannotundelete'
1214 ) . '</div>'
1215 );
1216 }
1217
1218 // Show file undeletion warnings and errors
1219 $status = $archive->getFileStatus();
1220 if ( $status && !$status->isGood() ) {
1221 $out->wrapWikiTextAsInterface(
1222 'error',
1223 $status->getWikiText(
1224 'undelete-error-short',
1225 'undelete-error-long'
1226 )
1227 );
1228 }
1229 }
1230
1231 /**
1232 * Return an array of subpages beginning with $search that this special page will accept.
1233 *
1234 * @param string $search Prefix to search for
1235 * @param int $limit Maximum number of results to return (usually 10)
1236 * @param int $offset Number of results to skip (usually 0)
1237 * @return string[] Matching subpages
1238 */
1239 public function prefixSearchSubpages( $search, $limit, $offset ) {
1240 return $this->prefixSearchString( $search, $limit, $offset );
1241 }
1242
1243 protected function getGroupName() {
1244 return 'pagetools';
1245 }
1246 }