Cleanup for r43315 (per aaron's comment): remove extra set of parenthesis
[lhc/web/wiklou.git] / includes / Article.php
index 806a3d0..f64e9f4 100644 (file)
@@ -441,14 +441,14 @@ class Article {
                        }
                        $revision = Revision::newFromId( $this->mLatest );
                        if( is_null( $revision ) ) {
-                               wfDebug( __METHOD__." failed to retrieve current page, rev_id {$data->page_latest}\n" );
+                               wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
                                return false;
                        }
                }
 
                // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
                // We should instead work with the Revision object when we need it...
-               $this->mContent   = $revision->revText(); // Loads if user is allowed
+               $this->mContent   = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
 
                $this->mUser      = $revision->getUser();
                $this->mUserText  = $revision->getUserText();
@@ -809,6 +809,32 @@ class Article {
                }
                # Fetch content and check for errors
                if ( !$outputDone ) {
+                       # If the article does not exist and was deleted, show the log
+                       if ($this->getID() == 0) {
+                               $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
+                               $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
+                               $count = $pager->getNumRows();
+                               if( $count > 0 ) {
+                                       $pager->mLimit = 10;
+                                       $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
+                                       $wgOut->addWikiMsg( 'deleted-notice' );
+                                       $wgOut->addHTML(
+                                               $loglist->beginLogEventsList() .
+                                               $pager->getBody() .
+                                               $loglist->endLogEventsList()
+                                       );
+                                       if($count > 10){
+                                               $wgOut->addHTML( $wgUser->getSkin()->link(
+                                                       SpecialPage::getTitleFor( 'Log' ),
+                                                       wfMsgHtml( 'deletelog-fulllog' ),
+                                                       array(),
+                                                       array(
+                                                               'type' => 'delete',
+                                                               'page' => $this->mTitle->getPrefixedText() ) ) );
+                                       }
+                                       $wgOut->addHTML( '</div>' );
+                               }
+                       }
                        $text = $this->getContent();
                        if ( $text === false ) {
                                # Failed to load, replace text with error message
@@ -854,15 +880,15 @@ class Article {
 
                         // Pages containing custom CSS or JavaScript get special treatment
                        if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
-                               $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
+                               $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
                                // Give hooks a chance to customise the output
                                if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
                                        // Wrap the whole lot in a <pre> and don't parse
                                        $m = array();
                                        preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
-                                       $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
-                                       $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
-                                       $wgOut->addHtml( "\n</pre>\n" );
+                                       $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
+                                       $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
+                                       $wgOut->addHTML( "\n</pre>\n" );
                                }
                        } else if ( $rt = Title::newFromRedirect( $text ) ) {
                                # Don't append the subtitle if this was an old revision
@@ -1049,17 +1075,16 @@ class Article {
                                $this->view();
                        }
                } else {
-                       $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
-                       $action = htmlspecialchars( $_SERVER['REQUEST_URI'] );
-                       $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
-                       $msg = str_replace( '$1',
-                               "<form method=\"post\" action=\"$action\">\n" .
-                               "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
-                               "</form>\n", $msg );
-
+                       $action = htmlspecialchars( $wgRequest->getRequestURL() );
+                       $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
+                       $form = "<form method=\"post\" action=\"$action\">\n" .
+                                       "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
+                                       "</form>\n";
+                       $top = wfMsgExt( 'confirm-purge-top', array('parse') );
+                       $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
                        $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
                        $wgOut->setRobotPolicy( 'noindex,nofollow' );
-                       $wgOut->addHTML( $msg );
+                       $wgOut->addHTML( $top . $form . $bottom );
                }
        }
 
@@ -1099,7 +1124,7 @@ class Article {
         * Best if all done inside a transaction.
         *
         * @param Database $dbw
-        * @return int     The newly created page_id key
+        * @return int     The newly created page_id key, or false if the title already existed
         * @private
         */
        function insertOn( $dbw ) {
@@ -1118,13 +1143,15 @@ class Article {
                        'page_touched'      => $dbw->timestamp(),
                        'page_latest'       => 0, # Fill this in shortly...
                        'page_len'          => 0, # Fill this in shortly...
-               ), __METHOD__ );
-               $newid = $dbw->insertId();
-
-               $this->mTitle->resetArticleId( $newid );
+               ), __METHOD__, 'IGNORE' );
 
+               $affected = $dbw->affectedRows();
+               if ( $affected ) {
+                       $newid = $dbw->insertId();
+                       $this->mTitle->resetArticleId( $newid );
+               }
                wfProfileOut( __METHOD__ );
