BUG#1860 - Anchors of interwiki links did not get normalized
[lhc/web/wiklou.git] / includes / SpecialUndelete.php
index d213e56..e4b34b2 100644 (file)
@@ -1,10 +1,13 @@
 <?php
 /**
- *
+ * @todo document
  * @package MediaWiki
  * @subpackage SpecialPage
  */
 
+/** */
+require_once( 'Revision.php' );
+
 /**
  *
  */
@@ -30,6 +33,13 @@ class PageArchive {
                $this->title =& $title;
        }
        
+       /**
+        * List all deleted pages recorded in the archive table. Returns result
+        * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
+        * namespace/title. Can be called staticaly.
+        *
+        * @return ResultWrapper
+        */
        /* static */ function &listAllPages() {
                $dbr =& wfGetDB( DB_SLAVE );
                $archive = $dbr->tableName( 'archive' );
@@ -40,42 +50,65 @@ class PageArchive {
                return $dbr->resultObject( $dbr->query( $sql, 'PageArchive::listAllPages' ) );
        }
        
+       /**
+        * List the revisions of the given page. Returns result wrapper with
+        * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
+        *
+        * @return ResultWrapper
+        */
        function &listRevisions() {
                $dbr =& wfGetDB( DB_SLAVE );
-               $sql = "SELECT ar_minor_edit,ar_timestamp,ar_user,ar_user_text,ar_comment
-                 FROM archive WHERE ar_namespace=" . $this->title->getNamespace() .
-                 " AND ar_title='" . $dbr->strencode( $this->title->getDBkey() ) .
-                 "' ORDER BY ar_timestamp DESC";
-               return $dbr->resultObject( $dbr->query( $sql ) );
+               return $dbr->resultObject( $dbr->select( 'archive',
+                       array( 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text', 'ar_comment' ),
+                       array( 'ar_namespace' => $this->title->getNamespace(),
+                              'ar_title' => $this->title->getDBkey() ),
+                       'PageArchive::listRevisions',
+                       array( 'ORDER BY' => 'ar_timestamp DESC' ) ) );
        }
        
+       /**
+        * Fetch (and decompress if necessary) the stored text for the deleted
+        * revision of the page with the given timestamp.
+        *
+        * @return string
+        */
        function getRevisionText( $timestamp ) {
                $dbr =& wfGetDB( DB_SLAVE );
                $row = $dbr->selectRow( 'archive',
                        array( 'ar_text', 'ar_flags' ),
                        array( 'ar_namespace' => $this->title->getNamespace(),
                               'ar_title' => $this->title->getDbkey(),
-                              'ar_timestamp' => $timestamp ) );
-               return Article::getRevisionText( $row, "ar_" );
+                              'ar_timestamp' => $dbr->timestamp( $timestamp ) ) );
+               return Revision::getRevisionText( $row, "ar_" );
        }
        
+       /**
+        * Fetch (and decompress if necessary) the stored text of the most
+        * recently edited deleted revision of the page.
+        *
+        * If there are no archived revisions for the page, returns NULL.
+        *
+        * @return string
+        */
        function getLastRevisionText() {
                $dbr =& wfGetDB( DB_SLAVE );
-               $archive = $dbr->tableName( 'archive' );
-               
-               # Get text of first revision
-               $sql = "SELECT ar_text,ar_flags FROM $archive WHERE ar_namespace=" . $this->title->getNamespace() . " AND ar_title='" .
-                 $dbr->strencode( $this->title->getDBkey() ) . "' ORDER BY ar_timestamp DESC LIMIT 1";
-               $ret = $dbr->query( $sql );
-               $row = $dbr->fetchObject( $ret );
-               $dbr->freeResult( $ret );
+               $row = $dbr->selectRow( 'archive',
+                       array( 'ar_text', 'ar_flags' ),
+                       array( 'ar_namespace' => $this->title->getNamespace(),
+                              'ar_title' => $this->title->getDBkey() ),
+                       'PageArchive::getLastRevisionText',
+                       'ORDER BY ar_timestamp DESC LIMIT 1' );
                if( $row ) {
-                       return Article::getRevisionText( $row, "ar_" );
+                       return Revision::getRevisionText( $row, "ar_" );
                } else {
                        return NULL;
                }
        }
        
