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