-               return $newid;
+               return $affected ? $newid : false;
        }
 
        /**
@@ -1337,29 +1364,31 @@ class Article {
                        ( $minor ? EDIT_MINOR : 0 ) |
                        ( $forceBot ? EDIT_FORCE_BOT : 0 );
 
-               $good = $this->doEdit( $text, $summary, $flags );
-               if ( $good ) {
-                       $dbw = wfGetDB( DB_MASTER );
-                       if ($watchthis) {
-                               if (!$this->mTitle->userIsWatching()) {
-                                       $dbw->begin();
-                                       $this->doWatch();
-                                       $dbw->commit();
-                               }
-                       } else {
-                               if ( $this->mTitle->userIsWatching() ) {
-                                       $dbw->begin();
-                                       $this->doUnwatch();
-                                       $dbw->commit();
-                               }
+               $status = $this->doEdit( $text, $summary, $flags );
+               if ( !$status->isOK() ) {
+                       return false;
+               }
+
+               $dbw = wfGetDB( DB_MASTER );
+               if ($watchthis) {
+                       if (!$this->mTitle->userIsWatching()) {
+                               $dbw->begin();
+                               $this->doWatch();
+                               $dbw->commit();
+                       }
+               } else {
+                       if ( $this->mTitle->userIsWatching() ) {
+                               $dbw->begin();
+                               $this->doUnwatch();
+                               $dbw->commit();
                        }
+               }
 
-                       $extraQuery = ''; // Give extensions a chance to modify URL query on update
-                       wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
+               $extraQuery = ''; // Give extensions a chance to modify URL query on update
+               wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
 
-                       $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
-               }
-               return $good;
+               $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
+               return true;
        }
 
        /**
@@ -1389,26 +1418,48 @@ class Article {
         *          Fill in blank summaries with generated text where possible
         *
         * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
-        * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
-        * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
-        * to be thrown from the Database. These two conditions are also possible with auto-detection due
-        * to MediaWiki's performance-optimised locking strategy.
+        * If EDIT_UPDATE is specified and the article doesn't exist, the function will an 
+        * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an 
+        * edit-already-exists error will be returned. These two conditions are also possible with 
+        * auto-detection due to MediaWiki's performance-optimised locking strategy.
+        *
         * @param $baseRevId, the revision ID this edit was based off, if any
         *
-        * @return bool success
+        * @return Status object. Possible errors:
+        *     edit-hook-aborted:       The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
+        *     edit-gone-missing:       In update mode, but the article didn't exist
+        *     edit-conflict:           In update mode, the article changed unexpectedly
+        *     edit-no-change:          Warning that the text was the same as before
+        *     edit-already-exists:     In creation mode, but the article already exists
+        *
+        *  Extensions may define additional errors.
+        *
+        *  $return->value will contain an associative array with members as follows:
+        *     new:                     Boolean indicating if the function attempted to create a new article
+        *     revision:                The revision object for the inserted revision, or null
+        *
+        *  Compatibility note: this function previously returned a boolean value indicating success/failure
         */
        function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
                global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
 
+               # Low-level sanity check
+               if( $this->mTitle->getText() == '' ) {
+                       throw new MWException( 'Something is trying to edit an article with an empty title' );
+               }
+
+               wfProfileIn( __METHOD__ );
+
                if ($user == null) {
                        $user = $wgUser;
                }
+               $status = Status::newGood( array() );
 
-               wfProfileIn( __METHOD__ );
-               $good = true;
+               # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
+               $this->loadPageData(); 
 
                if ( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
-                       $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
+                       $aid = $this->mTitle->getArticleID();
                        if ( $aid ) {
                                $flags |= EDIT_UPDATE;
                        } else {
@@ -1418,11 +1469,14 @@ class Article {
 
                if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text,
                        &$summary, $flags & EDIT_MINOR,
-                       null, null, &$flags ) ) )
+                       null, null, &$flags, &$status ) ) )
                {
                        wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
                        wfProfileOut( __METHOD__ );
-                       return false;
+                       if ( $status->isOK() ) {
+                               $status->fatal( 'edit-hook-aborted');
+                       }
+                       return $status;
                }
 
                # Silently ignore EDIT_MINOR if not allowed
