Merge "Convert Special:DeletedContributions to use OOUI."
[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 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Used to show archived pages and eventually restore them.
27 *
28 * @ingroup SpecialPage
29 */
30 class PageArchive {
31 /** @var Title */
32 protected $title;
33
34 /** @var Status */
35 protected $fileStatus;
36
37 /** @var Status */
38 protected $revisionStatus;
39
40 /** @var Config */
41 protected $config;
42
43 function __construct( $title, Config $config = null ) {
44 if ( is_null( $title ) ) {
45 throw new MWException( __METHOD__ . ' given a null title.' );
46 }
47 $this->title = $title;
48 if ( $config === null ) {
49 wfDebug( __METHOD__ . ' did not have a Config object passed to it' );
50 $config = MediaWikiServices::getInstance()->getMainConfig();
51 }
52 $this->config = $config;
53 }
54
55 public function doesWrites() {
56 return true;
57 }
58
59 /**
60 * List all deleted pages recorded in the archive table. Returns result
61 * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
62 * namespace/title.
63 *
64 * @return ResultWrapper
65 */
66 public static function listAllPages() {
67 $dbr = wfGetDB( DB_REPLICA );
68
69 return self::listPages( $dbr, '' );
70 }
71
72 /**
73 * List deleted pages recorded in the archive table matching the
74 * given title prefix.
75 * Returns result wrapper with (ar_namespace, ar_title, count) fields.
76 *
77 * @param string $prefix Title prefix
78 * @return ResultWrapper
79 */
80 public static function listPagesByPrefix( $prefix ) {
81 $dbr = wfGetDB( DB_REPLICA );
82
83 $title = Title::newFromText( $prefix );
84 if ( $title ) {
85 $ns = $title->getNamespace();
86 $prefix = $title->getDBkey();
87 } else {
88 // Prolly won't work too good
89 // @todo handle bare namespace names cleanly?
90 $ns = 0;
91 }
92
93 $conds = [
94 'ar_namespace' => $ns,
95 'ar_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
96 ];
97
98 return self::listPages( $dbr, $conds );
99 }
100
101 /**
102 * @param IDatabase $dbr
103 * @param string|array $condition
104 * @return bool|ResultWrapper
105 */
106 protected static function listPages( $dbr, $condition ) {
107 return $dbr->select(
108 [ 'archive' ],
109 [
110 'ar_namespace',
111 'ar_title',
112 'count' => 'COUNT(*)'
113 ],
114 $condition,
115 __METHOD__,
116 [
117 'GROUP BY' => [ 'ar_namespace', 'ar_title' ],
118 'ORDER BY' => [ 'ar_namespace', 'ar_title' ],
119 'LIMIT' => 100,
120 ]
121 );
122 }
123
124 /**
125 * List the revisions of the given page. Returns result wrapper with
126 * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
127 *
128 * @return ResultWrapper
129 */
130 function listRevisions() {
131 $dbr = wfGetDB( DB_REPLICA );
132
133 $tables = [ 'archive' ];
134
135 $fields = [
136 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text',
137 'ar_comment', 'ar_len', 'ar_deleted', 'ar_rev_id', 'ar_sha1',
138 ];
139
140 if ( $this->config->get( 'ContentHandlerUseDB' ) ) {
141 $fields[] = 'ar_content_format';
142 $fields[] = 'ar_content_model';
143 }
144
145 $conds = [ 'ar_namespace' => $this->title->getNamespace(),
146 'ar_title' => $this->title->getDBkey() ];
147
148 $options = [ 'ORDER BY' => 'ar_timestamp DESC' ];
149
150 $join_conds = [];
151
152 ChangeTags::modifyDisplayQuery(
153 $tables,
154 $fields,
155 $conds,
156 $join_conds,
157 $options,
158 ''
159 );
160
161 return $dbr->select( $tables,
162 $fields,
163 $conds,
164 __METHOD__,
165 $options,
166 $join_conds
167 );
168 }
169
170 /**
171 * List the deleted file revisions for this page, if it's a file page.
172 * Returns a result wrapper with various filearchive fields, or null
173 * if not a file page.
174 *
175 * @return ResultWrapper
176 * @todo Does this belong in Image for fuller encapsulation?
177 */
178 function listFiles() {
179 if ( $this->title->getNamespace() != NS_FILE ) {
180 return null;
181 }
182
183 $dbr = wfGetDB( DB_REPLICA );
184 return $dbr->select(
185 'filearchive',
186 ArchivedFile::selectFields(),
187 [ 'fa_name' => $this->title->getDBkey() ],
188 __METHOD__,
189 [ 'ORDER BY' => 'fa_timestamp DESC' ]
190 );
191 }
192
193 /**
194 * Return a Revision object containing data for the deleted revision.
195 * Note that the result *may* or *may not* have a null page ID.
196 *
197 * @param string $timestamp
198 * @return Revision|null
199 */
200 function getRevision( $timestamp ) {
201 $dbr = wfGetDB( DB_REPLICA );
202
203 $fields = [
204 'ar_rev_id',
205 'ar_text',
206 'ar_comment',
207 'ar_user',
208 'ar_user_text',
209 'ar_timestamp',
210 'ar_minor_edit',
211 'ar_flags',
212 'ar_text_id',
213 'ar_deleted',
214 'ar_len',
215 'ar_sha1',
216 ];
217
218 if ( $this->config->get( 'ContentHandlerUseDB' ) ) {
219 $fields[] = 'ar_content_format';
220 $fields[] = 'ar_content_model';
221 }
222
223 $row = $dbr->selectRow( 'archive',
224 $fields,
225 [ 'ar_namespace' => $this->title->getNamespace(),
226 'ar_title' => $this->title->getDBkey(),
227 'ar_timestamp' => $dbr->timestamp( $timestamp ) ],
228 __METHOD__ );
229
230 if ( $row ) {
231 return Revision::newFromArchiveRow( $row, [ 'title' => $this->title ] );
232 }
233
234 return null;
235 }
236
237 /**
238 * Return the most-previous revision, either live or deleted, against
239 * the deleted revision given by timestamp.
240 *
241 * May produce unexpected results in case of history merges or other
242 * unusual time issues.
243 *
244 * @param string $timestamp
245 * @return Revision|null Null when there is no previous revision
246 */
247 function getPreviousRevision( $timestamp ) {
248 $dbr = wfGetDB( DB_REPLICA );
249
250 // Check the previous deleted revision...
251 $row = $dbr->selectRow( 'archive',
252 'ar_timestamp',
253 [ 'ar_namespace' => $this->title->getNamespace(),
254 'ar_title' => $this->title->getDBkey(),
255 'ar_timestamp < ' .
256 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ],
257 __METHOD__,
258 [
259 'ORDER BY' => 'ar_timestamp DESC',
260 'LIMIT' => 1 ] );
261 $prevDeleted = $row ? wfTimestamp( TS_MW, $row->ar_timestamp ) : false;
262
263 $row = $dbr->selectRow( [ 'page', 'revision' ],
264 [ 'rev_id', 'rev_timestamp' ],
265 [
266 'page_namespace' => $this->title->getNamespace(),
267 'page_title' => $this->title->getDBkey(),
268 'page_id = rev_page',
269 'rev_timestamp < ' .
270 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ],
271 __METHOD__,
272 [
273 'ORDER BY' => 'rev_timestamp DESC',
274 'LIMIT' => 1 ] );
275 $prevLive = $row ? wfTimestamp( TS_MW, $row->rev_timestamp ) : false;
276 $prevLiveId = $row ? intval( $row->rev_id ) : null;
277
278 if ( $prevLive && $prevLive > $prevDeleted ) {
279 // Most prior revision was live
280 return Revision::newFromId( $prevLiveId );
281 } elseif ( $prevDeleted ) {
282 // Most prior revision was deleted
283 return $this->getRevision( $prevDeleted );
284 }
285
286 // No prior revision on this page.
287 return null;
288 }
289
290 /**
291 * Get the text from an archive row containing ar_text, ar_flags and ar_text_id
292 *
293 * @param object $row Database row
294 * @return string
295 */
296 function getTextFromRow( $row ) {
297 if ( is_null( $row->ar_text_id ) ) {
298 // An old row from MediaWiki 1.4 or previous.
299 // Text is embedded in this row in classic compression format.
300 return Revision::getRevisionText( $row, 'ar_' );
301 }
302
303 // New-style: keyed to the text storage backend.
304 $dbr = wfGetDB( DB_REPLICA );
305 $text = $dbr->selectRow( 'text',
306 [ 'old_text', 'old_flags' ],
307 [ 'old_id' => $row->ar_text_id ],
308 __METHOD__ );
309
310 return Revision::getRevisionText( $text );
311 }
312
313 /**
314 * Fetch (and decompress if necessary) the stored text of the most
315 * recently edited deleted revision of the page.
316 *
317 * If there are no archived revisions for the page, returns NULL.
318 *
319 * @return string|null
320 */
321 function getLastRevisionText() {
322 $dbr = wfGetDB( DB_REPLICA );
323 $row = $dbr->selectRow( 'archive',
324 [ 'ar_text', 'ar_flags', 'ar_text_id' ],
325 [ 'ar_namespace' => $this->title->getNamespace(),
326 'ar_title' => $this->title->getDBkey() ],
327 __METHOD__,
328 [ 'ORDER BY' => 'ar_timestamp DESC' ] );
329
330 if ( $row ) {
331 return $this->getTextFromRow( $row );
332 }
333
334 return null;
335 }
336
337 /**
338 * Quick check if any archived revisions are present for the page.
339 *
340 * @return bool
341 */
342 function isDeleted() {
343 $dbr = wfGetDB( DB_REPLICA );
344 $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
345 [ 'ar_namespace' => $this->title->getNamespace(),
346 'ar_title' => $this->title->getDBkey() ],
347 __METHOD__
348 );
349
350 return ( $n > 0 );
351 }
352
353 /**
354 * Restore the given (or all) text and file revisions for the page.
355 * Once restored, the items will be removed from the archive tables.
356 * The deletion log will be updated with an undeletion notice.
357 *
358 * This also sets Status objects, $this->fileStatus and $this->revisionStatus
359 * (depending what operations are attempted).
360 *
361 * @param array $timestamps Pass an empty array to restore all revisions,
362 * otherwise list the ones to undelete.
363 * @param string $comment
364 * @param array $fileVersions
365 * @param bool $unsuppress
366 * @param User $user User performing the action, or null to use $wgUser
367 * @param string|string[] $tags Change tags to add to log entry
368 * ($user should be able to add the specified tags before this is called)
369 * @return array(number of file revisions restored, number of image revisions
370 * restored, log message) on success, false on failure.
371 */
372 function undelete( $timestamps, $comment = '', $fileVersions = [],
373 $unsuppress = false, User $user = null, $tags = null
374 ) {
375 // If both the set of text revisions and file revisions are empty,
376 // restore everything. Otherwise, just restore the requested items.
377 $restoreAll = empty( $timestamps ) && empty( $fileVersions );
378
379 $restoreText = $restoreAll || !empty( $timestamps );
380 $restoreFiles = $restoreAll || !empty( $fileVersions );
381
382 if ( $restoreFiles && $this->title->getNamespace() == NS_FILE ) {
383 $img = wfLocalFile( $this->title );
384 $img->load( File::READ_LATEST );
385 $this->fileStatus = $img->restore( $fileVersions, $unsuppress );
386 if ( !$this->fileStatus->isOK() ) {
387 return false;
388 }
389 $filesRestored = $this->fileStatus->successCount;
390 } else {
391 $filesRestored = 0;
392 }
393
394 if ( $restoreText ) {
395 $this->revisionStatus = $this->undeleteRevisions( $timestamps, $unsuppress, $comment );
396 if ( !$this->revisionStatus->isOK() ) {
397 return false;
398 }
399
400 $textRestored = $this->revisionStatus->getValue();
401 } else {
402 $textRestored = 0;
403 }
404
405 // Touch the log!
406
407 if ( $textRestored && $filesRestored ) {
408 $reason = wfMessage( 'undeletedrevisions-files' )
409 ->numParams( $textRestored, $filesRestored )->inContentLanguage()->text();
410 } elseif ( $textRestored ) {
411 $reason = wfMessage( 'undeletedrevisions' )->numParams( $textRestored )
412 ->inContentLanguage()->text();
413 } elseif ( $filesRestored ) {
414 $reason = wfMessage( 'undeletedfiles' )->numParams( $filesRestored )
415 ->inContentLanguage()->text();
416 } else {
417 wfDebug( "Undelete: nothing undeleted...\n" );
418
419 return false;
420 }
421
422 if ( trim( $comment ) != '' ) {
423 $reason .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
424 }
425
426 if ( $user === null ) {
427 global $wgUser;
428 $user = $wgUser;
429 }
430
431 $logEntry = new ManualLogEntry( 'delete', 'restore' );
432 $logEntry->setPerformer( $user );
433 $logEntry->setTarget( $this->title );
434 $logEntry->setComment( $reason );
435 $logEntry->setTags( $tags );
436
437 Hooks::run( 'ArticleUndeleteLogEntry', [ $this, &$logEntry, $user ] );
438
439 $logid = $logEntry->insert();
440 $logEntry->publish( $logid );
441
442 return [ $textRestored, $filesRestored, $reason ];
443 }
444
445 /**
446 * This is the meaty bit -- It restores archived revisions of the given page
447 * to the revision table.
448 *
449 * @param array $timestamps Pass an empty array to restore all revisions,
450 * otherwise list the ones to undelete.
451 * @param bool $unsuppress Remove all ar_deleted/fa_deleted restrictions of seletected revs
452 * @param string $comment
453 * @throws ReadOnlyError
454 * @return Status Status object containing the number of revisions restored on success
455 */
456 private function undeleteRevisions( $timestamps, $unsuppress = false, $comment = '' ) {
457 if ( wfReadOnly() ) {
458 throw new ReadOnlyError();
459 }
460
461 $dbw = wfGetDB( DB_MASTER );
462 $dbw->startAtomic( __METHOD__ );
463
464 $restoreAll = empty( $timestamps );
465
466 # Does this page already exist? We'll have to update it...
467 $article = WikiPage::factory( $this->title );
468 # Load latest data for the current page (bug 31179)
469 $article->loadPageData( 'fromdbmaster' );
470 $oldcountable = $article->isCountable();
471
472 $page = $dbw->selectRow( 'page',
473 [ 'page_id', 'page_latest' ],
474 [ 'page_namespace' => $this->title->getNamespace(),
475 'page_title' => $this->title->getDBkey() ],
476 __METHOD__,
477 [ 'FOR UPDATE' ] // lock page
478 );
479
480 if ( $page ) {
481 $makepage = false;
482 # Page already exists. Import the history, and if necessary
483 # we'll update the latest revision field in the record.
484
485 # Get the time span of this page
486 $previousTimestamp = $dbw->selectField( 'revision', 'rev_timestamp',
487 [ 'rev_id' => $page->page_latest ],
488 __METHOD__ );
489
490 if ( $previousTimestamp === false ) {
491 wfDebug( __METHOD__ . ": existing page refers to a page_latest that does not exist\n" );
492
493 $status = Status::newGood( 0 );
494 $status->warning( 'undeleterevision-missing' );
495 $dbw->endAtomic( __METHOD__ );
496
497 return $status;
498 }
499 } else {
500 # Have to create a new article...
501 $makepage = true;
502 $previousTimestamp = 0;
503 }
504
505 $oldWhere = [
506 'ar_namespace' => $this->title->getNamespace(),
507 'ar_title' => $this->title->getDBkey(),
508 ];
509 if ( !$restoreAll ) {
510 $oldWhere['ar_timestamp'] = array_map( [ &$dbw, 'timestamp' ], $timestamps );
511 }
512
513 $fields = [
514 'ar_id',
515 'ar_rev_id',
516 'rev_id',
517 'ar_text',
518 'ar_comment',
519 'ar_user',
520 'ar_user_text',
521 'ar_timestamp',
522 'ar_minor_edit',
523 'ar_flags',
524 'ar_text_id',
525 'ar_deleted',
526 'ar_page_id',
527 'ar_len',
528 'ar_sha1'
529 ];
530
531 if ( $this->config->get( 'ContentHandlerUseDB' ) ) {
532 $fields[] = 'ar_content_format';
533 $fields[] = 'ar_content_model';
534 }
535
536 /**
537 * Select each archived revision...
538 */
539 $result = $dbw->select(
540 [ 'archive', 'revision' ],
541 $fields,
542 $oldWhere,
543 __METHOD__,
544 /* options */
545 [ 'ORDER BY' => 'ar_timestamp' ],
546 [ 'revision' => [ 'LEFT JOIN', 'ar_rev_id=rev_id' ] ]
547 );
548
549 $rev_count = $result->numRows();
550 if ( !$rev_count ) {
551 wfDebug( __METHOD__ . ": no revisions to restore\n" );
552
553 $status = Status::newGood( 0 );
554 $status->warning( "undelete-no-results" );
555 $dbw->endAtomic( __METHOD__ );
556
557 return $status;
558 }
559
560 // We use ar_id because there can be duplicate ar_rev_id even for the same
561 // page. In this case, we may be able to restore the first one.
562 $restoreFailedArIds = [];
563
564 // Map rev_id to the ar_id that is allowed to use it. When checking later,
565 // if it doesn't match, the current ar_id can not be restored.
566
567 // Value can be an ar_id or -1 (-1 means no ar_id can use it, since the
568 // rev_id is taken before we even start the restore).
569 $allowedRevIdToArIdMap = [];
570
571 $latestRestorableRow = null;
572
573 foreach ( $result as $row ) {
574 if ( $row->ar_rev_id ) {
575 // rev_id is taken even before we start restoring.
576 if ( $row->ar_rev_id === $row->rev_id ) {
577 $restoreFailedArIds[] = $row->ar_id;
578 $allowedRevIdToArIdMap[$row->ar_rev_id] = -1;
579 } else {
580 // rev_id is not taken yet in the DB, but it might be taken
581 // by a prior revision in the same restore operation. If
582 // not, we need to reserve it.
583 if ( isset( $allowedRevIdToArIdMap[$row->ar_rev_id] ) ) {
584 $restoreFailedArIds[] = $row->ar_id;
585 } else {
586 $allowedRevIdToArIdMap[$row->ar_rev_id] = $row->ar_id;
587 $latestRestorableRow = $row;
588 }
589 }
590 } else {
591 // If ar_rev_id is null, there can't be a collision, and a
592 // rev_id will be chosen automatically.
593 $latestRestorableRow = $row;
594 }
595 }
596
597 $result->seek( 0 ); // move back
598
599 $oldPageId = 0;
600 if ( $latestRestorableRow !== null ) {
601 $oldPageId = (int)$latestRestorableRow->ar_page_id; // pass this to ArticleUndelete hook
602
603 // grab the content to check consistency with global state before restoring the page.
604 $revision = Revision::newFromArchiveRow( $latestRestorableRow,
605 [
606 'title' => $article->getTitle(), // used to derive default content model
607 ]
608 );
609 $user = User::newFromName( $revision->getUserText( Revision::RAW ), false );
610 $content = $revision->getContent( Revision::RAW );
611
612 // NOTE: article ID may not be known yet. prepareSave() should not modify the database.
613 $status = $content->prepareSave( $article, 0, -1, $user );
614 if ( !$status->isOK() ) {
615 $dbw->endAtomic( __METHOD__ );
616
617 return $status;
618 }
619 }
620
621 $newid = false; // newly created page ID
622 $restored = 0; // number of revisions restored
623 /** @var Revision $revision */
624 $revision = null;
625
626 // If there are no restorable revisions, we can skip most of the steps.
627 if ( $latestRestorableRow === null ) {
628 $failedRevisionCount = $rev_count;
629 } else {
630 if ( $makepage ) {
631 // Check the state of the newest to-be version...
632 if ( !$unsuppress
633 && ( $latestRestorableRow->ar_deleted & Revision::DELETED_TEXT )
634 ) {
635 $dbw->endAtomic( __METHOD__ );
636
637 return Status::newFatal( "undeleterevdel" );
638 }
639 // Safe to insert now...
640 $newid = $article->insertOn( $dbw, $latestRestorableRow->ar_page_id );
641 if ( $newid === false ) {
642 // The old ID is reserved; let's pick another
643 $newid = $article->insertOn( $dbw );
644 }
645 $pageId = $newid;
646 } else {
647 // Check if a deleted revision will become the current revision...
648 if ( $latestRestorableRow->ar_timestamp > $previousTimestamp ) {
649 // Check the state of the newest to-be version...
650 if ( !$unsuppress
651 && ( $latestRestorableRow->ar_deleted & Revision::DELETED_TEXT )
652 ) {
653 $dbw->endAtomic( __METHOD__ );
654
655 return Status::newFatal( "undeleterevdel" );
656 }
657 }
658
659 $newid = false;
660 $pageId = $article->getId();
661 }
662
663 foreach ( $result as $row ) {
664 // Check for key dupes due to needed archive integrity.
665 if ( $row->ar_rev_id && $allowedRevIdToArIdMap[$row->ar_rev_id] !== $row->ar_id ) {
666 continue;
667 }
668 // Insert one revision at a time...maintaining deletion status
669 // unless we are specifically removing all restrictions...
670 $revision = Revision::newFromArchiveRow( $row,
671 [
672 'page' => $pageId,
673 'title' => $this->title,
674 'deleted' => $unsuppress ? 0 : $row->ar_deleted
675 ] );
676
677 $revision->insertOn( $dbw );
678 $restored++;
679
680 Hooks::run( 'ArticleRevisionUndeleted',
681 [ &$this->title, $revision, $row->ar_page_id ] );
682 }
683
684 // Now that it's safely stored, take it out of the archive
685 // Don't delete rows that we failed to restore
686 $toDeleteConds = $oldWhere;
687 $failedRevisionCount = count( $restoreFailedArIds );
688 if ( $failedRevisionCount > 0 ) {
689 $toDeleteConds[] = 'ar_id NOT IN ( ' . $dbw->makeList( $restoreFailedArIds ) . ' )';
690 }
691
692 $dbw->delete( 'archive',
693 $toDeleteConds,
694 __METHOD__ );
695 }
696
697 $status = Status::newGood( $restored );
698
699 if ( $failedRevisionCount > 0 ) {
700 $status->warning(
701 wfMessage( 'undeleterevision-duplicate-revid', $failedRevisionCount ) );
702 }
703
704 // Was anything restored at all?
705 if ( $restored ) {
706 $created = (bool)$newid;
707 // Attach the latest revision to the page...
708 $wasnew = $article->updateIfNewerOn( $dbw, $revision );
709 if ( $created || $wasnew ) {
710 // Update site stats, link tables, etc
711 $article->doEditUpdates(
712 $revision,
713 User::newFromName( $revision->getUserText( Revision::RAW ), false ),
714 [
715 'created' => $created,
716 'oldcountable' => $oldcountable,
717 'restored' => true
718 ]
719 );
720 }
721
722 Hooks::run( 'ArticleUndelete', [ &$this->title, $created, $comment, $oldPageId ] );
723 if ( $this->title->getNamespace() == NS_FILE ) {
724 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->title, 'imagelinks' ) );
725 }
726 }
727
728 $dbw->endAtomic( __METHOD__ );
729
730 return $status;
731 }
732
733 /**
734 * @return Status
735 */
736 function getFileStatus() {
737 return $this->fileStatus;
738 }
739
740 /**
741 * @return Status
742 */
743 function getRevisionStatus() {
744 return $this->revisionStatus;
745 }
746 }
747
748 /**
749 * Special page allowing users with the appropriate permissions to view
750 * and restore deleted content.
751 *
752 * @ingroup SpecialPage
753 */
754 class SpecialUndelete extends SpecialPage {
755 private $mAction;
756 private $mTarget;
757 private $mTimestamp;
758 private $mRestore;
759 private $mRevdel;
760 private $mInvert;
761 private $mFilename;
762 private $mTargetTimestamp;
763 private $mAllowed;
764 private $mCanView;
765 private $mComment;
766 private $mToken;
767
768 /** @var Title */
769 private $mTargetObj;
770
771 function __construct() {
772 parent::__construct( 'Undelete', 'deletedhistory' );
773 }
774
775 public function doesWrites() {
776 return true;
777 }
778
779 function loadRequest( $par ) {
780 $request = $this->getRequest();
781 $user = $this->getUser();
782
783 $this->mAction = $request->getVal( 'action' );
784 if ( $par !== null && $par !== '' ) {
785 $this->mTarget = $par;
786 } else {
787 $this->mTarget = $request->getVal( 'target' );
788 }
789
790 $this->mTargetObj = null;
791
792 if ( $this->mTarget !== null && $this->mTarget !== '' ) {
793 $this->mTargetObj = Title::newFromText( $this->mTarget );
794 }
795
796 $this->mSearchPrefix = $request->getText( 'prefix' );
797 $time = $request->getVal( 'timestamp' );
798 $this->mTimestamp = $time ? wfTimestamp( TS_MW, $time ) : '';
799 $this->mFilename = $request->getVal( 'file' );
800
801 $posted = $request->wasPosted() &&
802 $user->matchEditToken( $request->getVal( 'wpEditToken' ) );
803 $this->mRestore = $request->getCheck( 'restore' ) && $posted;
804 $this->mRevdel = $request->getCheck( 'revdel' ) && $posted;
805 $this->mInvert = $request->getCheck( 'invert' ) && $posted;
806 $this->mPreview = $request->getCheck( 'preview' ) && $posted;
807 $this->mDiff = $request->getCheck( 'diff' );
808 $this->mDiffOnly = $request->getBool( 'diffonly', $this->getUser()->getOption( 'diffonly' ) );
809 $this->mComment = $request->getText( 'wpComment' );
810 $this->mUnsuppress = $request->getVal( 'wpUnsuppress' ) && $user->isAllowed( 'suppressrevision' );
811 $this->mToken = $request->getVal( 'token' );
812
813 if ( $this->isAllowed( 'undelete' ) && !$user->isBlocked() ) {
814 $this->mAllowed = true; // user can restore
815 $this->mCanView = true; // user can view content
816 } elseif ( $this->isAllowed( 'deletedtext' ) ) {
817 $this->mAllowed = false; // user cannot restore
818 $this->mCanView = true; // user can view content
819 $this->mRestore = false;
820 } else { // user can only view the list of revisions
821 $this->mAllowed = false;
822 $this->mCanView = false;
823 $this->mTimestamp = '';
824 $this->mRestore = false;
825 }
826
827 if ( $this->mRestore || $this->mInvert ) {
828 $timestamps = [];
829 $this->mFileVersions = [];
830 foreach ( $request->getValues() as $key => $val ) {
831 $matches = [];
832 if ( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
833 array_push( $timestamps, $matches[1] );
834 }
835
836 if ( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
837 $this->mFileVersions[] = intval( $matches[1] );
838 }
839 }
840 rsort( $timestamps );
841 $this->mTargetTimestamp = $timestamps;
842 }
843 }
844
845 /**
846 * Checks whether a user is allowed the permission for the
847 * specific title if one is set.
848 *
849 * @param string $permission
850 * @param User $user
851 * @return bool
852 */
853 protected function isAllowed( $permission, User $user = null ) {
854 $user = $user ?: $this->getUser();
855 if ( $this->mTargetObj !== null ) {
856 return $this->mTargetObj->userCan( $permission, $user );
857 } else {
858 return $user->isAllowed( $permission );
859 }
860 }
861
862 function userCanExecute( User $user ) {
863 return $this->isAllowed( $this->mRestriction, $user );
864 }
865
866 function execute( $par ) {
867 $this->useTransactionalTimeLimit();
868
869 $user = $this->getUser();
870
871 $this->setHeaders();
872 $this->outputHeader();
873
874 $this->loadRequest( $par );
875 $this->checkPermissions(); // Needs to be after mTargetObj is set
876
877 $out = $this->getOutput();
878
879 if ( is_null( $this->mTargetObj ) ) {
880 $out->addWikiMsg( 'undelete-header' );
881
882 # Not all users can just browse every deleted page from the list
883 if ( $user->isAllowed( 'browsearchive' ) ) {
884 $this->showSearchForm();
885 }
886
887 return;
888 }
889
890 $this->addHelpLink( 'Help:Undelete' );
891 if ( $this->mAllowed ) {
892 $out->setPageTitle( $this->msg( 'undeletepage' ) );
893 } else {
894 $out->setPageTitle( $this->msg( 'viewdeletedpage' ) );
895 }
896
897 $this->getSkin()->setRelevantTitle( $this->mTargetObj );
898
899 if ( $this->mTimestamp !== '' ) {
900 $this->showRevision( $this->mTimestamp );
901 } elseif ( $this->mFilename !== null && $this->mTargetObj->inNamespace( NS_FILE ) ) {
902 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
903 // Check if user is allowed to see this file
904 if ( !$file->exists() ) {
905 $out->addWikiMsg( 'filedelete-nofile', $this->mFilename );
906 } elseif ( !$file->userCan( File::DELETED_FILE, $user ) ) {
907 if ( $file->isDeleted( File::DELETED_RESTRICTED ) ) {
908 throw new PermissionsError( 'suppressrevision' );
909 } else {
910 throw new PermissionsError( 'deletedtext' );
911 }
912 } elseif ( !$user->matchEditToken( $this->mToken, $this->mFilename ) ) {
913 $this->showFileConfirmationForm( $this->mFilename );
914 } else {
915 $this->showFile( $this->mFilename );
916 }
917 } elseif ( $this->mAction === "submit" ) {
918 if ( $this->mRestore ) {
919 $this->undelete();
920 } elseif ( $this->mRevdel ) {
921 $this->redirectToRevDel();
922 }
923
924 } else {
925 $this->showHistory();
926 }
927 }
928
929 /**
930 * Convert submitted form data to format expected by RevisionDelete and
931 * redirect the request
932 */
933 private function redirectToRevDel() {
934 $archive = new PageArchive( $this->mTargetObj );
935
936 $revisions = [];
937
938 foreach ( $this->getRequest()->getValues() as $key => $val ) {
939 $matches = [];
940 if ( preg_match( "/^ts(\d{14})$/", $key, $matches ) ) {
941 $revisions[ $archive->getRevision( $matches[1] )->getId() ] = 1;
942 }
943 }
944 $query = [
945 "type" => "revision",
946 "ids" => $revisions,
947 "target" => $this->mTargetObj->getPrefixedText()
948 ];
949 $url = SpecialPage::getTitleFor( 'Revisiondelete' )->getFullURL( $query );
950 $this->getOutput()->redirect( $url );
951 }
952
953 function showSearchForm() {
954 $out = $this->getOutput();
955 $out->setPageTitle( $this->msg( 'undelete-search-title' ) );
956 $out->addHTML(
957 Xml::openElement( 'form', [ 'method' => 'get', 'action' => wfScript() ] ) .
958 Xml::fieldset( $this->msg( 'undelete-search-box' )->text() ) .
959 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
960 Html::rawElement(
961 'label',
962 [ 'for' => 'prefix' ],
963 $this->msg( 'undelete-search-prefix' )->parse()
964 ) .
965 Xml::input(
966 'prefix',
967 20,
968 $this->mSearchPrefix,
969 [ 'id' => 'prefix', 'autofocus' => '' ]
970 ) . ' ' .
971 Xml::submitButton( $this->msg( 'undelete-search-submit' )->text() ) .
972 Xml::closeElement( 'fieldset' ) .
973 Xml::closeElement( 'form' )
974 );
975
976 # List undeletable articles
977 if ( $this->mSearchPrefix ) {
978 $result = PageArchive::listPagesByPrefix( $this->mSearchPrefix );
979 $this->showList( $result );
980 }
981 }
982
983 /**
984 * Generic list of deleted pages
985 *
986 * @param ResultWrapper $result
987 * @return bool
988 */
989 private function showList( $result ) {
990 $out = $this->getOutput();
991
992 if ( $result->numRows() == 0 ) {
993 $out->addWikiMsg( 'undelete-no-results' );
994
995 return false;
996 }
997
998 $out->addWikiMsg( 'undeletepagetext', $this->getLanguage()->formatNum( $result->numRows() ) );
999
1000 $linkRenderer = $this->getLinkRenderer();
1001 $undelete = $this->getPageTitle();
1002 $out->addHTML( "<ul>\n" );
1003 foreach ( $result as $row ) {
1004 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
1005 if ( $title !== null ) {
1006 $item = $linkRenderer->makeKnownLink(
1007 $undelete,
1008 $title->getPrefixedText(),
1009 [],
1010 [ 'target' => $title->getPrefixedText() ]
1011 );
1012 } else {
1013 // The title is no longer valid, show as text
1014 $item = Html::element(
1015 'span',
1016 [ 'class' => 'mw-invalidtitle' ],
1017 Linker::getInvalidTitleDescription(
1018 $this->getContext(),
1019 $row->ar_namespace,
1020 $row->ar_title
1021 )
1022 );
1023 }
1024 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count )->parse();
1025 $out->addHTML( "<li>{$item} ({$revs})</li>\n" );
1026 }
1027 $result->free();
1028 $out->addHTML( "</ul>\n" );
1029
1030 return true;
1031 }
1032
1033 private function showRevision( $timestamp ) {
1034 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
1035 return;
1036 }
1037
1038 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1039 if ( !Hooks::run( 'UndeleteForm::showRevision', [ &$archive, $this->mTargetObj ] ) ) {
1040 return;
1041 }
1042 $rev = $archive->getRevision( $timestamp );
1043
1044 $out = $this->getOutput();
1045 $user = $this->getUser();
1046
1047 if ( !$rev ) {
1048 $out->addWikiMsg( 'undeleterevision-missing' );
1049
1050 return;
1051 }
1052
1053 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1054 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1055 $out->wrapWikiMsg(
1056 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1057 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
1058 'rev-suppressed-text-permission' : 'rev-deleted-text-permission'
1059 );
1060
1061 return;
1062 }
1063
1064 $out->wrapWikiMsg(
1065 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1066 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
1067 'rev-suppressed-text-view' : 'rev-deleted-text-view'
1068 );
1069 $out->addHTML( '<br />' );
1070 // and we are allowed to see...
1071 }
1072
1073 if ( $this->mDiff ) {
1074 $previousRev = $archive->getPreviousRevision( $timestamp );
1075 if ( $previousRev ) {
1076 $this->showDiff( $previousRev, $rev );
1077 if ( $this->mDiffOnly ) {
1078 return;
1079 }
1080
1081 $out->addHTML( '<hr />' );
1082 } else {
1083 $out->addWikiMsg( 'undelete-nodiff' );
1084 }
1085 }
1086
1087 $link = $this->getLinkRenderer()->makeKnownLink(
1088 $this->getPageTitle( $this->mTargetObj->getPrefixedDBkey() ),
1089 $this->mTargetObj->getPrefixedText()
1090 );
1091
1092 $lang = $this->getLanguage();
1093
1094 // date and time are separate parameters to facilitate localisation.
1095 // $time is kept for backward compat reasons.
1096 $time = $lang->userTimeAndDate( $timestamp, $user );
1097 $d = $lang->userDate( $timestamp, $user );
1098 $t = $lang->userTime( $timestamp, $user );
1099 $userLink = Linker::revUserTools( $rev );
1100
1101 $content = $rev->getContent( Revision::FOR_THIS_USER, $user );
1102
1103 $isText = ( $content instanceof TextContent );
1104
1105 if ( $this->mPreview || $isText ) {
1106 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
1107 } else {
1108 $openDiv = '<div id="mw-undelete-revision">';
1109 }
1110 $out->addHTML( $openDiv );
1111
1112 // Revision delete links
1113 if ( !$this->mDiff ) {
1114 $revdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
1115 if ( $revdel ) {
1116 $out->addHTML( "$revdel " );
1117 }
1118 }
1119
1120 $out->addHTML( $this->msg( 'undelete-revision' )->rawParams( $link )->params(
1121 $time )->rawParams( $userLink )->params( $d, $t )->parse() . '</div>' );
1122
1123 if ( !Hooks::run( 'UndeleteShowRevision', [ $this->mTargetObj, $rev ] ) ) {
1124 return;
1125 }
1126
1127 if ( ( $this->mPreview || !$isText ) && $content ) {
1128 // NOTE: non-text content has no source view, so always use rendered preview
1129
1130 // Hide [edit]s
1131 $popts = $out->parserOptions();
1132 $popts->setEditSection( false );
1133
1134 $pout = $content->getParserOutput( $this->mTargetObj, $rev->getId(), $popts, true );
1135 $out->addParserOutput( $pout );
1136 }
1137
1138 if ( $isText ) {
1139 // source view for textual content
1140 $sourceView = Xml::element(
1141 'textarea',
1142 [
1143 'readonly' => 'readonly',
1144 'cols' => $user->getIntOption( 'cols' ),
1145 'rows' => $user->getIntOption( 'rows' )
1146 ],
1147 $content->getNativeData() . "\n"
1148 );
1149
1150 $previewButton = Xml::element( 'input', [
1151 'type' => 'submit',
1152 'name' => 'preview',
1153 'value' => $this->msg( 'showpreview' )->text()
1154 ] );
1155 } else {
1156 $sourceView = '';
1157 $previewButton = '';
1158 }
1159
1160 $diffButton = Xml::element( 'input', [
1161 'name' => 'diff',
1162 'type' => 'submit',
1163 'value' => $this->msg( 'showdiff' )->text() ] );
1164
1165 $out->addHTML(
1166 $sourceView .
1167 Xml::openElement( 'div', [
1168 'style' => 'clear: both' ] ) .
1169 Xml::openElement( 'form', [
1170 'method' => 'post',
1171 'action' => $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] ) ] ) .
1172 Xml::element( 'input', [
1173 'type' => 'hidden',
1174 'name' => 'target',
1175 'value' => $this->mTargetObj->getPrefixedDBkey() ] ) .
1176 Xml::element( 'input', [
1177 'type' => 'hidden',
1178 'name' => 'timestamp',
1179 'value' => $timestamp ] ) .
1180 Xml::element( 'input', [
1181 'type' => 'hidden',
1182 'name' => 'wpEditToken',
1183 'value' => $user->getEditToken() ] ) .
1184 $previewButton .
1185 $diffButton .
1186 Xml::closeElement( 'form' ) .
1187 Xml::closeElement( 'div' )
1188 );
1189 }
1190
1191 /**
1192 * Build a diff display between this and the previous either deleted
1193 * or non-deleted edit.
1194 *
1195 * @param Revision $previousRev
1196 * @param Revision $currentRev
1197 * @return string HTML
1198 */
1199 function showDiff( $previousRev, $currentRev ) {
1200 $diffContext = clone $this->getContext();
1201 $diffContext->setTitle( $currentRev->getTitle() );
1202 $diffContext->setWikiPage( WikiPage::factory( $currentRev->getTitle() ) );
1203
1204 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
1205 $diffEngine->showDiffStyle();
1206
1207 $formattedDiff = $diffEngine->generateContentDiffBody(
1208 $previousRev->getContent( Revision::FOR_THIS_USER, $this->getUser() ),
1209 $currentRev->getContent( Revision::FOR_THIS_USER, $this->getUser() )
1210 );
1211
1212 $formattedDiff = $diffEngine->addHeader(
1213 $formattedDiff,
1214 $this->diffHeader( $previousRev, 'o' ),
1215 $this->diffHeader( $currentRev, 'n' )
1216 );
1217
1218 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
1219 }
1220
1221 /**
1222 * @param Revision $rev
1223 * @param string $prefix
1224 * @return string
1225 */
1226 private function diffHeader( $rev, $prefix ) {
1227 $isDeleted = !( $rev->getId() && $rev->getTitle() );
1228 if ( $isDeleted ) {
1229 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
1230 $targetPage = $this->getPageTitle();
1231 $targetQuery = [
1232 'target' => $this->mTargetObj->getPrefixedText(),
1233 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
1234 ];
1235 } else {
1236 /// @todo FIXME: getId() may return non-zero for deleted revs...
1237 $targetPage = $rev->getTitle();
1238 $targetQuery = [ 'oldid' => $rev->getId() ];
1239 }
1240
1241 // Add show/hide deletion links if available
1242 $user = $this->getUser();
1243 $lang = $this->getLanguage();
1244 $rdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
1245
1246 if ( $rdel ) {
1247 $rdel = " $rdel";
1248 }
1249
1250 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
1251
1252 $tags = wfGetDB( DB_REPLICA )->selectField(
1253 'tag_summary',
1254 'ts_tags',
1255 [ 'ts_rev_id' => $rev->getId() ],
1256 __METHOD__
1257 );
1258 $tagSummary = ChangeTags::formatSummaryRow( $tags, 'deleteddiff', $this->getContext() );
1259
1260 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
1261 // and partially #showDiffPage, but worse
1262 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
1263 $this->getLinkRenderer()->makeLink(
1264 $targetPage,
1265 $this->msg(
1266 'revisionasof',
1267 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
1268 $lang->userDate( $rev->getTimestamp(), $user ),
1269 $lang->userTime( $rev->getTimestamp(), $user )
1270 )->text(),
1271 [],
1272 $targetQuery
1273 ) .
1274 '</strong></div>' .
1275 '<div id="mw-diff-' . $prefix . 'title2">' .
1276 Linker::revUserTools( $rev ) . '<br />' .
1277 '</div>' .
1278 '<div id="mw-diff-' . $prefix . 'title3">' .
1279 $minor . Linker::revComment( $rev ) . $rdel . '<br />' .
1280 '</div>' .
1281 '<div id="mw-diff-' . $prefix . 'title5">' .
1282 $tagSummary[0] . '<br />' .
1283 '</div>';
1284 }
1285
1286 /**
1287 * Show a form confirming whether a tokenless user really wants to see a file
1288 * @param string $key
1289 */
1290 private function showFileConfirmationForm( $key ) {
1291 $out = $this->getOutput();
1292 $lang = $this->getLanguage();
1293 $user = $this->getUser();
1294 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
1295 $out->addWikiMsg( 'undelete-show-file-confirm',
1296 $this->mTargetObj->getText(),
1297 $lang->userDate( $file->getTimestamp(), $user ),
1298 $lang->userTime( $file->getTimestamp(), $user ) );
1299 $out->addHTML(
1300 Xml::openElement( 'form', [
1301 'method' => 'POST',
1302 'action' => $this->getPageTitle()->getLocalURL( [
1303 'target' => $this->mTarget,
1304 'file' => $key,
1305 'token' => $user->getEditToken( $key ),
1306 ] ),
1307 ]
1308 ) .
1309 Xml::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
1310 '</form>'
1311 );
1312 }
1313
1314 /**
1315 * Show a deleted file version requested by the visitor.
1316 * @param string $key
1317 */
1318 private function showFile( $key ) {
1319 $this->getOutput()->disable();
1320
1321 # We mustn't allow the output to be CDN cached, otherwise
1322 # if an admin previews a deleted image, and it's cached, then
1323 # a user without appropriate permissions can toddle off and
1324 # nab the image, and CDN will serve it
1325 $response = $this->getRequest()->response();
1326 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1327 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1328 $response->header( 'Pragma: no-cache' );
1329
1330 $repo = RepoGroup::singleton()->getLocalRepo();
1331 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
1332 $repo->streamFile( $path );
1333 }
1334
1335 protected function showHistory() {
1336 $this->checkReadOnly();
1337
1338 $out = $this->getOutput();
1339 if ( $this->mAllowed ) {
1340 $out->addModules( 'mediawiki.special.undelete' );
1341 }
1342 $out->wrapWikiMsg(
1343 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
1344 [ 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj->getPrefixedText() ) ]
1345 );
1346
1347 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1348 Hooks::run( 'UndeleteForm::showHistory', [ &$archive, $this->mTargetObj ] );
1349 /*
1350 $text = $archive->getLastRevisionText();
1351 if( is_null( $text ) ) {
1352 $out->addWikiMsg( 'nohistory' );
1353 return;
1354 }
1355 */
1356 $out->addHTML( '<div class="mw-undelete-history">' );
1357 if ( $this->mAllowed ) {
1358 $out->addWikiMsg( 'undeletehistory' );
1359 $out->addWikiMsg( 'undeleterevdel' );
1360 } else {
1361 $out->addWikiMsg( 'undeletehistorynoadmin' );
1362 }
1363 $out->addHTML( '</div>' );
1364
1365 # List all stored revisions
1366 $revisions = $archive->listRevisions();
1367 $files = $archive->listFiles();
1368
1369 $haveRevisions = $revisions && $revisions->numRows() > 0;
1370 $haveFiles = $files && $files->numRows() > 0;
1371
1372 # Batch existence check on user and talk pages
1373 if ( $haveRevisions ) {
1374 $batch = new LinkBatch();
1375 foreach ( $revisions as $row ) {
1376 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
1377 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
1378 }
1379 $batch->execute();
1380 $revisions->seek( 0 );
1381 }
1382 if ( $haveFiles ) {
1383 $batch = new LinkBatch();
1384 foreach ( $files as $row ) {
1385 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
1386 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
1387 }
1388 $batch->execute();
1389 $files->seek( 0 );
1390 }
1391
1392 if ( $this->mAllowed ) {
1393 $action = $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] );
1394 # Start the form here
1395 $top = Xml::openElement(
1396 'form',
1397 [ 'method' => 'post', 'action' => $action, 'id' => 'undelete' ]
1398 );
1399 $out->addHTML( $top );
1400 }
1401
1402 # Show relevant lines from the deletion log:
1403 $deleteLogPage = new LogPage( 'delete' );
1404 $out->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
1405 LogEventsList::showLogExtract( $out, 'delete', $this->mTargetObj );
1406 # Show relevant lines from the suppression log:
1407 $suppressLogPage = new LogPage( 'suppress' );
1408 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
1409 $out->addHTML( Xml::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
1410 LogEventsList::showLogExtract( $out, 'suppress', $this->mTargetObj );
1411 }
1412
1413 if ( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
1414 # Format the user-visible controls (comment field, submission button)
1415 # in a nice little table
1416 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
1417 $unsuppressBox =
1418 "<tr>
1419 <td>&#160;</td>
1420 <td class='mw-input'>" .
1421 Xml::checkLabel( $this->msg( 'revdelete-unsuppress' )->text(),
1422 'wpUnsuppress', 'mw-undelete-unsuppress', $this->mUnsuppress ) .
1423 "</td>
1424 </tr>";
1425 } else {
1426 $unsuppressBox = '';
1427 }
1428
1429 $table = Xml::fieldset( $this->msg( 'undelete-fieldset-title' )->text() ) .
1430 Xml::openElement( 'table', [ 'id' => 'mw-undelete-table' ] ) .
1431 "<tr>
1432 <td colspan='2' class='mw-undelete-extrahelp'>" .
1433 $this->msg( 'undeleteextrahelp' )->parseAsBlock() .
1434 "</td>
1435 </tr>
1436 <tr>
1437 <td class='mw-label'>" .
1438 Xml::label( $this->msg( 'undeletecomment' )->text(), 'wpComment' ) .
1439 "</td>
1440 <td class='mw-input'>" .
1441 Xml::input(
1442 'wpComment',
1443 50,
1444 $this->mComment,
1445 [ 'id' => 'wpComment', 'autofocus' => '' ]
1446 ) .
1447 "</td>
1448 </tr>
1449 <tr>
1450 <td>&#160;</td>
1451 <td class='mw-submit'>" .
1452 Xml::submitButton(
1453 $this->msg( 'undeletebtn' )->text(),
1454 [ 'name' => 'restore', 'id' => 'mw-undelete-submit' ]
1455 ) . ' ' .
1456 Xml::submitButton(
1457 $this->msg( 'undeleteinvert' )->text(),
1458 [ 'name' => 'invert', 'id' => 'mw-undelete-invert' ]
1459 ) .
1460 "</td>
1461 </tr>" .
1462 $unsuppressBox .
1463 Xml::closeElement( 'table' ) .
1464 Xml::closeElement( 'fieldset' );
1465
1466 $out->addHTML( $table );
1467 }
1468
1469 $out->addHTML( Xml::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n" );
1470
1471 if ( $haveRevisions ) {
1472 # Show the page's stored (deleted) history
1473
1474 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
1475 $out->addHTML( Html::element(
1476 'button',
1477 [
1478 'name' => 'revdel',
1479 'type' => 'submit',
1480 'class' => 'deleterevision-log-submit mw-log-deleterevision-button'
1481 ],
1482 $this->msg( 'showhideselectedversions' )->text()
1483 ) . "\n" );
1484 }
1485
1486 $out->addHTML( '<ul>' );
1487 $remaining = $revisions->numRows();
1488 $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
1489
1490 foreach ( $revisions as $row ) {
1491 $remaining--;
1492 $out->addHTML( $this->formatRevisionRow( $row, $earliestLiveTime, $remaining ) );
1493 }
1494 $revisions->free();
1495 $out->addHTML( '</ul>' );
1496 } else {
1497 $out->addWikiMsg( 'nohistory' );
1498 }
1499
1500 if ( $haveFiles ) {
1501 $out->addHTML( Xml::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n" );
1502 $out->addHTML( '<ul>' );
1503 foreach ( $files as $row ) {
1504 $out->addHTML( $this->formatFileRow( $row ) );
1505 }
1506 $files->free();
1507 $out->addHTML( '</ul>' );
1508 }
1509
1510 if ( $this->mAllowed ) {
1511 # Slip in the hidden controls here
1512 $misc = Html::hidden( 'target', $this->mTarget );
1513 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
1514 $misc .= Xml::closeElement( 'form' );
1515 $out->addHTML( $misc );
1516 }
1517
1518 return true;
1519 }
1520
1521 protected function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
1522 $rev = Revision::newFromArchiveRow( $row,
1523 [
1524 'title' => $this->mTargetObj
1525 ] );
1526
1527 $revTextSize = '';
1528 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
1529 // Build checkboxen...
1530 if ( $this->mAllowed ) {
1531 if ( $this->mInvert ) {
1532 if ( in_array( $ts, $this->mTargetTimestamp ) ) {
1533 $checkBox = Xml::check( "ts$ts" );
1534 } else {
1535 $checkBox = Xml::check( "ts$ts", true );
1536 }
1537 } else {
1538 $checkBox = Xml::check( "ts$ts" );
1539 }
1540 } else {
1541 $checkBox = '';
1542 }
1543
1544 // Build page & diff links...
1545 $user = $this->getUser();
1546 if ( $this->mCanView ) {
1547 $titleObj = $this->getPageTitle();
1548 # Last link
1549 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
1550 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1551 $last = $this->msg( 'diff' )->escaped();
1552 } elseif ( $remaining > 0 || ( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
1553 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1554 $last = $this->getLinkRenderer()->makeKnownLink(
1555 $titleObj,
1556 $this->msg( 'diff' )->text(),
1557 [],
1558 [
1559 'target' => $this->mTargetObj->getPrefixedText(),
1560 'timestamp' => $ts,
1561 'diff' => 'prev'
1562 ]
1563 );
1564 } else {
1565 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1566 $last = $this->msg( 'diff' )->escaped();
1567 }
1568 } else {
1569 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1570 $last = $this->msg( 'diff' )->escaped();
1571 }
1572
1573 // User links
1574 $userLink = Linker::revUserTools( $rev );
1575
1576 // Minor edit
1577 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
1578
1579 // Revision text size
1580 $size = $row->ar_len;
1581 if ( !is_null( $size ) ) {
1582 $revTextSize = Linker::formatRevisionSize( $size );
1583 }
1584
1585 // Edit summary
1586 $comment = Linker::revComment( $rev );
1587
1588 // Tags
1589 $attribs = [];
1590 list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow(
1591 $row->ts_tags,
1592 'deletedhistory',
1593 $this->getContext()
1594 );
1595 if ( $classes ) {
1596 $attribs['class'] = implode( ' ', $classes );
1597 }
1598
1599 $revisionRow = $this->msg( 'undelete-revision-row2' )
1600 ->rawParams(
1601 $checkBox,
1602 $last,
1603 $pageLink,
1604 $userLink,
1605 $minor,
1606 $revTextSize,
1607 $comment,
1608 $tagSummary
1609 )
1610 ->escaped();
1611
1612 return Xml::tags( 'li', $attribs, $revisionRow ) . "\n";
1613 }
1614
1615 private function formatFileRow( $row ) {
1616 $file = ArchivedFile::newFromRow( $row );
1617 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
1618 $user = $this->getUser();
1619
1620 $checkBox = '';
1621 if ( $this->mCanView && $row->fa_storage_key ) {
1622 if ( $this->mAllowed ) {
1623 $checkBox = Xml::check( 'fileid' . $row->fa_id );
1624 }
1625 $key = urlencode( $row->fa_storage_key );
1626 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
1627 } else {
1628 $pageLink = $this->getLanguage()->userTimeAndDate( $ts, $user );
1629 }
1630 $userLink = $this->getFileUser( $file );
1631 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width, $row->fa_height )->text();
1632 $bytes = $this->msg( 'parentheses' )
1633 ->rawParams( $this->msg( 'nbytes' )->numParams( $row->fa_size )->text() )
1634 ->plain();
1635 $data = htmlspecialchars( $data . ' ' . $bytes );
1636 $comment = $this->getFileComment( $file );
1637
1638 // Add show/hide deletion links if available
1639 $canHide = $this->isAllowed( 'deleterevision' );
1640 if ( $canHide || ( $file->getVisibility() && $this->isAllowed( 'deletedhistory' ) ) ) {
1641 if ( !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1642 // Revision was hidden from sysops
1643 $revdlink = Linker::revDeleteLinkDisabled( $canHide );
1644 } else {
1645 $query = [
1646 'type' => 'filearchive',
1647 'target' => $this->mTargetObj->getPrefixedDBkey(),
1648 'ids' => $row->fa_id
1649 ];
1650 $revdlink = Linker::revDeleteLink( $query,
1651 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1652 }
1653 } else {
1654 $revdlink = '';
1655 }
1656
1657 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1658 }
1659
1660 /**
1661 * Fetch revision text link if it's available to all users
1662 *
1663 * @param Revision $rev
1664 * @param Title $titleObj
1665 * @param string $ts Timestamp
1666 * @return string
1667 */
1668 function getPageLink( $rev, $titleObj, $ts ) {
1669 $user = $this->getUser();
1670 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1671
1672 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1673 return '<span class="history-deleted">' . $time . '</span>';
1674 }
1675
1676 $link = $this->getLinkRenderer()->makeKnownLink(
1677 $titleObj,
1678 $time,
1679 [],
1680 [
1681 'target' => $this->mTargetObj->getPrefixedText(),
1682 'timestamp' => $ts
1683 ]
1684 );
1685
1686 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1687 $link = '<span class="history-deleted">' . $link . '</span>';
1688 }
1689
1690 return $link;
1691 }
1692
1693 /**
1694 * Fetch image view link if it's available to all users
1695 *
1696 * @param File|ArchivedFile $file
1697 * @param Title $titleObj
1698 * @param string $ts A timestamp
1699 * @param string $key A storage key
1700 *
1701 * @return string HTML fragment
1702 */
1703 function getFileLink( $file, $titleObj, $ts, $key ) {
1704 $user = $this->getUser();
1705 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1706
1707 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1708 return '<span class="history-deleted">' . $time . '</span>';
1709 }
1710
1711 $link = $this->getLinkRenderer()->makeKnownLink(
1712 $titleObj,
1713 $time,
1714 [],
1715 [
1716 'target' => $this->mTargetObj->getPrefixedText(),
1717 'file' => $key,
1718 'token' => $user->getEditToken( $key )
1719 ]
1720 );
1721
1722 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1723 $link = '<span class="history-deleted">' . $link . '</span>';
1724 }
1725
1726 return $link;
1727 }
1728
1729 /**
1730 * Fetch file's user id if it's available to this user
1731 *
1732 * @param File|ArchivedFile $file
1733 * @return string HTML fragment
1734 */
1735 function getFileUser( $file ) {
1736 if ( !$file->userCan( File::DELETED_USER, $this->getUser() ) ) {
1737 return '<span class="history-deleted">' .
1738 $this->msg( 'rev-deleted-user' )->escaped() .
1739 '</span>';
1740 }
1741
1742 $link = Linker::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1743 Linker::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1744
1745 if ( $file->isDeleted( File::DELETED_USER ) ) {
1746 $link = '<span class="history-deleted">' . $link . '</span>';
1747 }
1748
1749 return $link;
1750 }
1751
1752 /**
1753 * Fetch file upload comment if it's available to this user
1754 *
1755 * @param File|ArchivedFile $file
1756 * @return string HTML fragment
1757 */
1758 function getFileComment( $file ) {
1759 if ( !$file->userCan( File::DELETED_COMMENT, $this->getUser() ) ) {
1760 return '<span class="history-deleted"><span class="comment">' .
1761 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1762 }
1763
1764 $link = Linker::commentBlock( $file->getRawDescription() );
1765
1766 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1767 $link = '<span class="history-deleted">' . $link . '</span>';
1768 }
1769
1770 return $link;
1771 }
1772
1773 function undelete() {
1774 if ( $this->getConfig()->get( 'UploadMaintenance' )
1775 && $this->mTargetObj->getNamespace() == NS_FILE
1776 ) {
1777 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1778 }
1779
1780 $this->checkReadOnly();
1781
1782 $out = $this->getOutput();
1783 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1784 Hooks::run( 'UndeleteForm::undelete', [ &$archive, $this->mTargetObj ] );
1785 $ok = $archive->undelete(
1786 $this->mTargetTimestamp,
1787 $this->mComment,
1788 $this->mFileVersions,
1789 $this->mUnsuppress,
1790 $this->getUser()
1791 );
1792
1793 if ( is_array( $ok ) ) {
1794 if ( $ok[1] ) { // Undeleted file count
1795 Hooks::run( 'FileUndeleteComplete', [
1796 $this->mTargetObj, $this->mFileVersions,
1797 $this->getUser(), $this->mComment ] );
1798 }
1799
1800 $link = $this->getLinkRenderer()->makeKnownLink( $this->mTargetObj );
1801 $out->addHTML( $this->msg( 'undeletedpage' )->rawParams( $link )->parse() );
1802 } else {
1803 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1804 }
1805
1806 // Show revision undeletion warnings and errors
1807 $status = $archive->getRevisionStatus();
1808 if ( $status && !$status->isGood() ) {
1809 $out->addWikiText( '<div class="error">' .
1810 $status->getWikiText(
1811 'cannotundelete',
1812 'cannotundelete'
1813 ) . '</div>'
1814 );
1815 }
1816
1817 // Show file undeletion warnings and errors
1818 $status = $archive->getFileStatus();
1819 if ( $status && !$status->isGood() ) {
1820 $out->addWikiText( '<div class="error">' .
1821 $status->getWikiText(
1822 'undelete-error-short',
1823 'undelete-error-long'
1824 ) . '</div>'
1825 );
1826 }
1827 }
1828
1829 /**
1830 * Return an array of subpages beginning with $search that this special page will accept.
1831 *
1832 * @param string $search Prefix to search for
1833 * @param int $limit Maximum number of results to return (usually 10)
1834 * @param int $offset Number of results to skip (usually 0)
1835 * @return string[] Matching subpages
1836 */
1837 public function prefixSearchSubpages( $search, $limit, $offset ) {
1838 return $this->prefixSearchString( $search, $limit, $offset );
1839 }
1840
1841 protected function getGroupName() {
1842 return 'pagetools';
1843 }
1844 }