* Follow-up r84610: don't assume a Parser object is attached
[lhc/web/wiklou.git] / includes / Article.php
index 48ba854..560a261 100644 (file)
@@ -21,7 +21,6 @@ class Article {
        var $mContent;                    // !<
        var $mContentLoaded = false;      // !<
        var $mCounter = -1;               // !< Not loaded
-       var $mCurID = -1;                 // !< Not loaded
        var $mDataLoaded = false;         // !<
        var $mForUpdate = false;          // !<
        var $mGoodAdjustment = 0;         // !<
@@ -34,7 +33,7 @@ class Article {
        var $mRedirectTarget = null;      // !< Title object if set
        var $mRedirectUrl = false;        // !<
        var $mRevIdFetched = 0;           // !<
-       var $mRevision;                   // !< Revision object if set
+       var $mRevision = null;            // !< Revision object if set
        var $mTimestamp = '';             // !<
        var $mTitle;                      // !< Title object
        var $mTotalAdjustment = 0;        // !<
@@ -58,7 +57,7 @@ class Article {
 
        /**
         * Constructor from an page id
-        * @param $id The article ID to load
+        * @param $id Int article ID to load
         */
        public static function newFromID( $id ) {
                $t = Title::newFromID( $id );
@@ -119,14 +118,14 @@ class Article {
         */
        public function insertRedirect() {
                // recurse through to only get the final target
-               $retval = Title::newFromRedirectRecurse( $this->getContent() );
+               $retval = Title::newFromRedirectRecurse( $this->getRawText() );
                if ( !$retval ) {
                        return null;
                }
                $this->insertRedirectEntry( $retval );
                return $retval;
        }
-       
+
        /**
         * Insert or update the redirect table entry for this page to indicate
         * it redirects to $rt .
@@ -160,13 +159,13 @@ class Article {
         *
         * @param $text string article content containing redirect info
         * @return mixed false, Title of in-wiki target, or string with URL
-        * @deprecated
+        * @deprecated since 1.17
         */
        public function followRedirectText( $text ) {
                // recurse through to only get the final target
                return $this->getRedirectURL( Title::newFromRedirectRecurse( $text ) );
        }
-       
+
        /**
         * Get the Title object or URL to use for a redirect. We use Title
         * objects for same-wiki, non-special redirects and URLs for everything
@@ -224,7 +223,7 @@ class Article {
                $this->mDataLoaded    = false;
                $this->mContentLoaded = false;
 
-               $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
+               $this->mUser = $this->mCounter = -1; # Not loaded
                $this->mRedirectedFrom = null; # Title object if set
                $this->mRedirectTarget = null; # Title object if set
                $this->mUserText =
@@ -250,7 +249,7 @@ class Article {
         * @return Return the text of this revision
         */
        public function getContent() {
-               global $wgUser, $wgContLang, $wgMessageCache;
+               global $wgUser;
 
                wfProfileIn( __METHOD__ );
 
@@ -258,12 +257,10 @@ class Article {
                        # If this is a MediaWiki:x message, then load the messages
                        # and return the message value for x.
                        if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
-                               # If this is a system message, get the default text.
-                               list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
-                               $text = wfMsgGetKey( $message, false, $lang, false );
-
-                               if ( wfEmptyMsg( $message, $text ) )
+                               $text = $this->mTitle->getDefaultMessageText();
+                               if ( $text === false ) {
                                        $text = '';
+                               }
                        } else {
                                $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
                        }
@@ -321,9 +318,13 @@ class Article {
         * @return mixed string on success, false on failure
         */
        public function getUndoText( Revision $undo, Revision $undoafter = null ) {
+               $currentRev = Revision::newFromTitle( $this->mTitle );
+               if ( !$currentRev ) {
+                       return false; // no page
+               }
                $undo_text = $undo->getText();
                $undoafter_text = $undoafter->getText();
-               $cur_text = $this->getContent();
+               $cur_text = $currentRev->getText();
 
                if ( $cur_text == $undo_text ) {
                        # No use doing a merge if it's just a straight revert.
@@ -397,9 +398,7 @@ class Article {
 
                wfProfileIn( __METHOD__ );
 
-               $oldid = $this->getOldID();
-               $this->mOldId = $oldid;
-               $this->fetchContent( $oldid );
+               $this->fetchContent( $this->getOldID() );
 
                wfProfileOut( __METHOD__ );
        }
@@ -466,8 +465,8 @@ class Article {
         */
        public function loadPageData( $data = 'fromdb' ) {
                if ( $data === 'fromdb' ) {
-                       $dbr = wfGetDB( DB_MASTER );
-                       $data = $this->pageDataFromId( $dbr, $this->getId() );
+                       $dbr = wfGetDB( DB_SLAVE );
+                       $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
                }
 
                $lc = LinkCache::singleton();
@@ -504,8 +503,6 @@ class Article {
                        return $this->mContent;
                }
 
-               $dbr = wfGetDB( DB_MASTER );
-
                # Pre-fill content with error message so that if something
                # fails we'll have something telling us what we intended.
                $t = $this->mTitle->getPrefixedText();
@@ -519,28 +516,29 @@ class Article {
                                return false;
                        }
 
-                       $data = $this->pageDataFromId( $dbr, $revision->getPage() );
-
-                       if ( !$data ) {
-                               wfDebug( __METHOD__ . " failed to get page data linked to revision id $oldid\n" );
-                               return false;
-                       }
-
-                       $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
-                       $this->loadPageData( $data );
-               } else {
-                       if ( !$this->mDataLoaded ) {
-                               $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
+                       if ( !$this->mDataLoaded || $this->getID() != $revision->getPage() ) {
+                               $data = $this->pageDataFromId( wfGetDB( DB_SLAVE ), $revision->getPage() );
 
                                if ( !$data ) {
-                                       wfDebug( __METHOD__ . " failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
+                                       wfDebug( __METHOD__ . " failed to get page data linked to revision id $oldid\n" );
                                        return false;
                                }
 
+                               $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
                                $this->loadPageData( $data );
                        }
+               } else {
+                       if ( !$this->mDataLoaded ) {
+                               $this->loadPageData();
+                       }
+
+                       if ( $this->mLatest === false ) {
+                               wfDebug( __METHOD__ . " failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
+                               return false;
+                       }
+
                        $revision = Revision::newFromId( $this->mLatest );
-                       if (  $revision === null ) {
+                       if ( $revision === null ) {
                                wfDebug( __METHOD__ . " failed to retrieve current page, rev_id {$this->mLatest}\n" );
                                return false;
                        }
@@ -550,10 +548,9 @@ class Article {
                // We should instead work with the Revision object when we need it...
                $this->mContent   = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
 
-               $this->mUser      = $revision->getUser();
-               $this->mUserText  = $revision->getUserText();
-               $this->mComment   = $revision->getComment();
-               $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
+               if ( $revision->getId() == $this->mLatest ) {
+                       $this->setLastEdit( $revision );
+               }
 
                $this->mRevIdFetched = $revision->getId();
                $this->mContentLoaded = true;
@@ -665,18 +662,14 @@ class Article {
         */
        public function isRedirect( $text = false ) {
                if ( $text === false ) {
-                       if ( $this->mDataLoaded ) {
-                               return $this->mIsRedirect;
+                       if ( !$this->mDataLoaded ) {
+                               $this->loadPageData();
                        }
 
-                       // Apparently loadPageData was never called
-                       $this->loadContent();
-                       $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
+                       return (bool)$this->mIsRedirect;
                } else {
-                       $titleObj = Title::newFromRedirect( $text );
+                       return Title::newFromRedirect( $text ) !== null;
                }
-
-               return $titleObj !== null;
        }
 
        /**
@@ -690,7 +683,7 @@ class Article {
                        return true;
                }
 
-               return $this->exists() && isset( $this->mRevision ) && $this->mRevision->isCurrent();
+               return $this->exists() && $this->mRevision && $this->mRevision->isCurrent();
        }
 
        /**
@@ -708,21 +701,27 @@ class Article {
                        return;
                }
 
-               $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
-               if ( !is_null( $this->mLastRevision ) ) {
-                       $this->mUser      = $this->mLastRevision->getUser();
-                       $this->mUserText  = $this->mLastRevision->getUserText();
-                       $this->mTimestamp = $this->mLastRevision->getTimestamp();
-                       $this->mComment   = $this->mLastRevision->getComment();
-                       $this->mMinorEdit = $this->mLastRevision->isMinor();
-                       $this->mRevIdFetched = $this->mLastRevision->getId();
+               $revision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
+               if ( !is_null( $revision ) ) {
+                       $this->setLastEdit( $revision );
                }
        }
 
        /**
-        * @return string GMT timestamp of last article revision
-        **/
+        * Set the latest revision
+        */
+       protected function setLastEdit( Revision $revision ) {
+               $this->mLastRevision = $revision;
+               $this->mUser = $revision->getUser();
+               $this->mUserText = $revision->getUserText();
+               $this->mTimestamp = $revision->getTimestamp();
+               $this->mComment = $revision->getComment();
+               $this->mMinorEdit = $revision->isMinor();
+       }
 
+       /**
+        * @return string GMT timestamp of last article revision
+        */
        public function getTimestamp() {
                // Check if the field has been filled by ParserCache::get()
                if ( !$this->mTimestamp ) {
@@ -772,8 +771,11 @@ class Article {
         * @return int revision ID of last article revision
         */
        public function getRevIdFetched() {
-               $this->loadLastEdit();
-               return $this->mRevIdFetched;
+               if ( $this->mRevIdFetched ) {
+                       return $this->mRevIdFetched;
+               } else {
+                       return $this->getLatest();
+               }
        }
 
        /**
@@ -832,9 +834,35 @@ class Article {
 
                # Get variables from query string
                $oldid = $this->getOldID();
+
+               # getOldID may want us to redirect somewhere else
+               if ( $this->mRedirectUrl ) {
+                       $wgOut->redirect( $this->mRedirectUrl );
+                       wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
+                       wfProfileOut( __METHOD__ );
+
+                       return;
+               }
+
+               $wgOut->setArticleFlag( true );
+               # Set page title (may be overridden by DISPLAYTITLE)
+               $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
+
+               # If we got diff in the query, we want to see a diff page instead of the article.
+               if ( $wgRequest->getCheck( 'diff' ) ) {
+                       wfDebug( __METHOD__ . ": showing diff page\n" );
+                       $this->showDiffPage();
+                       wfProfileOut( __METHOD__ );
+
+                       return;
+               }
+
+               # Allow frames by default
+               $wgOut->allowClickjacking();
+
                $parserCache = ParserCache::singleton();
 
-               $parserOptions = clone $this->getParserOptions();
+               $parserOptions = $this->getParserOptions();
                # Render printable version, use printable version cache
                if ( $wgOut->isPrintable() ) {
                        $parserOptions->setIsPrintable( true );
@@ -849,7 +877,7 @@ class Article {
                                $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
                        }
 
-                       # Is is client cached?
+                       # Is it client cached?
                        if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
                                wfDebug( __METHOD__ . ": done 304\n" );
                                wfProfileOut( __METHOD__ );
@@ -867,28 +895,6 @@ class Article {
                        }
                }
 
-               # getOldID may want us to redirect somewhere else
-               if ( $this->mRedirectUrl ) {
-                       $wgOut->redirect( $this->mRedirectUrl );
-                       wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
-                       wfProfileOut( __METHOD__ );
-
-                       return;
-               }
-
-               $wgOut->setArticleFlag( true );
-               # Set page title (may be overridden by DISPLAYTITLE)
-               $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
-
-               # If we got diff in the query, we want to see a diff page instead of the article.
-               if ( $wgRequest->getCheck( 'diff' ) ) {
-                       wfDebug( __METHOD__ . ": showing diff page\n" );
-                       $this->showDiffPage();
-                       wfProfileOut( __METHOD__ );
-
-                       return;
-               }
-
                if ( !$wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
                        $parserOptions->setEditSection( false );
                }
@@ -965,10 +971,8 @@ class Article {
                                                                wfDebug( __METHOD__ . ": showing parser cache for current rev permalink\n" );
                                                                $wgOut->addParserOutput( $this->mParserOutput );
                                                                $wgOut->setRevisionId( $this->mLatest );
-                                                               $this->showViewFooter();
-                                                               $this->viewUpdates();
-                                                               wfProfileOut( __METHOD__ );
-                                                               return;
+                                                               $outputDone = true;
+                                                               break;
                                                        }
                                                }
                                        }
@@ -982,28 +986,29 @@ class Article {
                                                wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
                                                $this->showCssOrJsPage();
                                                $outputDone = true;
-                                       } else if ( $rt = Title::newFromRedirectArray( $text ) ) {
-                                               wfDebug( __METHOD__ . ": showing redirect=no page\n" );
-                                               # Viewing a redirect page (e.g. with parameter redirect=no)
-                                               # Don't append the subtitle if this was an old revision
-                                               $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
-                                               # Parse just to get categories, displaytitle, etc.
-                                               $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
-                                               $wgOut->addParserOutputNoText( $this->mParserOutput );
-                                               $outputDone = true;
+                                       } else {
+                                               $rt = Title::newFromRedirectArray( $text );
+                                               if ( $rt ) {
+                                                       wfDebug( __METHOD__ . ": showing redirect=no page\n" );
+                                                       # Viewing a redirect page (e.g. with parameter redirect=no)
+                                                       # Don't append the subtitle if this was an old revision
+                                                       $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
+                                                       # Parse just to get categories, displaytitle, etc.
+                                                       $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
+                                                       $wgOut->addParserOutputNoText( $this->mParserOutput );
+                                                       $outputDone = true;
+                                               }
                                        }
                                        break;
                                case 4:
                                        # Run the parse, protected by a pool counter
                                        wfDebug( __METHOD__ . ": doing uncached parse\n" );
+
                                        $key = $parserCache->getKey( $this, $parserOptions );
-                                       $poolCounter = PoolCounter::factory( 'Article::view', $key );
-                                       $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
-                                       $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
+                                       $poolArticleView = new PoolWorkArticleView( $this, $key, $useParserCache, $parserOptions );
 
-                                       if ( !$status->isOK() ) {
+                                       if ( !$poolArticleView->execute() ) {
                                                # Connection or timeout error
-                                               $this->showPoolError( $status );
                                                wfProfileOut( __METHOD__ );
                                                return;
                                        } else {
@@ -1029,10 +1034,11 @@ class Article {
                # tents of 'pagetitle-view-mainpage' instead of the default (if
                # that's not empty).
                # This message always exists because it is in the i18n files
-               if ( $this->mTitle->equals( Title::newMainPage() )
-                       && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
-               {
-                       $wgOut->setHTMLTitle( $m );
+               if ( $this->mTitle->equals( Title::newMainPage() ) ) {
+                       $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
+                       if ( !$msg->isDisabled() ) {
+                               $wgOut->setHTMLTitle( $msg->title( $this->mTitle )->text() );
+                       }
                }
 
                # Now that we've filled $this->mParserOutput, we know whether
@@ -1065,9 +1071,7 @@ class Article {
                $this->mRevIdFetched = $de->mNewid;
                $de->showDiffPage( $diffOnly );
 
-               // Needed to get the page's current revision
-               $this->loadPageData();
-               if ( $diff == 0 || $diff == $this->mLatest ) {
+               if ( $diff == 0 || $diff == $this->getLatest() ) {
                        # Run view updates for current revision only
                        $this->viewUpdates();
                }
@@ -1080,7 +1084,7 @@ class Article {
         * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
         * page views.
         */
-       public function showCssOrJsPage() {
+       protected function showCssOrJsPage() {
                global $wgOut;
 
                $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache'>\n$1\n</div>", 'clearyourcache' );
@@ -1111,8 +1115,7 @@ class Article {
                if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
                        # Don't index user and user talk pages for blocked users (bug 11443)
                        if ( !$this->mTitle->isSubpage() ) {
-                               $block = new Block();
-                               if ( $block->load( $this->mTitle->getText() ) ) {
+                               if ( Block::newFromTarget( null, $this->mTitle->getText() ) instanceof Block ) {
                                        return array(
                                                'index'  => 'noindex',
                                                'follow' => 'nofollow'
@@ -1176,7 +1179,7 @@ class Article {
         * merging of several policies using array_merge().
         * @param $policy Mixed, returns empty array on null/false/'', transparent
         *            to already-converted arrays, converts String.
-        * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
+        * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
         */
        public static function formatRobotPolicy( $policy ) {
                if ( is_array( $policy ) ) {
@@ -1211,13 +1214,12 @@ class Article {
                global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
 
                $rdfrom = $wgRequest->getVal( 'rdfrom' );
-               $sk = $wgUser->getSkin();
 
                if ( isset( $this->mRedirectedFrom ) ) {
                        // This is an internally redirected page view.
                        // We'll need a backlink to the source page for navigation.
                        if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
-                               $redir = $sk->link(
+                               $redir = $wgUser->getSkin()->link(
                                        $this->mRedirectedFrom,
                                        null,
                                        array(),
@@ -1245,7 +1247,7 @@ class Article {
                        // This is an externally redirected view, from some other wiki.
                        // If it was reported from a trusted site, supply a backlink.
                        if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
-                               $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
+                               $redir = $wgUser->getSkin()->makeExternalLink( $rdfrom, $rdfrom );
                                $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
                                $wgOut->setSubtitle( $s );
 
@@ -1264,8 +1266,7 @@ class Article {
                global $wgOut;
 
                if ( $this->mTitle->isTalkPage() ) {
-                       $msg = wfMsgNoTrans( 'talkpageheader' );
-                       if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
+                       if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
                                $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
                        }
                }
@@ -1290,6 +1291,9 @@ class Article {
                if ( $wgUseTrackbacks ) {
                        $this->addTrackbacks();
                }
+
+               wfRunHooks( 'ArticleViewFooter', array( $this ) );
+
        }
 
        /**
@@ -1307,7 +1311,8 @@ class Article {
                }
 
                $sk = $wgUser->getSkin();
-               $token = $wgUser->editToken();
+               $token = $wgUser->editToken( $rcid );
+               $wgOut->preventClickjacking();
 
                $wgOut->addHTML(
                        "<div class='patrollink'>" .
@@ -1382,7 +1387,7 @@ class Article {
                                wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
                } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
                        // Use the default message text
-                       $text = $this->getContent();
+                       $text = $this->mTitle->getDefaultMessageText();
                } else {
                        $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
                        $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
@@ -1469,19 +1474,20 @@ class Article {
                global $wgOut;
 
                $oldid = $this->getOldID();
-               $useParserCache = $this->useParserCache( $oldid );
-               $parserOptions = clone $this->getParserOptions();
+               $parserOptions = $this->getParserOptions();
 
                # Render printable version, use printable version cache
                $parserOptions->setIsPrintable( $wgOut->isPrintable() );
 
                # Don't show section-edit links on old revisions... this way lies madness.
-               if ( !$this->isCurrent() || $wgOut->isPrintable() ) {
+               if ( !$this->isCurrent() || $wgOut->isPrintable() || !$this->mTitle->quickUserCan( 'edit' ) ) {
                        $parserOptions->setEditSection( false );
                }
-               
+
                $useParserCache = $this->useParserCache( $oldid );
                $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
+
+               return true;
        }
 
        /**
@@ -1493,16 +1499,15 @@ class Article {
         * @return boolean
         */
        public function tryDirtyCache() {
-
                global $wgOut;
                $parserCache = ParserCache::singleton();
                $options = $this->getParserOptions();
-               
+
                if ( $wgOut->isPrintable() ) {
                        $options->setIsPrintable( true );
-                       $parserOptions->setEditSection( false );
+                       $options->setEditSection( false );
                }
-               
+
                $output = $parserCache->getDirty( $this, $options );
 
                if ( $output ) {
@@ -1522,27 +1527,10 @@ class Article {
                }
        }
 
-       /**
-        * Show an error page for an error from the pool counter.
-        * @param $status Status
-        */
-       public function showPoolError( $status ) {
-               global $wgOut;
-
-               $wgOut->clearHTML(); // for release() errors
-               $wgOut->enableClientCache( false );
-               $wgOut->setRobotPolicy( 'noindex,nofollow' );
-               $wgOut->addWikiText(
-                       '<div class="errorbox">' .
-                       $status->getWikiText( false, 'view-pool-error' ) .
-                       '</div>'
-               );
-       }
-
        /**
         * View redirect
         *
-        * @param $target Title object or Array of destination(s) to redirect
+        * @param $target Title|Array of destination(s) to redirect
         * @param $appendSubtitle Boolean [optional]
         * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
         * @return string containing HMTL with redirect link
@@ -1573,19 +1561,19 @@ class Article {
                $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
                $alt = $wgContLang->isRTL() ? '←' : '→';
                // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
-               // FIXME: where this happens?
                foreach ( $target as $rt ) {
                        $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
                        if ( $forceKnown ) {
-                               $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText() ) );
+                               $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
                        } else {
-                               $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
+                               $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
                        }
                }
 
-               $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';              
-               return Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
-                       '<span class="redirectText">' . $link . '</span>';
+               $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
+               return '<div class="redirectMsg">' .
+                       Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
+                       '<span class="redirectText">' . $link . '</span></div>';
        }
 
        /**
@@ -1604,8 +1592,10 @@ class Article {
                        return;
                }
 
+               $wgOut->preventClickjacking();
+
                $tbtext = "";
-               while ( $o = $dbr->fetchObject( $tbs ) ) {
+               foreach ( $tbs as $o ) {
                        $rmvtxt = "";
 
                        if ( $wgUser->isAllowed( 'trackback' ) ) {
@@ -1687,7 +1677,7 @@ class Article {
                        $form  = Html::openElement( 'form', $formParams );
                        $form .= Xml::submitButton( wfMsg( 'confirm_purge_button' ) );
                        $form .= Html::closeElement( 'form' );
-                       
+
                        $wgOut->addHTML( $form );
                        $wgOut->addWikiMsg( 'confirm-purge-bottom' );
 
@@ -1704,6 +1694,7 @@ class Article {
 
                // Invalidate the cache
                $this->mTitle->invalidateCache();
+               $this->clear();
 
                if ( $wgUseSquid ) {
                        // Commit the transaction before the purge is sent
@@ -1716,15 +1707,13 @@ class Article {
                }
 
                if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
-                       global $wgMessageCache;
-
                        if ( $this->getID() == 0 ) {
                                $text = false;
                        } else {
                                $text = $this->getRawText();
                        }
 
-                       $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
+                       MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
                }
        }
 
@@ -1761,7 +1750,7 @@ class Article {
 
                if ( $affected ) {
                        $newid = $dbw->insertId();
-                       $this->mTitle->resetArticleId( $newid );
+                       $this->mTitle->resetArticleID( $newid );
                }
                wfProfileOut( __METHOD__ );
 
@@ -1771,9 +1760,9 @@ class Article {
        /**
         * Update the page record to point to a newly saved revision.
         *
-        * @param $dbw Database object
+        * @param $dbw DatabaseBase: object
         * @param $revision Revision: For ID number, and text used to set
-                           length and redirect status fields
+                                               length and redirect status fields
         * @param $lastRevision Integer: if given, will not overwrite the page field
         *                      when different from the currently set value.
         *                      Giving 0 indicates the new page flag should be set
@@ -1826,7 +1815,7 @@ class Article {
         * Add row to the redirect table if this is a redirect, remove otherwise.
         *
         * @param $dbw Database
-        * @param $redirectTitle a title object pointing to the redirect target,
+        * @param $redirectTitle Title object pointing to the redirect target,
         *                       or NULL if this is not a redirect
         * @param $lastRevIsRedirect If given, will optimize adding and
         *                           removing rows in redirect table.
@@ -1839,25 +1828,25 @@ class Article {
                // Delete if changing from redirect to non-redirect
                $isRedirect = !is_null( $redirectTitle );
 
-               if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
-                       wfProfileIn( __METHOD__ );
-                       if ( $isRedirect ) {
-                               $this->insertRedirectEntry( $redirectTitle );
-                       } else {
-                               // This is not a redirect, remove row from redirect table
-                               $where = array( 'rd_from' => $this->getId() );
-                               $dbw->delete( 'redirect', $where, __METHOD__ );
-                       }
+               if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
+                       return true;
+               }
 
-                       if ( $this->getTitle()->getNamespace() == NS_FILE ) {
-                               RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
-                       }
-                       wfProfileOut( __METHOD__ );
+               wfProfileIn( __METHOD__ );
+               if ( $isRedirect ) {
+                       $this->insertRedirectEntry( $redirectTitle );
+               } else {
+                       // This is not a redirect, remove row from redirect table
+                       $where = array( 'rd_from' => $this->getId() );
+                       $dbw->delete( 'redirect', $where, __METHOD__ );
+               }
 
-                       return ( $dbw->affectedRows() != 0 );
+               if ( $this->getTitle()->getNamespace() == NS_FILE ) {
+                       RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
                }
+               wfProfileOut( __METHOD__ );
 
-               return true;
+               return ( $dbw->affectedRows() != 0 );
        }
 
        /**
@@ -1921,6 +1910,7 @@ class Article {
                        if ( !$rev ) {
                                wfDebug( "Article::replaceSection asked for bogus section (page: " .
                                        $this->getId() . "; section: $section; edittime: $edittime)\n" );
+                               wfProfileOut( __METHOD__ );
                                return null;
                        }
 
@@ -1944,37 +1934,6 @@ class Article {
                return $text;
        }
 
-       /**
-        * @deprecated use Article::doEdit()
-        */
-       function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
-               wfDeprecated( __METHOD__ );
-               $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
-                       ( $isminor ? EDIT_MINOR : 0 ) |
-                       ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
-                       ( $bot ? EDIT_FORCE_BOT : 0 );
-
-               $this->doEdit( $text, $summary, $flags, false, null, $watchthis, $comment, '', true );
-       }
-
-       /**
-        * @deprecated use Article::doEdit()
-        */
-       function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
-               wfDeprecated( __METHOD__ );
-               $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
-                       ( $minor ? EDIT_MINOR : 0 ) |
-                       ( $forceBot ? EDIT_FORCE_BOT : 0 );
-
-               $status = $this->doEdit( $text, $summary, $flags, false, null, $watchthis, false, $sectionanchor, true );
-
-               if ( !$status->isOK() ) {
-                       return false;
-               }
-
-               return true;
-       }
-
        /**
         * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
         * @param $flags Int
@@ -2025,12 +1984,7 @@ class Article {
         * auto-detection due to MediaWiki's performance-optimised locking strategy.
         *
         * @param $baseRevId the revision ID this edit was based off, if any
-        * @param $user Optional user object, $wgUser will be used if not passed
-        * @param $watchthis Watch the page if true, unwatch the page if false, do nothing if null
-        * @param $comment Boolean: whether the edit is a new section
-        * @param $sectionanchor The section anchor for the page; used for redirecting the user back to the page
-        *              after the edit is successfully committed
-        * @param $redirect If true, redirect the user back to the page after the edit is successfully committed
+        * @param $user User (optional), $wgUser will be used if not passed
         *
         * @return Status object. Possible errors:
         *     edit-hook-aborted:       The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
@@ -2047,8 +2001,7 @@ class Article {
         *
         *  Compatibility note: this function previously returned a boolean value indicating success/failure
         */
-       public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null , $watchthis = null,
-                       $comment = false, $sectionanchor = '', $redirect = false) {
+       public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
                global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
 
                # Low-level sanity check
@@ -2066,21 +2019,16 @@ class Article {
 
                $flags = $this->checkFlags( $flags );
 
-               # If this is a comment, add the summary as headline
-               if ( $comment && $summary != "" ) {
-                       $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
-               }
-
                if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
-                       $flags & EDIT_MINOR, &$watchthis, null, &$flags, &$status) ) )
+                       $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
                {
                        wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
-                       wfProfileOut( __METHOD__ );
 
                        if ( $status->isOK() ) {
                                $status->fatal( 'edit-hook-aborted' );
                        }
 
+                       wfProfileOut( __METHOD__ );
                        return $status;
                }
 
@@ -2096,7 +2044,7 @@ class Article {
                        $summary = $this->getAutosummary( $oldtext, $text, $flags );
                }
 
-               $editInfo = $this->prepareTextForEdit( $text );
+               $editInfo = $this->prepareTextForEdit( $text, null, $user );
                $text = $editInfo->pst;
                $newsize = strlen( $text );
 
@@ -2113,8 +2061,6 @@ class Article {
                                $userAbort = ignore_user_abort( true );
                        }
 
-                       $revisionId = 0;
-
                        $changed = ( strcmp( $text, $oldtext ) != 0 );
 
                        if ( $changed ) {
@@ -2139,6 +2085,7 @@ class Article {
                                        'parent_id'  => $this->mLatest,
                                        'user'       => $user->getId(),
                                        'user_text'  => $user->getName(),
+                                       'timestamp'  => $now
                                ) );
 
                                $dbw->begin();
@@ -2170,7 +2117,8 @@ class Article {
                                        # Update recentchanges
                                        if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
                                                # Mark as patrolled if the user can do so
-                                               $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
+                                               $patrolled = $wgUseRCPatrol && !count(
+                                                       $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
                                                # Add RC row to the DB
                                                $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
                                                        $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
@@ -2189,7 +2137,7 @@ class Article {
                                $status->warning( 'edit-no-change' );
                                $revision = null;
                                // Keep the same revision ID, but do some updates on it
-                               $revisionId = $this->getRevIdFetched();
+                               $revisionId = $this->getLatest();
                                // Update page_touched, this is usually implicit in the page update
                                // Other cache updates are done in onArticleEdit()
                                $this->mTitle->invalidateCache();
@@ -2209,7 +2157,7 @@ class Article {
                        # as a template. Partly deferred.
                        Article::onArticleEdit( $this->mTitle );
                        # Update links tables, site stats, etc.
-                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
+                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed, $user );
                } else {
                        # Create new article
                        $status->value['new'] = true;
@@ -2242,10 +2190,13 @@ class Article {
                                'text'       => $text,
                                'user'       => $user->getId(),
                                'user_text'  => $user->getName(),
-                               ) );
+                               'timestamp'  => $now
+                       ) );
                        $revisionId = $revision->insertOn( $dbw );
 
                        $this->mTitle->resetArticleID( $newid );
+                       # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached (FIXME?)
+                       LinkCache::singleton()->addGoodLinkObj( $newid, $this->mTitle, strlen( $text ), (bool)Title::newFromRedirect( $text ), $revisionId );
 
                        # Update the page record with revision data
                        $this->updateRevisionOn( $dbw, $revision, 0 );
@@ -2257,7 +2208,8 @@ class Article {
                                global $wgUseRCPatrol, $wgUseNPPatrol;
 
                                # Mark as patrolled if the user can do so
-                               $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
+                               $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
+                                       $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
                                # Add RC row to the DB
                                $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
                                        '', strlen( $text ), $revisionId, $patrolled );
@@ -2271,13 +2223,13 @@ class Article {
                        $dbw->commit();
 
                        # Update links, etc.
-                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
+                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
 
                        # Clear caches
                        Article::onArticleCreate( $this->mTitle );
 
                        wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
-                               $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision ) );
+                               $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
                }
 
                # Do updates right now unless deferral was requested
@@ -2289,50 +2241,12 @@ class Article {
                $status->value['revision'] = $revision;
 
                wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
-                       $flags & EDIT_MINOR, &$watchthis, null, &$flags, $revision, &$status, $baseRevId,
-                       &$redirect) );
-
-               # Watch or unwatch the page
-               if ( $watchthis === true ) {
-                       if ( !$this->mTitle->userIsWatching() ) {
-                               $dbw->begin();
-                               $this->doWatch();
-                               $dbw->commit();
-                       }
-               } elseif ( $watchthis === false ) {
-                       if ( $this->mTitle->userIsWatching() ) {
-                               $dbw->begin();
-                               $this->doUnwatch();
-                               $dbw->commit();
-                       }
-               }
-
-               # Give extensions a chance to modify URL query on update
-               $extraQuery = '';
-
-               wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
-
-               if ( $redirect ) {
-                       if ( $sectionanchor || $extraQuery ) {
-                               $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
-                       } else {
-                               $this->doRedirect( $this->isRedirect( $text ) );
-                       }
-               }
+                       $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
 
                wfProfileOut( __METHOD__ );
-
                return $status;
        }
 
-       /**
-        * @deprecated wrapper for doRedirect
-        */
-       public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
-               wfDeprecated( __METHOD__ );
-               $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
-       }
-
        /**
         * Output a redirect back to the article.
         * This is typically used after an edit.
@@ -2366,7 +2280,7 @@ class Article {
                # If we haven't been given an rc_id value, we can't do anything
                $rcid = (int) $wgRequest->getVal( 'rcid' );
 
-               if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
+               if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $rcid ) ) {
                        $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
                        return;
                }
@@ -2442,6 +2356,9 @@ class Article {
 
        /**
         * Add this page to $wgUser's watchlist
+        *
+        * This is safe to be called multiple times
+        *
         * @return bool true on successful watch operation
         */
        public function doWatch() {
@@ -2535,7 +2452,7 @@ class Article {
                $id = $this->mTitle->getArticleID();
 
                if ( $id <= 0 ) {
-                       wfDebug( "updateRestrictions failed: $id <= 0\n" );
+                       wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
                        return false;
                }
 
@@ -2625,9 +2542,9 @@ class Article {
                                $protect_description = '';
                                foreach ( $limit as $action => $restrictions ) {
                                        if ( !isset( $expiry[$action] ) )
-                                               $expiry[$action] = 'infinite';
+                                               $expiry[$action] = $dbw->getInfinity();
 
-                                       $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
+                                       $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
                                        if ( $restrictions != '' ) {
                                                $protect_description .= "[$action=$restrictions] (";
                                                if ( $encodedExpiry[$action] != 'infinity' ) {
@@ -2788,8 +2705,6 @@ class Article {
                        $onlyAuthor = false;
                }
 
-               $dbw->freeResult( $res );
-
                // Generate the summary with a '$1' placeholder
                if ( $blank ) {
                        // The current revision is blank and the one before is also
@@ -2927,7 +2842,10 @@ class Article {
                        //FIXME: lego
                        $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
                                wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
-                               wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
+                               wfMsgHtml( 'word-separator' ) . $skin->link( $this->mTitle,
+                                       wfMsgHtml( 'history' ),
+                                       array( 'rel' => 'archives' ),
+                                       array( 'action' => 'history' ) ) .
                                '</strong>'
                        );
 
@@ -3012,7 +2930,7 @@ class Article {
 
                $authors = array( $row->rev_user_text );
 
-               while ( $row = $db->fetchObject( $res ) ) {
+               foreach ( $res as $row ) {
                        $authors[] = $row->rev_user_text;
                }
 
@@ -3038,7 +2956,7 @@ class Article {
                wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
 
                if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
-                       $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
+                       $suppress = "<tr id=\"wpDeleteSuppressRow\">
                                        <td></td>
                                        <td class='mw-input'><strong>" .
                                                Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
@@ -3103,7 +3021,7 @@ class Article {
                        </tr>" .
                        Xml::closeElement( 'table' ) .
                        Xml::closeElement( 'fieldset' ) .
-                       Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
+                       Html::hidden( 'wpEditToken', $wgUser->editToken() ) .
                        Xml::closeElement( 'form' );
 
                        if ( $wgUser->isAllowed( 'editinterface' ) ) {
@@ -3131,7 +3049,7 @@ class Article {
        public function doDelete( $reason, $suppress = false ) {
                global $wgOut, $wgUser;
 
-               $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
+               $id = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
 
                $error = '';
                if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
@@ -3190,9 +3108,8 @@ class Article {
                wfDebug( __METHOD__ . "\n" );
 
                $dbw = wfGetDB( DB_MASTER );
-               $ns = $this->mTitle->getNamespace();
                $t = $this->mTitle->getDBkey();
-               $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
+               $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
 
                if ( $t === '' || $id == 0 ) {
                        return false;
@@ -3468,7 +3385,7 @@ class Article {
                        $flags |= EDIT_MINOR;
                }
 
-               if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) ) {
+               if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
                        $flags |= EDIT_FORCE_BOT;
                }
 
@@ -3589,9 +3506,8 @@ class Article {
 
                # Don't update page view counters on views from bot users (bug 14044)
                if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
-                       Article::incViewCount( $this->getID() );
-                       $u = new SiteStatsUpdate( 1, 0, 0 );
-                       array_push( $wgDeferredUpdateList, $u );
+                       $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
+                       $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
                }
 
                # Update newtalk / watchlist notification status
@@ -3602,7 +3518,7 @@ class Article {
         * Prepare text which is about to be saved.
         * Returns a stdclass with source, pst and output members
         */
-       public function prepareTextForEdit( $text, $revid = null ) {
+       public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
                if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
                        // Already prepared
                        return $this->mPreparedEdit;
@@ -3610,13 +3526,20 @@ class Article {
 
                global $wgParser;
 
+               if( $user === null ) {
+                       global $wgUser;
+                       $user = $wgUser;
+               }
+               $popts = ParserOptions::newFromUser( $user );
+               wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
+
                $edit = (object)array();
                $edit->revid = $revid;
                $edit->newText = $text;
-               $edit->pst = $this->preSaveTransform( $text );
-               $options = $this->getParserOptions();
-               $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
-               $edit->oldText = $this->getContent();
+               $edit->pst = $this->preSaveTransform( $text, $user, $popts );
+               $edit->popts = $this->getParserOptions();
+               $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
+               $edit->oldText = $this->getRawText();
 
                $this->mPreparedEdit = $edit;
 
@@ -3630,15 +3553,16 @@ class Article {
         * Every 100th edit, prune the recent changes table.
         *
         * @private
-        * @param $text New text of the article
-        * @param $summary Edit summary
-        * @param $minoredit Minor edit
-        * @param $timestamp_of_pagechange Timestamp associated with the page change
-        * @param $newid rev_id value of the new revision
-        * @param $changed Whether or not the content actually changed
+        * @param $text String: New text of the article
+        * @param $summary String: Edit summary
+        * @param $minoredit Boolean: Minor edit
+        * @param $timestamp_of_pagechange String timestamp associated with the page change
+        * @param $newid Integer: rev_id value of the new revision
+        * @param $changed Boolean: Whether or not the content actually changed
+        * @param $user User object: User doing the edit
         */
-       public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
-               global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
+       public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User $user = null ) {
+               global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
 
                wfProfileIn( __METHOD__ );
 
@@ -3646,7 +3570,7 @@ class Article {
                # Be careful not to double-PST: $text is usually already PST-ed once
                if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
                        wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
-                       $editInfo = $this->prepareTextForEdit( $text, $newid );
+                       $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
                } else {
                        wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
                        $editInfo = $this->mPreparedEdit;
@@ -3654,9 +3578,8 @@ class Article {
 
                # Save it to the parser cache
                if ( $wgEnableParserCache ) {
-                       $popts = $this->getParserOptions();
                        $parserCache = ParserCache::singleton();
-                       $parserCache->save( $editInfo->output, $this, $popts );
+                       $parserCache->save( $editInfo->output, $this, $editInfo->popts );
                }
 
                # Update the links tables
@@ -3717,7 +3640,7 @@ class Article {
                }
 
                if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
-                       $wgMessageCache->replace( $shortTitle, $text );
+                       MessageCache::singleton()->replace( $shortTitle, $text );
                }
 
                wfProfileOut( __METHOD__ );
@@ -3861,8 +3784,7 @@ class Article {
                # Show user links if allowed to see them. If hidden, then show them only if requested...
                $userlinks = $sk->revUserTools( $revision, !$unhide );
 
-               $m = wfMsg( 'revision-info-current' );
-               $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
+               $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
                        ? 'revision-info-current'
                        : 'revision-info';
 
@@ -3889,13 +3811,26 @@ class Article {
         * so we can do things like signatures and links-in-context.
         *
         * @param $text String article contents
+        * @param $user User object: user doing the edit, $wgUser will be used if
+        *              null is given
+        * @param $popts ParserOptions object: parser options, default options for
+        *               the user loaded if null given
         * @return string article contents with altered wikitext markup (signatures
         *      converted, {{subst:}}, templates, etc.)
         */
-       public function preSaveTransform( $text ) {
-               global $wgParser, $wgUser;
+       public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
+               global $wgParser;
+
+               if ( $user === null ) {
+                       global $wgUser;
+                       $user = $wgUser;
+               }
 
-               return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
+               if ( $popts === null ) {
+                       $popts = ParserOptions::newFromUser( $user );
+               }
+
+               return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
        }
 
        /* Caching functions */
@@ -3941,7 +3876,7 @@ class Article {
                $cacheable = false;
 
                if ( HTMLFileCache::useFileCache() ) {
-                       $cacheable = $this->getID() && !$this->mRedirectedFrom;
+                       $cacheable = $this->getID() && !$this->mRedirectedFrom && !$this->mTitle->isRedirect();
                        // Extension may have reason to disable file caching on some pages.
                        if ( $cacheable ) {
                                $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
@@ -4016,73 +3951,6 @@ class Article {
        }
 
        /**
-        * Used to increment the view counter
-        *
-        * @param $id Integer: article id
-        */
-       public static function incViewCount( $id ) {
-               $id = intval( $id );
-
-               global $wgHitcounterUpdateFreq;
-
-               $dbw = wfGetDB( DB_MASTER );
-               $pageTable = $dbw->tableName( 'page' );
-               $hitcounterTable = $dbw->tableName( 'hitcounter' );
-               $acchitsTable = $dbw->tableName( 'acchits' );
-               $dbType = $dbw->getType();
-
-               if ( $wgHitcounterUpdateFreq <= 1 || $dbType == 'sqlite' ) {
-                       $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
-
-                       return;
-               }
-
-               # Not important enough to warrant an error page in case of failure
-               $oldignore = $dbw->ignoreErrors( true );
-
-               $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
-
-               $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
-               if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
-                       # Most of the time (or on SQL errors), skip row count check
-                       $dbw->ignoreErrors( $oldignore );
-
-                       return;
-               }
-
-               $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
-               $row = $dbw->fetchObject( $res );
-               $rown = intval( $row->n );
-
-               if ( $rown >= $wgHitcounterUpdateFreq ) {
-                       wfProfileIn( 'Article::incViewCount-collect' );
-                       $old_user_abort = ignore_user_abort( true );
-
-                       $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
-                       $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
-                       $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
-                               "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
-                               'GROUP BY hc_id', __METHOD__ );
-                       $dbw->delete( 'hitcounter', '*', __METHOD__ );
-                       $dbw->unlockTables( __METHOD__ );
-
-                       if ( $dbType == 'mysql' ) {
-                               $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
-                                       'WHERE page_id = hc_id', __METHOD__ );
-                       } else {
-                               $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
-                                       "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
-                       }
-                       $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
-
-                       ignore_user_abort( $old_user_abort );
-                       wfProfileOut( 'Article::incViewCount-collect' );
-               }
-
-               $dbw->ignoreErrors( $oldignore );
-       }
-
-       /**#@+
         * The onArticle*() functions are supposed to be a kind of hooks
         * which should be called whenever any of the specified actions
         * are done.
@@ -4091,7 +3959,7 @@ class Article {
         *
         * This is called on page move and undelete, as well as edit
         *
-        * @param $title a title object
+        * @param $title Title object
         */
        public static function onArticleCreate( $title ) {
                # Update existence markers on article/talk tabs...
@@ -4113,8 +3981,6 @@ class Article {
         * Clears caches when article is deleted
         */
        public static function onArticleDelete( $title ) {
-               global $wgMessageCache;
-
                # Update existence markers on article/talk tabs...
                if ( $title->isTalkPage() ) {
                        $other = $title->getSubjectPage();
@@ -4133,7 +3999,7 @@ class Article {
 
                # Messages
                if ( $title->getNamespace() == NS_MEDIAWIKI ) {
-                       $wgMessageCache->replace( $title->getDBkey(), false );
+                       MessageCache::singleton()->replace( $title->getDBkey(), false );
                }
 
                # Images
@@ -4208,7 +4074,7 @@ class Article {
                        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( $this->mTitle->getDefaultMessageText() ) );
                        } else {
                                $msg = $wgUser->isLoggedIn()
                                        ? 'noarticletext'
@@ -4311,8 +4177,6 @@ class Article {
                        }
                }
 
-               $dbr->freeResult( $res );
-
                return $result;
        }
 
@@ -4343,8 +4207,6 @@ class Article {
                        }
                }
 
-               $dbr->freeResult( $res );
-
                return $result;
        }
 
@@ -4352,12 +4214,12 @@ class Article {
        * Return an applicable autosummary if one exists for the given edit.
        * @param $oldtext String: the previous text of the page.
        * @param $newtext String: The submitted text of the page.
-       * @param $flags Bitmask: a bitmask of flags submitted for the edit.
+       * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
        * @return string An appropriate autosummary, or an empty string.
        */
        public static function getAutosummary( $oldtext, $newtext, $flags ) {
                global $wgContLang;
-               
+
                # Decide what kind of autosummary is needed.
 
                # Redirect autosummaries
@@ -4471,7 +4333,9 @@ class Article {
                        $this->mParserOptions->enableLimitReport();
                }
 
-               return $this->mParserOptions;
+               // Clone to allow modifications of the return value without affecting
+               // the cache
+               return clone $this->mParserOptions;
        }
 
        /**
@@ -4479,7 +4343,6 @@ class Article {
         *
         * @param $parserOutput mixed ParserOptions object, or boolean false
         **/
-
        protected function doCascadeProtectionUpdates( $parserOutput ) {
                if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
                        return;
@@ -4517,7 +4380,6 @@ class Article {
                }
 
                # Get the diff
-               # Note that we simulate array_diff_key in PHP <5.0.x
                $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
 
                if ( count( $templates_diff ) > 0 ) {
@@ -4595,7 +4457,10 @@ class Article {
         * and so on. Doesn't consider most of the stuff that Article::view is forced to
         * consider, so it's not appropriate to use there.
         *
+        * @since 1.16 (r52326) for LiquidThreads
+        *
         * @param $oldid mixed integer Revision ID or null
+        * @return ParserOutput or false if the given revsion ID is not found
         */
        public function getParserOutput( $oldid = null ) {
                global $wgEnableParserCache, $wgUser;
@@ -4612,31 +4477,74 @@ class Article {
                        wfIncrStats( 'pcache_miss_stub' );
                }
 
-               $parserOutput = false;
                if ( $useParserCache ) {
                        $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
+                       if ( $parserOutput !== false ) {
+                               return $parserOutput;
+                       }
                }
 
-               if ( $parserOutput === false ) {
-                       // Cache miss; parse and output it.
+               // Cache miss; parse and output it.
+               if ( $oldid === null ) {
+                       $text = $this->getRawText();
+               } else {
                        $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
+                       if ( $rev === null ) {
+                               return false;
+                       }
+                       $text = $rev->getText();
+               }
 
-                       return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
-               } else {
-                       return $parserOutput;
+               return $this->getOutputFromWikitext( $text, $useParserCache );
+       }
+
+}
+
+class PoolWorkArticleView extends PoolCounterWork {
+       private $mArticle;
+
+       function __construct( $article, $key, $useParserCache, $parserOptions ) {
+               parent::__construct( 'ArticleView', $key );
+               $this->mArticle = $article;
+               $this->cacheable = $useParserCache;
+               $this->parserOptions = $parserOptions;
+       }
+
+       function doWork() {
+               return $this->mArticle->doViewParse();
+       }
+
+       function getCachedWork() {
+               global $wgOut;
+
+               $parserCache = ParserCache::singleton();
+               $this->mArticle->mParserOutput = $parserCache->get( $this->mArticle, $this->parserOptions );
+
+               if ( $this->mArticle->mParserOutput !== false ) {
+                       wfDebug( __METHOD__ . ": showing contents parsed by someone else\n" );
+                       $wgOut->addParserOutput( $this->mArticle->mParserOutput );
+                       # Ensure that UI elements requiring revision ID have
+                       # the correct version information.
+                       $wgOut->setRevisionId( $this->mArticle->getLatest() );
+                       return true;
                }
+               return false;
        }
 
-       // Deprecated methods
-       /**
-        * Get the database which should be used for reads
-        *
-        * @return Database
-        * @deprecated - just call wfGetDB( DB_MASTER ) instead
-        */
-       function getDB() {
-               wfDeprecated( __METHOD__ );
-               return wfGetDB( DB_MASTER );
+       function fallback() {
+               return $this->mArticle->tryDirtyCache();
        }
 
+       function error( $status ) {
+               global $wgOut;
+
+               $wgOut->clearHTML(); // for release() errors
+               $wgOut->enableClientCache( false );
+               $wgOut->setRobotPolicy( 'noindex,nofollow' );
+
+               $errortext = $status->getWikiText( false, 'view-pool-error' );
+               $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
+
+               return false;
+       }
 }