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