Merge "Remove unused messages"
[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 $undelete = $this->getPageTitle();
1001 $out->addHTML( "<ul>\n" );
1002 foreach ( $result as $row ) {
1003 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
1004 if ( $title !== null ) {
1005 $item = Linker::linkKnown(
1006 $undelete,
1007 htmlspecialchars( $title->getPrefixedText() ),
1008 [],
1009 [ 'target' => $title->getPrefixedText() ]
1010 );
1011 } else {
1012 // The title is no longer valid, show as text
1013 $item = Html::element(
1014 'span',
1015 [ 'class' => 'mw-invalidtitle' ],
1016 Linker::getInvalidTitleDescription(
1017 $this->getContext(),
1018 $row->ar_namespace,
1019 $row->ar_title
1020 )
1021 );
1022 }
1023 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count )->parse();
1024 $out->addHTML( "<li>{$item} ({$revs})</li>\n" );
1025 }
1026 $result->free();
1027 $out->addHTML( "</ul>\n" );
1028
1029 return true;
1030 }
1031
1032 private function showRevision( $timestamp ) {
1033 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
1034 return;
1035 }
1036
1037 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1038 if ( !Hooks::run( 'UndeleteForm::showRevision', [ &$archive, $this->mTargetObj ] ) ) {
1039 return;
1040 }
1041 $rev = $archive->getRevision( $timestamp );
1042
1043 $out = $this->getOutput();
1044 $user = $this->getUser();
1045
1046 if ( !$rev ) {
1047 $out->addWikiMsg( 'undeleterevision-missing' );
1048
1049 return;
1050 }
1051
1052 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1053 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1054 $out->wrapWikiMsg(
1055 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1056 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
1057 'rev-suppressed-text-permission' : 'rev-deleted-text-permission'
1058 );
1059
1060 return;
1061 }
1062
1063 $out->wrapWikiMsg(
1064 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1065 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
1066 'rev-suppressed-text-view' : 'rev-deleted-text-view'
1067 );
1068 $out->addHTML( '<br />' );
1069 // and we are allowed to see...
1070 }
1071
1072 if ( $this->mDiff ) {
1073 $previousRev = $archive->getPreviousRevision( $timestamp );
1074 if ( $previousRev ) {
1075 $this->showDiff( $previousRev, $rev );
1076 if ( $this->mDiffOnly ) {
1077 return;
1078 }
1079
1080 $out->addHTML( '<hr />' );
1081 } else {
1082 $out->addWikiMsg( 'undelete-nodiff' );
1083 }
1084 }
1085
1086 $link = Linker::linkKnown(
1087 $this->getPageTitle( $this->mTargetObj->getPrefixedDBkey() ),
1088 htmlspecialchars( $this->mTargetObj->getPrefixedText() )
1089 );
1090
1091 $lang = $this->getLanguage();
1092
1093 // date and time are separate parameters to facilitate localisation.
1094 // $time is kept for backward compat reasons.
1095 $time = $lang->userTimeAndDate( $timestamp, $user );
1096 $d = $lang->userDate( $timestamp, $user );
1097 $t = $lang->userTime( $timestamp, $user );
1098 $userLink = Linker::revUserTools( $rev );
1099
1100 $content = $rev->getContent( Revision::FOR_THIS_USER, $user );
1101
1102 $isText = ( $content instanceof TextContent );
1103
1104 if ( $this->mPreview || $isText ) {
1105 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
1106 } else {
1107 $openDiv = '<div id="mw-undelete-revision">';
1108 }
1109 $out->addHTML( $openDiv );
1110
1111 // Revision delete links
1112 if ( !$this->mDiff ) {
1113 $revdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
1114 if ( $revdel ) {
1115 $out->addHTML( "$revdel " );
1116 }
1117 }
1118
1119 $out->addHTML( $this->msg( 'undelete-revision' )->rawParams( $link )->params(
1120 $time )->rawParams( $userLink )->params( $d, $t )->parse() . '</div>' );
1121
1122 if ( !Hooks::run( 'UndeleteShowRevision', [ $this->mTargetObj, $rev ] ) ) {
1123 return;
1124 }
1125
1126 if ( ( $this->mPreview || !$isText ) && $content ) {
1127 // NOTE: non-text content has no source view, so always use rendered preview
1128
1129 // Hide [edit]s
1130 $popts = $out->parserOptions();
1131 $popts->setEditSection( false );
1132
1133 $pout = $content->getParserOutput( $this->mTargetObj, $rev->getId(), $popts, true );
1134 $out->addParserOutput( $pout );
1135 }
1136
1137 if ( $isText ) {
1138 // source view for textual content
1139 $sourceView = Xml::element(
1140 'textarea',
1141 [
1142 'readonly' => 'readonly',
1143 'cols' => $user->getIntOption( 'cols' ),
1144 'rows' => $user->getIntOption( 'rows' )
1145 ],
1146 $content->getNativeData() . "\n"
1147 );
1148
1149 $previewButton = Xml::element( 'input', [
1150 'type' => 'submit',
1151 'name' => 'preview',
1152 'value' => $this->msg( 'showpreview' )->text()
1153 ] );
1154 } else {
1155 $sourceView = '';
1156 $previewButton = '';
1157 }
1158
1159 $diffButton = Xml::element( 'input', [
1160 'name' => 'diff',
1161 'type' => 'submit',
1162 'value' => $this->msg( 'showdiff' )->text() ] );
1163
1164 $out->addHTML(
1165 $sourceView .
1166 Xml::openElement( 'div', [
1167 'style' => 'clear: both' ] ) .
1168 Xml::openElement( 'form', [
1169 'method' => 'post',
1170 'action' => $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] ) ] ) .
1171 Xml::element( 'input', [
1172 'type' => 'hidden',
1173 'name' => 'target',
1174 'value' => $this->mTargetObj->getPrefixedDBkey() ] ) .
1175 Xml::element( 'input', [
1176 'type' => 'hidden',
1177 'name' => 'timestamp',
1178 'value' => $timestamp ] ) .
1179 Xml::element( 'input', [
1180 'type' => 'hidden',
1181 'name' => 'wpEditToken',
1182 'value' => $user->getEditToken() ] ) .
1183 $previewButton .
1184 $diffButton .
1185 Xml::closeElement( 'form' ) .
1186 Xml::closeElement( 'div' )
1187 );
1188 }
1189
1190 /**
1191 * Build a diff display between this and the previous either deleted
1192 * or non-deleted edit.
1193 *
1194 * @param Revision $previousRev
1195 * @param Revision $currentRev
1196 * @return string HTML
1197 */
1198 function showDiff( $previousRev, $currentRev ) {
1199 $diffContext = clone $this->getContext();
1200 $diffContext->setTitle( $currentRev->getTitle() );
1201 $diffContext->setWikiPage( WikiPage::factory( $currentRev->getTitle() ) );
1202
1203 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
1204 $diffEngine->showDiffStyle();
1205
1206 $formattedDiff = $diffEngine->generateContentDiffBody(
1207 $previousRev->getContent( Revision::FOR_THIS_USER, $this->getUser() ),
1208 $currentRev->getContent( Revision::FOR_THIS_USER, $this->getUser() )
1209 );
1210
1211 $formattedDiff = $diffEngine->addHeader(
1212 $formattedDiff,
1213 $this->diffHeader( $previousRev, 'o' ),
1214 $this->diffHeader( $currentRev, 'n' )
1215 );
1216
1217 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
1218 }
1219
1220 /**
1221 * @param Revision $rev
1222 * @param string $prefix
1223 * @return string
1224 */
1225 private function diffHeader( $rev, $prefix ) {
1226 $isDeleted = !( $rev->getId() && $rev->getTitle() );
1227 if ( $isDeleted ) {
1228 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
1229 $targetPage = $this->getPageTitle();
1230 $targetQuery = [
1231 'target' => $this->mTargetObj->getPrefixedText(),
1232 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
1233 ];
1234 } else {
1235 /// @todo FIXME: getId() may return non-zero for deleted revs...
1236 $targetPage = $rev->getTitle();
1237 $targetQuery = [ 'oldid' => $rev->getId() ];
1238 }
1239
1240 // Add show/hide deletion links if available
1241 $user = $this->getUser();
1242 $lang = $this->getLanguage();
1243 $rdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
1244
1245 if ( $rdel ) {
1246 $rdel = " $rdel";
1247 }
1248
1249 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
1250
1251 $tags = wfGetDB( DB_REPLICA )->selectField(
1252 'tag_summary',
1253 'ts_tags',
1254 [ 'ts_rev_id' => $rev->getId() ],
1255 __METHOD__
1256 );
1257 $tagSummary = ChangeTags::formatSummaryRow( $tags, 'deleteddiff', $this->getContext() );
1258
1259 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
1260 // and partially #showDiffPage, but worse
1261 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
1262 Linker::link(
1263 $targetPage,
1264 $this->msg(
1265 'revisionasof',
1266 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
1267 $lang->userDate( $rev->getTimestamp(), $user ),
1268 $lang->userTime( $rev->getTimestamp(), $user )
1269 )->escaped(),
1270 [],
1271 $targetQuery
1272 ) .
1273 '</strong></div>' .
1274 '<div id="mw-diff-' . $prefix . 'title2">' .
1275 Linker::revUserTools( $rev ) . '<br />' .
1276 '</div>' .
1277 '<div id="mw-diff-' . $prefix . 'title3">' .
1278 $minor . Linker::revComment( $rev ) . $rdel . '<br />' .
1279 '</div>' .
1280 '<div id="mw-diff-' . $prefix . 'title5">' .
1281 $tagSummary[0] . '<br />' .
1282 '</div>';
1283 }
1284
1285 /**
1286 * Show a form confirming whether a tokenless user really wants to see a file
1287 * @param string $key
1288 */
1289 private function showFileConfirmationForm( $key ) {
1290 $out = $this->getOutput();
1291 $lang = $this->getLanguage();
1292 $user = $this->getUser();
1293 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
1294 $out->addWikiMsg( 'undelete-show-file-confirm',
1295 $this->mTargetObj->getText(),
1296 $lang->userDate( $file->getTimestamp(), $user ),
1297 $lang->userTime( $file->getTimestamp(), $user ) );
1298 $out->addHTML(
1299 Xml::openElement( 'form', [
1300 'method' => 'POST',
1301 'action' => $this->getPageTitle()->getLocalURL( [
1302 'target' => $this->mTarget,
1303 'file' => $key,
1304 'token' => $user->getEditToken( $key ),
1305 ] ),
1306 ]
1307 ) .
1308 Xml::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
1309 '</form>'
1310 );
1311 }
1312
1313 /**
1314 * Show a deleted file version requested by the visitor.
1315 * @param string $key
1316 */
1317 private function showFile( $key ) {
1318 $this->getOutput()->disable();
1319
1320 # We mustn't allow the output to be CDN cached, otherwise
1321 # if an admin previews a deleted image, and it's cached, then
1322 # a user without appropriate permissions can toddle off and
1323 # nab the image, and CDN will serve it
1324 $response = $this->getRequest()->response();
1325 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1326 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1327 $response->header( 'Pragma: no-cache' );
1328
1329 $repo = RepoGroup::singleton()->getLocalRepo();
1330 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
1331 $repo->streamFile( $path );
1332 }
1333
1334 protected function showHistory() {
1335 $this->checkReadOnly();
1336
1337 $out = $this->getOutput();
1338 if ( $this->mAllowed ) {
1339 $out->addModules( 'mediawiki.special.undelete' );
1340 }
1341 $out->wrapWikiMsg(
1342 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
1343 [ 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj->getPrefixedText() ) ]
1344 );
1345
1346 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1347 Hooks::run( 'UndeleteForm::showHistory', [ &$archive, $this->mTargetObj ] );
1348 /*
1349 $text = $archive->getLastRevisionText();
1350 if( is_null( $text ) ) {
1351 $out->addWikiMsg( 'nohistory' );
1352 return;
1353 }
1354 */
1355 $out->addHTML( '<div class="mw-undelete-history">' );
1356 if ( $this->mAllowed ) {
1357 $out->addWikiMsg( 'undeletehistory' );
1358 $out->addWikiMsg( 'undeleterevdel' );
1359 } else {
1360 $out->addWikiMsg( 'undeletehistorynoadmin' );
1361 }
1362 $out->addHTML( '</div>' );
1363
1364 # List all stored revisions
1365 $revisions = $archive->listRevisions();
1366 $files = $archive->listFiles();
1367
1368 $haveRevisions = $revisions && $revisions->numRows() > 0;
1369 $haveFiles = $files && $files->numRows() > 0;
1370
1371 # Batch existence check on user and talk pages
1372 if ( $haveRevisions ) {
1373 $batch = new LinkBatch();
1374 foreach ( $revisions as $row ) {
1375 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
1376 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
1377 }
1378 $batch->execute();
1379 $revisions->seek( 0 );
1380 }
1381 if ( $haveFiles ) {
1382 $batch = new LinkBatch();
1383 foreach ( $files as $row ) {
1384 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
1385 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
1386 }
1387 $batch->execute();
1388 $files->seek( 0 );
1389 }
1390
1391 if ( $this->mAllowed ) {
1392 $action = $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] );
1393 # Start the form here
1394 $top = Xml::openElement(
1395 'form',
1396 [ 'method' => 'post', 'action' => $action, 'id' => 'undelete' ]
1397 );
1398 $out->addHTML( $top );
1399 }
1400
1401 # Show relevant lines from the deletion log:
1402 $deleteLogPage = new LogPage( 'delete' );
1403 $out->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
1404 LogEventsList::showLogExtract( $out, 'delete', $this->mTargetObj );
1405 # Show relevant lines from the suppression log:
1406 $suppressLogPage = new LogPage( 'suppress' );
1407 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
1408 $out->addHTML( Xml::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
1409 LogEventsList::showLogExtract( $out, 'suppress', $this->mTargetObj );
1410 }
1411
1412 if ( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
1413 # Format the user-visible controls (comment field, submission button)
1414 # in a nice little table
1415 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
1416 $unsuppressBox =
1417 "<tr>
1418 <td>&#160;</td>
1419 <td class='mw-input'>" .
1420 Xml::checkLabel( $this->msg( 'revdelete-unsuppress' )->text(),
1421 'wpUnsuppress', 'mw-undelete-unsuppress', $this->mUnsuppress ) .
1422 "</td>
1423 </tr>";
1424 } else {
1425 $unsuppressBox = '';
1426 }
1427
1428 $table = Xml::fieldset( $this->msg( 'undelete-fieldset-title' )->text() ) .
1429 Xml::openElement( 'table', [ 'id' => 'mw-undelete-table' ] ) .
1430 "<tr>
1431 <td colspan='2' class='mw-undelete-extrahelp'>" .
1432 $this->msg( 'undeleteextrahelp' )->parseAsBlock() .
1433 "</td>
1434 </tr>
1435 <tr>
1436 <td class='mw-label'>" .
1437 Xml::label( $this->msg( 'undeletecomment' )->text(), 'wpComment' ) .
1438 "</td>
1439 <td class='mw-input'>" .
1440 Xml::input(
1441 'wpComment',
1442 50,
1443 $this->mComment,
1444 [ 'id' => 'wpComment', 'autofocus' => '' ]
1445 ) .
1446 "</td>
1447 </tr>
1448 <tr>
1449 <td>&#160;</td>
1450 <td class='mw-submit'>" .
1451 Xml::submitButton(
1452 $this->msg( 'undeletebtn' )->text(),
1453 [ 'name' => 'restore', 'id' => 'mw-undelete-submit' ]
1454 ) . ' ' .
1455 Xml::submitButton(
1456 $this->msg( 'undeleteinvert' )->text(),
1457 [ 'name' => 'invert', 'id' => 'mw-undelete-invert' ]
1458 ) .
1459 "</td>
1460 </tr>" .
1461 $unsuppressBox .
1462 Xml::closeElement( 'table' ) .
1463 Xml::closeElement( 'fieldset' );
1464
1465 $out->addHTML( $table );
1466 }
1467
1468 $out->addHTML( Xml::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n" );
1469
1470 if ( $haveRevisions ) {
1471 # Show the page's stored (deleted) history
1472
1473 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
1474 $out->addHTML( Html::element(
1475 'button',
1476 [
1477 'name' => 'revdel',
1478 'type' => 'submit',
1479 'class' => 'deleterevision-log-submit mw-log-deleterevision-button'
1480 ],
1481 $this->msg( 'showhideselectedversions' )->text()
1482 ) . "\n" );
1483 }
1484
1485 $out->addHTML( '<ul>' );
1486 $remaining = $revisions->numRows();
1487 $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
1488
1489 foreach ( $revisions as $row ) {
1490 $remaining--;
1491 $out->addHTML( $this->formatRevisionRow( $row, $earliestLiveTime, $remaining ) );
1492 }
1493 $revisions->free();
1494 $out->addHTML( '</ul>' );
1495 } else {
1496 $out->addWikiMsg( 'nohistory' );
1497 }
1498
1499 if ( $haveFiles ) {
1500 $out->addHTML( Xml::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n" );
1501 $out->addHTML( '<ul>' );
1502 foreach ( $files as $row ) {
1503 $out->addHTML( $this->formatFileRow( $row ) );
1504 }
1505 $files->free();
1506 $out->addHTML( '</ul>' );
1507 }
1508
1509 if ( $this->mAllowed ) {
1510 # Slip in the hidden controls here
1511 $misc = Html::hidden( 'target', $this->mTarget );
1512 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
1513 $misc .= Xml::closeElement( 'form' );
1514 $out->addHTML( $misc );
1515 }
1516
1517 return true;
1518 }
1519
1520 protected function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
1521 $rev = Revision::newFromArchiveRow( $row,
1522 [
1523 'title' => $this->mTargetObj
1524 ] );
1525
1526 $revTextSize = '';
1527 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
1528 // Build checkboxen...
1529 if ( $this->mAllowed ) {
1530 if ( $this->mInvert ) {
1531 if ( in_array( $ts, $this->mTargetTimestamp ) ) {
1532 $checkBox = Xml::check( "ts$ts" );
1533 } else {
1534 $checkBox = Xml::check( "ts$ts", true );
1535 }
1536 } else {
1537 $checkBox = Xml::check( "ts$ts" );
1538 }
1539 } else {
1540 $checkBox = '';
1541 }
1542
1543 // Build page & diff links...
1544 $user = $this->getUser();
1545 if ( $this->mCanView ) {
1546 $titleObj = $this->getPageTitle();
1547 # Last link
1548 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
1549 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1550 $last = $this->msg( 'diff' )->escaped();
1551 } elseif ( $remaining > 0 || ( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
1552 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1553 $last = Linker::linkKnown(
1554 $titleObj,
1555 $this->msg( 'diff' )->escaped(),
1556 [],
1557 [
1558 'target' => $this->mTargetObj->getPrefixedText(),
1559 'timestamp' => $ts,
1560 'diff' => 'prev'
1561 ]
1562 );
1563 } else {
1564 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1565 $last = $this->msg( 'diff' )->escaped();
1566 }
1567 } else {
1568 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1569 $last = $this->msg( 'diff' )->escaped();
1570 }
1571
1572 // User links
1573 $userLink = Linker::revUserTools( $rev );
1574
1575 // Minor edit
1576 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
1577
1578 // Revision text size
1579 $size = $row->ar_len;
1580 if ( !is_null( $size ) ) {
1581 $revTextSize = Linker::formatRevisionSize( $size );
1582 }
1583
1584 // Edit summary
1585 $comment = Linker::revComment( $rev );
1586
1587 // Tags
1588 $attribs = [];
1589 list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow(
1590 $row->ts_tags,
1591 'deletedhistory',
1592 $this->getContext()
1593 );
1594 if ( $classes ) {
1595 $attribs['class'] = implode( ' ', $classes );
1596 }
1597
1598 $revisionRow = $this->msg( 'undelete-revision-row2' )
1599 ->rawParams(
1600 $checkBox,
1601 $last,
1602 $pageLink,
1603 $userLink,
1604 $minor,
1605 $revTextSize,
1606 $comment,
1607 $tagSummary
1608 )
1609 ->escaped();
1610
1611 return Xml::tags( 'li', $attribs, $revisionRow ) . "\n";
1612 }
1613
1614 private function formatFileRow( $row ) {
1615 $file = ArchivedFile::newFromRow( $row );
1616 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
1617 $user = $this->getUser();
1618
1619 $checkBox = '';
1620 if ( $this->mCanView && $row->fa_storage_key ) {
1621 if ( $this->mAllowed ) {
1622 $checkBox = Xml::check( 'fileid' . $row->fa_id );
1623 }
1624 $key = urlencode( $row->fa_storage_key );
1625 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
1626 } else {
1627 $pageLink = $this->getLanguage()->userTimeAndDate( $ts, $user );
1628 }
1629 $userLink = $this->getFileUser( $file );
1630 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width, $row->fa_height )->text();
1631 $bytes = $this->msg( 'parentheses' )
1632 ->rawParams( $this->msg( 'nbytes' )->numParams( $row->fa_size )->text() )
1633 ->plain();
1634 $data = htmlspecialchars( $data . ' ' . $bytes );
1635 $comment = $this->getFileComment( $file );
1636
1637 // Add show/hide deletion links if available
1638 $canHide = $this->isAllowed( 'deleterevision' );
1639 if ( $canHide || ( $file->getVisibility() && $this->isAllowed( 'deletedhistory' ) ) ) {
1640 if ( !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1641 // Revision was hidden from sysops
1642 $revdlink = Linker::revDeleteLinkDisabled( $canHide );
1643 } else {
1644 $query = [
1645 'type' => 'filearchive',
1646 'target' => $this->mTargetObj->getPrefixedDBkey(),
1647 'ids' => $row->fa_id
1648 ];
1649 $revdlink = Linker::revDeleteLink( $query,
1650 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1651 }
1652 } else {
1653 $revdlink = '';
1654 }
1655
1656 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1657 }
1658
1659 /**
1660 * Fetch revision text link if it's available to all users
1661 *
1662 * @param Revision $rev
1663 * @param Title $titleObj
1664 * @param string $ts Timestamp
1665 * @return string
1666 */
1667 function getPageLink( $rev, $titleObj, $ts ) {
1668 $user = $this->getUser();
1669 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1670
1671 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1672 return '<span class="history-deleted">' . $time . '</span>';
1673 }
1674
1675 $link = Linker::linkKnown(
1676 $titleObj,
1677 htmlspecialchars( $time ),
1678 [],
1679 [
1680 'target' => $this->mTargetObj->getPrefixedText(),
1681 'timestamp' => $ts
1682 ]
1683 );
1684
1685 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1686 $link = '<span class="history-deleted">' . $link . '</span>';
1687 }
1688
1689 return $link;
1690 }
1691
1692 /**
1693 * Fetch image view link if it's available to all users
1694 *
1695 * @param File|ArchivedFile $file
1696 * @param Title $titleObj
1697 * @param string $ts A timestamp
1698 * @param string $key A storage key
1699 *
1700 * @return string HTML fragment
1701 */
1702 function getFileLink( $file, $titleObj, $ts, $key ) {
1703 $user = $this->getUser();
1704 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1705
1706 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1707 return '<span class="history-deleted">' . $time . '</span>';
1708 }
1709
1710 $link = Linker::linkKnown(
1711 $titleObj,
1712 htmlspecialchars( $time ),
1713 [],
1714 [
1715 'target' => $this->mTargetObj->getPrefixedText(),
1716 'file' => $key,
1717 'token' => $user->getEditToken( $key )
1718 ]
1719 );
1720
1721 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1722 $link = '<span class="history-deleted">' . $link . '</span>';
1723 }
1724
1725 return $link;
1726 }
1727
1728 /**
1729 * Fetch file's user id if it's available to this user
1730 *
1731 * @param File|ArchivedFile $file
1732 * @return string HTML fragment
1733 */
1734 function getFileUser( $file ) {
1735 if ( !$file->userCan( File::DELETED_USER, $this->getUser() ) ) {
1736 return '<span class="history-deleted">' .
1737 $this->msg( 'rev-deleted-user' )->escaped() .
1738 '</span>';
1739 }
1740
1741 $link = Linker::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1742 Linker::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1743
1744 if ( $file->isDeleted( File::DELETED_USER ) ) {
1745 $link = '<span class="history-deleted">' . $link . '</span>';
1746 }
1747
1748 return $link;
1749 }
1750
1751 /**
1752 * Fetch file upload comment if it's available to this user
1753 *
1754 * @param File|ArchivedFile $file
1755 * @return string HTML fragment
1756 */
1757 function getFileComment( $file ) {
1758 if ( !$file->userCan( File::DELETED_COMMENT, $this->getUser() ) ) {
1759 return '<span class="history-deleted"><span class="comment">' .
1760 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1761 }
1762
1763 $link = Linker::commentBlock( $file->getRawDescription() );
1764
1765 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1766 $link = '<span class="history-deleted">' . $link . '</span>';
1767 }
1768
1769 return $link;
1770 }
1771
1772 function undelete() {
1773 if ( $this->getConfig()->get( 'UploadMaintenance' )
1774 && $this->mTargetObj->getNamespace() == NS_FILE
1775 ) {
1776 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1777 }
1778
1779 $this->checkReadOnly();
1780
1781 $out = $this->getOutput();
1782 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1783 Hooks::run( 'UndeleteForm::undelete', [ &$archive, $this->mTargetObj ] );
1784 $ok = $archive->undelete(
1785 $this->mTargetTimestamp,
1786 $this->mComment,
1787 $this->mFileVersions,
1788 $this->mUnsuppress,
1789 $this->getUser()
1790 );
1791
1792 if ( is_array( $ok ) ) {
1793 if ( $ok[1] ) { // Undeleted file count
1794 Hooks::run( 'FileUndeleteComplete', [
1795 $this->mTargetObj, $this->mFileVersions,
1796 $this->getUser(), $this->mComment ] );
1797 }
1798
1799 $link = Linker::linkKnown( $this->mTargetObj );
1800 $out->addHTML( $this->msg( 'undeletedpage' )->rawParams( $link )->parse() );
1801 } else {
1802 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1803 }
1804
1805 // Show revision undeletion warnings and errors
1806 $status = $archive->getRevisionStatus();
1807 if ( $status && !$status->isGood() ) {
1808 $out->addWikiText( '<div class="error">' .
1809 $status->getWikiText(
1810 'cannotundelete',
1811 'cannotundelete'
1812 ) . '</div>'
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 }