+       /**
+        * Quick check if any archived revisions are present for the page.
+        * @return bool
+        */
        function isDeleted() {
                $dbr =& wfGetDB( DB_SLAVE );
                $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
@@ -84,95 +117,149 @@ class PageArchive {
                return ($n > 0);
        }
        
-       function undelete() {
+       /**
+        * This is the meaty bit -- restores archived revisions of the given page
+        * to the cur/old tables. If the page currently exists, all revisions will
+        * be stuffed into old, otherwise the most recent will go into cur.
+        * The deletion log will be updated with an undeletion notice.
+        *
+        * Returns true on success.
+        *
+        * @param array $timestamps Pass an empty array to restore all revisions, otherwise list the ones to undelete.
+        * @return bool
+        */
+       function undelete( $timestamps ) {
                global $wgUser, $wgOut, $wgLang, $wgDeferredUpdateList;
-               global  $wgUseSquid, $wgInternalServer, $wgLinkCache;
+               global $wgUseSquid, $wgInternalServer, $wgLinkCache;
+               global $wgDBtype;
 
                $fname = "doUndeleteArticle";
+               $restoreAll = empty( $timestamps );
+               $restoreRevisions = count( $timestamps );
 
                $dbw =& wfGetDB( DB_MASTER );
-               extract( $dbw->tableNames( 'cur', 'archive', 'old' ) );
-               $namespace = $this->title->getNamespace();
-               $t = $dbw->strencode( $this->title->getDBkey() );
+               extract( $dbw->tableNames( 'page', 'archive' ) );
 
-               # Move article and history from the "archive" table
-               $sql = "SELECT COUNT(*) AS count FROM $cur WHERE cur_namespace={$namespace} AND cur_title='{$t}' FOR UPDATE";
-               $res = $dbw->query( $sql, $fname );
-               $row = $dbw->fetchObject( $res );
-               $now = wfTimestampNow();
-
-               if( $row->count == 0) {
-                       # Have to create new article...
-                       $sql = "SELECT ar_text,ar_timestamp,ar_flags FROM $archive WHERE ar_namespace={$namespace} AND ar_title='{$t}' " .
-                               "ORDER BY ar_timestamp DESC LIMIT 1 FOR UPDATE";
-                       $res = $dbw->query( $sql, $fname );
-                       $s = $dbw->fetchObject( $res );
-                       $max = $s->ar_timestamp;
-                       $redirect = MagicWord::get( MAG_REDIRECT );
-                       $redir = $redirect->matchStart( $s->ar_text ) ? 1 : 0;
-                       
-                       $seqVal = $dbw->addQuotes( $dbw->nextSequenceValue( 'cur_cur_id_seq' ) );
-
-                       $sql = "INSERT INTO $cur (cur_id,cur_namespace,cur_title,cur_text," .
-                         "cur_comment,cur_user,cur_user_text,cur_timestamp,inverse_timestamp,cur_minor_edit,cur_is_redirect,cur_random,cur_touched)" .
-                         "SELECT $seqVal,ar_namespace,ar_title,ar_text,ar_comment," .
-                         "ar_user,ar_user_text,ar_timestamp,99999999999999-ar_timestamp,ar_minor_edit,{$redir},RAND(),'{$now}' FROM $archive " .
-                         "WHERE ar_namespace={$namespace} AND ar_title='{$t}' AND ar_timestamp={$max}";
-                       $dbw->query( $sql, $fname );
-                       $newid = $dbw->insertId();
-                       $oldones = "AND ar_timestamp<{$max}";
+               # Does this page already exist? We'll have to update it...
+               $article = new Article( $this->title );
+               $options = ( $wgDBtype == 'PostgreSQL' )
+                       ? '' // pg doesn't support this?
+                       : 'FOR UPDATE';
+               $page = $dbw->selectRow( 'page',
+                       array( 'page_id', 'page_latest' ),
+                       array( 'page_namespace' => $this->title->getNamespace(),
+                              'page_title'     => $this->title->getDBkey() ),
+                       $fname,
+                       $options );
+               if( $page ) {
+                       # Page already exists. Import the history, and if necessary
+                       # we'll update the latest revision field in the record.
+                       $newid             = 0;
+                       $pageId            = $page->page_id;
+                       $previousRevId     = $page->page_latest;
+                       $previousTimestamp = $page->rev_timestamp;
                } else {
-                       # If already exists, put history entirely into old table
-                       $oldones = "";
-                       $newid = 0;
-                       
-                       # But to make the history list show up right, we need to touch it.
-                       $sql = "UPDATE $cur SET cur_touched='{$now}' WHERE cur_namespace={$namespace} AND cur_title='{$t}'";
-                       $dbw->query( $sql, $fname );
+                       # Have to create a new article...
+                       $newid  = $article->insertOn( $dbw );
+                       $pageId = $newid;
+                       $previousRevId = 0;
+                       $previousTimestamp = 0;
+               }
+               
+               if( $restoreAll ) {
+                       $oldones = '1'; # All revisions...
+               } else {
+                       $oldts = implode( ',',
+                               array_map( array( &$dbw, 'addQuotes' ),
+                                       array_map( array( &$dbw, 'timestamp' ),
+                                               $timestamps ) ) );
                        
-                       # FIXME: Sometimes restored entries will be _newer_ than the current version.
-                       # We should merge.
+                       $oldones = "ar_timestamp IN ( {$oldts} )";
                }
                
-               $sql = "INSERT INTO $old (old_namespace,old_title,old_text," .
-                 "old_comment,old_user,old_user_text,old_timestamp,inverse_timestamp,old_minor_edit," .
-                 "old_flags) SELECT ar_namespace,ar_title,ar_text,ar_comment," .
-                 "ar_user,ar_user_text,ar_timestamp,99999999999999-ar_timestamp,ar_minor_edit,ar_flags " .
-                 "FROM $archive WHERE ar_namespace={$namespace} AND ar_title='{$t}' {$oldones}";
-               $dbw->query( $sql, $fname );
-
-               # Finally, clean up the link tables 
-               if( $newid ) {
-                       $wgLinkCache = new LinkCache();
-                       # Select for update
-                       $wgLinkCache->forUpdate( true );
-                       # Create a dummy OutputPage to update the outgoing links
-                       $dummyOut = new OutputPage();
-                       # Get the text
-                       $text = $dbw->selectField( 'cur', 'cur_text', 
-                               array( 'cur_id' => $newid, 'cur_namespace' => $namespace ), 
-                               $fname, 'FOR UPDATE' 
+               /**
+                * Restore each revision...
+                */
+               $result = $dbw->select( 'archive',
+                       /* fields */ array(
+                               'ar_rev_id',
+                               'ar_text',
+                               'ar_comment',
+                               'ar_user',
+                               'ar_user_text',
+                               'ar_timestamp',
+                               'ar_minor_edit',
+                               'ar_flags' ),
+                       /* WHERE */ array(
+                               'ar_namespace' => $this->title->getNamespace(),
+                               'ar_title'     => $this->title->getDBkey(),
+                               $oldones ),
+                       $fname,
+                       /* options */ array(
+                               'ORDER BY' => 'ar_timestamp' )
                        );
-                       $dummyOut->addWikiText( $text );
-
-                       $u = new LinksUpdate( $newid, $this->title->getPrefixedDBkey() );
-                       array_push( $wgDeferredUpdateList, $u );
-                       
-                       Article::onArticleCreate( $this->title );
+               $revision = null;
+               while( $row = $dbw->fetchObject( $result ) ) {
+                       $revision = new Revision( array(
+                               'page'       => $pageId,
+                               'id'         => $row->ar_rev_id,
+                               'text'       => Revision::getRevisionText( $row, 'ar_' ),
+                               'comment'    => $row->ar_comment,
+                               'user'       => $row->ar_user,
+                               'user_text'  => $row->ar_user_text,
+                               'timestamp'  => $row->ar_timestamp,
+                               'minor_edit' => $row->ar_minor_edit,
+                               ) );
+                       $revision->insertOn( $dbw );
+               }
+               
+               if( $revision ) {
+                       # FIXME: Update latest if newer as well...
+                       if( $newid ) {
+                               # FIXME: update article count if changed...
+                               $article->updateRevisionOn( $dbw, $revision, $previousRevId );
+                               
+                               # Finally, clean up the link tables
+                               $wgLinkCache = new LinkCache();
+                               # Select for update
+                               $wgLinkCache->forUpdate( true );
+                               
+                               # Create a dummy OutputPage to update the outgoing links
+                               $dummyOut = new OutputPage();
+                               $dummyOut->addWikiText( $revision->getText() );
 
-                       #TODO: SearchUpdate, etc.
+                               $u = new LinksUpdate( $newid, $this->title->getPrefixedDBkey() );
+                               array_push( $wgDeferredUpdateList, $u );
+                               
+                               #TODO: SearchUpdate, etc.
+                       }
+                               
+                       if( $newid ) {
+                               Article::onArticleCreate( $this->title );
+                       } else {
+                               Article::onArticleEdit( $this->title );
+                       }
+               } else {
+                       # Something went terribly worong!
                }
 
                # Now that it's safely stored, take it out of the archive
-               $sql = "DELETE FROM $archive WHERE ar_namespace={$namespace} AND " .
-                 "ar_title='{$t}'";
-               $dbw->query( $sql, $fname );
-
+               $dbw->delete( 'archive',
+                       /* WHERE */ array(
+                               'ar_namespace' => $this->title->getNamespace(),
+                               'ar_title' => $this->title->getDBkey(),
+                               $oldones ),
+                       $fname );
                
-               # Touch the log?
+               # Touch the log!
                $log = new LogPage( 'delete' );
-               $log->addEntry( 'restore', $this->title, "" );
-               
+               if( $restoreAll ) {
+                       $reason = "";
+               } else {
+                       $reason = wfMsg( 'undeletedrevisions', $restoreRevisions );
+               }
+               $log->addEntry( 'restore', $this->title, $reason );
+
                return true;
        }
 }
@@ -184,12 +271,16 @@ class PageArchive {
  */
 class UndeleteForm {
        var $mAction, $mTarget, $mTimestamp, $mRestore, $mTargetObj;
+       var $mTargetTimestamp;
 
        function UndeleteForm( &$request, $par = "" ) {
+               global $wgUser;
                $this->mAction = $request->getText( 'action' );
                $this->mTarget = $request->getText( 'target' );
                $this->mTimestamp = $request->getText( 'timestamp' );
-               $this->mRestore = $request->getCheck( 'restore' ) && $request->wasPosted();
+               $this->mRestore = $request->getCheck( 'restore' ) &&
+                       $request->wasPosted() &&
+                       $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
                if( $par != "" ) {
                        $this->mTarget = $par;
                }
@@ -198,6 +289,16 @@ class UndeleteForm {
                } else {
                        $this->mTargetObj = NULL;
                }
+               if( $this->mRestore ) {
+                       $timestamps = array();
+                       foreach( $_REQUEST as $key => $val ) {
+                               if( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
+                                       array_push( $timestamps, $matches[1] );
+                               }
+                       }
+                       rsort( $timestamps );
+                       $this->mTargetTimestamp = $timestamps;
+               }
        }
 
        function execute() {
@@ -277,12 +378,14 @@ class UndeleteForm {
                $action = $titleObj->escapeLocalURL( "action=submit" );
                $encTarget = htmlspecialchars( $this->mTarget );
                $button = htmlspecialchars( wfMsg("undeletebtn") );
+               $token = htmlspecialchars( $wgUser->editToken() );
                
                $wgOut->addHTML("
        <form id=\"undelete\" method=\"post\" action=\"{$action}\">
        <input type=\"hidden\" name=\"target\" value=\"{$encTarget}\" />
        <input type=\"submit\" name=\"restore\" value=\"{$button}\" />
-       </form>");
+       <input type='hidden' name='wpEditToken' value=\"{$token}\" />
+       ");
 
                # Show relevant lines from the deletion log:
                $wgOut->addHTML( "<h2>" . htmlspecialchars( LogPage::logName( 'delete' ) ) . "</h2>\n" );
@@ -290,7 +393,8 @@ class UndeleteForm {
                $logViewer =& new LogViewer(
                        new LogReader(
                                new FauxRequest(
-                                       array( 'page', $this->mTargetObj->getPrefixedText() ) ) ) );
+                                       array( 'page' => $this->mTargetObj->getPrefixedText(),
+                                              'type' => 'delete' ) ) ) );
                $logViewer->showList( $wgOut );
                
                # The page's stored (deleted) history:
@@ -298,21 +402,27 @@ class UndeleteForm {
                $wgOut->addHTML("<ul>");
                $target = urlencode( $this->mTarget );
                while( $row = $revisions->fetchObject() ) {
+                       $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
+                       $checkBox = "<input type=\"checkbox\" name=\"ts$ts\" value=\"1\" />";
                        $pageLink = $sk->makeKnownLinkObj( $titleObj,
                                $wgLang->timeanddate( $row->ar_timestamp, true ),
-                               "target=$target&timestamp={$row->ar_timestamp}" );
+                               "target=$target&timestamp=$ts" );
                        $userLink = htmlspecialchars( $row->ar_user_text );
                        if( $row->ar_user ) {
                                $userLink = $sk->makeKnownLinkObj(
                                        Title::makeTitle( NS_USER, $row->ar_user_text ),
                                        $userLink );
+                       } else {
+                               $userLink = $sk->makeKnownLinkObj(
+                                       Title::makeTitle( NS_SPECIAL, 'Contributions' ),
+                                       $userLink, 'target=' . $row->ar_user_text );
                        }
-                       $comment = $sk->formatComment( $row->ar_comment );
-                       $wgOut->addHTML( "<li>$pageLink . . $userLink (<i>$comment</i>)</li>\n" );
+                       $comment = $sk->commentBlock( $row->ar_comment );
+                       $wgOut->addHTML( "<li>$checkBox $pageLink . . $userLink $comment</li>\n" );
 
                }
                $revisions->free();
-               $wgOut->addHTML("</ul>");
+               $wgOut->addHTML("</ul>\n</form>");
                
                return true;
        }
@@ -321,8 +431,14 @@ class UndeleteForm {
                global $wgOut;
                if( !is_null( $this->mTargetObj ) ) {
                        $archive = new PageArchive( $this->mTargetObj );
-                       if( $archive->undelete() ) {
+                       if( $archive->undelete( $this->mTargetTimestamp ) ) {
                                $wgOut->addWikiText( wfMsg( "undeletedtext", $this->mTarget ) );
+
+                               if (NS_IMAGE == $this->mTargetObj->getNamespace()) {
+                                       /* refresh image metadata cache */
+                                       new Image( $this->mTargetObj->getText(), true );
+                               }
+
                                return true;
                        }
                }