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