Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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
162 $this->loadRequest( $par );
163 $this->checkPermissions(); // Needs to be after mTargetObj is set
164
165 $out = $this->getOutput();
166
167 if ( is_null( $this->mTargetObj ) ) {
168 $out->addWikiMsg( 'undelete-header' );
169
170 # Not all users can just browse every deleted page from the list
171 if ( $user->isAllowed( 'browsearchive' ) ) {
172 $this->showSearchForm();
173 }
174
175 return;
176 }
177
178 $this->addHelpLink( 'Help:Undelete' );
179 if ( $this->mAllowed ) {
180 $out->setPageTitle( $this->msg( 'undeletepage' ) );
181 } else {
182 $out->setPageTitle( $this->msg( 'viewdeletedpage' ) );
183 }
184
185 $this->getSkin()->setRelevantTitle( $this->mTargetObj );
186
187 if ( $this->mTimestamp !== '' ) {
188 $this->showRevision( $this->mTimestamp );
189 } elseif ( $this->mFilename !== null && $this->mTargetObj->inNamespace( NS_FILE ) ) {
190 $file = new ArchivedFile( $this->mTargetObj, 0, $this->mFilename );
191 // Check if user is allowed to see this file
192 if ( !$file->exists() ) {
193 $out->addWikiMsg( 'filedelete-nofile', $this->mFilename );
194 } elseif ( !$file->userCan( File::DELETED_FILE, $user ) ) {
195 if ( $file->isDeleted( File::DELETED_RESTRICTED ) ) {
196 throw new PermissionsError( 'suppressrevision' );
197 } else {
198 throw new PermissionsError( 'deletedtext' );
199 }
200 } elseif ( !$user->matchEditToken( $this->mToken, $this->mFilename ) ) {
201 $this->showFileConfirmationForm( $this->mFilename );
202 } else {
203 $this->showFile( $this->mFilename );
204 }
205 } elseif ( $this->mAction === 'submit' ) {
206 if ( $this->mRestore ) {
207 $this->undelete();
208 } elseif ( $this->mRevdel ) {
209 $this->redirectToRevDel();
210 }
211
212 } else {
213 $this->showHistory();
214 }
215 }
216
217 /**
218 * Convert submitted form data to format expected by RevisionDelete and
219 * redirect the request
220 */
221 private function redirectToRevDel() {
222 $archive = new PageArchive( $this->mTargetObj );
223
224 $revisions = [];
225
226 foreach ( $this->getRequest()->getValues() as $key => $val ) {
227 $matches = [];
228 if ( preg_match( "/^ts(\d{14})$/", $key, $matches ) ) {
229 $revisions[$archive->getRevision( $matches[1] )->getId()] = 1;
230 }
231 }
232
233 $query = [
234 'type' => 'revision',
235 'ids' => $revisions,
236 'target' => $this->mTargetObj->getPrefixedText()
237 ];
238 $url = SpecialPage::getTitleFor( 'Revisiondelete' )->getFullURL( $query );
239 $this->getOutput()->redirect( $url );
240 }
241
242 function showSearchForm() {
243 $out = $this->getOutput();
244 $out->setPageTitle( $this->msg( 'undelete-search-title' ) );
245 $fuzzySearch = $this->getRequest()->getVal( 'fuzzy', true );
246
247 $out->enableOOUI();
248
249 $fields[] = new OOUI\ActionFieldLayout(
250 new OOUI\TextInputWidget( [
251 'name' => 'prefix',
252 'inputId' => 'prefix',
253 'infusable' => true,
254 'value' => $this->mSearchPrefix,
255 'autofocus' => true,
256 ] ),
257 new OOUI\ButtonInputWidget( [
258 'label' => $this->msg( 'undelete-search-submit' )->text(),
259 'flags' => [ 'primary', 'progressive' ],
260 'inputId' => 'searchUndelete',
261 'type' => 'submit',
262 ] ),
263 [
264 'label' => new OOUI\HtmlSnippet(
265 $this->msg(
266 $fuzzySearch ? 'undelete-search-full' : 'undelete-search-prefix'
267 )->parse()
268 ),
269 'align' => 'left',
270 ]
271 );
272
273 $fieldset = new OOUI\FieldsetLayout( [
274 'label' => $this->msg( 'undelete-search-box' )->text(),
275 'items' => $fields,
276 ] );
277
278 $form = new OOUI\FormLayout( [
279 'method' => 'get',
280 'action' => wfScript(),
281 ] );
282
283 $form->appendContent(
284 $fieldset,
285 new OOUI\HtmlSnippet(
286 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
287 Html::hidden( 'fuzzy', $fuzzySearch )
288 )
289 );
290
291 $out->addHTML(
292 new OOUI\PanelLayout( [
293 'expanded' => false,
294 'padded' => true,
295 'framed' => true,
296 'content' => $form,
297 ] )
298 );
299
300 # List undeletable articles
301 if ( $this->mSearchPrefix ) {
302 // For now, we enable search engine match only when specifically asked to
303 // by using fuzzy=1 parameter.
304 if ( $fuzzySearch ) {
305 $result = PageArchive::listPagesBySearch( $this->mSearchPrefix );
306 } else {
307 $result = PageArchive::listPagesByPrefix( $this->mSearchPrefix );
308 }
309 $this->showList( $result );
310 }
311 }
312
313 /**
314 * Generic list of deleted pages
315 *
316 * @param IResultWrapper $result
317 * @return bool
318 */
319 private function showList( $result ) {
320 $out = $this->getOutput();
321
322 if ( $result->numRows() == 0 ) {
323 $out->addWikiMsg( 'undelete-no-results' );
324
325 return false;
326 }
327
328 $out->addWikiMsg( 'undeletepagetext', $this->getLanguage()->formatNum( $result->numRows() ) );
329
330 $linkRenderer = $this->getLinkRenderer();
331 $undelete = $this->getPageTitle();
332 $out->addHTML( "<ul id='undeleteResultsList'>\n" );
333 foreach ( $result as $row ) {
334 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
335 if ( $title !== null ) {
336 $item = $linkRenderer->makeKnownLink(
337 $undelete,
338 $title->getPrefixedText(),
339 [],
340 [ 'target' => $title->getPrefixedText() ]
341 );
342 } else {
343 // The title is no longer valid, show as text
344 $item = Html::element(
345 'span',
346 [ 'class' => 'mw-invalidtitle' ],
347 Linker::getInvalidTitleDescription(
348 $this->getContext(),
349 $row->ar_namespace,
350 $row->ar_title
351 )
352 );
353 }
354 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count )->parse();
355 $out->addHTML(
356 Html::rawElement(
357 'li',
358 [ 'class' => 'undeleteResult' ],
359 "{$item} ({$revs})"
360 )
361 );
362 }
363 $result->free();
364 $out->addHTML( "</ul>\n" );
365
366 return true;
367 }
368
369 private function showRevision( $timestamp ) {
370 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
371 return;
372 }
373
374 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
375 if ( !Hooks::run( 'UndeleteForm::showRevision', [ &$archive, $this->mTargetObj ] ) ) {
376 return;
377 }
378 $rev = $archive->getRevision( $timestamp );
379
380 $out = $this->getOutput();
381 $user = $this->getUser();
382
383 if ( !$rev ) {
384 $out->addWikiMsg( 'undeleterevision-missing' );
385
386 return;
387 }
388
389 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
390 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
391 $out->wrapWikiMsg(
392 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
393 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
394 'rev-suppressed-text-permission' : 'rev-deleted-text-permission'
395 );
396
397 return;
398 }
399
400 $out->wrapWikiMsg(
401 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
402 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
403 'rev-suppressed-text-view' : 'rev-deleted-text-view'
404 );
405 $out->addHTML( '<br />' );
406 // and we are allowed to see...
407 }
408
409 if ( $this->mDiff ) {
410 $previousRev = $archive->getPreviousRevision( $timestamp );
411 if ( $previousRev ) {
412 $this->showDiff( $previousRev, $rev );
413 if ( $this->mDiffOnly ) {
414 return;
415 }
416
417 $out->addHTML( '<hr />' );
418 } else {
419 $out->addWikiMsg( 'undelete-nodiff' );
420 }
421 }
422
423 $link = $this->getLinkRenderer()->makeKnownLink(
424 $this->getPageTitle( $this->mTargetObj->getPrefixedDBkey() ),
425 $this->mTargetObj->getPrefixedText()
426 );
427
428 $lang = $this->getLanguage();
429
430 // date and time are separate parameters to facilitate localisation.
431 // $time is kept for backward compat reasons.
432 $time = $lang->userTimeAndDate( $timestamp, $user );
433 $d = $lang->userDate( $timestamp, $user );
434 $t = $lang->userTime( $timestamp, $user );
435 $userLink = Linker::revUserTools( $rev );
436
437 $content = $rev->getContent( RevisionRecord::FOR_THIS_USER, $user );
438
439 // TODO: MCR: this will have to become something like $hasTextSlots and $hasNonTextSlots
440 $isText = ( $content instanceof TextContent );
441
442 if ( $this->mPreview || $isText ) {
443 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
444 } else {
445 $openDiv = '<div id="mw-undelete-revision">';
446 }
447 $out->addHTML( $openDiv );
448
449 // Revision delete links
450 if ( !$this->mDiff ) {
451 $revdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
452 if ( $revdel ) {
453 $out->addHTML( "$revdel " );
454 }
455 }
456
457 $out->addWikiMsg(
458 'undelete-revision',
459 Message::rawParam( $link ), $time,
460 Message::rawParam( $userLink ), $d, $t
461 );
462 $out->addHTML( '</div>' );
463
464 if ( !Hooks::run( 'UndeleteShowRevision', [ $this->mTargetObj, $rev ] ) ) {
465 return;
466 }
467
468 if ( $this->mPreview || !$isText ) {
469 // NOTE: non-text content has no source view, so always use rendered preview
470
471 $popts = $out->parserOptions();
472 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
473
474 $rendered = $renderer->getRenderedRevision(
475 $rev->getRevisionRecord(),
476 $popts,
477 $user,
478 [ 'audience' => RevisionRecord::FOR_THIS_USER ]
479 );
480
481 // Fail hard if the audience check fails, since we already checked
482 // at the beginning of this method.
483 $pout = $rendered->getRevisionParserOutput();
484
485 $out->addParserOutput( $pout, [
486 'enableSectionEditLinks' => false,
487 ] );
488 }
489
490 $out->enableOOUI();
491 $buttonFields = [];
492
493 if ( $isText ) {
494 // TODO: MCR: make this work for multiple slots
495 // source view for textual content
496 $sourceView = Xml::element( 'textarea', [
497 'readonly' => 'readonly',
498 'cols' => 80,
499 'rows' => 25
500 ], $content->getText() . "\n" );
501
502 $buttonFields[] = new OOUI\ButtonInputWidget( [
503 'type' => 'submit',
504 'name' => 'preview',
505 'label' => $this->msg( 'showpreview' )->text()
506 ] );
507 } else {
508 $sourceView = '';
509 }
510
511 $buttonFields[] = new OOUI\ButtonInputWidget( [
512 'name' => 'diff',
513 'type' => 'submit',
514 'label' => $this->msg( 'showdiff' )->text()
515 ] );
516
517 $out->addHTML(
518 $sourceView .
519 Xml::openElement( 'div', [
520 'style' => 'clear: both' ] ) .
521 Xml::openElement( 'form', [
522 'method' => 'post',
523 'action' => $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] ) ] ) .
524 Xml::element( 'input', [
525 'type' => 'hidden',
526 'name' => 'target',
527 'value' => $this->mTargetObj->getPrefixedDBkey() ] ) .
528 Xml::element( 'input', [
529 'type' => 'hidden',
530 'name' => 'timestamp',
531 'value' => $timestamp ] ) .
532 Xml::element( 'input', [
533 'type' => 'hidden',
534 'name' => 'wpEditToken',
535 'value' => $user->getEditToken() ] ) .
536 new OOUI\FieldLayout(
537 new OOUI\Widget( [
538 'content' => new OOUI\HorizontalLayout( [
539 'items' => $buttonFields
540 ] )
541 ] )
542 ) .
543 Xml::closeElement( 'form' ) .
544 Xml::closeElement( 'div' )
545 );
546 }
547
548 /**
549 * Build a diff display between this and the previous either deleted
550 * or non-deleted edit.
551 *
552 * @param Revision $previousRev
553 * @param Revision $currentRev
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, 0, $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->streamFileWithStatus( $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 }