3 * Implements Special:Undelete
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.
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.
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
21 * @ingroup SpecialPage
25 * Used to show archived pages and eventually restore them.
27 * @ingroup SpecialPage
38 protected $fileStatus;
43 protected $revisionStatus;
45 function __construct( $title ) {
46 if ( is_null( $title ) ) {
47 throw new MWException( __METHOD__
. ' given a null title.' );
49 $this->title
= $title;
53 * List all deleted pages recorded in the archive table. Returns result
54 * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
57 * @return ResultWrapper
59 public static function listAllPages() {
60 $dbr = wfGetDB( DB_SLAVE
);
62 return self
::listPages( $dbr, '' );
66 * List deleted pages recorded in the archive table matching the
68 * Returns result wrapper with (ar_namespace, ar_title, count) fields.
70 * @param string $prefix Title prefix
71 * @return ResultWrapper
73 public static function listPagesByPrefix( $prefix ) {
74 $dbr = wfGetDB( DB_SLAVE
);
76 $title = Title
::newFromText( $prefix );
78 $ns = $title->getNamespace();
79 $prefix = $title->getDBkey();
81 // Prolly won't work too good
82 // @todo handle bare namespace names cleanly?
87 'ar_namespace' => $ns,
88 'ar_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
91 return self
::listPages( $dbr, $conds );
95 * @param DatabaseBase $dbr
96 * @param string|array $condition
97 * @return bool|ResultWrapper
99 protected static function listPages( $dbr, $condition ) {
100 return $dbr->resultObject( $dbr->select(
105 'count' => 'COUNT(*)'
110 'GROUP BY' => array( 'ar_namespace', 'ar_title' ),
111 'ORDER BY' => array( 'ar_namespace', 'ar_title' ),
118 * List the revisions of the given page. Returns result wrapper with
119 * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
121 * @return ResultWrapper
123 function listRevisions() {
124 global $wgContentHandlerUseDB;
126 $dbr = wfGetDB( DB_SLAVE
);
128 $tables = array( 'archive' );
131 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text',
132 'ar_comment', 'ar_len', 'ar_deleted', 'ar_rev_id', 'ar_sha1',
135 if ( $wgContentHandlerUseDB ) {
136 $fields[] = 'ar_content_format';
137 $fields[] = 'ar_content_model';
140 $conds = array( 'ar_namespace' => $this->title
->getNamespace(),
141 'ar_title' => $this->title
->getDBkey() );
143 $options = array( 'ORDER BY' => 'ar_timestamp DESC' );
145 $join_conds = array();
147 ChangeTags
::modifyDisplayQuery(
155 $res = $dbr->select( $tables,
163 return $dbr->resultObject( $res );
167 * List the deleted file revisions for this page, if it's a file page.
168 * Returns a result wrapper with various filearchive fields, or null
169 * if not a file page.
171 * @return ResultWrapper
172 * @todo Does this belong in Image for fuller encapsulation?
174 function listFiles() {
175 if ( $this->title
->getNamespace() != NS_FILE
) {
179 $dbr = wfGetDB( DB_SLAVE
);
182 ArchivedFile
::selectFields(),
183 array( 'fa_name' => $this->title
->getDBkey() ),
185 array( 'ORDER BY' => 'fa_timestamp DESC' )
188 return $dbr->resultObject( $res );
192 * Return a Revision object containing data for the deleted revision.
193 * Note that the result *may* or *may not* have a null page ID.
195 * @param string $timestamp
196 * @return Revision|null
198 function getRevision( $timestamp ) {
199 global $wgContentHandlerUseDB;
201 $dbr = wfGetDB( DB_SLAVE
);
218 if ( $wgContentHandlerUseDB ) {
219 $fields[] = 'ar_content_format';
220 $fields[] = 'ar_content_model';
223 $row = $dbr->selectRow( 'archive',
225 array( 'ar_namespace' => $this->title
->getNamespace(),
226 'ar_title' => $this->title
->getDBkey(),
227 'ar_timestamp' => $dbr->timestamp( $timestamp ) ),
231 return Revision
::newFromArchiveRow( $row, array( 'title' => $this->title
) );
238 * Return the most-previous revision, either live or deleted, against
239 * the deleted revision given by timestamp.
241 * May produce unexpected results in case of history merges or other
242 * unusual time issues.
244 * @param string $timestamp
245 * @return Revision|null Null when there is no previous revision
247 function getPreviousRevision( $timestamp ) {
248 $dbr = wfGetDB( DB_SLAVE
);
250 // Check the previous deleted revision...
251 $row = $dbr->selectRow( 'archive',
253 array( 'ar_namespace' => $this->title
->getNamespace(),
254 'ar_title' => $this->title
->getDBkey(),
256 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
259 'ORDER BY' => 'ar_timestamp DESC',
261 $prevDeleted = $row ?
wfTimestamp( TS_MW
, $row->ar_timestamp
) : false;
263 $row = $dbr->selectRow( array( 'page', 'revision' ),
264 array( 'rev_id', 'rev_timestamp' ),
266 'page_namespace' => $this->title
->getNamespace(),
267 'page_title' => $this->title
->getDBkey(),
268 'page_id = rev_page',
270 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
273 'ORDER BY' => 'rev_timestamp DESC',
275 $prevLive = $row ?
wfTimestamp( TS_MW
, $row->rev_timestamp
) : false;
276 $prevLiveId = $row ?
intval( $row->rev_id
) : null;
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 );
286 // No prior revision on this page.
291 * Get the text from an archive row containing ar_text, ar_flags and ar_text_id
293 * @param object $row Database row
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_' );
303 // New-style: keyed to the text storage backend.
304 $dbr = wfGetDB( DB_SLAVE
);
305 $text = $dbr->selectRow( 'text',
306 array( 'old_text', 'old_flags' ),
307 array( 'old_id' => $row->ar_text_id
),
310 return Revision
::getRevisionText( $text );
314 * Fetch (and decompress if necessary) the stored text of the most
315 * recently edited deleted revision of the page.
317 * If there are no archived revisions for the page, returns NULL.
319 * @return string|null
321 function getLastRevisionText() {
322 $dbr = wfGetDB( DB_SLAVE
);
323 $row = $dbr->selectRow( 'archive',
324 array( 'ar_text', 'ar_flags', 'ar_text_id' ),
325 array( 'ar_namespace' => $this->title
->getNamespace(),
326 'ar_title' => $this->title
->getDBkey() ),
328 array( 'ORDER BY' => 'ar_timestamp DESC' ) );
331 return $this->getTextFromRow( $row );
338 * Quick check if any archived revisions are present for the page.
342 function isDeleted() {
343 $dbr = wfGetDB( DB_SLAVE
);
344 $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
345 array( 'ar_namespace' => $this->title
->getNamespace(),
346 'ar_title' => $this->title
->getDBkey() ),
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.
358 * @param array $timestamps Pass an empty array to restore all revisions, otherwise list the ones to undelete.
359 * @param string $comment
360 * @param array $fileVersions
361 * @param bool $unsuppress
362 * @param User $user User performing the action, or null to use $wgUser
364 * @return array(number of file revisions restored, number of image revisions restored, log message)
365 * on success, false on failure
367 function undelete( $timestamps, $comment = '', $fileVersions = array(), $unsuppress = false, User
$user = null ) {
368 // If both the set of text revisions and file revisions are empty,
369 // restore everything. Otherwise, just restore the requested items.
370 $restoreAll = empty( $timestamps ) && empty( $fileVersions );
372 $restoreText = $restoreAll ||
!empty( $timestamps );
373 $restoreFiles = $restoreAll ||
!empty( $fileVersions );
375 if ( $restoreFiles && $this->title
->getNamespace() == NS_FILE
) {
376 $img = wfLocalFile( $this->title
);
377 $this->fileStatus
= $img->restore( $fileVersions, $unsuppress );
378 if ( !$this->fileStatus
->isOK() ) {
381 $filesRestored = $this->fileStatus
->successCount
;
386 if ( $restoreText ) {
387 $this->revisionStatus
= $this->undeleteRevisions( $timestamps, $unsuppress, $comment );
388 if ( !$this->revisionStatus
->isOK() ) {
392 $textRestored = $this->revisionStatus
->getValue();
399 if ( $textRestored && $filesRestored ) {
400 $reason = wfMessage( 'undeletedrevisions-files' )
401 ->numParams( $textRestored, $filesRestored )->inContentLanguage()->text();
402 } elseif ( $textRestored ) {
403 $reason = wfMessage( 'undeletedrevisions' )->numParams( $textRestored )
404 ->inContentLanguage()->text();
405 } elseif ( $filesRestored ) {
406 $reason = wfMessage( 'undeletedfiles' )->numParams( $filesRestored )
407 ->inContentLanguage()->text();
409 wfDebug( "Undelete: nothing undeleted...\n" );
414 if ( trim( $comment ) != '' ) {
415 $reason .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
418 if ( $user === null ) {
423 $logEntry = new ManualLogEntry( 'delete', 'restore' );
424 $logEntry->setPerformer( $user );
425 $logEntry->setTarget( $this->title
);
426 $logEntry->setComment( $reason );
428 wfRunHooks( 'ArticleUndeleteLogEntry', array( $this, &$logEntry, $user ) );
430 $logid = $logEntry->insert();
431 $logEntry->publish( $logid );
433 return array( $textRestored, $filesRestored, $reason );
437 * This is the meaty bit -- restores archived revisions of the given page
438 * to the cur/old tables. If the page currently exists, all revisions will
439 * be stuffed into old, otherwise the most recent will go into cur.
441 * @param array $timestamps Pass an empty array to restore all revisions, otherwise list the ones to undelete.
442 * @param bool $unsuppress Remove all ar_deleted/fa_deleted restrictions of seletected revs
443 * @param string $comment
444 * @throws ReadOnlyError
445 * @return Status Object containing the number of revisions restored on success
447 private function undeleteRevisions( $timestamps, $unsuppress = false, $comment = '' ) {
448 global $wgContentHandlerUseDB;
450 if ( wfReadOnly() ) {
451 throw new ReadOnlyError();
454 $restoreAll = empty( $timestamps );
455 $dbw = wfGetDB( DB_MASTER
);
457 # Does this page already exist? We'll have to update it...
458 $article = WikiPage
::factory( $this->title
);
459 # Load latest data for the current page (bug 31179)
460 $article->loadPageData( 'fromdbmaster' );
461 $oldcountable = $article->isCountable();
463 $page = $dbw->selectRow( 'page',
464 array( 'page_id', 'page_latest' ),
465 array( 'page_namespace' => $this->title
->getNamespace(),
466 'page_title' => $this->title
->getDBkey() ),
468 array( 'FOR UPDATE' ) // lock page
473 # Page already exists. Import the history, and if necessary
474 # we'll update the latest revision field in the record.
476 $previousRevId = $page->page_latest
;
478 # Get the time span of this page
479 $previousTimestamp = $dbw->selectField( 'revision', 'rev_timestamp',
480 array( 'rev_id' => $previousRevId ),
483 if ( $previousTimestamp === false ) {
484 wfDebug( __METHOD__
. ": existing page refers to a page_latest that does not exist\n" );
486 $status = Status
::newGood( 0 );
487 $status->warning( 'undeleterevision-missing' );
492 # Have to create a new article...
495 $previousTimestamp = 0;
499 $oldones = '1 = 1'; # All revisions...
501 $oldts = implode( ',',
502 array_map( array( &$dbw, 'addQuotes' ),
503 array_map( array( &$dbw, 'timestamp' ),
506 $oldones = "ar_timestamp IN ( {$oldts} )";
525 if ( $wgContentHandlerUseDB ) {
526 $fields[] = 'ar_content_format';
527 $fields[] = 'ar_content_model';
531 * Select each archived revision...
533 $result = $dbw->select( 'archive',
536 'ar_namespace' => $this->title
->getNamespace(),
537 'ar_title' => $this->title
->getDBkey(),
540 /* options */ array( 'ORDER BY' => 'ar_timestamp' )
542 $ret = $dbw->resultObject( $result );
543 $rev_count = $dbw->numRows( $result );
546 wfDebug( __METHOD__
. ": no revisions to restore\n" );
548 $status = Status
::newGood( 0 );
549 $status->warning( "undelete-no-results" );
554 $ret->seek( $rev_count - 1 ); // move to last
555 $row = $ret->fetchObject(); // get newest archived rev
556 $ret->seek( 0 ); // move back
558 // grab the content to check consistency with global state before restoring the page.
559 $revision = Revision
::newFromArchiveRow( $row,
561 'title' => $article->getTitle(), // used to derive default content model
564 $user = User
::newFromName( $revision->getRawUserText(), false );
565 $content = $revision->getContent( Revision
::RAW
);
567 //NOTE: article ID may not be known yet. prepareSave() should not modify the database.
568 $status = $content->prepareSave( $article, 0, -1, $user );
570 if ( !$status->isOK() ) {
575 // Check the state of the newest to-be version...
576 if ( !$unsuppress && ( $row->ar_deleted
& Revision
::DELETED_TEXT
) ) {
577 return Status
::newFatal( "undeleterevdel" );
579 // Safe to insert now...
580 $newid = $article->insertOn( $dbw );
583 // Check if a deleted revision will become the current revision...
584 if ( $row->ar_timestamp
> $previousTimestamp ) {
585 // Check the state of the newest to-be version...
586 if ( !$unsuppress && ( $row->ar_deleted
& Revision
::DELETED_TEXT
) ) {
587 return Status
::newFatal( "undeleterevdel" );
592 $pageId = $article->getId();
598 foreach ( $ret as $row ) {
599 // Check for key dupes due to shitty archive integrity.
600 if ( $row->ar_rev_id
) {
601 $exists = $dbw->selectField( 'revision', '1',
602 array( 'rev_id' => $row->ar_rev_id
), __METHOD__
);
604 continue; // don't throw DB errors
607 // Insert one revision at a time...maintaining deletion status
608 // unless we are specifically removing all restrictions...
609 $revision = Revision
::newFromArchiveRow( $row,
612 'title' => $this->title
,
613 'deleted' => $unsuppress ?
0 : $row->ar_deleted
616 $revision->insertOn( $dbw );
619 wfRunHooks( 'ArticleRevisionUndeleted', array( &$this->title
, $revision, $row->ar_page_id
) );
621 # Now that it's safely stored, take it out of the archive
622 $dbw->delete( 'archive',
624 'ar_namespace' => $this->title
->getNamespace(),
625 'ar_title' => $this->title
->getDBkey(),
629 // Was anything restored at all?
630 if ( $restored == 0 ) {
631 return Status
::newGood( 0 );
634 $created = (bool)$newid;
636 // Attach the latest revision to the page...
637 $wasnew = $article->updateIfNewerOn( $dbw, $revision, $previousRevId );
638 if ( $created ||
$wasnew ) {
639 // Update site stats, link tables, etc
640 $user = User
::newFromName( $revision->getRawUserText(), false );
641 $article->doEditUpdates( $revision, $user, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
644 wfRunHooks( 'ArticleUndelete', array( &$this->title
, $created, $comment ) );
646 if ( $this->title
->getNamespace() == NS_FILE
) {
647 $update = new HTMLCacheUpdate( $this->title
, 'imagelinks' );
651 return Status
::newGood( $restored );
657 function getFileStatus() {
658 return $this->fileStatus
;
664 function getRevisionStatus() {
665 return $this->revisionStatus
;
670 * Special page allowing users with the appropriate permissions to view
671 * and restore deleted content.
673 * @ingroup SpecialPage
675 class SpecialUndelete
extends SpecialPage
{
676 var $mAction, $mTarget, $mTimestamp, $mRestore, $mInvert, $mFilename;
677 var $mTargetTimestamp, $mAllowed, $mCanView, $mComment, $mToken;
684 function __construct() {
685 parent
::__construct( 'Undelete', 'deletedhistory' );
688 function loadRequest( $par ) {
689 $request = $this->getRequest();
690 $user = $this->getUser();
692 $this->mAction
= $request->getVal( 'action' );
693 if ( $par !== null && $par !== '' ) {
694 $this->mTarget
= $par;
696 $this->mTarget
= $request->getVal( 'target' );
699 $this->mTargetObj
= null;
701 if ( $this->mTarget
!== null && $this->mTarget
!== '' ) {
702 $this->mTargetObj
= Title
::newFromURL( $this->mTarget
);
705 $this->mSearchPrefix
= $request->getText( 'prefix' );
706 $time = $request->getVal( 'timestamp' );
707 $this->mTimestamp
= $time ?
wfTimestamp( TS_MW
, $time ) : '';
708 $this->mFilename
= $request->getVal( 'file' );
710 $posted = $request->wasPosted() &&
711 $user->matchEditToken( $request->getVal( 'wpEditToken' ) );
712 $this->mRestore
= $request->getCheck( 'restore' ) && $posted;
713 $this->mInvert
= $request->getCheck( 'invert' ) && $posted;
714 $this->mPreview
= $request->getCheck( 'preview' ) && $posted;
715 $this->mDiff
= $request->getCheck( 'diff' );
716 $this->mDiffOnly
= $request->getBool( 'diffonly', $this->getUser()->getOption( 'diffonly' ) );
717 $this->mComment
= $request->getText( 'wpComment' );
718 $this->mUnsuppress
= $request->getVal( 'wpUnsuppress' ) && $user->isAllowed( 'suppressrevision' );
719 $this->mToken
= $request->getVal( 'token' );
721 if ( $user->isAllowed( 'undelete' ) && !$user->isBlocked() ) {
722 $this->mAllowed
= true; // user can restore
723 $this->mCanView
= true; // user can view content
724 } elseif ( $user->isAllowed( 'deletedtext' ) ) {
725 $this->mAllowed
= false; // user cannot restore
726 $this->mCanView
= true; // user can view content
727 $this->mRestore
= false;
728 } else { // user can only view the list of revisions
729 $this->mAllowed
= false;
730 $this->mCanView
= false;
731 $this->mTimestamp
= '';
732 $this->mRestore
= false;
735 if ( $this->mRestore ||
$this->mInvert
) {
736 $timestamps = array();
737 $this->mFileVersions
= array();
738 foreach ( $request->getValues() as $key => $val ) {
740 if ( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
741 array_push( $timestamps, $matches[1] );
744 if ( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
745 $this->mFileVersions
[] = intval( $matches[1] );
748 rsort( $timestamps );
749 $this->mTargetTimestamp
= $timestamps;
753 function execute( $par ) {
754 $this->checkPermissions();
755 $user = $this->getUser();
758 $this->outputHeader();
760 $this->loadRequest( $par );
762 $out = $this->getOutput();
764 if ( is_null( $this->mTargetObj
) ) {
765 $out->addWikiMsg( 'undelete-header' );
767 # Not all users can just browse every deleted page from the list
768 if ( $user->isAllowed( 'browsearchive' ) ) {
769 $this->showSearchForm();
775 if ( $this->mAllowed
) {
776 $out->setPageTitle( $this->msg( 'undeletepage' ) );
778 $out->setPageTitle( $this->msg( 'viewdeletedpage' ) );
781 $this->getSkin()->setRelevantTitle( $this->mTargetObj
);
783 if ( $this->mTimestamp
!== '' ) {
784 $this->showRevision( $this->mTimestamp
);
785 } elseif ( $this->mFilename
!== null && $this->mTargetObj
->inNamespace( NS_FILE
) ) {
786 $file = new ArchivedFile( $this->mTargetObj
, '', $this->mFilename
);
787 // Check if user is allowed to see this file
788 if ( !$file->exists() ) {
789 $out->addWikiMsg( 'filedelete-nofile', $this->mFilename
);
790 } elseif ( !$file->userCan( File
::DELETED_FILE
, $user ) ) {
791 if ( $file->isDeleted( File
::DELETED_RESTRICTED
) ) {
792 throw new PermissionsError( 'suppressrevision' );
794 throw new PermissionsError( 'deletedtext' );
796 } elseif ( !$user->matchEditToken( $this->mToken
, $this->mFilename
) ) {
797 $this->showFileConfirmationForm( $this->mFilename
);
799 $this->showFile( $this->mFilename
);
801 } elseif ( $this->mRestore
&& $this->mAction
== 'submit' ) {
804 $this->showHistory();
808 function showSearchForm() {
811 $out = $this->getOutput();
812 $out->setPageTitle( $this->msg( 'undelete-search-title' ) );
814 Xml
::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) ) .
815 Xml
::fieldset( $this->msg( 'undelete-search-box' )->text() ) .
816 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
819 array( 'for' => 'prefix' ),
820 $this->msg( 'undelete-search-prefix' )->parse()
825 $this->mSearchPrefix
,
826 array( 'id' => 'prefix', 'autofocus' => true )
828 Xml
::submitButton( $this->msg( 'undelete-search-submit' )->text() ) .
829 Xml
::closeElement( 'fieldset' ) .
830 Xml
::closeElement( 'form' )
833 # List undeletable articles
834 if ( $this->mSearchPrefix
) {
835 $result = PageArchive
::listPagesByPrefix( $this->mSearchPrefix
);
836 $this->showList( $result );
841 * Generic list of deleted pages
843 * @param ResultWrapper $result
846 private function showList( $result ) {
847 $out = $this->getOutput();
849 if ( $result->numRows() == 0 ) {
850 $out->addWikiMsg( 'undelete-no-results' );
855 $out->addWikiMsg( 'undeletepagetext', $this->getLanguage()->formatNum( $result->numRows() ) );
857 $undelete = $this->getPageTitle();
858 $out->addHTML( "<ul>\n" );
859 foreach ( $result as $row ) {
860 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
861 if ( $title !== null ) {
862 $item = Linker
::linkKnown(
864 htmlspecialchars( $title->getPrefixedText() ),
866 array( 'target' => $title->getPrefixedText() )
869 // The title is no longer valid, show as text
870 $item = Html
::element(
872 array( 'class' => 'mw-invalidtitle' ),
873 Linker
::getInvalidTitleDescription(
880 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count
)->parse();
881 $out->addHTML( "<li>{$item} ({$revs})</li>\n" );
884 $out->addHTML( "</ul>\n" );
889 private function showRevision( $timestamp ) {
890 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
894 $archive = new PageArchive( $this->mTargetObj
);
895 if ( !wfRunHooks( 'UndeleteForm::showRevision', array( &$archive, $this->mTargetObj
) ) ) {
898 $rev = $archive->getRevision( $timestamp );
900 $out = $this->getOutput();
901 $user = $this->getUser();
904 $out->addWikiMsg( 'undeleterevision-missing' );
909 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
910 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
912 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
913 'rev-deleted-text-permission'
920 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
921 'rev-deleted-text-view'
923 $out->addHTML( '<br />' );
924 // and we are allowed to see...
927 if ( $this->mDiff
) {
928 $previousRev = $archive->getPreviousRevision( $timestamp );
929 if ( $previousRev ) {
930 $this->showDiff( $previousRev, $rev );
931 if ( $this->mDiffOnly
) {
935 $out->addHTML( '<hr />' );
937 $out->addWikiMsg( 'undelete-nodiff' );
941 $link = Linker
::linkKnown(
942 $this->getPageTitle( $this->mTargetObj
->getPrefixedDBkey() ),
943 htmlspecialchars( $this->mTargetObj
->getPrefixedText() )
946 $lang = $this->getLanguage();
948 // date and time are separate parameters to facilitate localisation.
949 // $time is kept for backward compat reasons.
950 $time = $lang->userTimeAndDate( $timestamp, $user );
951 $d = $lang->userDate( $timestamp, $user );
952 $t = $lang->userTime( $timestamp, $user );
953 $userLink = Linker
::revUserTools( $rev );
955 $content = $rev->getContent( Revision
::FOR_THIS_USER
, $user );
957 $isText = ( $content instanceof TextContent
);
959 if ( $this->mPreview ||
$isText ) {
960 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
962 $openDiv = '<div id="mw-undelete-revision">';
964 $out->addHTML( $openDiv );
966 // Revision delete links
967 if ( !$this->mDiff
) {
968 $revdel = Linker
::getRevDeleteLink( $user, $rev, $this->mTargetObj
);
970 $out->addHTML( "$revdel " );
974 $out->addHTML( $this->msg( 'undelete-revision' )->rawParams( $link )->params(
975 $time )->rawParams( $userLink )->params( $d, $t )->parse() . '</div>' );
977 if ( !wfRunHooks( 'UndeleteShowRevision', array( $this->mTargetObj
, $rev ) ) ) {
981 if ( $this->mPreview ||
!$isText ) {
982 // NOTE: non-text content has no source view, so always use rendered preview
985 $popts = $out->parserOptions();
986 $popts->setEditSection( false );
988 $pout = $content->getParserOutput( $this->mTargetObj
, $rev->getId(), $popts, true );
989 $out->addParserOutput( $pout );
993 // source view for textual content
994 $sourceView = Xml
::element(
997 'readonly' => 'readonly',
998 'cols' => $user->getIntOption( 'cols' ),
999 'rows' => $user->getIntOption( 'rows' )
1001 $content->getNativeData() . "\n"
1004 $previewButton = Xml
::element( 'input', array(
1006 'name' => 'preview',
1007 'value' => $this->msg( 'showpreview' )->text()
1011 $previewButton = '';
1014 $diffButton = Xml
::element( 'input', array(
1017 'value' => $this->msg( 'showdiff' )->text() ) );
1021 Xml
::openElement( 'div', array(
1022 'style' => 'clear: both' ) ) .
1023 Xml
::openElement( 'form', array(
1025 'action' => $this->getPageTitle()->getLocalURL( array( 'action' => 'submit' ) ) ) ) .
1026 Xml
::element( 'input', array(
1029 'value' => $this->mTargetObj
->getPrefixedDBkey() ) ) .
1030 Xml
::element( 'input', array(
1032 'name' => 'timestamp',
1033 'value' => $timestamp ) ) .
1034 Xml
::element( 'input', array(
1036 'name' => 'wpEditToken',
1037 'value' => $user->getEditToken() ) ) .
1040 Xml
::closeElement( 'form' ) .
1041 Xml
::closeElement( 'div' )
1046 * Build a diff display between this and the previous either deleted
1047 * or non-deleted edit.
1049 * @param Revision $previousRev
1050 * @param Revision $currentRev
1051 * @return string HTML
1053 function showDiff( $previousRev, $currentRev ) {
1054 $diffContext = clone $this->getContext();
1055 $diffContext->setTitle( $currentRev->getTitle() );
1056 $diffContext->setWikiPage( WikiPage
::factory( $currentRev->getTitle() ) );
1058 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
1059 $diffEngine->showDiffStyle();
1061 $formattedDiff = $diffEngine->generateContentDiffBody(
1062 $previousRev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() ),
1063 $currentRev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() )
1066 $formattedDiff = $diffEngine->addHeader(
1068 $this->diffHeader( $previousRev, 'o' ),
1069 $this->diffHeader( $currentRev, 'n' )
1072 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
1076 * @param Revision $rev
1077 * @param string $prefix
1080 private function diffHeader( $rev, $prefix ) {
1081 $isDeleted = !( $rev->getId() && $rev->getTitle() );
1083 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
1084 $targetPage = $this->getPageTitle();
1085 $targetQuery = array(
1086 'target' => $this->mTargetObj
->getPrefixedText(),
1087 'timestamp' => wfTimestamp( TS_MW
, $rev->getTimestamp() )
1090 /// @todo FIXME: getId() may return non-zero for deleted revs...
1091 $targetPage = $rev->getTitle();
1092 $targetQuery = array( 'oldid' => $rev->getId() );
1095 // Add show/hide deletion links if available
1096 $user = $this->getUser();
1097 $lang = $this->getLanguage();
1098 $rdel = Linker
::getRevDeleteLink( $user, $rev, $this->mTargetObj
);
1104 $minor = $rev->isMinor() ? ChangesList
::flag( 'minor' ) : '';
1106 $tags = wfGetDB( DB_SLAVE
)->selectField(
1109 array( 'ts_rev_id' => $rev->getId() ),
1112 $tagSummary = ChangeTags
::formatSummaryRow( $tags, 'deleteddiff' );
1114 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
1115 // and partially #showDiffPage, but worse
1116 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
1121 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
1122 $lang->userDate( $rev->getTimestamp(), $user ),
1123 $lang->userTime( $rev->getTimestamp(), $user )
1129 '<div id="mw-diff-' . $prefix . 'title2">' .
1130 Linker
::revUserTools( $rev ) . '<br />' .
1132 '<div id="mw-diff-' . $prefix . 'title3">' .
1133 $minor . Linker
::revComment( $rev ) . $rdel . '<br />' .
1135 '<div id="mw-diff-' . $prefix . 'title5">' .
1136 $tagSummary[0] . '<br />' .
1141 * Show a form confirming whether a tokenless user really wants to see a file
1143 private function showFileConfirmationForm( $key ) {
1144 $out = $this->getOutput();
1145 $lang = $this->getLanguage();
1146 $user = $this->getUser();
1147 $file = new ArchivedFile( $this->mTargetObj
, '', $this->mFilename
);
1148 $out->addWikiMsg( 'undelete-show-file-confirm',
1149 $this->mTargetObj
->getText(),
1150 $lang->userDate( $file->getTimestamp(), $user ),
1151 $lang->userTime( $file->getTimestamp(), $user ) );
1153 Xml
::openElement( 'form', array(
1155 'action' => $this->getPageTitle()->getLocalURL( array(
1156 'target' => $this->mTarget
,
1158 'token' => $user->getEditToken( $key ),
1162 Xml
::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
1168 * Show a deleted file version requested by the visitor.
1170 private function showFile( $key ) {
1171 $this->getOutput()->disable();
1173 # We mustn't allow the output to be Squid cached, otherwise
1174 # if an admin previews a deleted image, and it's cached, then
1175 # a user without appropriate permissions can toddle off and
1176 # nab the image, and Squid will serve it
1177 $response = $this->getRequest()->response();
1178 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1179 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1180 $response->header( 'Pragma: no-cache' );
1182 $repo = RepoGroup
::singleton()->getLocalRepo();
1183 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
1184 $repo->streamFile( $path );
1187 private function showHistory() {
1188 $out = $this->getOutput();
1189 if ( $this->mAllowed
) {
1190 $out->addModules( 'mediawiki.special.undelete' );
1193 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
1194 array( 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj
->getPrefixedText() ) )
1197 $archive = new PageArchive( $this->mTargetObj
);
1198 wfRunHooks( 'UndeleteForm::showHistory', array( &$archive, $this->mTargetObj
) );
1200 $text = $archive->getLastRevisionText();
1201 if( is_null( $text ) ) {
1202 $out->addWikiMsg( 'nohistory' );
1206 $out->addHTML( '<div class="mw-undelete-history">' );
1207 if ( $this->mAllowed
) {
1208 $out->addWikiMsg( 'undeletehistory' );
1209 $out->addWikiMsg( 'undeleterevdel' );
1211 $out->addWikiMsg( 'undeletehistorynoadmin' );
1213 $out->addHTML( '</div>' );
1215 # List all stored revisions
1216 $revisions = $archive->listRevisions();
1217 $files = $archive->listFiles();
1219 $haveRevisions = $revisions && $revisions->numRows() > 0;
1220 $haveFiles = $files && $files->numRows() > 0;
1222 # Batch existence check on user and talk pages
1223 if ( $haveRevisions ) {
1224 $batch = new LinkBatch();
1225 foreach ( $revisions as $row ) {
1226 $batch->addObj( Title
::makeTitleSafe( NS_USER
, $row->ar_user_text
) );
1227 $batch->addObj( Title
::makeTitleSafe( NS_USER_TALK
, $row->ar_user_text
) );
1230 $revisions->seek( 0 );
1233 $batch = new LinkBatch();
1234 foreach ( $files as $row ) {
1235 $batch->addObj( Title
::makeTitleSafe( NS_USER
, $row->fa_user_text
) );
1236 $batch->addObj( Title
::makeTitleSafe( NS_USER_TALK
, $row->fa_user_text
) );
1242 if ( $this->mAllowed
) {
1243 $action = $this->getPageTitle()->getLocalURL( array( 'action' => 'submit' ) );
1244 # Start the form here
1245 $top = Xml
::openElement(
1247 array( 'method' => 'post', 'action' => $action, 'id' => 'undelete' )
1249 $out->addHTML( $top );
1252 # Show relevant lines from the deletion log:
1253 $deleteLogPage = new LogPage( 'delete' );
1254 $out->addHTML( Xml
::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
1255 LogEventsList
::showLogExtract( $out, 'delete', $this->mTargetObj
);
1256 # Show relevant lines from the suppression log:
1257 $suppressLogPage = new LogPage( 'suppress' );
1258 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
1259 $out->addHTML( Xml
::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
1260 LogEventsList
::showLogExtract( $out, 'suppress', $this->mTargetObj
);
1263 if ( $this->mAllowed
&& ( $haveRevisions ||
$haveFiles ) ) {
1264 # Format the user-visible controls (comment field, submission button)
1265 # in a nice little table
1266 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
1270 <td class='mw-input'>" .
1271 Xml
::checkLabel( $this->msg( 'revdelete-unsuppress' )->text(),
1272 'wpUnsuppress', 'mw-undelete-unsuppress', $this->mUnsuppress
) .
1276 $unsuppressBox = '';
1279 $table = Xml
::fieldset( $this->msg( 'undelete-fieldset-title' )->text() ) .
1280 Xml
::openElement( 'table', array( 'id' => 'mw-undelete-table' ) ) .
1282 <td colspan='2' class='mw-undelete-extrahelp'>" .
1283 $this->msg( 'undeleteextrahelp' )->parseAsBlock() .
1287 <td class='mw-label'>" .
1288 Xml
::label( $this->msg( 'undeletecomment' )->text(), 'wpComment' ) .
1290 <td class='mw-input'>" .
1291 Xml
::input( 'wpComment', 50, $this->mComment
, array( 'id' => 'wpComment', 'autofocus' => true ) ) .
1296 <td class='mw-submit'>" .
1297 Xml
::submitButton( $this->msg( 'undeletebtn' )->text(), array( 'name' => 'restore', 'id' => 'mw-undelete-submit' ) ) . ' ' .
1298 Xml
::submitButton( $this->msg( 'undeleteinvert' )->text(), array( 'name' => 'invert', 'id' => 'mw-undelete-invert' ) ) .
1302 Xml
::closeElement( 'table' ) .
1303 Xml
::closeElement( 'fieldset' );
1305 $out->addHTML( $table );
1308 $out->addHTML( Xml
::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n" );
1310 if ( $haveRevisions ) {
1311 # The page's stored (deleted) history:
1312 $out->addHTML( '<ul>' );
1313 $remaining = $revisions->numRows();
1314 $earliestLiveTime = $this->mTargetObj
->getEarliestRevTime();
1316 foreach ( $revisions as $row ) {
1318 $out->addHTML( $this->formatRevisionRow( $row, $earliestLiveTime, $remaining ) );
1321 $out->addHTML( '</ul>' );
1323 $out->addWikiMsg( 'nohistory' );
1327 $out->addHTML( Xml
::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n" );
1328 $out->addHTML( '<ul>' );
1329 foreach ( $files as $row ) {
1330 $out->addHTML( $this->formatFileRow( $row ) );
1333 $out->addHTML( '</ul>' );
1336 if ( $this->mAllowed
) {
1337 # Slip in the hidden controls here
1338 $misc = Html
::hidden( 'target', $this->mTarget
);
1339 $misc .= Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
1340 $misc .= Xml
::closeElement( 'form' );
1341 $out->addHTML( $misc );
1347 private function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
1348 $rev = Revision
::newFromArchiveRow( $row,
1350 'title' => $this->mTargetObj
1354 $ts = wfTimestamp( TS_MW
, $row->ar_timestamp
);
1355 // Build checkboxen...
1356 if ( $this->mAllowed
) {
1357 if ( $this->mInvert
) {
1358 if ( in_array( $ts, $this->mTargetTimestamp
) ) {
1359 $checkBox = Xml
::check( "ts$ts" );
1361 $checkBox = Xml
::check( "ts$ts", true );
1364 $checkBox = Xml
::check( "ts$ts" );
1370 // Build page & diff links...
1371 $user = $this->getUser();
1372 if ( $this->mCanView
) {
1373 $titleObj = $this->getPageTitle();
1375 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
1376 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1377 $last = $this->msg( 'diff' )->escaped();
1378 } elseif ( $remaining > 0 ||
( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
1379 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1380 $last = Linker
::linkKnown(
1382 $this->msg( 'diff' )->escaped(),
1385 'target' => $this->mTargetObj
->getPrefixedText(),
1391 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1392 $last = $this->msg( 'diff' )->escaped();
1395 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1396 $last = $this->msg( 'diff' )->escaped();
1400 $userLink = Linker
::revUserTools( $rev );
1403 $minor = $rev->isMinor() ? ChangesList
::flag( 'minor' ) : '';
1405 // Revision text size
1406 $size = $row->ar_len
;
1407 if ( !is_null( $size ) ) {
1408 $revTextSize = Linker
::formatRevisionSize( $size );
1412 $comment = Linker
::revComment( $rev );
1416 list( $tagSummary, $classes ) = ChangeTags
::formatSummaryRow( $row->ts_tags
, 'deletedhistory' );
1418 $attribs['class'] = implode( ' ', $classes );
1421 // Revision delete links
1422 $revdlink = Linker
::getRevDeleteLink( $user, $rev, $this->mTargetObj
);
1424 $revisionRow = $this->msg( 'undelete-revision-row' )
1425 ->rawParams( $checkBox, $revdlink, $last, $pageLink, $userLink, $minor, $revTextSize, $comment, $tagSummary )
1428 return Xml
::tags( 'li', $attribs, $revisionRow ) . "\n";
1431 private function formatFileRow( $row ) {
1432 $file = ArchivedFile
::newFromRow( $row );
1433 $ts = wfTimestamp( TS_MW
, $row->fa_timestamp
);
1434 $user = $this->getUser();
1436 if ( $this->mAllowed
&& $row->fa_storage_key
) {
1437 $checkBox = Xml
::check( 'fileid' . $row->fa_id
);
1438 $key = urlencode( $row->fa_storage_key
);
1439 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
1442 $pageLink = $this->getLanguage()->userTimeAndDate( $ts, $user );
1444 $userLink = $this->getFileUser( $file );
1445 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width
, $row->fa_height
)->text();
1446 $bytes = $this->msg( 'parentheses' )
1447 ->rawParams( $this->msg( 'nbytes' )->numParams( $row->fa_size
)->text() )
1449 $data = htmlspecialchars( $data . ' ' . $bytes );
1450 $comment = $this->getFileComment( $file );
1452 // Add show/hide deletion links if available
1453 $canHide = $user->isAllowed( 'deleterevision' );
1454 if ( $canHide ||
( $file->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1455 if ( !$file->userCan( File
::DELETED_RESTRICTED
, $user ) ) {
1456 // Revision was hidden from sysops
1457 $revdlink = Linker
::revDeleteLinkDisabled( $canHide );
1460 'type' => 'filearchive',
1461 'target' => $this->mTargetObj
->getPrefixedDBkey(),
1462 'ids' => $row->fa_id
1464 $revdlink = Linker
::revDeleteLink( $query,
1465 $file->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
1471 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1475 * Fetch revision text link if it's available to all users
1477 * @param Revision $rev
1478 * @param Title $titleObj
1479 * @param string $ts Timestamp
1482 function getPageLink( $rev, $titleObj, $ts ) {
1483 $user = $this->getUser();
1484 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1486 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1487 return '<span class="history-deleted">' . $time . '</span>';
1490 $link = Linker
::linkKnown(
1492 htmlspecialchars( $time ),
1495 'target' => $this->mTargetObj
->getPrefixedText(),
1500 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1501 $link = '<span class="history-deleted">' . $link . '</span>';
1508 * Fetch image view link if it's available to all users
1510 * @param File|ArchivedFile $file
1511 * @param Title $titleObj
1512 * @param string $ts A timestamp
1513 * @param string $key a storage key
1515 * @return string HTML fragment
1517 function getFileLink( $file, $titleObj, $ts, $key ) {
1518 $user = $this->getUser();
1519 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1521 if ( !$file->userCan( File
::DELETED_FILE
, $user ) ) {
1522 return '<span class="history-deleted">' . $time . '</span>';
1525 $link = Linker
::linkKnown(
1527 htmlspecialchars( $time ),
1530 'target' => $this->mTargetObj
->getPrefixedText(),
1532 'token' => $user->getEditToken( $key )
1536 if ( $file->isDeleted( File
::DELETED_FILE
) ) {
1537 $link = '<span class="history-deleted">' . $link . '</span>';
1544 * Fetch file's user id if it's available to this user
1546 * @param File|ArchivedFile $file
1547 * @return string HTML fragment
1549 function getFileUser( $file ) {
1550 if ( !$file->userCan( File
::DELETED_USER
, $this->getUser() ) ) {
1551 return '<span class="history-deleted">' .
1552 $this->msg( 'rev-deleted-user' )->escaped() .
1556 $link = Linker
::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1557 Linker
::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1559 if ( $file->isDeleted( File
::DELETED_USER
) ) {
1560 $link = '<span class="history-deleted">' . $link . '</span>';
1567 * Fetch file upload comment if it's available to this user
1569 * @param File|ArchivedFile $file
1570 * @return string HTML fragment
1572 function getFileComment( $file ) {
1573 if ( !$file->userCan( File
::DELETED_COMMENT
, $this->getUser() ) ) {
1574 return '<span class="history-deleted"><span class="comment">' .
1575 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1578 $link = Linker
::commentBlock( $file->getRawDescription() );
1580 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
1581 $link = '<span class="history-deleted">' . $link . '</span>';
1587 function undelete() {
1588 global $wgUploadMaintenance;
1590 if ( $wgUploadMaintenance && $this->mTargetObj
->getNamespace() == NS_FILE
) {
1591 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1594 if ( wfReadOnly() ) {
1595 throw new ReadOnlyError
;
1598 $out = $this->getOutput();
1599 $archive = new PageArchive( $this->mTargetObj
);
1600 wfRunHooks( 'UndeleteForm::undelete', array( &$archive, $this->mTargetObj
) );
1601 $ok = $archive->undelete(
1602 $this->mTargetTimestamp
,
1604 $this->mFileVersions
,
1609 if ( is_array( $ok ) ) {
1610 if ( $ok[1] ) { // Undeleted file count
1611 wfRunHooks( 'FileUndeleteComplete', array(
1612 $this->mTargetObj
, $this->mFileVersions
,
1613 $this->getUser(), $this->mComment
) );
1616 $link = Linker
::linkKnown( $this->mTargetObj
);
1617 $out->addHTML( $this->msg( 'undeletedpage' )->rawParams( $link )->parse() );
1619 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1622 // Show revision undeletion warnings and errors
1623 $status = $archive->getRevisionStatus();
1624 if ( $status && !$status->isGood() ) {
1625 $out->addWikiText( '<div class="error">' . $status->getWikiText( 'cannotundelete', 'cannotundelete' ) . '</div>' );
1628 // Show file undeletion warnings and errors
1629 $status = $archive->getFileStatus();
1630 if ( $status && !$status->isGood() ) {
1631 $out->addWikiText( '<div class="error">' . $status->getWikiText( 'undelete-error-short', 'undelete-error-long' ) . '</div>' );
1635 protected function getGroupName() {