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