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