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