Merge "Include change tags in revision import structure"
[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 '@phan-var TextContent $content';
497 // TODO: MCR: make this work for multiple slots
498 // source view for textual content
499 $sourceView = Xml::element( 'textarea', [
500 'readonly' => 'readonly',
501 'cols' => 80,
502 'rows' => 25
503 ], $content->getText() . "\n" );
504
505 $buttonFields[] = new OOUI\ButtonInputWidget( [
506 'type' => 'submit',
507 'name' => 'preview',
508 'label' => $this->msg( 'showpreview' )->text()
509 ] );
510 } else {
511 $sourceView = '';
512 }
513
514 $buttonFields[] = new OOUI\ButtonInputWidget( [
515 'name' => 'diff',
516 'type' => 'submit',
517 'label' => $this->msg( 'showdiff' )->text()
518 ] );
519
520 $out->addHTML(
521 $sourceView .
522 Xml::openElement( 'div', [
523 'style' => 'clear: both' ] ) .
524 Xml::openElement( 'form', [
525 'method' => 'post',
526 'action' => $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] ) ] ) .
527 Xml::element( 'input', [
528 'type' => 'hidden',
529 'name' => 'target',
530 'value' => $this->mTargetObj->getPrefixedDBkey() ] ) .
531 Xml::element( 'input', [
532 'type' => 'hidden',
533 'name' => 'timestamp',
534 'value' => $timestamp ] ) .
535 Xml::element( 'input', [
536 'type' => 'hidden',
537 'name' => 'wpEditToken',
538 'value' => $user->getEditToken() ] ) .
539 new OOUI\FieldLayout(
540 new OOUI\Widget( [
541 'content' => new OOUI\HorizontalLayout( [
542 'items' => $buttonFields
543 ] )
544 ] )
545 ) .
546 Xml::closeElement( 'form' ) .
547 Xml::closeElement( 'div' )
548 );
549 }
550
551 /**
552 * Build a diff display between this and the previous either deleted
553 * or non-deleted edit.
554 *
555 * @param Revision $previousRev
556 * @param Revision $currentRev
557 */
558 function showDiff( $previousRev, $currentRev ) {
559 $diffContext = clone $this->getContext();
560 $diffContext->setTitle( $currentRev->getTitle() );
561 $diffContext->setWikiPage( WikiPage::factory( $currentRev->getTitle() ) );
562
563 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
564 $diffEngine->setRevisions( $previousRev->getRevisionRecord(), $currentRev->getRevisionRecord() );
565 $diffEngine->showDiffStyle();
566 $formattedDiff = $diffEngine->getDiff(
567 $this->diffHeader( $previousRev, 'o' ),
568 $this->diffHeader( $currentRev, 'n' )
569 );
570
571 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
572 }
573
574 /**
575 * @param Revision $rev
576 * @param string $prefix
577 * @return string
578 */
579 private function diffHeader( $rev, $prefix ) {
580 $isDeleted = !( $rev->getId() && $rev->getTitle() );
581 if ( $isDeleted ) {
582 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
583 $targetPage = $this->getPageTitle();
584 $targetQuery = [
585 'target' => $this->mTargetObj->getPrefixedText(),
586 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
587 ];
588 } else {
589 /// @todo FIXME: getId() may return non-zero for deleted revs...
590 $targetPage = $rev->getTitle();
591 $targetQuery = [ 'oldid' => $rev->getId() ];
592 }
593
594 // Add show/hide deletion links if available
595 $user = $this->getUser();
596 $lang = $this->getLanguage();
597 $rdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
598
599 if ( $rdel ) {
600 $rdel = " $rdel";
601 }
602
603 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
604
605 $tagIds = wfGetDB( DB_REPLICA )->selectFieldValues(
606 'change_tag',
607 'ct_tag_id',
608 [ 'ct_rev_id' => $rev->getId() ],
609 __METHOD__
610 );
611 $tags = [];
612 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
613 foreach ( $tagIds as $tagId ) {
614 try {
615 $tags[] = $changeTagDefStore->getName( (int)$tagId );
616 } catch ( NameTableAccessException $exception ) {
617 continue;
618 }
619 }
620 $tags = implode( ',', $tags );
621 $tagSummary = ChangeTags::formatSummaryRow( $tags, 'deleteddiff', $this->getContext() );
622
623 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
624 // and partially #showDiffPage, but worse
625 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
626 $this->getLinkRenderer()->makeLink(
627 $targetPage,
628 $this->msg(
629 'revisionasof',
630 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
631 $lang->userDate( $rev->getTimestamp(), $user ),
632 $lang->userTime( $rev->getTimestamp(), $user )
633 )->text(),
634 [],
635 $targetQuery
636 ) .
637 '</strong></div>' .
638 '<div id="mw-diff-' . $prefix . 'title2">' .
639 Linker::revUserTools( $rev ) . '<br />' .
640 '</div>' .
641 '<div id="mw-diff-' . $prefix . 'title3">' .
642 $minor . Linker::revComment( $rev ) . $rdel . '<br />' .
643 '</div>' .
644 '<div id="mw-diff-' . $prefix . 'title5">' .
645 $tagSummary[0] . '<br />' .
646 '</div>';
647 }
648
649 /**
650 * Show a form confirming whether a tokenless user really wants to see a file
651 * @param string $key
652 */
653 private function showFileConfirmationForm( $key ) {
654 $out = $this->getOutput();
655 $lang = $this->getLanguage();
656 $user = $this->getUser();
657 $file = new ArchivedFile( $this->mTargetObj, 0, $this->mFilename );
658 $out->addWikiMsg( 'undelete-show-file-confirm',
659 $this->mTargetObj->getText(),
660 $lang->userDate( $file->getTimestamp(), $user ),
661 $lang->userTime( $file->getTimestamp(), $user ) );
662 $out->addHTML(
663 Xml::openElement( 'form', [
664 'method' => 'POST',
665 'action' => $this->getPageTitle()->getLocalURL( [
666 'target' => $this->mTarget,
667 'file' => $key,
668 'token' => $user->getEditToken( $key ),
669 ] ),
670 ]
671 ) .
672 Xml::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
673 '</form>'
674 );
675 }
676
677 /**
678 * Show a deleted file version requested by the visitor.
679 * @param string $key
680 */
681 private function showFile( $key ) {
682 $this->getOutput()->disable();
683
684 # We mustn't allow the output to be CDN cached, otherwise
685 # if an admin previews a deleted image, and it's cached, then
686 # a user without appropriate permissions can toddle off and
687 # nab the image, and CDN will serve it
688 $response = $this->getRequest()->response();
689 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
690 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
691 $response->header( 'Pragma: no-cache' );
692
693 $repo = RepoGroup::singleton()->getLocalRepo();
694 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
695 $repo->streamFileWithStatus( $path );
696 }
697
698 protected function showHistory() {
699 $this->checkReadOnly();
700
701 $out = $this->getOutput();
702 if ( $this->mAllowed ) {
703 $out->addModules( 'mediawiki.special.undelete' );
704 }
705 $out->wrapWikiMsg(
706 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
707 [ 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj->getPrefixedText() ) ]
708 );
709
710 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
711 Hooks::run( 'UndeleteForm::showHistory', [ &$archive, $this->mTargetObj ] );
712
713 $out->addHTML( '<div class="mw-undelete-history">' );
714 if ( $this->mAllowed ) {
715 $out->addWikiMsg( 'undeletehistory' );
716 $out->addWikiMsg( 'undeleterevdel' );
717 } else {
718 $out->addWikiMsg( 'undeletehistorynoadmin' );
719 }
720 $out->addHTML( '</div>' );
721
722 # List all stored revisions
723 $revisions = $archive->listRevisions();
724 $files = $archive->listFiles();
725
726 $haveRevisions = $revisions && $revisions->numRows() > 0;
727 $haveFiles = $files && $files->numRows() > 0;
728
729 # Batch existence check on user and talk pages
730 if ( $haveRevisions ) {
731 $batch = new LinkBatch();
732 foreach ( $revisions as $row ) {
733 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
734 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
735 }
736 $batch->execute();
737 $revisions->seek( 0 );
738 }
739 if ( $haveFiles ) {
740 $batch = new LinkBatch();
741 foreach ( $files as $row ) {
742 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
743 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
744 }
745 $batch->execute();
746 $files->seek( 0 );
747 }
748
749 if ( $this->mAllowed ) {
750 $out->enableOOUI();
751
752 $action = $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] );
753 # Start the form here
754 $form = new OOUI\FormLayout( [
755 'method' => 'post',
756 'action' => $action,
757 'id' => 'undelete',
758 ] );
759 }
760
761 # Show relevant lines from the deletion log:
762 $deleteLogPage = new LogPage( 'delete' );
763 $out->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
764 LogEventsList::showLogExtract( $out, 'delete', $this->mTargetObj );
765 # Show relevant lines from the suppression log:
766 $suppressLogPage = new LogPage( 'suppress' );
767 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
768 $out->addHTML( Xml::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
769 LogEventsList::showLogExtract( $out, 'suppress', $this->mTargetObj );
770 }
771
772 if ( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
773 $fields = [];
774 $fields[] = new OOUI\Layout( [
775 'content' => new OOUI\HtmlSnippet( $this->msg( 'undeleteextrahelp' )->parseAsBlock() )
776 ] );
777
778 $fields[] = new OOUI\FieldLayout(
779 new OOUI\TextInputWidget( [
780 'name' => 'wpComment',
781 'inputId' => 'wpComment',
782 'infusable' => true,
783 'value' => $this->mComment,
784 'autofocus' => true,
785 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
786 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
787 // Unicode codepoints.
788 'maxLength' => CommentStore::COMMENT_CHARACTER_LIMIT,
789 ] ),
790 [
791 'label' => $this->msg( 'undeletecomment' )->text(),
792 'align' => 'top',
793 ]
794 );
795
796 $fields[] = new OOUI\FieldLayout(
797 new OOUI\Widget( [
798 'content' => new OOUI\HorizontalLayout( [
799 'items' => [
800 new OOUI\ButtonInputWidget( [
801 'name' => 'restore',
802 'inputId' => 'mw-undelete-submit',
803 'value' => '1',
804 'label' => $this->msg( 'undeletebtn' )->text(),
805 'flags' => [ 'primary', 'progressive' ],
806 'type' => 'submit',
807 ] ),
808 new OOUI\ButtonInputWidget( [
809 'name' => 'invert',
810 'inputId' => 'mw-undelete-invert',
811 'value' => '1',
812 'label' => $this->msg( 'undeleteinvert' )->text()
813 ] ),
814 ]
815 ] )
816 ] )
817 );
818
819 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
820 $fields[] = new OOUI\FieldLayout(
821 new OOUI\CheckboxInputWidget( [
822 'name' => 'wpUnsuppress',
823 'inputId' => 'mw-undelete-unsuppress',
824 'value' => '1',
825 ] ),
826 [
827 'label' => $this->msg( 'revdelete-unsuppress' )->text(),
828 'align' => 'inline',
829 ]
830 );
831 }
832
833 $fieldset = new OOUI\FieldsetLayout( [
834 'label' => $this->msg( 'undelete-fieldset-title' )->text(),
835 'id' => 'mw-undelete-table',
836 'items' => $fields,
837 ] );
838
839 $form->appendContent(
840 new OOUI\PanelLayout( [
841 'expanded' => false,
842 'padded' => true,
843 'framed' => true,
844 'content' => $fieldset,
845 ] ),
846 new OOUI\HtmlSnippet(
847 Html::hidden( 'target', $this->mTarget ) .
848 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() )
849 )
850 );
851 }
852
853 $history = '';
854 $history .= Xml::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n";
855
856 if ( $haveRevisions ) {
857 # Show the page's stored (deleted) history
858
859 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
860 $history .= Html::element(
861 'button',
862 [
863 'name' => 'revdel',
864 'type' => 'submit',
865 'class' => 'deleterevision-log-submit mw-log-deleterevision-button'
866 ],
867 $this->msg( 'showhideselectedversions' )->text()
868 ) . "\n";
869 }
870
871 $history .= '<ul class="mw-undelete-revlist">';
872 $remaining = $revisions->numRows();
873 $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
874
875 foreach ( $revisions as $row ) {
876 $remaining--;
877 $history .= $this->formatRevisionRow( $row, $earliestLiveTime, $remaining );
878 }
879 $revisions->free();
880 $history .= '</ul>';
881 } else {
882 $out->addWikiMsg( 'nohistory' );
883 }
884
885 if ( $haveFiles ) {
886 $history .= Xml::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n";
887 $history .= '<ul class="mw-undelete-revlist">';
888 foreach ( $files as $row ) {
889 $history .= $this->formatFileRow( $row );
890 }
891 $files->free();
892 $history .= '</ul>';
893 }
894
895 if ( $this->mAllowed ) {
896 # Slip in the hidden controls here
897 $misc = Html::hidden( 'target', $this->mTarget );
898 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
899 $history .= $misc;
900
901 $form->appendContent( new OOUI\HtmlSnippet( $history ) );
902 $out->addHTML( $form );
903 } else {
904 $out->addHTML( $history );
905 }
906
907 return true;
908 }
909
910 protected function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
911 $rev = Revision::newFromArchiveRow( $row,
912 [
913 'title' => $this->mTargetObj
914 ] );
915
916 $revTextSize = '';
917 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
918 // Build checkboxen...
919 if ( $this->mAllowed ) {
920 if ( $this->mInvert ) {
921 if ( in_array( $ts, $this->mTargetTimestamp ) ) {
922 $checkBox = Xml::check( "ts$ts" );
923 } else {
924 $checkBox = Xml::check( "ts$ts", true );
925 }
926 } else {
927 $checkBox = Xml::check( "ts$ts" );
928 }
929 } else {
930 $checkBox = '';
931 }
932
933 // Build page & diff links...
934 $user = $this->getUser();
935 if ( $this->mCanView ) {
936 $titleObj = $this->getPageTitle();
937 # Last link
938 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() ) ) {
939 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
940 $last = $this->msg( 'diff' )->escaped();
941 } elseif ( $remaining > 0 || ( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
942 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
943 $last = $this->getLinkRenderer()->makeKnownLink(
944 $titleObj,
945 $this->msg( 'diff' )->text(),
946 [],
947 [
948 'target' => $this->mTargetObj->getPrefixedText(),
949 'timestamp' => $ts,
950 'diff' => 'prev'
951 ]
952 );
953 } else {
954 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
955 $last = $this->msg( 'diff' )->escaped();
956 }
957 } else {
958 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
959 $last = $this->msg( 'diff' )->escaped();
960 }
961
962 // User links
963 $userLink = Linker::revUserTools( $rev );
964
965 // Minor edit
966 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
967
968 // Revision text size
969 $size = $row->ar_len;
970 if ( !is_null( $size ) ) {
971 $revTextSize = Linker::formatRevisionSize( $size );
972 }
973
974 // Edit summary
975 $comment = Linker::revComment( $rev );
976
977 // Tags
978 $attribs = [];
979 list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow(
980 $row->ts_tags,
981 'deletedhistory',
982 $this->getContext()
983 );
984 if ( $classes ) {
985 $attribs['class'] = implode( ' ', $classes );
986 }
987
988 $revisionRow = $this->msg( 'undelete-revision-row2' )
989 ->rawParams(
990 $checkBox,
991 $last,
992 $pageLink,
993 $userLink,
994 $minor,
995 $revTextSize,
996 $comment,
997 $tagSummary
998 )
999 ->escaped();
1000
1001 return Xml::tags( 'li', $attribs, $revisionRow ) . "\n";
1002 }
1003
1004 private function formatFileRow( $row ) {
1005 $file = ArchivedFile::newFromRow( $row );
1006 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
1007 $user = $this->getUser();
1008
1009 $checkBox = '';
1010 if ( $this->mCanView && $row->fa_storage_key ) {
1011 if ( $this->mAllowed ) {
1012 $checkBox = Xml::check( 'fileid' . $row->fa_id );
1013 }
1014 $key = urlencode( $row->fa_storage_key );
1015 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
1016 } else {
1017 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1018 }
1019 $userLink = $this->getFileUser( $file );
1020 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width, $row->fa_height )->text();
1021 $bytes = $this->msg( 'parentheses' )
1022 ->plaintextParams( $this->msg( 'nbytes' )->numParams( $row->fa_size )->text() )
1023 ->plain();
1024 $data = htmlspecialchars( $data . ' ' . $bytes );
1025 $comment = $this->getFileComment( $file );
1026
1027 // Add show/hide deletion links if available
1028 $canHide = $this->isAllowed( 'deleterevision' );
1029 if ( $canHide || ( $file->getVisibility() && $this->isAllowed( 'deletedhistory' ) ) ) {
1030 if ( !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1031 // Revision was hidden from sysops
1032 $revdlink = Linker::revDeleteLinkDisabled( $canHide );
1033 } else {
1034 $query = [
1035 'type' => 'filearchive',
1036 'target' => $this->mTargetObj->getPrefixedDBkey(),
1037 'ids' => $row->fa_id
1038 ];
1039 $revdlink = Linker::revDeleteLink( $query,
1040 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1041 }
1042 } else {
1043 $revdlink = '';
1044 }
1045
1046 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1047 }
1048
1049 /**
1050 * Fetch revision text link if it's available to all users
1051 *
1052 * @param Revision $rev
1053 * @param Title $titleObj
1054 * @param string $ts Timestamp
1055 * @return string
1056 */
1057 function getPageLink( $rev, $titleObj, $ts ) {
1058 $user = $this->getUser();
1059 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1060
1061 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
1062 return '<span class="history-deleted">' . $time . '</span>';
1063 }
1064
1065 $link = $this->getLinkRenderer()->makeKnownLink(
1066 $titleObj,
1067 $time,
1068 [],
1069 [
1070 'target' => $this->mTargetObj->getPrefixedText(),
1071 'timestamp' => $ts
1072 ]
1073 );
1074
1075 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
1076 $link = '<span class="history-deleted">' . $link . '</span>';
1077 }
1078
1079 return $link;
1080 }
1081
1082 /**
1083 * Fetch image view link if it's available to all users
1084 *
1085 * @param File|ArchivedFile $file
1086 * @param Title $titleObj
1087 * @param string $ts A timestamp
1088 * @param string $key A storage key
1089 *
1090 * @return string HTML fragment
1091 */
1092 function getFileLink( $file, $titleObj, $ts, $key ) {
1093 $user = $this->getUser();
1094 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1095
1096 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1097 return '<span class="history-deleted">' . htmlspecialchars( $time ) . '</span>';
1098 }
1099
1100 $link = $this->getLinkRenderer()->makeKnownLink(
1101 $titleObj,
1102 $time,
1103 [],
1104 [
1105 'target' => $this->mTargetObj->getPrefixedText(),
1106 'file' => $key,
1107 'token' => $user->getEditToken( $key )
1108 ]
1109 );
1110
1111 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1112 $link = '<span class="history-deleted">' . $link . '</span>';
1113 }
1114
1115 return $link;
1116 }
1117
1118 /**
1119 * Fetch file's user id if it's available to this user
1120 *
1121 * @param File|ArchivedFile $file
1122 * @return string HTML fragment
1123 */
1124 function getFileUser( $file ) {
1125 if ( !$file->userCan( File::DELETED_USER, $this->getUser() ) ) {
1126 return '<span class="history-deleted">' .
1127 $this->msg( 'rev-deleted-user' )->escaped() .
1128 '</span>';
1129 }
1130
1131 $link = Linker::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1132 Linker::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1133
1134 if ( $file->isDeleted( File::DELETED_USER ) ) {
1135 $link = '<span class="history-deleted">' . $link . '</span>';
1136 }
1137
1138 return $link;
1139 }
1140
1141 /**
1142 * Fetch file upload comment if it's available to this user
1143 *
1144 * @param File|ArchivedFile $file
1145 * @return string HTML fragment
1146 */
1147 function getFileComment( $file ) {
1148 if ( !$file->userCan( File::DELETED_COMMENT, $this->getUser() ) ) {
1149 return '<span class="history-deleted"><span class="comment">' .
1150 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1151 }
1152
1153 $link = Linker::commentBlock( $file->getRawDescription() );
1154
1155 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1156 $link = '<span class="history-deleted">' . $link . '</span>';
1157 }
1158
1159 return $link;
1160 }
1161
1162 function undelete() {
1163 if ( $this->getConfig()->get( 'UploadMaintenance' )
1164 && $this->mTargetObj->getNamespace() == NS_FILE
1165 ) {
1166 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1167 }
1168
1169 $this->checkReadOnly();
1170
1171 $out = $this->getOutput();
1172 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1173 Hooks::run( 'UndeleteForm::undelete', [ &$archive, $this->mTargetObj ] );
1174 $ok = $archive->undelete(
1175 $this->mTargetTimestamp,
1176 $this->mComment,
1177 $this->mFileVersions,
1178 $this->mUnsuppress,
1179 $this->getUser()
1180 );
1181
1182 if ( is_array( $ok ) ) {
1183 if ( $ok[1] ) { // Undeleted file count
1184 Hooks::run( 'FileUndeleteComplete', [
1185 $this->mTargetObj, $this->mFileVersions,
1186 $this->getUser(), $this->mComment ] );
1187 }
1188
1189 $link = $this->getLinkRenderer()->makeKnownLink( $this->mTargetObj );
1190 $out->addWikiMsg( 'undeletedpage', Message::rawParam( $link ) );
1191 } else {
1192 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1193 }
1194
1195 // Show revision undeletion warnings and errors
1196 $status = $archive->getRevisionStatus();
1197 if ( $status && !$status->isGood() ) {
1198 $out->wrapWikiTextAsInterface(
1199 'error',
1200 '<div id="mw-error-cannotundelete">' .
1201 $status->getWikiText(
1202 'cannotundelete',
1203 'cannotundelete'
1204 ) . '</div>'
1205 );
1206 }
1207
1208 // Show file undeletion warnings and errors
1209 $status = $archive->getFileStatus();
1210 if ( $status && !$status->isGood() ) {
1211 $out->wrapWikiTextAsInterface(
1212 'error',
1213 $status->getWikiText(
1214 'undelete-error-short',
1215 'undelete-error-long'
1216 )
1217 );
1218 }
1219 }
1220
1221 /**
1222 * Return an array of subpages beginning with $search that this special page will accept.
1223 *
1224 * @param string $search Prefix to search for
1225 * @param int $limit Maximum number of results to return (usually 10)
1226 * @param int $offset Number of results to skip (usually 0)
1227 * @return string[] Matching subpages
1228 */
1229 public function prefixSearchSubpages( $search, $limit, $offset ) {
1230 return $this->prefixSearchString( $search, $limit, $offset );
1231 }
1232
1233 protected function getGroupName() {
1234 return 'pagetools';
1235 }
1236 }