@@ -1446,31 +1500,28 @@ class Article {
 
                if ( $flags & EDIT_UPDATE ) {
                        # Update article, but only if changed.
+                       $status->value['new'] = false;
 
                        # Make sure the revision is either completely inserted or not inserted at all
                        if( !$wgDBtransactions ) {
                                $userAbort = ignore_user_abort( true );
                        }
 
-                       $lastRevision = 0;
                        $revisionId = 0;
 
-                       $dbw->begin();
-
                        $changed = ( strcmp( $text, $oldtext ) != 0 );
+
                        if ( $changed ) {
                                $this->mGoodAdjustment = (int)$this->isCountable( $text )
                                  - (int)$this->isCountable( $oldtext );
                                $this->mTotalAdjustment = 0;
 
-                               $lastRevision = $dbw->selectField(
-                                       'page', 'page_latest', array( 'page_id' => $this->getId() ) );
-
-                               if ( !$lastRevision ) {
+                               if ( !$this->mLatest ) {
                                        # Article gone missing
                                        wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
+                                       $status->fatal( 'edit-gone-missing' );
                                        wfProfileOut( __METHOD__ );
-                                       return false;
+                                       return $status;
                                }
 
                                $revision = new Revision( array(
@@ -1478,38 +1529,51 @@ class Article {
                                        'comment'    => $summary,
                                        'minor_edit' => $isminor,
                                        'text'       => $text,
-                                       'parent_id'  => $lastRevision,
+                                       'parent_id'  => $this->mLatest,
                                        'user'       => $user->getId(),
                                        'user_text'  => $user->getName(),
                                        ) );
 
+                               $dbw->begin();
                                $revisionId = $revision->insertOn( $dbw );
 
                                # Update page
-                               $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
+                               #
+                               # Note that we use $this->mLatest instead of fetching a value from the master DB 
+                               # during the course of this function. This makes sure that EditPage can detect 
+                               # edit conflicts reliably, either by $ok here, or by $article->getTimestamp() 
+                               # before this function is called. A previous function used a separate query, this
+                               # creates a window where concurrent edits can cause an ignored edit conflict.
+                               $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
 
                                if( !$ok ) {
                                        /* Belated edit conflict! Run away!! */
-                                       $good = false;
+                                       $status->fatal( 'edit-conflict' );
+                                       # Delete the invalid revision if the DB is not transactional
+                                       if ( !$wgDBtransactions ) {
+                                               $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
+                                       }
+                                       $revisionId = 0;
                                        $dbw->rollback();
                                } else {
                                        wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId ) );
 
                                        # Update recentchanges
                                        if( !( $flags & EDIT_SUPPRESS_RC ) ) {
-                                               $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
-                                                       $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
+                                               $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
+                                                       $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
                                                        $revisionId );
 
                                                # Mark as patrolled if the user can do so
                                                if( $GLOBALS['wgUseRCPatrol'] && $user->isAllowed( 'autopatrol' ) ) {
-                                                       RecentChange::markPatrolled( $rcid );
-                                                       PatrolLog::record( $rcid, true );
+                                                       RecentChange::markPatrolled( $rc, true );
                                                }
                                        }
                                        $user->incEditCount();
+                                       $dbw->commit();
                                }
                        } else {
+                               $status->warning( 'edit-no-change' );
                                $revision = null;
                                // Keep the same revision ID, but do some updates on it
                                $revisionId = $this->getRevIdFetched();
@@ -1521,18 +1585,20 @@ class Article {
                        if( !$wgDBtransactions ) {
                                ignore_user_abort( $userAbort );
                        }
-
-                       if ( $good ) {
-                               # Invalidate cache of this article and all pages using this article
-                               # as a template. Partly deferred.
-                               Article::onArticleEdit( $this->mTitle );
-
-                               # Update links tables, site stats, etc.
-                               $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
-                               $dbw->commit();
+                       // Now that ignore_user_abort is restored, we can respond to fatal errors
+                       if ( !$status->isOK() ) {
+                               wfProfileOut( __METHOD__ );
+                               return $status;
                        }
+
+                       # Invalidate cache of this article and all pages using this article
+                       # as a template. Partly deferred. Leave templatelinks for editUpdates().
+                       Article::onArticleEdit( $this->mTitle, 'skiptransclusions' );
+                       # Update links tables, site stats, etc.
+                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
                } else {
                        # Create new article
+                       $status->value['new'] = true;
 
                        # Set statistics members
                        # We work out if it's countable after PST to avoid counter drift
@@ -1543,9 +1609,16 @@ class Article {
                        $dbw->begin();
 
                        # Add the page record; stake our claim on this title!
-                       # This will fail with a database query exception if the article already exists
+                       # This will return false if the article already exists
                        $newid = $this->insertOn( $dbw );
 
+                       if ( $newid === false ) {
+                               $dbw->rollback();
+                               $status->fatal( 'edit-already-exists' );
+                               wfProfileOut( __METHOD__ );
+                               return $status;
+                       }
+
                        # Save the revision text...
                        $revision = new Revision( array(
                                'page'       => $newid,
@@ -1565,12 +1638,11 @@ class Article {
                        wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
 
                        if( !( $flags & EDIT_SUPPRESS_RC ) ) {
-                               $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
+                               $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
                                  '', strlen( $text ), $revisionId );
                                # Mark as patrolled if the user can
                                if( ($GLOBALS['wgUseRCPatrol'] || $GLOBALS['wgUseNPPatrol']) && $user->isAllowed( 'autopatrol' ) ) {
-                                       RecentChange::markPatrolled( $rcid );
-                                       PatrolLog::record( $rcid, true );
+                                       RecentChange::markPatrolled( $rc, true );
                                }
                        }
                        $user->incEditCount();
@@ -1583,20 +1655,22 @@ class Article {
                        Article::onArticleCreate( $this->mTitle );
 
                        wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
-                        $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
+                               $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
                }
 
-               if ( $good && !( $flags & EDIT_DEFER_UPDATES ) ) {
+               # Do updates right now unless deferral was requested
+               if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
                        wfDoUpdates();
                }
 
-               if ( $good ) {
-                       wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
-                               $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
-               }
+               // Return the new revision (or null) to the caller
+               $status->value['revision'] = $revision;
+
+               wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
+                       $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status ) );
 
                wfProfileOut( __METHOD__ );
-               return $good;
+               return $status;
        }
 
        /**
@@ -1636,8 +1710,7 @@ class Article {
                # If we haven't been given an rc_id value, we can't do anything
                $rcid = (int) $wgRequest->getVal('rcid');
                $rc = RecentChange::newFromId($rcid);
-               if (is_null($rc))
-               {
+               if ( is_null($rc) ) {
                        $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
                        return;
                }
@@ -1646,26 +1719,27 @@ class Article {
                $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
                $return = Title::makeTitle( NS_SPECIAL, $returnto );
 
+               $dbw = wfGetDB( DB_MASTER );
                $errors = $rc->doMarkPatrolled();
-               if (in_array(array('rcpatroldisabled'), $errors)) {
+
+               if ( in_array(array('rcpatroldisabled'), $errors) ) {
                        $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
                        return;
                }
                
-               if (in_array(array('hookaborted'), $errors)) {
+               if ( in_array(array('hookaborted'), $errors) ) {
                        // The hook itself has handled any output
                        return;
                }
                
-               if (in_array(array('markedaspatrollederror-noautopatrol'), $errors)) {
+               if ( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
                        $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
                        $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
                        $wgOut->returnToMain( false, $return );
                        return;
                }
 
-               if (!empty($errors))
-               {
+               if ( !empty($errors) ) {
                        $wgOut->showPermissionsErrorPage( $errors );
                        return;
                }
@@ -1857,16 +1931,18 @@ class Article {
                                $protect_description = '';
                                foreach( $limit as $action => $restrictions  ) {
                                        $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
-                                       if ($restrictions != '') {
+                                       if( $restrictions != '' ) {
                                                $protect_description .= "[$action=$restrictions] (";
                                                if( $encodedExpiry[$action] != 'infinity' ) {
-                                                       $protect_description .= wfMsgForContent( 'protect-expiring',  $wgContLang->timeanddate( $expiry[$action], false, false ) );      
+                                                       $protect_description .= wfMsgForContent( 'protect-expiring', 
+                                                               $wgContLang->timeanddate( $expiry[$action], false, false ) );    
                                                } else {
                                                        $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
                                                }
                                                $protect_description .= ') ';
                                        }
                                }
+                               $protect_description = trim($protect_description);
                                        
                                if( $protect_description && $protect )
                                        $editComment .= " ($protect_description)";
@@ -1946,24 +2022,22 @@ class Article {
         * Auto-generates a deletion reason
         * @param bool &$hasHistory Whether the page has a history
         */
-       public function generateReason(&$hasHistory)
-       {
+       public function generateReason( &$hasHistory ) {
                global $wgContLang;
-               $dbw = wfGetDB(DB_MASTER);
+               $dbw = wfGetDB( DB_MASTER );
                // Get the last revision
-               $rev = Revision::newFromTitle($this->mTitle);
-               if(is_null($rev))
+               $rev = Revision::newFromTitle( $this->mTitle );
+               if( is_null( $rev ) )
                        return false;
+
                // Get the article's contents
                $contents = $rev->getText();
                $blank = false;
                // If the page is blank, use the text from the previous revision,
                // which can only be blank if there's a move/import/protect dummy revision involved
-               if($contents == '')
-               {
+               if( $contents == '' ) {
                        $prev = $rev->getPrevious();
-                       if($prev)
-                       {
+                       if( $prev )     {
                                $contents = $prev->getText();
                                $blank = true;
                        }
@@ -1972,44 +2046,46 @@ class Article {
                // Find out if there was only one contributor
                // Only scan the last 20 revisions
                $limit = 20;
-               $res = $dbw->select('revision', 'rev_user_text', array('rev_page' => $this->getID()), __METHOD__,
-                               array('LIMIT' => $limit));
-               if($res === false)
+               $res = $dbw->select( 'revision', 'rev_user_text',
+                       array( 'rev_page' => $this->getID() ), __METHOD__,
+                       array( 'LIMIT' => $limit )
+               );
+               if( $res === false )
                        // This page has no revisions, which is very weird
                        return false;
-               if($res->numRows() > 1)
+               if( $res->numRows() > 1 )
                                $hasHistory = true;
                else
                                $hasHistory = false;
-               $row = $dbw->fetchObject($res);
+               $row = $dbw->fetchObject( $res );
                $onlyAuthor = $row->rev_user_text;
                // Try to find a second contributor
                foreach( $res as $row ) {
-                       if($row->rev_user_text != $onlyAuthor) {
+                       if( $row->rev_user_text != $onlyAuthor ) {
                                $onlyAuthor = false;
                                break;
                        }
                }
-               $dbw->freeResult($res);
+               $dbw->freeResult( $res );
 
                // Generate the summary with a '$1' placeholder
-               if($blank) {
+               if( $blank ) {
                        // The current revision is blank and the one before is also
                        // blank. It's just not our lucky day
-                       $reason = wfMsgForContent('exbeforeblank', '$1');
+                       $reason = wfMsgForContent( 'exbeforeblank', '$1' );
                } else {
-                       if($onlyAuthor)
-                               $reason = wfMsgForContent('excontentauthor', '$1', $onlyAuthor);
+                       if( $onlyAuthor )
+                               $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
                        else
-                               $reason = wfMsgForContent('excontent', '$1');
+                               $reason = wfMsgForContent( 'excontent', '$1' );
                }
 
                // Replace newlines with spaces to prevent uglyness
-               $contents = preg_replace("/[\n\r]/", ' ', $contents);
+               $contents = preg_replace( "/[\n\r]/", ' ', $contents );
                // Calculate the maximum amount of chars to get
                // Max content length = max comment length - length of the comment (excl. $1) - '...'
-               $maxLength = 255 - (strlen($reason) - 2) - 3;
-               $contents = $wgContLang->truncate($contents, $maxLength, '...');
+               $maxLength = 255 - (strlen( $reason ) - 2) - 3;
+               $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
                // Remove possible unfinished links
                $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
                // Now replace the '$1' placeholder
@@ -2121,7 +2197,7 @@ class Article {
         * @return int approximate revision count
         */
        function estimateRevisionCount() {
-               $dbr = wfGetDB();
+               $dbr = wfGetDB( DB_SLAVE );
                // For an exact count...
                //return $dbr->selectField( 'revision', 'COUNT(*)',
                //      array( 'rev_page' => $this->getId() ), __METHOD__ );
@@ -2180,8 +2256,7 @@ class Article {
         * @param $reason string Prefilled reason
         */
        function confirmDelete( $reason ) {
-               global $wgOut, $wgUser, $wgContLang;
-               $align = $wgContLang->isRtl() ? 'left' : 'right';
+               global $wgOut, $wgUser;
 
                wfDebug( "Article::confirmDelete\n" );
 
@@ -2190,46 +2265,55 @@ class Article {
                $wgOut->addWikiMsg( 'confirmdeletetext' );
 
                if( $wgUser->isAllowed( 'suppressrevision' ) ) {
-                       $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\"><td></td><td>";
-                       $suppress .= Xml::checkLabel( wfMsg( 'revdelete-suppress' ), 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '2' ) );
-                       $suppress .= "</td></tr>";
+                       $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
+                                       <td></td>
+                                       <td class='mw-input'>" .
+                                               Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
+                                                       'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
+                                       "</td>
+                               </tr>";
                } else {
                        $suppress = '';
                }
+               $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
 
-               $form = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
+               $form = Xml::openElement( 'form', array( 'method' => 'post', 
+                       'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
                        Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
                        Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
-                       Xml::openElement( 'table' ) .
+                       Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
                        "<tr id=\"wpDeleteReasonListRow\">
-                               <td align='$align'>" .
+                               <td class='mw-label'>" .
                                        Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
                                "</td>
-                               <td>" .
+                               <td class='mw-input'>" .
                                        Xml::listDropDown( 'wpDeleteReasonList',
                                                wfMsgForContent( 'deletereason-dropdown' ),
                                                wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
                                "</td>
                        </tr>
                        <tr id=\"wpDeleteReasonRow\">
-                               <td align='$align'>" .
+                               <td class='mw-label'>" .
                                        Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
                                "</td>
-                               <td>" .
-                                       Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ) ) .
+                               <td class='mw-input'>" .
+                                       Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255', 
+                                               'tabindex' => '2', 'id' => 'wpReason' ) ) .
                                "</td>
                        </tr>
                        <tr>
                                <td></td>
-                               <td>" .
-                                       Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '3' ) ) .
+                               <td class='mw-input'>" .
+                                       Xml::checkLabel( wfMsg( 'watchthis' ),
+                                               'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
                                "</td>
                        </tr>
                        $suppress
                        <tr>
                                <td></td>
-                               <td>" .
-                                       Xml::submitButton( wfMsg( 'deletepage' ), array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '4' ) ) .
+                               <td class='mw-submit'>" .
+                                       Xml::submitButton( wfMsg( 'deletepage' ),
+                                               array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
                                "</td>
                        </tr>" .
                        Xml::closeElement( 'table' ) .
@@ -2252,7 +2336,7 @@ class Article {
         * Show relevant lines from the deletion log
         */
        function showLogExtract( $out ) {
-               $out->addHtml( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
+               $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
                LogEventsList::showLogExtract( $out, 'delete', $this->mTitle->getPrefixedText() );
        }
 
@@ -2264,12 +2348,12 @@ class Article {
                global $wgOut, $wgUser;
                wfDebug( __METHOD__."\n" );
 
-               $id = $this->getId();
+               $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
 
                $error = '';
 
-               if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error))) {
-                       if ( $this->doDeleteArticle( $reason, $suppress ) ) {
+               if ( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
+                       if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
                                $deleted = $this->mTitle->getPrefixedText();
 
                                $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
@@ -2281,7 +2365,7 @@ class Article {
                                $wgOut->returnToMain( false );
                                wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
                        } else {
-                               if ($error = '')
+                               if ($error == '')
                                        $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
                                else
                                        $wgOut->showFatalError( $error );
@@ -2294,7 +2378,7 @@ class Article {
         * Deletes the article with database consistency, writes logs, purges caches
         * Returns success
         */
-       function doDeleteArticle( $reason, $suppress = false ) {
+       function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
                global $wgUseSquid, $wgDeferredUpdateList;
                global $wgUseTrackbacks;
 
@@ -2303,7 +2387,7 @@ class Article {
                $dbw = wfGetDB( DB_MASTER );
                $ns = $this->mTitle->getNamespace();
                $t = $this->mTitle->getDBkey();
-               $id = $this->mTitle->getArticleID();
+               $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
 
                if ( $t == '' || $id == 0 ) {
                        return false;
@@ -2360,15 +2444,6 @@ class Article {
                # Delete restrictions for it
                $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
 
-               # Fix category table counts
-               $cats = array();
-               $res = $dbw->select( 'categorylinks', 'cl_to',
-                       array( 'cl_from' => $id ), __METHOD__ );
-               foreach( $res as $row ) {
-                       $cats []= $row->cl_to;
-               }
-               $this->updateCategoryCounts( array(), $cats );
-
                # Now that it's safely backed up, delete it
                $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
                $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
@@ -2396,16 +2471,27 @@ class Article {
 
                # If using cleanup triggers, we can skip some manual deletes
                if ( !$dbw->cleanupTriggers() ) {
-
                        # Clean up recentchanges entries...
                        $dbw->delete( 'recentchanges',
-                               array( 'rc_namespace' => $ns, 'rc_title' => $t, 'rc_type != '.RC_LOG ),
+                               array( 'rc_type != '.RC_LOG, 
+                                       'rc_namespace' => $this->mTitle->getNamespace(),
+                                       'rc_title' => $this->mTitle->getDBKey() ),
+                               __METHOD__ );
+                       $dbw->delete( 'recentchanges',
+                               array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
                                __METHOD__ );
                }
-               $dbw->commit();
 
                # Clear caches
                Article::onArticleDelete( $this->mTitle );
+               
+               # Fix category table counts
+               $cats = array();
+               $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
+               foreach( $res as $row ) {
+                       $cats []= $row->cl_to;
+               }
+               $this->updateCategoryCounts( array(), $cats );
 
                # Clear the cached article id so the interface doesn't act like we exist
                $this->mTitle->resetArticleID( 0 );
@@ -2417,6 +2503,8 @@ class Article {
 
                # Make sure logging got through
                $log->addEntry( 'delete', $this->mTitle, $reason, array() );
+               
+               $dbw->commit();
 
                return true;
        }
@@ -2448,7 +2536,7 @@ class Article {
 
                # Check permissions
                $errors = array_merge( $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser ),
-                                               $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
+                       $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser ) );
                if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
                        $errors[] = array( 'sessionfailure' );
 
@@ -2552,12 +2640,18 @@ class Article {
                # Save
                $flags = EDIT_UPDATE;
 
-               if ($wgUser->isAllowed('minoredit'))
+               if( $wgUser->isAllowed('minoredit') )
                        $flags |= EDIT_MINOR;
 
                if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
                        $flags |= EDIT_FORCE_BOT;
-               $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
+               # Actually store the edit
+               $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
+               if ( !empty( $status->value['revision'] ) ) {
+                       $revId = $status->value['revision']->getId();
+               } else {
+                       $revId = false;
+               }
 
                wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
 
@@ -2565,6 +2659,7 @@ class Article {
                        'summary' => $summary,
                        'current' => $current,
                        'target' => $target,
+                       'newid' => $revId
                );
                return array();
        }
@@ -2592,7 +2687,7 @@ class Article {
                        $wgOut->rateLimited();
                        return;
                }
-               if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ){
+               if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
                        $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
                        $errArray = $result[0];
                        $errMsg = array_shift( $errArray );
@@ -2600,7 +2695,8 @@ class Article {
                        if( isset( $details['current'] ) ){
                                $current = $details['current'];
                                if( $current->getComment() != '' ) {
-                                       $wgOut->addWikiMsgArray( 'editcomment', array( $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
+                                       $wgOut->addWikiMsgArray( 'editcomment', array( 
+                                               $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
                                }
                        }
                        return;
@@ -2627,17 +2723,18 @@ class Article {
 
                $current = $details['current'];
                $target = $details['target'];
+               $newId = $details['newid'];
                $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
                        . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
                $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
                        . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
-               $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
+               $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
                $wgOut->returnToMain( false, $this->mTitle );
 
-               if( !$wgRequest->getBool( 'hidediff', false ) ) {
-                       $de = new DifferenceEngine( $this->mTitle, $current->getId(), 'next', false, true );
+               if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
+                       $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
                        $de->showDiff( '', '' );
                }
        }
@@ -2690,6 +2787,7 @@ class Article {
        /**
         * Do standard deferred updates after page edit.
         * Update links tables, site stats, search index and message cache.
+        * Purges pages that include this page if the text was changed here.
         * Every 100th edit, prune the recent changes table.
         *
         * @private
@@ -2722,8 +2820,11 @@ class Article {
                }
 
                # Update the links tables
-               $u = new LinksUpdate( $this->mTitle, $editInfo->output );
+               $u = new LinksUpdate( $this->mTitle, $editInfo->output, false );
+               $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
                $u->doUpdate();
+               
+               wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
 
                if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
                        if ( 0 == mt_rand( 0, 99 ) ) {
@@ -2866,9 +2967,10 @@ class Article {
                        ? 'revision-info-current'
                        : 'revision-info';
 
-               $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
+               $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks, $revision->getID() ) . "</div>\n" .
 
-                    "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
+                    "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, 
+                               $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
                $wgOut->setSubtitle( $r );
        }
 
@@ -2894,13 +2996,13 @@ class Article {
                static $called = false;
                if( $called ) {
                        wfDebug( "Article::tryFileCache(): called twice!?\n" );
-                       return;
+                       return false;
                }
                $called = true;
-               if($this->isFileCacheable()) {
+               if( $this->isFileCacheable() ) {
                        $touched = $this->mTouched;
                        $cache = new HTMLFileCache( $this->mTitle );
-                       if($cache->isFileCacheGood( $touched )) {
+                       if( $cache->isFileCacheGood( $touched ) ) {
                                wfDebug( "Article::tryFileCache(): about to load file\n" );
                                $cache->loadFromFileCache();
                                return true;
@@ -2911,6 +3013,7 @@ class Article {
                } else {
                        wfDebug( "Article::tryFileCache(): not cacheable\n" );
                }
+               return false;
        }
 
        /**
@@ -2919,40 +3022,31 @@ class Article {
         */
        function isFileCacheable() {
                global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
-               $action    = $wgRequest->getVal( 'action'    );
-               $oldid     = $wgRequest->getVal( 'oldid'     );
-               $diff      = $wgRequest->getVal( 'diff'      );
-               $redirect  = $wgRequest->getVal( 'redirect'  );
-               $printable = $wgRequest->getVal( 'printable' );
-               $page      = $wgRequest->getVal( 'page' );
-               $useskin   = $wgRequest->getVal( 'useskin' );
-
-               //check for non-standard user language; this covers uselang,
-               //and extensions for auto-detecting user language.
-               $ulang     = $wgLang->getCode();
-               $clang     = $wgContLang->getCode();
+               // Get all query values
+               $queryVals = $wgRequest->getValues();
+               foreach( $queryVals as $query => $val ) {
+                       if( $query == 'title' || ($query == 'action' && $val == 'view') ) {
+                               // Normal page view in query form
+                       } else {
+                               return false;
+                       }
+               }
+               // Check for non-standard user language; this covers uselang,
+               // and extensions for auto-detecting user language.
+               $ulang = $wgLang->getCode();
+               $clang = $wgContLang->getCode();
 
                $cacheable = $wgUseFileCache
                        && (!$wgShowIPinHeader)
-                       && ($this->getID() != 0)
+                       && ($this->getID() > 0)
                        && ($wgUser->isAnon())
                        && (!$wgUser->getNewtalk())
-                       && ($this->mTitle->getNamespace() != NS_SPECIAL )
-                       && (!isset($useskin))
-                       && (empty( $action ) || $action == 'view')
-                       && (!isset($oldid))
-                       && (!isset($diff))
-                       && (!isset($redirect))
-                       && (!isset($printable))
-                       && !isset($page)
                        && (!$this->mRedirectedFrom)
                        && ($ulang === $clang);
-
-               if ( $cacheable ) {
-                       //extension may have reason to disable file caching on some pages.
+               // Extension may have reason to disable file caching on some pages.
+               if( $cacheable ) {
                        $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
                }
-
                return $cacheable;
        }
 
@@ -3001,7 +3095,6 @@ class Article {
                wfProfileIn( __METHOD__ );
 
                $dbw = wfGetDB( DB_MASTER );
-               $dbw->begin();
                $revision = new Revision( array(
                        'page'       => $this->getId(),
                        'text'       => $text,
@@ -3010,7 +3103,6 @@ class Article {
                        ) );
                $revision->insertOn( $dbw );
                $this->updateRevisionOn( $dbw, $revision );
-               $dbw->commit();
 
                wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false) );
 
@@ -3092,8 +3184,8 @@ class Article {
         * @param $title_obj a title object
         */
 
-       static function onArticleCreate($title) {
-               # The talk page isn't in the regular link tables, so we need to update manually:
+       public static function onArticleCreate( $title ) {
+               # Update existence markers on article/talk tabs...
                if ( $title->isTalkPage() ) {
                        $other = $title->getSubjectPage();
                } else {
@@ -3107,10 +3199,9 @@ class Article {
                $title->deleteTitleProtection();
        }
 
-       static function onArticleDelete( $title ) {
+       public static function onArticleDelete( $title ) {
                global $wgUseFileCache, $wgMessageCache;
-
-               // Update existence markers on article/talk tabs...
+               # Update existence markers on article/talk tabs...
                if( $title->isTalkPage() ) {
                        $other = $title->getSubjectPage();
                } else {
@@ -3147,11 +3238,12 @@ class Article {
        /**
         * Purge caches on page update etc
         */
-       static function onArticleEdit( $title ) {
+       public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
                global $wgDeferredUpdateList, $wgUseFileCache;
 
                // Invalidate caches of articles which include this page
-               $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
+               if( $transclusions !== 'skiptransclusions' )
+                       $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
 
                // Invalidate the caches of all pages which redirect here
                $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
@@ -3159,7 +3251,7 @@ class Article {
                # Purge squid for this page only
                $title->purgeSquid();
 
-               # Clear file cache
+               # Clear file cache for this page only
                if ( $wgUseFileCache ) {
                        $cm = new HTMLFileCache( $title );
                        @unlink( $cm->fileCacheName() );
@@ -3198,18 +3290,18 @@ class Article {
                $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
 
                if( !$this->mTitle->exists() ) {
-                       $wgOut->addHtml( '<div class="noarticletext">' );
+                       $wgOut->addHTML( '<div class="noarticletext">' );
                        if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
                                // This doesn't quite make sense; the user is asking for
                                // information about the _page_, not the message... -- RC
-                               $wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
+                               $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
                        } else {
                                $msg = $wgUser->isLoggedIn()
                                        ? 'noarticletext'
                                        : 'noarticletextanon';
-                               $wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
+                               $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
                        }
-                       $wgOut->addHtml( '</div>' );
+                       $wgOut->addHTML( '</div>' );
                } else {
                        $dbr = wfGetDB( DB_SLAVE );
                        $wl_clause = array(
@@ -3280,7 +3372,7 @@ class Article {
         *
         * @return array Array of Title objects
         */
-       function getUsedTemplates() {
+       public function getUsedTemplates() {
                $result = array();
                $id = $this->mTitle->getArticleID();
                if( $id == 0 ) {
@@ -3307,7 +3399,7 @@ class Article {
         *
         * @return array Array of Title objects
         */
-       function getHiddenCategories() {
+       public function getHiddenCategories() {
                $result = array();
                $id = $this->mTitle->getArticleID();
                if( $id == 0 ) {
@@ -3340,8 +3432,9 @@ class Article {
                # Decide what kind of autosummary is needed.
 
                # Redirect autosummaries
+               $ot = Title::newFromRedirect( $oldtext );
                $rt = Title::newFromRedirect( $newtext );
-               if( is_object( $rt ) ) {
+               if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
                        return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
                }
 
@@ -3351,14 +3444,14 @@ class Article {
                        global $wgContLang;
                        $truncatedtext = $wgContLang->truncate(
                                str_replace("\n", ' ', $newtext),
-                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
+                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
                                '...' );
                        return wfMsgForContent( 'autosumm-new', $truncatedtext );
                }
 
                # Blanking autosummaries
                if( $oldtext != '' && $newtext == '' ) {
-                       return wfMsgForContent('autosumm-blank');
+                       return wfMsgForContent( 'autosumm-blank' );
                } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
                        # Removing more than 90% of the article
                        global $wgContLang;
@@ -3384,7 +3477,7 @@ class Article {
         * @param bool    $cache
         */
        public function outputWikiText( $text, $cache = true ) {
-               global $wgParser, $wgUser, $wgOut, $wgEnableParserCache;
+               global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
 
                $popts = $wgOut->parserOptions();
                $popts->setTidy(true);
@@ -3397,8 +3490,14 @@ class Article {
                        $parserCache = ParserCache::singleton();
                        $parserCache->save( $parserOutput, $this, $wgUser );
                }
+               // Make sure file cache is not used on uncacheable content.
+               // Output that has magic words in it can still use the parser cache
+               // (if enabled), though it will generally expire sooner.
+               if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
+                       $wgUseFileCache = false;
+               }
 
-               if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
+               if ( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
                        // templatelinks table may have become out of sync,
                        // especially if using variable-based transclusions.
                        // For paranoia, check if things have changed and if
@@ -3439,13 +3538,7 @@ class Article {
                        if ( count( $templates_diff ) > 0 ) {
                                # Whee, link updates time.
                                $u = new LinksUpdate( $this->mTitle, $parserOutput );
-
-                               $dbw = wfGetDb( DB_MASTER );
-                               $dbw->begin();
-
                                $u->doUpdate();
-
-                               $dbw->commit();
                        }
                }