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