Followup r78924: keep track of exception/warning comments separately, to prevent...
[lhc/web/wiklou.git] / includes / Article.php
index 9dc8074..d3673a3 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;         // !<
@@ -41,7 +40,7 @@ class Article {
        var $mTouched = '19700101000000'; // !<
        var $mUser = -1;                  // !< Not loaded
        var $mUserText = '';              // !< username from Revision if set
-       var $mParserOptions;              // !< ParserOptions object
+       var $mParserOptions;              // !< ParserOptions object for $wgUser articles
        var $mParserOutput;               // !< ParserCache object if set
        /**@}}*/
 
@@ -51,13 +50,14 @@ class Article {
         * @param $oldId Integer revision ID, null to fetch from request, zero for current
         */
        public function __construct( Title $title, $oldId = null ) {
+               // FIXME: does the reference play any role here?
                $this->mTitle =& $title;
                $this->mOldId = $oldId;
        }
 
        /**
-        * Constructor from an article article
-        * @param $id The article ID to load
+        * Constructor from an page id
+        * @param $id Int article ID to load
         */
        public static function newFromID( $id ) {
                $t = Title::newFromID( $id );
@@ -83,24 +83,27 @@ class Article {
         * @return mixed Title object, or null if this page is not a redirect
         */
        public function getRedirectTarget() {
-               if ( !$this->mTitle || !$this->mTitle->isRedirect() ) {
+               if ( !$this->mTitle->isRedirect() ) {
                        return null;
                }
 
-               if ( !is_null( $this->mRedirectTarget ) ) {
+               if ( $this->mRedirectTarget !== null ) {
                        return $this->mRedirectTarget;
                }
 
                # Query the redirect table
                $dbr = wfGetDB( DB_SLAVE );
                $row = $dbr->selectRow( 'redirect',
-                       array( 'rd_namespace', 'rd_title' ),
+                       array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
                        array( 'rd_from' => $this->getID() ),
                        __METHOD__
                );
 
-               if ( $row ) {
-                       return $this->mRedirectTarget = Title::makeTitle( $row->rd_namespace, $row->rd_title );
+               // rd_fragment and rd_interwiki were added later, populate them if empty
+               if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
+                       return $this->mRedirectTarget = Title::makeTitle(
+                               $row->rd_namespace, $row->rd_title,
+                               $row->rd_fragment, $row->rd_interwiki );
                }
 
                # This page doesn't have an entry in the redirect table
@@ -111,37 +114,44 @@ class Article {
         * Insert an entry for this page into the redirect table.
         *
         * Don't call this function directly unless you know what you're doing.
-        * @return Title object
+        * @return Title object or null if not a redirect
         */
        public function insertRedirect() {
-               $retval = Title::newFromRedirect( $this->getContent() );
-
+               // recurse through to only get the final target
+               $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 .
+        * @param $rt Title redirect target
+        */
+       public function insertRedirectEntry( $rt ) {
                $dbw = wfGetDB( DB_MASTER );
                $dbw->replace( 'redirect', array( 'rd_from' ),
                        array(
                                'rd_from' => $this->getID(),
-                               'rd_namespace' => $retval->getNamespace(),
-                               'rd_title' => $retval->getDBkey()
+                               'rd_namespace' => $rt->getNamespace(),
+                               'rd_title' => $rt->getDBkey(),
+                               'rd_fragment' => $rt->getFragment(),
+                               'rd_interwiki' => $rt->getInterwiki(),
                        ),
                        __METHOD__
                );
-
-               return $retval;
        }
 
        /**
-        * Get the Title object this page redirects to
+        * Get the Title object or URL this page redirects to
         *
         * @return mixed false, Title of in-wiki target, or string with URL
         */
        public function followRedirect() {
-               $text = $this->getContent();
-
-               return $this->followRedirectText( $text );
+               return $this->getRedirectURL( $this->getRedirectTarget() );
        }
 
        /**
@@ -149,11 +159,21 @@ class Article {
         *
         * @param $text string article content containing redirect info
         * @return mixed false, Title of in-wiki target, or string with URL
+        * @deprecated @since 1.17
         */
        public function followRedirectText( $text ) {
-               $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
-               # process if title object is valid and not special:userlogout
+               // 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
+        * else.
+        * @param $rt Title Redirect target
+        * @return mixed false, Title object of local target, or string with URL
+        */
+       public function getRedirectURL( $rt ) {
                if ( $rt ) {
                        if ( $rt->getInterwiki() != '' ) {
                                if ( $rt->isLocal() ) {
@@ -187,8 +207,8 @@ class Article {
        }
 
        /**
-        * get the title object of the article
-        * @return Title object of current title
+        * Get the title object of the article
+        * @return Title object of this page
         */
        public function getTitle() {
                return $this->mTitle;
@@ -196,13 +216,14 @@ class Article {
 
        /**
         * Clear the object
+        * FIXME: shouldn't this be public?
         * @private
         */
        public function clear() {
                $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 =
@@ -222,10 +243,13 @@ class Article {
         * If you need to fetch redirectable content easily, try
         * the shortcut in Article::followRedirect()
         *
+        * This function has side effects! Do not use this function if you
+        * only want the real revision text if any.
+        *
         * @return Return the text of this revision
         */
        public function getContent() {
-               global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
+               global $wgUser, $wgContLang, $wgMessageCache;
 
                wfProfileIn( __METHOD__ );
 
@@ -235,7 +259,6 @@ class Article {
                        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() ) );
-                               $wgMessageCache->loadAllMessages( $lang );
                                $text = wfMsgGetKey( $message, false, $lang, false );
 
                                if ( wfEmptyMsg( $message, $text ) )
@@ -285,7 +308,6 @@ class Article {
         */
        public function getSection( $text, $section ) {
                global $wgParser;
-
                return $wgParser->getSection( $text, $section );
        }
 
@@ -298,9 +320,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.
@@ -374,12 +400,7 @@ class Article {
 
                wfProfileIn( __METHOD__ );
 
-               # Query variables :P
-               $oldid = $this->getOldID();
-               # Pre-fill content with error message so that if something
-               # fails we'll have something telling us what we intended.
-               $this->mOldId = $oldid;
-               $this->fetchContent( $oldid );
+               $this->fetchContent( $this->getOldID() );
 
                wfProfileOut( __METHOD__ );
        }
@@ -407,16 +428,11 @@ class Article {
 
                wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
 
-               $row = $dbr->selectRow(
-                       'page',
-                       $fields,
-                       $conditions,
-                       __METHOD__
-               );
+               $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ );
 
                wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
 
-               return $row ;
+               return $row;
        }
 
        /**
@@ -451,8 +467,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();
@@ -470,9 +486,7 @@ class Article {
                        $this->mIsRedirect  = intval( $data->page_is_redirect );
                        $this->mLatest      = intval( $data->page_latest );
                } else {
-                       if ( is_object( $this->mTitle ) ) {
-                               $lc->addBadLinkObj( $this->mTitle );
-                       }
+                       $lc->addBadLinkObj( $this->mTitle );
                        $this->mTitle->mArticleID = 0;
                }
 
@@ -491,8 +505,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();
@@ -501,33 +513,34 @@ class Article {
 
                if ( $oldid ) {
                        $revision = Revision::newFromId( $oldid );
-                       if ( is_null( $revision ) ) {
+                       if ( $revision === null ) {
                                wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
                                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 ( is_null( $revision ) ) {
+                       if ( $revision === null ) {
                                wfDebug( __METHOD__ . " failed to retrieve current page, rev_id {$this->mLatest}\n" );
                                return false;
                        }
@@ -537,16 +550,15 @@ 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;
                $this->mRevision =& $revision;
 
-               wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
+               wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
 
                return $this->mContent;
        }
@@ -561,17 +573,6 @@ class Article {
                return wfSetVar( $this->mForUpdate, $x );
        }
 
-       /**
-        * 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 );
-       }
-
        /**
         * Get options for all SELECT statements
         *
@@ -595,11 +596,7 @@ class Article {
         * @return int Page ID
         */
        public function getID() {
-               if ( $this->mTitle ) {
-                       return $this->mTitle->getArticleID();
-               } else {
-                       return 0;
-               }
+               return $this->mTitle->getArticleID();
        }
 
        /**
@@ -667,18 +664,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;
        }
 
        /**
@@ -710,17 +703,25 @@ 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 );
                }
        }
 
+       /**
+        * 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();
+               $this->mRevIdFetched = $revision->getId();
+       }
+
        /**
         * @return string GMT timestamp of last article revision
         **/
@@ -739,7 +740,6 @@ class Article {
         */
        public function getUser() {
                $this->loadLastEdit();
-
                return $this->mUser;
        }
 
@@ -748,7 +748,6 @@ class Article {
         */
        public function getUserText() {
                $this->loadLastEdit();
-
                return $this->mUserText;
        }
 
@@ -757,7 +756,6 @@ class Article {
         */
        public function getComment() {
                $this->loadLastEdit();
-
                return $this->mComment;
        }
 
@@ -768,7 +766,6 @@ class Article {
         */
        public function getMinorEdit() {
                $this->loadLastEdit();
-
                return $this->mMinorEdit;
        }
 
@@ -779,11 +776,11 @@ class Article {
         */
        public function getRevIdFetched() {
                $this->loadLastEdit();
-
                return $this->mRevIdFetched;
        }
 
        /**
+        * FIXME: this does what?
         * @param $limit Integer: default 0.
         * @param $offset Integer: default 0.
         * @return UserArrayFromResult object with User objects of article contributors for requested range
@@ -831,9 +828,8 @@ class Article {
         * page of the given title.
         */
        public function view() {
-               global $wgUser, $wgOut, $wgRequest, $wgContLang;
-               global $wgEnableParserCache, $wgStylePath, $wgParser;
-               global $wgUseTrackbacks, $wgUseFileCache;
+               global $wgUser, $wgOut, $wgRequest, $wgParser;
+               global $wgUseFileCache, $wgUseETag;
 
                wfProfileIn( __METHOD__ );
 
@@ -841,21 +837,22 @@ class Article {
                $oldid = $this->getOldID();
                $parserCache = ParserCache::singleton();
 
-               $parserOptions = clone $this->getParserOptions();
+               $parserOptions = $this->getParserOptions();
                # Render printable version, use printable version cache
                if ( $wgOut->isPrintable() ) {
                        $parserOptions->setIsPrintable( true );
+                       $parserOptions->setEditSection( false );
+               } else if ( $wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
+                       $parserOptions->setEditSection( false );
                }
 
                # Try client and file cache
                if ( $oldid === 0 && $this->checkTouched() ) {
-                       global $wgUseETag;
-
                        if ( $wgUseETag ) {
                                $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__ );
@@ -887,7 +884,7 @@ class Article {
                $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
 
                # If we got diff in the query, we want to see a diff page instead of the article.
-               if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
+               if ( $wgRequest->getCheck( 'diff' ) ) {
                        wfDebug( __METHOD__ . ": showing diff page\n" );
                        $this->showDiffPage();
                        wfProfileOut( __METHOD__ );
@@ -895,10 +892,17 @@ class Article {
                        return;
                }
 
+               # Allow frames by default
+               $wgOut->allowClickjacking();
+
+               if ( !$wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
+                       $parserOptions->setEditSection( false );
+               }
+
                # Should the parser cache be used?
                $useParserCache = $this->useParserCache( $oldid );
                wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
-               if ( $wgUser->getOption( 'stubthreshold' ) ) {
+               if ( $wgUser->getStubThreshold() ) {
                        wfIncrStats( 'pcache_miss_stub' );
                }
 
@@ -967,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;
                                                        }
                                                }
                                        }
@@ -984,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 {
@@ -1030,6 +1033,7 @@ class Article {
                # For the main page, overwrite the <title> element with the con-
                # 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' ) ) !== '' )
                {
@@ -1052,7 +1056,7 @@ class Article {
         * Article::view() only, other callers should use the DifferenceEngine class.
         */
        public function showDiffPage() {
-               global $wgOut, $wgRequest, $wgUser;
+               global $wgRequest, $wgUser;
 
                $diff = $wgRequest->getVal( 'diff' );
                $rcid = $wgRequest->getVal( 'rcid' );
@@ -1081,7 +1085,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' );
@@ -1097,19 +1101,6 @@ class Article {
                }
        }
 
-       /**
-        * Get the robot policy to be used for the current action=view request.
-        * @return String the policy that should be set
-        * @deprecated use getRobotPolicy() instead, which returns an associative
-        *    array
-        */
-       public function getRobotPolicyForView() {
-               wfDeprecated( __METHOD__ );
-               $policy = $this->getRobotPolicy( 'view' );
-
-               return $policy['index'] . ',' . $policy['follow'];
-       }
-
        /**
         * Get the robot policy to be used for the current view
         * @param $action String the action= GET parameter
@@ -1190,7 +1181,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 ) ) {
@@ -1289,7 +1280,7 @@ class Article {
         * Show the footer section of an ordinary page view
         */
        public function showViewFooter() {
-               global $wgOut, $wgUseTrackbacks, $wgRequest;
+               global $wgOut, $wgUseTrackbacks;
 
                # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
                if ( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
@@ -1316,11 +1307,13 @@ class Article {
 
                $rcid = $wgRequest->getVal( 'rcid' );
 
-               if ( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
+               if ( !$rcid || !$this->mTitle->quickUserCan( 'patrol' ) ) {
                        return;
                }
 
                $sk = $wgUser->getSkin();
+               $token = $wgUser->editToken( $rcid );
+               $wgOut->preventClickjacking();
 
                $wgOut->addHTML(
                        "<div class='patrollink'>" .
@@ -1332,7 +1325,8 @@ class Article {
                                                array(),
                                                array(
                                                        'action' => 'markpatrolled',
-                                                       'rcid' => $rcid
+                                                       'rcid' => $rcid,
+                                                       'token' => $token,
                                                ),
                                                array( 'known', 'noclasses' )
                                        )
@@ -1467,7 +1461,7 @@ class Article {
                global $wgUser, $wgEnableParserCache;
 
                return $wgEnableParserCache
-                       && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
+                       && $wgUser->getStubThreshold() == 0
                        && $this->exists()
                        && empty( $oldid )
                        && !$this->mTitle->isCssOrJsPage()
@@ -1481,16 +1475,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.
-               $parserOptions->setEditSection( $this->isCurrent() );
+               if ( !$this->isCurrent() || $wgOut->isPrintable() || !$this->mTitle->quickUserCan( 'edit' ) ) {
+                       $parserOptions->setEditSection( false );
+               }
+
                $useParserCache = $this->useParserCache( $oldid );
                $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
+
+               return true;
        }
 
        /**
@@ -1502,11 +1500,15 @@ class Article {
         * @return boolean
         */
        public function tryDirtyCache() {
-
                global $wgOut;
                $parserCache = ParserCache::singleton();
                $options = $this->getParserOptions();
-               $options->setIsPrintable( $wgOut->isPrintable() );
+
+               if ( $wgOut->isPrintable() ) {
+                       $options->setIsPrintable( true );
+                       $options->setEditSection( false );
+               }
+
                $output = $parserCache->getDirty( $this, $options );
 
                if ( $output ) {
@@ -1526,27 +1528,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
@@ -1554,15 +1539,11 @@ class Article {
        public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
                global $wgOut, $wgContLang, $wgStylePath, $wgUser;
 
-               # Display redirect
                if ( !is_array( $target ) ) {
                        $target = array( $target );
                }
 
                $imageDir = $wgContLang->getDir();
-               $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
-               $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
-               $alt2 = $wgContLang->isRTL() ? '←' : '→'; // should -> and <- be used instead of Unicode?
 
                if ( $appendSubtitle ) {
                        $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
@@ -1573,36 +1554,28 @@ class Article {
                $title = array_shift( $target );
 
                if ( $forceKnown ) {
-                       $link = $sk->link(
-                               $title,
-                               htmlspecialchars( $title->getFullText() ),
-                               array(),
-                               array(),
-                               array( 'known', 'noclasses' )
-                       );
+                       $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
                } else {
                        $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
                }
 
+               $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 .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
-                                       . $sk->link(
-                                               $rt,
-                                               htmlspecialchars( $rt->getFullText() ),
-                                               array(),
-                                               array(),
-                                               array( 'known', 'noclasses' )
-                                       );
+                               $link .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText() ) );
                        } else {
-                               $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
-                                       . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
+                               $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
                        }
                }
 
-               return '<img 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>';
        }
 
        /**
@@ -1621,8 +1594,10 @@ class Article {
                        return;
                }
 
+               $wgOut->preventClickjacking();
+
                $tbtext = "";
-               while ( $o = $dbr->fetchObject( $tbs ) ) {
+               foreach ( $tbs as $o ) {
                        $rmvtxt = "";
 
                        if ( $wgUser->isAllowed( 'trackback' ) ) {
@@ -1632,7 +1607,7 @@ class Article {
                        }
 
                        $tbtext .= "\n";
-                       $tbtext .= wfMsg( strlen( $o->tb_ex ) ? 'trackbackexcerpt' : 'trackback',
+                       $tbtext .= wfMsgNoTrans( strlen( $o->tb_ex ) ? 'trackbackexcerpt' : 'trackback',
                                        $o->tb_title,
                                        $o->tb_url,
                                        $o->tb_ex,
@@ -1688,21 +1663,28 @@ class Article {
                global $wgUser, $wgRequest, $wgOut;
 
                if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
+                       //FIXME: shouldn't this be in doPurge()?
                        if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
                                $this->doPurge();
                                $this->view();
                        }
                } else {
-                       $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' ) );
+                       $formParams = array(
+                               'method' => 'post',
+                               'action' =>  $wgRequest->getRequestURL(),
+                       );
+
+                       $wgOut->addWikiMsg( 'confirm-purge-top' );
+
+                       $form  = Html::openElement( 'form', $formParams );
+                       $form .= Xml::submitButton( wfMsg( 'confirm_purge_button' ) );
+                       $form .= Html::closeElement( 'form' );
+
+                       $wgOut->addHTML( $form );
+                       $wgOut->addWikiMsg( 'confirm-purge-bottom' );
+
                        $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
                        $wgOut->setRobotPolicy( 'noindex,nofollow' );
-                       $wgOut->addHTML( $top . $form . $bottom );
                }
        }
 
@@ -1714,6 +1696,7 @@ class Article {
 
                // Invalidate the cache
                $this->mTitle->invalidateCache();
+               $this->clear();
 
                if ( $wgUseSquid ) {
                        // Commit the transaction before the purge is sent
@@ -1781,7 +1764,7 @@ 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
         * @param $lastRevision Integer: if given, will not overwrite the page field
@@ -1799,7 +1782,7 @@ class Article {
                wfProfileIn( __METHOD__ );
 
                $text = $revision->getText();
-               $rt = Title::newFromRedirect( $text );
+               $rt = Title::newFromRedirectRecurse( $text );
 
                $conditions = array( 'page_id' => $this->getId() );
 
@@ -1836,7 +1819,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.
@@ -1852,13 +1835,7 @@ class Article {
                if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
                        wfProfileIn( __METHOD__ );
                        if ( $isRedirect ) {
-                               // This title is a redirect, Add/Update row in the redirect table
-                               $set = array( /* SET */
-                                       'rd_namespace' => $redirectTitle->getNamespace(),
-                                       'rd_title'     => $redirectTitle->getDBkey(),
-                                       'rd_from'      => $this->getId(),
-                               );
-                               $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
+                               $this->insertRedirectEntry( $redirectTitle );
                        } else {
                                // This is not a redirect, remove row from redirect table
                                $where = array( 'rd_from' => $this->getId() );
@@ -1963,6 +1940,7 @@ class Article {
        /**
         * This function is not deprecated until somebody fixes the core not to use
         * it. Nevertheless, use Article::doEdit() instead.
+        * @deprecated @since 1.7
         */
        function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
                $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
@@ -1970,24 +1948,62 @@ class Article {
                        ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
                        ( $bot ? EDIT_FORCE_BOT : 0 );
 
-               $this->doEdit( $text, $summary, $flags, false, null, $watchthis, $comment, '', true );
+               # If this is a comment, add the summary as headline
+               if ( $comment && $summary != "" ) {
+                       $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
+               }
+               $this->doEdit( $text, $summary, $flags );
+
+               $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();
+                       }
+               }
+               $this->doRedirect( $this->isRedirect( $text ) );
        }
 
        /**
-        * @deprecated use Article::doEdit()
+        * @deprecated @since 1.7 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 );
+               $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 ) );
+
+               $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
                return true;
        }
 
@@ -2041,12 +2057,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
@@ -2063,12 +2074,11 @@ 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
-               if ( $this->mTitle->getText() == '' ) {
+               if ( $this->mTitle->getText() === '' ) {
                        throw new MWException( 'Something is trying to edit an article with an empty title' );
                }
 
@@ -2082,13 +2092,8 @@ 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__ );
@@ -2112,7 +2117,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 );
 
@@ -2129,8 +2134,6 @@ class Article {
                                $userAbort = ignore_user_abort( true );
                        }
 
-                       $revisionId = 0;
-
                        $changed = ( strcmp( $text, $oldtext ) != 0 );
 
                        if ( $changed ) {
@@ -2155,6 +2158,7 @@ class Article {
                                        'parent_id'  => $this->mLatest,
                                        'user'       => $user->getId(),
                                        'user_text'  => $user->getName(),
+                                       'timestamp'  => $now
                                ) );
 
                                $dbw->begin();
@@ -2186,7 +2190,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,
@@ -2225,7 +2230,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;
@@ -2258,7 +2263,8 @@ class Article {
                                'text'       => $text,
                                'user'       => $user->getId(),
                                'user_text'  => $user->getName(),
-                               ) );
+                               'timestamp'  => $now
+                       ) );
                        $revisionId = $revision->insertOn( $dbw );
 
                        $this->mTitle->resetArticleID( $newid );
@@ -2273,7 +2279,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 );
@@ -2287,13 +2294,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
@@ -2305,50 +2312,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.
@@ -2375,12 +2344,18 @@ class Article {
         * Mark this particular edit/page as patrolled
         */
        public function markpatrolled() {
-               global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
+               global $wgOut, $wgUser, $wgRequest;
 
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
 
                # 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' ), $rcid ) ) {
+                       $wgOut->showErrorPage( 'sessionfailure-title', 'sessionfailure' );
+                       return;
+               }
+
                $rc = RecentChange::newFromId( $rcid );
 
                if ( is_null( $rc ) ) {
@@ -2392,7 +2367,6 @@ class Article {
                $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
                $return = SpecialPage::getTitleFor( $returnto );
 
-               $dbw = wfGetDB( DB_MASTER );
                $errors = $rc->doMarkPatrolled();
 
                if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
@@ -2546,7 +2520,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;
                }
 
@@ -2636,7 +2610,7 @@ class Article {
                                $protect_description = '';
                                foreach ( $limit as $action => $restrictions ) {
                                        if ( !isset( $expiry[$action] ) )
-                                               $expiry[$action] = 'infinite';
+                                               $expiry[$action] = Block::infinity();
 
                                        $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
                                        if ( $restrictions != '' ) {
@@ -2799,8 +2773,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
@@ -2935,6 +2907,7 @@ class Article {
 
                        $skin = $wgUser->getSkin();
                        $revisions = $this->estimateRevisionCount();
+                       //FIXME: lego
                        $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
                                wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
                                wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
@@ -2943,7 +2916,6 @@ class Article {
 
                        if ( $bigHistory ) {
                                global $wgDeleteRevisionsLimit;
-
                                $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
                                        array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
                        }
@@ -3023,7 +2995,7 @@ class Article {
 
                $authors = array( $row->rev_user_text );
 
-               while ( $row = $db->fetchObject( $res ) ) {
+               foreach ( $res as $row ) {
                        $authors[] = $row->rev_user_text;
                }
 
@@ -3033,6 +3005,7 @@ class Article {
 
        /**
         * Output deletion confirmation dialog
+        * FIXME: Move to another file?
         * @param $reason String: prefilled reason
         */
        public function confirmDelete( $reason ) {
@@ -3040,13 +3013,7 @@ class Article {
 
                wfDebug( "Article::confirmDelete\n" );
 
-               $deleteBackLink = $wgUser->getSkin()->link(
-                       $this->mTitle,
-                       null,
-                       array(),
-                       array(),
-                       array( 'known', 'noclasses' )
-               );
+               $deleteBackLink = $wgUser->getSkin()->linkKnown( $this->mTitle );
                $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $wgOut->addWikiMsg( 'confirmdeletetext' );
@@ -3054,7 +3021,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' ),
@@ -3119,7 +3086,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' ) ) {
@@ -3136,9 +3103,7 @@ class Article {
 
                $wgOut->addHTML( $form );
                $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
-               LogEventsList::showLogExtract(
-                       $wgOut,
-                       'delete',
+               LogEventsList::showLogExtract( $wgOut, 'delete',
                        $this->mTitle->getPrefixedText()
                );
        }
@@ -3149,7 +3114,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 ) ) ) {
@@ -3203,17 +3168,15 @@ class Article {
         * @return boolean true if successful
         */
        public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
-               global $wgUseSquid, $wgDeferredUpdateList;
-               global $wgUseTrackbacks;
+               global $wgDeferredUpdateList, $wgUseTrackbacks;
 
                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 ) {
+               if ( $t === '' || $id == 0 ) {
                        return false;
                }
 
@@ -3436,7 +3399,7 @@ class Article {
                if ( $s === false ) {
                        # No one else ever edited this page
                        return array( array( 'cantrollback' ) );
-               } else if ( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
+               } else if ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
                        # Only admins can see this text
                        return array( array( 'notvisiblerev' ) );
                }
@@ -3515,7 +3478,7 @@ class Article {
         * User interface for rollback operations
         */
        public function rollback() {
-               global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
+               global $wgUser, $wgOut, $wgRequest;
 
                $details = null;
 
@@ -3608,9 +3571,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
@@ -3621,7 +3583,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;
@@ -3632,10 +3594,10 @@ class Article {
                $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 );
+               $edit->popts = $this->getParserOptions( true );
+               $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
+               $edit->oldText = $this->getRawText();
 
                $this->mPreparedEdit = $edit;
 
@@ -3649,14 +3611,15 @@ 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 ) {
+       public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User $user = null ) {
                global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
 
                wfProfileIn( __METHOD__ );
@@ -3665,7 +3628,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;
@@ -3673,9 +3636,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
@@ -3908,13 +3870,20 @@ 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
         * @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 ) {
+               global $wgParser;
+
+               if ( $user === null ) {
+                       global $wgUser;
+                       $user = $wgUser;
+               }
 
-               return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
+               return $wgParser->preSaveTransform( $text, $this->mTitle, $user, ParserOptions::newFromUser( $user ) );
        }
 
        /* Caching functions */
@@ -3960,7 +3929,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 ) );
@@ -3987,7 +3956,6 @@ class Article {
         * @return string containing GMT timestamp
         */
        public function getTouched() {
-               # Ensure that page data has been loaded
                if ( !$this->mDataLoaded ) {
                        $this->loadPageData();
                }
@@ -4029,79 +3997,13 @@ class Article {
                $revision->insertOn( $dbw );
                $this->updateRevisionOn( $dbw, $revision );
 
+               global $wgUser;
                wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
 
                wfProfileOut( __METHOD__ );
        }
 
        /**
-        * 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' );
-
-               if ( $wgHitcounterUpdateFreq <= 1 ) {
-                       $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 );
-
-                       $dbType = $dbw->getType();
-                       $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.
@@ -4110,7 +4012,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...
@@ -4201,7 +4103,6 @@ class Article {
         */
        public function revert() {
                global $wgOut;
-
                $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
        }
 
@@ -4252,6 +4153,8 @@ class Article {
                        $pageInfo = $this->pageCountInfo( $page );
                        $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
 
+
+                       //FIXME: unescaped messages
                        $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
                        $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
 
@@ -4329,8 +4232,6 @@ class Article {
                        }
                }
 
-               $dbr->freeResult( $res );
-
                return $result;
        }
 
@@ -4361,8 +4262,6 @@ class Article {
                        }
                }
 
-               $dbr->freeResult( $res );
-
                return $result;
        }
 
@@ -4370,10 +4269,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
@@ -4387,7 +4288,6 @@ class Article {
                # New page autosummaries
                if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
                        # If they're making a new article, give its text, truncated, in the summary.
-                       global $wgContLang;
 
                        $truncatedtext = $wgContLang->truncate(
                                str_replace( "\n", ' ', $newtext ),
@@ -4401,7 +4301,6 @@ class Article {
                        return wfMsgForContent( 'autosumm-blank' );
                } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
                        # Removing more than 90% of the article
-                       global $wgContLang;
 
                        $truncatedtext = $wgContLang->truncate(
                                $newtext,
@@ -4442,7 +4341,7 @@ class Article {
         * @return string containing parsed output
         */
        public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
-               global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
+               global $wgParser, $wgEnableParserCache, $wgUseFileCache;
 
                if ( !$parserOptions ) {
                        $parserOptions = $this->getParserOptions();
@@ -4478,18 +4377,28 @@ class Article {
 
        /**
         * Get parser options suitable for rendering the primary article wikitext
+        * @param $canonical boolean Determines that the generated must not depend on user preferences (see bug 14404)
         * @return mixed ParserOptions object or boolean false
         */
-       public function getParserOptions() {
-               global $wgUser;
-
-               if ( !$this->mParserOptions ) {
-                       $this->mParserOptions = new ParserOptions( $wgUser );
-                       $this->mParserOptions->setTidy( true );
-                       $this->mParserOptions->enableLimitReport();
+       public function getParserOptions( $canonical = false ) {
+               global $wgUser, $wgLanguageCode;
+
+               if ( !$this->mParserOptions || $canonical ) {
+                       $user = !$canonical ? $wgUser : new User;
+                       $parserOptions = new ParserOptions( $user );
+                       $parserOptions->setTidy( true );
+                       $parserOptions->enableLimitReport();
+                       
+                       if ( $canonical ) {
+                               $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
+                               return $parserOptions;
+                       }
+                       $this->mParserOptions = $parserOptions;
                }
 
-               return $this->mParserOptions;
+               // Clone to allow modifications of the return value without affecting
+               // the cache
+               return clone $this->mParserOptions;
        }
 
        /**
@@ -4497,7 +4406,6 @@ class Article {
         *
         * @param $parserOutput mixed ParserOptions object, or boolean false
         **/
-
        protected function doCascadeProtectionUpdates( $parserOutput ) {
                if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
                        return;
@@ -4522,8 +4430,6 @@ class Article {
                        __METHOD__
                );
 
-               global $wgContLang;
-
                foreach ( $res as $row ) {
                        $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
                }
@@ -4537,7 +4443,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 ) {
@@ -4615,20 +4520,23 @@ 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
         */
        public function getParserOutput( $oldid = null ) {
-               global $wgEnableParserCache, $wgUser, $wgOut;
+               global $wgEnableParserCache, $wgUser;
 
                // Should the parser cache be used?
                $useParserCache = $wgEnableParserCache &&
-                       intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
+                       $wgUser->getStubThreshold() == 0 &&
                        $this->exists() &&
                        $oldid === null;
 
                wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
 
-               if ( $wgUser->getOption( 'stubthreshold' ) ) {
+               if ( $wgUser->getStubThreshold() ) {
                        wfIncrStats( 'pcache_miss_stub' );
                }
 
@@ -4646,4 +4554,54 @@ class Article {
                        return $parserOutput;
                }
        }
+
+}
+
+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;
+       }
+
+       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;
+       }
 }