Simplify a bit by using getRawText() instead of creating a Revision object
[lhc/web/wiklou.git] / includes / Article.php
index 2d673af..d66795d 100644 (file)
@@ -17,51 +17,115 @@ class Article {
        /**@{{
         * @private
         */
-       var $mComment = '';               // !<
+
+       /**
+        * @var RequestContext
+        */
+       protected $mContext;
+
        var $mContent;                    // !<
        var $mContentLoaded = false;      // !<
        var $mCounter = -1;               // !< Not loaded
        var $mDataLoaded = false;         // !<
-       var $mForUpdate = false;          // !<
-       var $mGoodAdjustment = 0;         // !<
        var $mIsRedirect = false;         // !<
        var $mLatest = false;             // !<
-       var $mMinorEdit;                  // !<
        var $mOldId;                      // !<
-       var $mPreparedEdit = false;       // !< Title object if set
-       var $mRedirectedFrom = null;      // !< Title object if set
-       var $mRedirectTarget = null;      // !< Title object if set
+       var $mPreparedEdit = false;
+
+       /**
+        * @var Title
+        */
+       var $mRedirectedFrom = null;
+
+       /**
+        * @var Title
+        */
+       var $mRedirectTarget = null;
+
+       /**
+        * @var mixed: boolean false or URL string
+        */
        var $mRedirectUrl = false;        // !<
        var $mRevIdFetched = 0;           // !<
-       var $mRevision;                   // !< Revision object if set
+
+       /**
+        * @var Revision
+        */
+       var $mLastRevision = null;
+
+       /**
+        * @var Revision
+        */
+       var $mRevision = null;
+
        var $mTimestamp = '';             // !<
        var $mTitle;                      // !< Title object
-       var $mTotalAdjustment = 0;        // !<
        var $mTouched = '19700101000000'; // !<
-       var $mUser = -1;                  // !< Not loaded
-       var $mUserText = '';              // !< username from Revision if set
-       var $mParserOptions;              // !< ParserOptions object for $wgUser articles
-       var $mParserOutput;               // !< ParserCache object if set
+
+       /**
+        * @var ParserOptions: ParserOptions object for $wgUser articles
+        */
+       var $mParserOptions;
+
+       /**
+        * @var ParserOutput
+        */
+       var $mParserOutput;
+
        /**@}}*/
 
        /**
         * Constructor and clear the article
-        * @param $title Reference to a Title object.
+        * @param $title Title Reference to a Title object.
         * @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?
+               // @todo FIXME: Does the reference play any role here?
                $this->mTitle =& $title;
                $this->mOldId = $oldId;
        }
 
+       /**
+        * Create an Article object of the appropriate class for the given page.
+        *
+        * @param $title Title
+        * @param $context RequestContext
+        * @return Article object
+        */
+       public static function newFromTitle( $title, RequestContext $context ) {
+               if ( NS_MEDIA == $title->getNamespace() ) {
+                       // FIXME: where should this go?
+                       $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
+               }
+
+               $article = null;
+               wfRunHooks( 'ArticleFromTitle', array( &$title, &$article ) );
+               if ( $article ) {
+                       $article->setContext( $context );
+                       return $article;
+               }
+
+               switch( $title->getNamespace() ) {
+                       case NS_FILE:
+                               $page = new ImagePage( $title );
+                               break;
+                       case NS_CATEGORY:
+                               $page = new CategoryPage( $title );
+                               break;
+                       default:
+                               $page = new Article( $title );
+               }
+               $page->setContext( $context );
+               return $page;
+       }
+
        /**
         * Constructor from an page id
         * @param $id Int article ID to load
         */
        public static function newFromID( $id ) {
                $t = Title::newFromID( $id );
-               # FIXME: doesn't inherit right
+               # @todo FIXME: Doesn't inherit right
                return $t == null ? null : new self( $t );
                # return $t == null ? null : new static( $t ); // PHP 5.3
        }
@@ -80,7 +144,7 @@ class Article {
         *
         * The target will be fetched from the redirect table if possible.
         * If this page doesn't have an entry there, call insertRedirect()
-        * @return mixed Title object, or null if this page is not a redirect
+        * @return Title|mixed object, or null if this page is not a redirect
         */
        public function getRedirectTarget() {
                if ( !$this->mTitle->isRedirect() ) {
@@ -159,7 +223,7 @@ 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
+        * @deprecated since 1.17
         */
        public function followRedirectText( $text ) {
                // recurse through to only get the final target
@@ -216,21 +280,19 @@ class Article {
 
        /**
         * Clear the object
-        * FIXME: shouldn't this be public?
+        * @todo FIXME: Shouldn't this be public?
         * @private
         */
        public function clear() {
                $this->mDataLoaded    = false;
                $this->mContentLoaded = false;
 
-               $this->mUser = $this->mCounter = -1; # Not loaded
+               $this->mCounter = -1; # Not loaded
                $this->mRedirectedFrom = null; # Title object if set
                $this->mRedirectTarget = null; # Title object if set
-               $this->mUserText =
-               $this->mTimestamp = $this->mComment = '';
-               $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
+               $this->mLastRevision = null; # Latest revision
+               $this->mTimestamp = '';
                $this->mTouched = '19700101000000';
-               $this->mForUpdate = false;
                $this->mIsRedirect = false;
                $this->mRevIdFetched = 0;
                $this->mRedirectUrl = false;
@@ -249,7 +311,7 @@ class Article {
         * @return Return the text of this revision
         */
        public function getContent() {
-               global $wgUser, $wgContLang, $wgMessageCache;
+               global $wgUser;
 
                wfProfileIn( __METHOD__ );
 
@@ -257,12 +319,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' );
                        }
@@ -294,23 +354,6 @@ class Article {
                return $text;
        }
 
-       /**
-        * This function returns the text of a section, specified by a number ($section).
-        * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
-        * the first section before any such heading (section 0).
-        *
-        * If a section contains subsections, these are also returned.
-        *
-        * @param $text String: text to look in
-        * @param $section Integer: section number
-        * @return string text of the requested section
-        * @deprecated
-        */
-       public function getSection( $text, $section ) {
-               global $wgParser;
-               return $wgParser->getSection( $text, $section );
-       }
-
        /**
         * Get the text that needs to be saved in order to undo all revisions
         * between $undo and $undoafter. Revisions must belong to the same page,
@@ -320,13 +363,12 @@ 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 ) {
+               $cur_text = $this->getRawText();
+               if ( $cur_text === false ) {
                        return false; // no page
                }
                $undo_text = $undo->getText();
                $undoafter_text = $undoafter->getText();
-               $cur_text = $currentRev->getText();
 
                if ( $cur_text == $undo_text ) {
                        # No use doing a merge if it's just a straight revert.
@@ -405,26 +447,34 @@ class Article {
                wfProfileOut( __METHOD__ );
        }
 
+       /**
+        * Return the list of revision fields that should be selected to create
+        * a new page.
+        */
+       public static function selectFields() {
+               return array(
+                       'page_id',
+                       'page_namespace',
+                       'page_title',
+                       'page_restrictions',
+                       'page_counter',
+                       'page_is_redirect',
+                       'page_is_new',
+                       'page_random',
+                       'page_touched',
+                       'page_latest',
+                       'page_len',
+               );
+       }
+
        /**
         * Fetch a page record with the given conditions
-        * @param $dbr Database object
+        * @param $dbr DatabaseBase object
         * @param $conditions Array
         * @return mixed Database result resource, or false on failure
         */
        protected function pageData( $dbr, $conditions ) {
-               $fields = array(
-                               'page_id',
-                               'page_namespace',
-                               'page_title',
-                               'page_restrictions',
-                               'page_counter',
-                               'page_is_redirect',
-                               'page_is_new',
-                               'page_random',
-                               'page_touched',
-                               'page_latest',
-                               'page_len',
-               );
+               $fields = self::selectFields();
 
                wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
 
@@ -439,11 +489,11 @@ class Article {
         * Fetch a page record matching the Title object's namespace and title
         * using a sanitized title string
         *
-        * @param $dbr Database object
+        * @param $dbr DatabaseBase object
         * @param $title Title object
         * @return mixed Database result resource, or false on failure
         */
-       public function pageDataFromTitle( $dbr, $title ) {
+       protected function pageDataFromTitle( $dbr, $title ) {
                return $this->pageData( $dbr, array(
                        'page_namespace' => $title->getNamespace(),
                        'page_title'     => $title->getDBkey() ) );
@@ -452,8 +502,9 @@ class Article {
        /**
         * Fetch a page record matching the requested ID
         *
-        * @param $dbr Database
+        * @param $dbr DatabaseBase
         * @param $id Integer
+        * @return mixed Database result resource, or false on failure
         */
        protected function pageDataFromId( $dbr, $id ) {
                return $this->pageData( $dbr, array( 'page_id' => $id ) );
@@ -463,7 +514,7 @@ class Article {
         * Set the general counter, title etc data loaded from
         * some source.
         *
-        * @param $data Database row object or "fromdb"
+        * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
         */
        public function loadPageData( $data = 'fromdb' ) {
                if ( $data === 'fromdb' ) {
@@ -546,7 +597,7 @@ class Article {
                        }
                }
 
-               // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
+               // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
                // We should instead work with the Revision object when we need it...
                $this->mContent   = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
 
@@ -564,32 +615,11 @@ class Article {
        }
 
        /**
-        * Read/write accessor to select FOR UPDATE
-        *
-        * @param $x Mixed: FIXME
-        * @return mixed value of $x, or value stored in Article::mForUpdate
-        */
-       public function forUpdate( $x = null ) {
-               return wfSetVar( $this->mForUpdate, $x );
-       }
-
-       /**
-        * Get options for all SELECT statements
-        *
-        * @param $options Array: an optional options array which'll be appended to
-        *                       the default
-        * @return Array: options
+        * No-op
+        * @deprecated since 1.18
         */
-       protected function getSelectOptions( $options = '' ) {
-               if ( $this->mForUpdate ) {
-                       if ( is_array( $options ) ) {
-                               $options[] = 'FOR UPDATE';
-                       } else {
-                               $options = 'FOR UPDATE';
-                       }
-               }
-
-               return $options;
+       public function forUpdate() {
+               wfDeprecated( __METHOD__ );
        }
 
        /**
@@ -632,8 +662,7 @@ class Article {
                                $this->mCounter = $dbr->selectField( 'page',
                                        'page_counter',
                                        array( 'page_id' => $id ),
-                                       __METHOD__,
-                                       $this->getSelectOptions()
+                                       __METHOD__
                                );
                        }
                }
@@ -645,15 +674,43 @@ class Article {
         * Determine whether a page would be suitable for being counted as an
         * article in the site_stats table based on the title & its content
         *
-        * @param $text String: text to analyze
-        * @return bool
+        * @param $editInfo Object or false: object returned by prepareTextForEdit(),
+        *        if false, the current database state will be used
+        * @return Boolean
         */
-       public function isCountable( $text ) {
-               global $wgUseCommaCount;
+       public function isCountable( $editInfo = false ) {
+               global $wgArticleCountMethod;
 
-               $token = $wgUseCommaCount ? ',' : '[[';
+               if ( !$this->mTitle->isContentPage() ) {
+                       return false;
+               }
 
-               return $this->mTitle->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
+               $text = $editInfo ? $editInfo->pst : false;
+
+               if ( $this->isRedirect( $text ) ) {
+                       return false;
+               }
+
+               switch ( $wgArticleCountMethod ) {
+               case 'any':
+                       return true;
+               case 'comma':
+                       if ( $text === false ) {
+                               $text = $this->getRawText();
+                       }
+                       return strpos( $text,  ',' ) !== false;
+               case 'link':
+                       if ( $editInfo ) {
+                               // ParserOutput::getLinks() is a 2D array of page links, so
+                               // to be really correct we would need to recurse in the array
+                               // but the main array should only have items in it if there are
+                               // links.
+                               return (bool)count( $editInfo->output->getLinks() );
+                       } else {
+                               return (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
+                                       array( 'pl_from' => $this->getId() ), __METHOD__ );
+                       }
+               }
        }
 
        /**
@@ -685,7 +742,7 @@ class Article {
                        return true;
                }
 
-               return $this->exists() && isset( $this->mRevision ) && $this->mRevision->isCurrent();
+               return $this->exists() && $this->mRevision && $this->mRevision->isCurrent();
        }
 
        /**
@@ -693,8 +750,8 @@ class Article {
         * This isn't necessary for all uses, so it's only done if needed.
         */
        protected function loadLastEdit() {
-               if ( -1 != $this->mUser ) {
-                       return;
+               if ( $this->mLastRevision !== null ) {
+                       return; // already loaded
                }
 
                # New or non-existent articles have no user information
@@ -704,7 +761,7 @@ class Article {
                }
 
                $revision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
-               if ( !is_null( $revision ) ) {
+               if ( $revision ) {
                        $this->setLastEdit( $revision );
                }
        }
@@ -714,11 +771,7 @@ class Article {
         */
        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();
        }
 
        /**
@@ -729,32 +782,55 @@ class Article {
                if ( !$this->mTimestamp ) {
                        $this->loadLastEdit();
                }
-
                return wfTimestamp( TS_MW, $this->mTimestamp );
        }
 
        /**
+        * @param $audience Integer: one of:
+        *      Revision::FOR_PUBLIC       to be displayed to all users
+        *      Revision::FOR_THIS_USER    to be displayed to $wgUser
+        *      Revision::RAW              get the text regardless of permissions
         * @return int user ID for the user that made the last article revision
         */
-       public function getUser() {
+       public function getUser( $audience = Revision::FOR_PUBLIC ) {
                $this->loadLastEdit();
-               return $this->mUser;
+               if ( $this->mLastRevision ) {
+                       return $this->mLastRevision->getUser( $audience );
+               } else {
+                       return -1;
+               }
        }
 
        /**
+        * @param $audience Integer: one of:
+        *      Revision::FOR_PUBLIC       to be displayed to all users
+        *      Revision::FOR_THIS_USER    to be displayed to $wgUser
+        *      Revision::RAW              get the text regardless of permissions
         * @return string username of the user that made the last article revision
         */
-       public function getUserText() {
+       public function getUserText( $audience = Revision::FOR_PUBLIC ) {
                $this->loadLastEdit();
-               return $this->mUserText;
+               if ( $this->mLastRevision ) {
+                       return $this->mLastRevision->getUserText( $audience );
+               } else {
+                       return '';
+               }
        }
 
        /**
+        * @param $audience Integer: one of:
+        *      Revision::FOR_PUBLIC       to be displayed to all users
+        *      Revision::FOR_THIS_USER    to be displayed to $wgUser
+        *      Revision::RAW              get the text regardless of permissions
         * @return string Comment stored for the last article revision
         */
-       public function getComment() {
+       public function getComment( $audience = Revision::FOR_PUBLIC ) {
                $this->loadLastEdit();
-               return $this->mComment;
+               if ( $this->mLastRevision ) {
+                       return $this->mLastRevision->getComment( $audience );
+               } else {
+                       return '';
+               }
        }
 
        /**
@@ -764,7 +840,11 @@ class Article {
         */
        public function getMinorEdit() {
                $this->loadLastEdit();
-               return $this->mMinorEdit;
+               if ( $this->mLastRevision ) {
+                       return $this->mLastRevision->isMinor();
+               } else {
+                       return false;
+               }
        }
 
        /**
@@ -781,46 +861,53 @@ class Article {
        }
 
        /**
-        * 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
+        * Get a list of users who have edited this article, not including the user who made
+        * the most recent revision, which you can get from $article->getUser() if you want it
+        * @return UserArrayFromResult
         */
-       public function getContributors( $limit = 0, $offset = 0 ) {
-               # FIXME: this is expensive; cache this info somewhere.
+       public function getContributors() {
+               # @todo FIXME: This is expensive; cache this info somewhere.
 
                $dbr = wfGetDB( DB_SLAVE );
-               $revTable = $dbr->tableName( 'revision' );
-               $userTable = $dbr->tableName( 'user' );
 
-               $pageId = $this->getId();
+               if ( $dbr->implicitGroupby() ) {
+                       $realNameField = 'user_real_name';
+               } else {
+                       $realNameField = 'FIRST(user_real_name) AS user_real_name';
+               }
+
+               $tables = array( 'revision', 'user' );
 
-               $user = $this->getUser();
+               $fields = array(
+                       'rev_user as user_id',
+                       'rev_user_text AS user_name',
+                       $realNameField,
+                       'MAX(rev_timestamp) AS timestamp',
+               );
+
+               $conds = array( 'rev_page' => $this->getId() );
 
+               // The user who made the top revision gets credited as "this page was last edited by
+               // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
+               $user = $this->getUser();
                if ( $user ) {
-                       $excludeCond = "AND rev_user != $user";
+                       $conds[] = "rev_user != $user";
                } else {
-                       $userText = $dbr->addQuotes( $this->getUserText() );
-                       $excludeCond = "AND rev_user_text != $userText";
+                       $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
                }
 
-               $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ); // username hidden?
-
-               $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
-                       FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
-                       WHERE rev_page = $pageId
-                       $excludeCond
-                       AND $deletedBit = 0
-                       GROUP BY rev_user, rev_user_text
-                       ORDER BY timestamp DESC";
+               $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
 
-               if ( $limit > 0 ) {
-                       $sql = $dbr->limitResult( $sql, $limit, $offset );
-               }
+               $jconds = array(
+                       'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
+               );
 
-               $sql .= ' ' . $this->getSelectOptions();
-               $res = $dbr->query( $sql, __METHOD__ );
+               $options = array(
+                       'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
+                       'ORDER BY' => 'timestamp DESC',
+               );
 
+               $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
                return new UserArrayFromResult( $res );
        }
 
@@ -836,6 +923,32 @@ 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 = $this->getParserOptions();
@@ -843,7 +956,7 @@ class Article {
                if ( $wgOut->isPrintable() ) {
                        $parserOptions->setIsPrintable( true );
                        $parserOptions->setEditSection( false );
-               } else if ( $wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
+               } elseif ( $wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
                        $parserOptions->setEditSection( false );
                }
 
@@ -860,7 +973,7 @@ class Article {
 
                                return;
                        # Try file cache
-                       } else if ( $wgUseFileCache && $this->tryFileCache() ) {
+                       } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
                                wfDebug( __METHOD__ . ": done file cache\n" );
                                # tell wgOut that output is taken care of
                                $wgOut->disable();
@@ -871,31 +984,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;
-               }
-
-               # Allow frames by default
-               $wgOut->allowClickjacking();
-
                if ( !$wgUseETag && !$this->mTitle->quickUserCan( 'edit' ) ) {
                        $parserOptions->setEditSection( false );
                }
@@ -1035,10 +1123,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
@@ -1071,9 +1160,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();
                }
@@ -1117,8 +1204,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'
@@ -1214,16 +1300,15 @@ class Article {
         * @return boolean
         */
        public function showRedirectedFromHeader() {
-               global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
+               global $wgOut, $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 = Linker::link(
                                        $this->mRedirectedFrom,
                                        null,
                                        array(),
@@ -1251,7 +1336,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 = Linker::makeExternalLink( $rdfrom, $rdfrom );
                                $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
                                $wgOut->setSubtitle( $s );
 
@@ -1270,8 +1355,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' ) );
                        }
                }
@@ -1296,6 +1380,9 @@ class Article {
                if ( $wgUseTrackbacks ) {
                        $this->addTrackbacks();
                }
+
+               wfRunHooks( 'ArticleViewFooter', array( $this ) );
+
        }
 
        /**
@@ -1312,7 +1399,6 @@ class Article {
                        return;
                }
 
-               $sk = $wgUser->getSkin();
                $token = $wgUser->editToken( $rcid );
                $wgOut->preventClickjacking();
 
@@ -1320,7 +1406,7 @@ class Article {
                        "<div class='patrollink'>" .
                                wfMsgHtml(
                                        'markaspatrolledlink',
-                                       $sk->link(
+                                       Linker::link(
                                                $this->mTitle,
                                                wfMsgHtml( 'markaspatrolledtext' ),
                                                array(),
@@ -1352,8 +1438,8 @@ class Article {
 
                        if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
                                $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
-                                       array( 'userpage-userdoesnotexist-view', $rootPart ) );
-                       } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
+                                       array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
+                       } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
                                LogEventsList::showLogExtract(
                                        $wgOut,
                                        'block',
@@ -1389,7 +1475,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 );
@@ -1406,7 +1492,7 @@ class Article {
                if ( !$this->hasViewableContent() ) {
                        // If there's no backing content, send a 404 Not Found
                        // for better machine handling of broken links.
-                       $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
+                       $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
                }
 
                $wgOut->addWikiText( $text );
@@ -1433,7 +1519,7 @@ class Article {
 
                        return false;
                // If the user needs to confirm that they want to see it...
-               } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
+               } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
                        # Give explanation and add a link to view the revision...
                        $oldid = intval( $this->getOldID() );
                        $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
@@ -1538,7 +1624,7 @@ class Article {
         * @return string containing HMTL with redirect link
         */
        public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
-               global $wgOut, $wgContLang, $wgStylePath, $wgUser;
+               global $wgOut, $wgContLang, $wgStylePath;
 
                if ( !is_array( $target ) ) {
                        $target = array( $target );
@@ -1550,26 +1636,24 @@ class Article {
                        $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
                }
 
-               $sk = $wgUser->getSkin();
                // the loop prepends the arrow image before the link, so the first case needs to be outside
                $title = array_shift( $target );
 
                if ( $forceKnown ) {
-                       $link = $sk->linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
+                       $link = Linker::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
                } else {
-                       $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
+                       $link = Linker::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 .= $sk->linkKnown( $rt, htmlspecialchars( $rt->getFullText() ) );
+                               $link .= Linker::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
                        } else {
-                               $link .= $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
+                               $link .= Linker::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
                        }
                }
 
@@ -1583,7 +1667,7 @@ class Article {
         * Builds trackback links for article display if $wgUseTrackbacks is set to true
         */
        public function addTrackbacks() {
-               global $wgOut, $wgUser;
+               global $wgOut;
 
                $dbr = wfGetDB( DB_SLAVE );
                $tbs = $dbr->select( 'trackbacks',
@@ -1601,9 +1685,9 @@ class Article {
                foreach ( $tbs as $o ) {
                        $rmvtxt = "";
 
-                       if ( $wgUser->isAllowed( 'trackback' ) ) {
+                       if ( $wgOut->getUser()->isAllowed( 'trackback' ) ) {
                                $delurl = $this->mTitle->getFullURL( "action=deletetrackback&tbid=" .
-                                       $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
+                                       $o->tb_id . "&token=" . urlencode( $wgOut->getUser()->editToken() ) );
                                $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
                        }
 
@@ -1621,29 +1705,10 @@ class Article {
 
        /**
         * Removes trackback record for current article from trackbacks table
+        * @deprecated since 1.19
         */
        public function deletetrackback() {
-               global $wgUser, $wgRequest, $wgOut;
-
-               if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
-                       $wgOut->addWikiMsg( 'sessionfailure' );
-
-                       return;
-               }
-
-               $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
-
-               if ( count( $permission_errors ) ) {
-                       $wgOut->showPermissionsErrorPage( $permission_errors );
-
-                       return;
-               }
-
-               $db = wfGetDB( DB_MASTER );
-               $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
-
-               $wgOut->addWikiMsg( 'trackbackdeleteok' );
-               $this->mTitle->invalidateCache();
+               return Action::factory( 'deletetrackback', $this )->show();
        }
 
        /**
@@ -1661,32 +1726,7 @@ class Article {
         * Handle action=purge
         */
        public function purge() {
-               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 {
-                       $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' );
-               }
+               return Action::factory( 'purge', $this )->show();
        }
 
        /**
@@ -1695,6 +1735,10 @@ class Article {
        public function doPurge() {
                global $wgUseSquid;
 
+               if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
+                       return false;
+               }
+
                // Invalidate the cache
                $this->mTitle->invalidateCache();
                $this->clear();
@@ -1710,18 +1754,88 @@ 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 );
                }
        }
 
+       /**
+        * Mark this particular edit/page as patrolled
+        * @deprecated since 1.19
+        */
+       public function markpatrolled() {
+               Action::factory( 'markpatrolled', $this )->show();
+       }
+
+       /**
+        * User-interface handler for the "watch" action.
+        * Requires Request to pass a token as of 1.19.
+        * @deprecated since 1.18
+        */
+       public function watch() {
+               Action::factory( 'watch', $this )->show();
+       }
+
+       /**
+        * Add this page to $wgUser's watchlist
+        *
+        * This is safe to be called multiple times
+        *
+        * @return bool true on successful watch operation
+        * @deprecated since 1.18
+        */
+       public function doWatch() {
+               global $wgUser;
+               return WatchAction::doWatch( $this->mTitle, $wgUser );
+       }
+
+       /**
+        * User interface handler for the "unwatch" action.
+        * Requires Request to pass a token as of 1.19.
+        * @deprecated since 1.18
+        */
+       public function unwatch() {
+               Action::factory( 'unwatch', $this )->show();
+       }
+
+       /**
+        * Stop watching a page
+        * @return bool true on successful unwatch
+        * @deprecated since 1.18
+        */
+       public function doUnwatch() {
+               global $wgUser;
+               return WatchAction::doUnwatch( $this->mTitle, $wgUser );
+       }
+
+       /**
+        * action=protect handler
+        */
+       public function protect() {
+               $form = new ProtectionForm( $this );
+               $form->execute();
+       }
+
+       /**
+        * action=unprotect handler (alias)
+        */
+       public function unprotect() {
+               $this->protect();
+       }
+
+       /**
+        * Info about this page
+        * Called for ?action=info when $wgAllowPageInfo is on.
+        */
+       public function info() {
+               Action::factory( 'info', $this )->show();
+       }
+
        /**
         * Insert a new empty page record for this article.
         * This *must* be followed up by creating a revision
@@ -1729,7 +1843,7 @@ class Article {
         * or else the record will be left in a funky state.
         * Best if all done inside a transaction.
         *
-        * @param $dbw Database
+        * @param $dbw DatabaseBase
         * @return int The newly created page_id key, or false if the title already existed
         * @private
         */
@@ -1755,7 +1869,7 @@ class Article {
 
                if ( $affected ) {
                        $newid = $dbw->insertId();
-                       $this->mTitle->resetArticleId( $newid );
+                       $this->mTitle->resetArticleID( $newid );
                }
                wfProfileOut( __METHOD__ );
 
@@ -1767,19 +1881,17 @@ class Article {
         *
         * @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
         *                      on.
         * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
         *                           removing rows in redirect table.
-        * @param $setNewFlag Boolean: Set to true if a page flag should be set
-        *                    Needed when $lastRevision has to be set to sth. !=0
         * @return bool true on success, false on failure
         * @private
         */
-       public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null, $setNewFlag = false ) {
+       public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
                wfProfileIn( __METHOD__ );
 
                $text = $revision->getText();
@@ -1792,15 +1904,11 @@ class Article {
                        $conditions['page_latest'] = $lastRevision;
                }
 
-               if ( !$setNewFlag ) {
-                       $setNewFlag = ( $lastRevision === 0 );
-               }
-
                $dbw->update( 'page',
                        array( /* SET */
                                'page_latest'      => $revision->getId(),
                                'page_touched'     => $dbw->timestamp(),
-                               'page_is_new'      => $setNewFlag,
+                               'page_is_new'      => ( $lastRevision === 0 ) ? 1 : 0,
                                'page_is_redirect' => $rt !== null ? 1 : 0,
                                'page_len'         => strlen( $text ),
                        ),
@@ -1819,7 +1927,7 @@ class Article {
        /**
         * Add row to the redirect table if this is a redirect, remove otherwise.
         *
-        * @param $dbw Database
+        * @param $dbw DatabaseBase
         * @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
@@ -1833,25 +1941,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 );
        }
 
        /**
@@ -1915,6 +2023,7 @@ class Article {
                        if ( !$rev ) {
                                wfDebug( "Article::replaceSection asked for bogus section (page: " .
                                        $this->getId() . "; section: $section; edittime: $edittime)\n" );
+                               wfProfileOut( __METHOD__ );
                                return null;
                        }
 
@@ -1938,76 +2047,6 @@ class Article {
                return $text;
        }
 
-       /**
-        * 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 |
-                       ( $isminor ? EDIT_MINOR : 0 ) |
-                       ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
-                       ( $bot ? EDIT_FORCE_BOT : 0 );
-
-               # 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 @since 1.7 use Article::doEdit()
-        */
-       function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
-               $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
-                       ( $minor ? EDIT_MINOR : 0 ) |
-                       ( $forceBot ? EDIT_FORCE_BOT : 0 );
-
-               $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;
-       }
-
        /**
         * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
         * @param $flags Int
@@ -2097,12 +2136,12 @@ class Article {
                        $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;
                }
 
@@ -2138,10 +2177,6 @@ class Article {
                        $changed = ( strcmp( $text, $oldtext ) != 0 );
 
                        if ( $changed ) {
-                               $this->mGoodAdjustment = (int)$this->isCountable( $text )
-                                 - (int)$this->isCountable( $oldtext );
-                               $this->mTotalAdjustment = 0;
-
                                if ( !$this->mLatest ) {
                                        # Article gone missing
                                        wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
@@ -2236,12 +2271,6 @@ class Article {
                        # Create new article
                        $status->value['new'] = true;
 
-                       # Set statistics members
-                       # We work out if it's countable after PST to avoid counter drift
-                       # when articles are created with {{subst:}}
-                       $this->mGoodAdjustment = (int)$this->isCountable( $text );
-                       $this->mTotalAdjustment = 1;
-
                        $dbw->begin();
 
                        # Add the page record; stake our claim on this title!
@@ -2269,6 +2298,9 @@ class Article {
                        $revisionId = $revision->insertOn( $dbw );
 
                        $this->mTitle->resetArticleID( $newid );
+                       # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
+                       # @todo 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 );
@@ -2295,7 +2327,7 @@ class Article {
                        $dbw->commit();
 
                        # Update links, etc.
-                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user );
+                       $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true, $user, true );
 
                        # Clear caches
                        Article::onArticleCreate( $this->mTitle );
@@ -2323,11 +2355,13 @@ class Article {
         * Output a redirect back to the article.
         * This is typically used after an edit.
         *
+        * @deprecated in 1.19; call $wgOut->redirect() directly
         * @param $noRedir Boolean: add redirect=no
         * @param $sectionAnchor String: section to redirect to, including "#"
         * @param $extraQuery String: extra query params
         */
        public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
+               wfDeprecated( __METHOD__ );
                global $wgOut;
 
                if ( $noRedir ) {
@@ -2341,169 +2375,6 @@ class Article {
                $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
        }
 
-       /**
-        * Mark this particular edit/page as patrolled
-        */
-       public function markpatrolled() {
-               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 ) ) {
-                       $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
-                       return;
-               }
-
-               # It would be nice to see where the user had actually come from, but for now just guess
-               $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
-               $return = SpecialPage::getTitleFor( $returnto );
-
-               $errors = $rc->doMarkPatrolled();
-
-               if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
-                       $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
-
-                       return;
-               }
-
-               if ( in_array( array( 'hookaborted' ), $errors ) ) {
-                       // The hook itself has handled any output
-                       return;
-               }
-
-               if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
-                       $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
-                       $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
-                       $wgOut->returnToMain( false, $return );
-
-                       return;
-               }
-
-               if ( !empty( $errors ) ) {
-                       $wgOut->showPermissionsErrorPage( $errors );
-
-                       return;
-               }
-
-               # Inform the user
-               $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
-               $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
-               $wgOut->returnToMain( false, $return );
-       }
-
-       /**
-        * User-interface handler for the "watch" action
-        */
-       public function watch() {
-               global $wgUser, $wgOut;
-
-               if ( $wgUser->isAnon() ) {
-                       $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
-                       return;
-               }
-
-               if ( wfReadOnly() ) {
-                       $wgOut->readOnlyPage();
-                       return;
-               }
-
-               if ( $this->doWatch() ) {
-                       $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
-                       $wgOut->setRobotPolicy( 'noindex,nofollow' );
-                       $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
-               }
-
-               $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
-       }
-
-       /**
-        * Add this page to $wgUser's watchlist
-        * @return bool true on successful watch operation
-        */
-       public function doWatch() {
-               global $wgUser;
-
-               if ( $wgUser->isAnon() ) {
-                       return false;
-               }
-
-               if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
-                       $wgUser->addWatch( $this->mTitle );
-                       return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
-               }
-
-               return false;
-       }
-
-       /**
-        * User interface handler for the "unwatch" action.
-        */
-       public function unwatch() {
-               global $wgUser, $wgOut;
-
-               if ( $wgUser->isAnon() ) {
-                       $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
-                       return;
-               }
-
-               if ( wfReadOnly() ) {
-                       $wgOut->readOnlyPage();
-                       return;
-               }
-
-               if ( $this->doUnwatch() ) {
-                       $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
-                       $wgOut->setRobotPolicy( 'noindex,nofollow' );
-                       $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
-               }
-
-               $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
-       }
-
-       /**
-        * Stop watching a page
-        * @return bool true on successful unwatch
-        */
-       public function doUnwatch() {
-               global $wgUser;
-
-               if ( $wgUser->isAnon() ) {
-                       return false;
-               }
-
-               if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
-                       $wgUser->removeWatch( $this->mTitle );
-                       return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
-               }
-
-               return false;
-       }
-
-       /**
-        * action=protect handler
-        */
-       public function protect() {
-               $form = new ProtectionForm( $this );
-               $form->execute();
-       }
-
-       /**
-        * action=unprotect handler (alias)
-        */
-       public function unprotect() {
-               $this->protect();
-       }
-
        /**
         * Update the article's restriction field, and leave a log entry.
         *
@@ -2542,7 +2413,7 @@ class Article {
                // Take this opportunity to purge out expired restrictions
                Title::purgeExpiredRestrictions();
 
-               # FIXME: Same limitations as described in ProtectionForm.php (line 37);
+               # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
                # we expect a single selection, but the schema allows otherwise.
                $current = array();
                $updated = Article::flattenRestrictions( $limit );
@@ -2611,9 +2482,9 @@ class Article {
                                $protect_description = '';
                                foreach ( $limit as $action => $restrictions ) {
                                        if ( !isset( $expiry[$action] ) )
-                                               $expiry[$action] = Block::infinity();
+                                               $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' ) {
@@ -2795,8 +2666,8 @@ class Article {
                // Replace newlines with spaces to prevent uglyness
                $contents = preg_replace( "/[\n\r]/", ' ', $contents );
                // Calculate the maximum amount of chars to get
-               // Max content length = max comment length - length of the comment (excl. $1) - '...'
-               $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
+               // Max content length = max comment length - length of the comment (excl. $1)
+               $maxLength = 255 - ( strlen( $reason ) - 2 );
                $contents = $wgContLang->truncate( $contents, $maxLength );
                // Remove possible unfinished links
                $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
@@ -2807,14 +2678,14 @@ class Article {
        }
 
 
-       /*
+       /**
         * UI entry point for page deletion
         */
        public function delete() {
-               global $wgUser, $wgOut, $wgRequest;
+               global $wgOut, $wgRequest;
 
                $confirm = $wgRequest->wasPosted() &&
-                               $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
+                               $wgOut->getUser()->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
 
                $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
                $this->DeleteReason = $wgRequest->getText( 'wpReason' );
@@ -2829,7 +2700,7 @@ class Article {
                }
 
                # Flag to hide all contents of the archived revisions
-               $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
+               $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgOut->getUser()->isAllowed( 'suppressrevision' );
 
                # This code desperately needs to be totally rewritten
 
@@ -2841,7 +2712,7 @@ class Article {
                }
 
                # Check permissions
-               $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
+               $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgOut->getUser() );
 
                if ( count( $permission_errors ) > 0 ) {
                        $wgOut->showPermissionsErrorPage( $permission_errors );
@@ -2860,7 +2731,8 @@ class Article {
                                Html::rawElement(
                                        'div',
                                        array( 'class' => 'error mw-error-cannotdelete' ),
-                                       wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
+                                       wfMsgExt( 'cannotdelete', array( 'parse' ),
+                                               wfEscapeWikiText( $this->mTitle->getPrefixedText() ) )
                                )
                        );
                        $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
@@ -2887,7 +2759,7 @@ class Article {
                if ( $confirm ) {
                        $this->doDelete( $reason, $suppress );
 
-                       if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
+                       if ( $wgRequest->getCheck( 'wpWatch' ) && $wgOut->getUser()->isLoggedIn() ) {
                                $this->doWatch();
                        } elseif ( $this->mTitle->userIsWatching() ) {
                                $this->doUnwatch();
@@ -2906,12 +2778,14 @@ class Article {
                if ( $hasHistory && !$confirm ) {
                        global $wgLang;
 
-                       $skin = $wgUser->getSkin();
                        $revisions = $this->estimateRevisionCount();
-                       //FIXME: lego
+                       // @todo FIXME: i18n issue/patchwork message
                        $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
                                wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
-                               wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
+                               wfMsgHtml( 'word-separator' ) . Linker::link( $this->mTitle,
+                                       wfMsgHtml( 'history' ),
+                                       array( 'rel' => 'archives' ),
+                                       array( 'action' => 'history' ) ) .
                                '</strong>'
                        );
 
@@ -2973,10 +2847,11 @@ class Article {
                                        'page_namespace' => $this->mTitle->getNamespace(),
                                        'page_title' => $this->mTitle->getDBkey(),
                                        'rev_page = page_id'
-                               ), __METHOD__, $this->getSelectOptions( array(
+                               ), __METHOD__,
+                               array(
                                        'ORDER BY' => 'rev_timestamp DESC',
                                        'LIMIT' => $num
-                               ) )
+                               )
                        );
 
                        if ( !$res ) {
@@ -3006,22 +2881,22 @@ class Article {
 
        /**
         * Output deletion confirmation dialog
-        * FIXME: Move to another file?
+        * @todo FIXME: Move to another file?
         * @param $reason String: prefilled reason
         */
        public function confirmDelete( $reason ) {
-               global $wgOut, $wgUser;
+               global $wgOut;
 
                wfDebug( "Article::confirmDelete\n" );
 
-               $deleteBackLink = $wgUser->getSkin()->linkKnown( $this->mTitle );
+               $deleteBackLink = Linker::linkKnown( $this->mTitle );
                $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $wgOut->addWikiMsg( 'confirmdeletetext' );
 
                wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
 
-               if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
+               if ( $wgOut->getUser()->isAllowed( 'suppressrevision' ) ) {
                        $suppress = "<tr id=\"wpDeleteSuppressRow\">
                                        <td></td>
                                        <td class='mw-input'><strong>" .
@@ -3032,7 +2907,7 @@ class Article {
                } else {
                        $suppress = '';
                }
-               $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
+               $checkWatch = $wgOut->getUser()->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
 
                $form = Xml::openElement( 'form', array( 'method' => 'post',
                        'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
@@ -3065,7 +2940,7 @@ class Article {
                        </tr>";
 
                # Disallow watching if user is not logged in
-               if ( $wgUser->isLoggedIn() ) {
+               if ( $wgOut->getUser()->isLoggedIn() ) {
                        $form .= "
                        <tr>
                                <td></td>
@@ -3087,13 +2962,12 @@ class Article {
                        </tr>" .
                        Xml::closeElement( 'table' ) .
                        Xml::closeElement( 'fieldset' ) .
-                       Html::hidden( 'wpEditToken', $wgUser->editToken() ) .
+                       Html::hidden( 'wpEditToken', $wgOut->getUser()->editToken() ) .
                        Xml::closeElement( 'form' );
 
-                       if ( $wgUser->isAllowed( 'editinterface' ) ) {
-                               $skin = $wgUser->getSkin();
+                       if ( $wgOut->getUser()->isAllowed( 'editinterface' ) ) {
                                $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
-                               $link = $skin->link(
+                               $link = Linker::link(
                                        $title,
                                        wfMsgHtml( 'delete-edit-reasonlist' ),
                                        array(),
@@ -3113,31 +2987,29 @@ class Article {
         * Perform a deletion and output success or failure messages
         */
        public function doDelete( $reason, $suppress = false ) {
-               global $wgOut, $wgUser;
+               global $wgOut;
 
                $id = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
 
                $error = '';
-               if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
-                       if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
-                               $deleted = $this->mTitle->getPrefixedText();
+               if ( $this->doDeleteArticle( $reason, $suppress, $id, $error ) ) {
+                       $deleted = $this->mTitle->getPrefixedText();
 
-                               $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
-                               $wgOut->setRobotPolicy( 'noindex,nofollow' );
+                       $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
+                       $wgOut->setRobotPolicy( 'noindex,nofollow' );
 
-                               $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
+                       $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
 
-                               $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
-                               $wgOut->returnToMain( false );
-                               wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
-                       }
+                       $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
+                       $wgOut->returnToMain( false );
                } else {
                        if ( $error == '' ) {
                                $wgOut->showFatalError(
                                        Html::rawElement(
                                                'div',
                                                array( 'class' => 'error mw-error-cannotdelete' ),
-                                               wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
+                                               wfMsgExt( 'cannotdelete', array( 'parse' ),
+                                                       wfEscapeWikiText( $this->mTitle->getPrefixedText() ) )
                                        )
                                );
 
@@ -3168,11 +3040,15 @@ class Article {
         * @param $commit boolean defaults to true, triggers transaction end
         * @return boolean true if successful
         */
-       public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
+       public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
                global $wgDeferredUpdateList, $wgUseTrackbacks;
+               global $wgUser;
 
                wfDebug( __METHOD__ . "\n" );
 
+               if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
+                       return false;
+               }
                $dbw = wfGetDB( DB_MASTER );
                $t = $this->mTitle->getDBkey();
                $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
@@ -3181,7 +3057,7 @@ class Article {
                        return false;
                }
 
-               $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
+               $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
                array_push( $wgDeferredUpdateList, $u );
 
                // Bitfields to further suppress the content
@@ -3265,6 +3141,7 @@ class Article {
                        $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
                        $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
                        $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
+                       $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
                        $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
                }
 
@@ -3298,6 +3175,7 @@ class Article {
                        $dbw->commit();
                }
 
+               wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
                return true;
        }
 
@@ -3400,7 +3278,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 ) {
+               } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
                        # Only admins can see this text
                        return array( array( 'notvisiblerev' ) );
                }
@@ -3451,7 +3329,7 @@ class Article {
                        $flags |= EDIT_MINOR;
                }
 
-               if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) ) {
+               if ( $bot && ( $wgUser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
                        $flags |= EDIT_FORCE_BOT;
                }
 
@@ -3507,7 +3385,7 @@ class Article {
 
                                if ( $current->getComment() != '' ) {
                                        $wgOut->addWikiMsgArray( 'editcomment', array(
-                                               $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
+                                               Linker::formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
                                }
                        }
 
@@ -3546,12 +3424,12 @@ class Article {
                if ( $current->getUserText() === '' ) {
                        $old = wfMsg( 'rev-deleted-user' );
                } else {
-                       $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
-                               . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
+                       $old = Linker::userLink( $current->getUser(), $current->getUserText() )
+                               . Linker::userToolLinks( $current->getUser(), $current->getUserText() );
                }
 
-               $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
-                       . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
+               $new = Linker::userLink( $target->getUser(), $target->getUserText() )
+                       . Linker::userToolLinks( $target->getUser(), $target->getUserText() );
                $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
                $wgOut->returnToMain( false, $this->mTitle );
 
@@ -3592,10 +3470,17 @@ 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, $user );
+               $edit->pst = $this->preSaveTransform( $text, $user, $popts );
                $edit->popts = $this->getParserOptions( true );
                $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
                $edit->oldText = $this->getRawText();
@@ -3619,9 +3504,12 @@ class Article {
         * @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
+        * @param $created Boolean: Whether the edit created the page
         */
-       public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true, User $user = null ) {
-               global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
+       public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
+               $changed = true, User $user = null, $created = false )
+       {
+               global $wgDeferredUpdateList, $wgUser, $wgEnableParserCache;
 
                wfProfileIn( __METHOD__ );
 
@@ -3655,10 +3543,11 @@ class Article {
 
                                $dbw = wfGetDB( DB_MASTER );
                                $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
-                               $recentchanges = $dbw->tableName( 'recentchanges' );
-                               $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
-
-                               $dbw->query( $sql );
+                               $dbw->delete(
+                                       'recentchanges',
+                                       array( "rc_timestamp < '$cutoff'" ),
+                                       __METHOD__
+                               );
                        }
                }
 
@@ -3671,10 +3560,19 @@ class Article {
                        return;
                }
 
-               $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
-               array_push( $wgDeferredUpdateList, $u );
-               $u = new SearchUpdate( $id, $title, $text );
-               array_push( $wgDeferredUpdateList, $u );
+               if ( !$changed ) {
+                       $good = 0;
+                       $total = 0;
+               } elseif ( $created ) {
+                       $good = (int)$this->isCountable( $editInfo );
+                       $total = 1;
+               } else {
+                       $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
+                       $total = 0;
+               }
+
+               $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
+               $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
 
                # If this is another user's talk page, update newtalk
                # Don't do this if $changed = false otherwise some idiot can null-edit a
@@ -3699,7 +3597,7 @@ class Article {
                }
 
                if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
-                       $wgMessageCache->replace( $shortTitle, $text );
+                       MessageCache::singleton()->replace( $shortTitle, $text );
                }
 
                wfProfileOut( __METHOD__ );
@@ -3715,10 +3613,8 @@ class Article {
         * anymore.
         */
        public function createUpdates( $rev ) {
-               $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
-               $this->mTotalAdjustment = 1;
                $this->editUpdates( $rev->getText(), $rev->getComment(),
-                       $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
+                       $rev->isMinor(), wfTimestamp(), $rev->getId(), true, null, true );
        }
 
        /**
@@ -3745,15 +3641,16 @@ class Article {
                }
 
                $revision = Revision::newFromId( $oldid );
+               $timestamp = $revision->getTimestamp();
 
                $current = ( $oldid == $this->mLatest );
-               $td = $wgLang->timeanddate( $this->mTimestamp, true );
-               $tddate = $wgLang->date( $this->mTimestamp, true );
-               $tdtime = $wgLang->time( $this->mTimestamp, true );
-               $sk = $wgUser->getSkin();
+               $td = $wgLang->timeanddate( $timestamp, true );
+               $tddate = $wgLang->date( $timestamp, true );
+               $tdtime = $wgLang->time( $timestamp, true );
+
                $lnk = $current
                        ? wfMsgHtml( 'currentrevisionlink' )
-                       : $sk->link(
+                       : Linker::link(
                                $this->mTitle,
                                wfMsgHtml( 'currentrevisionlink' ),
                                array(),
@@ -3762,7 +3659,7 @@ class Article {
                        );
                $curdiff = $current
                        ? wfMsgHtml( 'diff' )
-                       : $sk->link(
+                       : Linker::link(
                                $this->mTitle,
                                wfMsgHtml( 'diff' ),
                                array(),
@@ -3774,7 +3671,7 @@ class Article {
                        );
                $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
                $prevlink = $prev
-                       ? $sk->link(
+                       ? Linker::link(
                                $this->mTitle,
                                wfMsgHtml( 'previousrevision' ),
                                array(),
@@ -3786,7 +3683,7 @@ class Article {
                        )
                        : wfMsgHtml( 'previousrevision' );
                $prevdiff = $prev
-                       ? $sk->link(
+                       ? Linker::link(
                                $this->mTitle,
                                wfMsgHtml( 'diff' ),
                                array(),
@@ -3799,7 +3696,7 @@ class Article {
                        : wfMsgHtml( 'diff' );
                $nextlink = $current
                        ? wfMsgHtml( 'nextrevision' )
-                       : $sk->link(
+                       : Linker::link(
                                $this->mTitle,
                                wfMsgHtml( 'nextrevision' ),
                                array(),
@@ -3811,7 +3708,7 @@ class Article {
                        );
                $nextdiff = $current
                        ? wfMsgHtml( 'diff' )
-                       : $sk->link(
+                       : Linker::link(
                                $this->mTitle,
                                wfMsgHtml( 'diff' ),
                                array(),
@@ -3828,23 +3725,22 @@ class Article {
                $canHide = $wgUser->isAllowed( 'deleterevision' );
                if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
                        if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
-                               $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
+                               $cdel = Linker::revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
                        } else {
                                $query = array(
                                        'type'   => 'revision',
                                        'target' => $this->mTitle->getPrefixedDbkey(),
                                        'ids'    => $oldid
                                );
-                               $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
+                               $cdel = Linker::revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
                        }
                        $cdel .= ' ';
                }
 
                # Show user links if allowed to see them. If hidden, then show them only if requested...
-               $userlinks = $sk->revUserTools( $revision, !$unhide );
+               $userlinks = Linker::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';
 
@@ -3863,7 +3759,7 @@ class Article {
                        "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
                        $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
 
-               $wgOut->setSubtitle( $r );
+               $wgOut->addHTML( $r );
        }
 
        /**
@@ -3873,10 +3769,12 @@ class Article {
         * @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, User $user = null ) {
+       public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
                global $wgParser;
 
                if ( $user === null ) {
@@ -3884,7 +3782,11 @@ class Article {
                        $user = $wgUser;
                }
 
-               return $wgParser->preSaveTransform( $text, $this->mTitle, $user, ParserOptions::newFromUser( $user ) );
+               if ( $popts === null ) {
+                       $popts = ParserOptions::newFromUser( $user );
+               }
+
+               return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
        }
 
        /* Caching functions */
@@ -4033,10 +3935,10 @@ class Article {
 
        /**
         * Clears caches when article is deleted
+        *
+        * @param $title Title
         */
        public static function onArticleDelete( $title ) {
-               global $wgMessageCache;
-
                # Update existence markers on article/talk tabs...
                if ( $title->isTalkPage() ) {
                        $other = $title->getSubjectPage();
@@ -4055,7 +3957,7 @@ class Article {
 
                # Messages
                if ( $title->getNamespace() == NS_MEDIAWIKI ) {
-                       $wgMessageCache->replace( $title->getDBkey(), false );
+                       MessageCache::singleton()->replace( $title->getDBkey(), false );
                }
 
                # Images
@@ -4107,106 +4009,6 @@ class Article {
                $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
        }
 
-       /**
-        * Info about this page
-        * Called for ?action=info when $wgAllowPageInfo is on.
-        */
-       public function info() {
-               global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
-
-               if ( !$wgAllowPageInfo ) {
-                       $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
-                       return;
-               }
-
-               $page = $this->mTitle->getSubjectPage();
-
-               $wgOut->setPagetitle( $page->getPrefixedText() );
-               $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
-               $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
-
-               if ( !$this->mTitle->exists() ) {
-                       $wgOut->addHTML( '<div class="noarticletext">' );
-                       if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
-                               // This doesn't quite make sense; the user is asking for
-                               // information about the _page_, not the message... -- RC
-                               $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
-                       } else {
-                               $msg = $wgUser->isLoggedIn()
-                                       ? 'noarticletext'
-                                       : 'noarticletextanon';
-                               $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
-                       }
-
-                       $wgOut->addHTML( '</div>' );
-               } else {
-                       $dbr = wfGetDB( DB_SLAVE );
-                       $wl_clause = array(
-                               'wl_title'     => $page->getDBkey(),
-                               'wl_namespace' => $page->getNamespace() );
-                       $numwatchers = $dbr->selectField(
-                               'watchlist',
-                               'COUNT(*)',
-                               $wl_clause,
-                               __METHOD__,
-                               $this->getSelectOptions() );
-
-                       $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>' );
-
-                       if ( $talkInfo ) {
-                               $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
-                       }
-
-                       $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
-
-                       if ( $talkInfo ) {
-                               $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
-                       }
-
-                       $wgOut->addHTML( '</ul>' );
-               }
-       }
-
-       /**
-        * Return the total number of edits and number of unique editors
-        * on a given page. If page does not exist, returns false.
-        *
-        * @param $title Title object
-        * @return mixed array or boolean false
-        */
-       public function pageCountInfo( $title ) {
-               $id = $title->getArticleId();
-
-               if ( $id == 0 ) {
-                       return false;
-               }
-
-               $dbr = wfGetDB( DB_SLAVE );
-               $rev_clause = array( 'rev_page' => $id );
-               $edits = $dbr->selectField(
-                       'revision',
-                       'COUNT(rev_page)',
-                       $rev_clause,
-                       __METHOD__,
-                       $this->getSelectOptions()
-               );
-               $authors = $dbr->selectField(
-                       'revision',
-                       'COUNT(DISTINCT rev_user_text)',
-                       $rev_clause,
-                       __METHOD__,
-                       $this->getSelectOptions()
-               );
-
-               return array( 'edits' => $edits, 'authors' => $authors );
-       }
-
        /**
         * Return a list of templates used by this article.
         * Uses the templatelinks table
@@ -4378,7 +4180,7 @@ 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)
+        * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
         * @return mixed ParserOptions object or boolean false
         */
        public function getParserOptions( $canonical = false ) {
@@ -4389,23 +4191,33 @@ class Article {
                        $parserOptions = new ParserOptions( $user );
                        $parserOptions->setTidy( true );
                        $parserOptions->enableLimitReport();
-                       
+
                        if ( $canonical ) {
                                $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
                                return $parserOptions;
                        }
                        $this->mParserOptions = $parserOptions;
                }
-
-               // Clone to allow modifications of the return value without affecting
-               // the cache
+               // Clone to allow modifications of the return value without affecting cache
                return clone $this->mParserOptions;
        }
 
+       /**
+       * Get parser options suitable for rendering the primary article wikitext
+       * @param User $user
+       * @return ParserOptions
+       */
+       public function makeParserOptions( User $user ) {
+               $options = ParserOptions::newFromUser( $user );
+               $options->enableLimitReport(); // show inclusion/loop reports
+               $options->setTidy( true ); // fix bad HTML
+               return $options;
+       }
+
        /**
         * Updates cascading protections
         *
-        * @param $parserOutput mixed ParserOptions object, or boolean false
+        * @param $parserOutput ParserOutput object, or boolean false
         **/
        protected function doCascadeProtectionUpdates( $parserOutput ) {
                if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
@@ -4524,7 +4336,7 @@ class Article {
         * @since 1.16 (r52326) for LiquidThreads
         *
         * @param $oldid mixed integer Revision ID or null
-        * @return ParserOutput
+        * @return ParserOutput or false if the given revsion ID is not found
         */
        public function getParserOutput( $oldid = null ) {
                global $wgEnableParserCache, $wgUser;
@@ -4541,24 +4353,59 @@ 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 );
+               return $this->getOutputFromWikitext( $text, $useParserCache );
+       }
+
+       /**
+        * Sets the context this Article is executed in
+        *
+        * @param $context RequestContext
+        * @since 1.18
+        */
+       public function setContext( $context ) {
+               $this->mContext = $context;
+       }
+
+       /**
+        * Gets the context this Article is executed in
+        *
+        * @return RequestContext
+        * @since 1.18
+        */
+       public function getContext() {
+               if ( $this->mContext instanceof RequestContext ) {
+                       return $this->mContext;
                } else {
-                       return $parserOutput;
+                       wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
+                       return RequestContext::getMain();
                }
        }
 
 }
 
 class PoolWorkArticleView extends PoolCounterWork {
+
+       /**
+        * @var Article
+        */
        private $mArticle;
 
        function __construct( $article, $key, $useParserCache, $parserOptions ) {
@@ -4593,6 +4440,9 @@ class PoolWorkArticleView extends PoolCounterWork {
                return $this->mArticle->tryDirtyCache();
        }
 
+       /**
+        * @param  $status Status
+        */
        function error( $status ) {
                global $wgOut;