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