* Use local context to get messages
[lhc/web/wiklou.git] / includes / EditPage.php
index 0537406..8f4761c 100644 (file)
  * headaches, which may be fatal.
  */
 class EditPage {
+
+       /**
+        * Status: Article successfully updated
+        */
        const AS_SUCCESS_UPDATE            = 200;
+
+       /**
+        * Status: Article successfully created
+        */
        const AS_SUCCESS_NEW_ARTICLE       = 201;
+
+       /**
+        * Status: Article update aborted by a hook function
+        */
        const AS_HOOK_ERROR                = 210;
+
+       /**
+        * Status: The filter function set in $wgFilterCallback returned true (= block it)
+        */
        const AS_FILTERING                 = 211;
+
+       /**
+        * Status: A hook function returned an error
+        */
        const AS_HOOK_ERROR_EXPECTED       = 212;
+
+       /**
+        * Status: User is blocked from editting this page
+        */
        const AS_BLOCKED_PAGE_FOR_USER     = 215;
+
+       /**
+        * Status: Content too big (> $wgMaxArticleSize)
+        */
        const AS_CONTENT_TOO_BIG           = 216;
+
+       /**
+        * Status: User cannot edit? (not used)
+        */
        const AS_USER_CANNOT_EDIT          = 217;
+
+       /**
+        * Status: this anonymous user is not allowed to edit this page
+        */
        const AS_READ_ONLY_PAGE_ANON       = 218;
+
+       /**
+        * Status: this logged in user is not allowed to edit this page
+        */
        const AS_READ_ONLY_PAGE_LOGGED     = 219;
+
+       /**
+        * Status: wiki is in readonly mode (wfReadOnly() == true)
+        */
        const AS_READ_ONLY_PAGE            = 220;
+
+       /**
+        * Status: rate limiter for action 'edit' was tripped
+        */
        const AS_RATE_LIMITED              = 221;
+
+       /**
+        * Status: article was deleted while editting and param wpRecreate == false or form
+        * was not posted
+        */
        const AS_ARTICLE_WAS_DELETED       = 222;
+
+       /**
+        * Status: user tried to create this page, but is not allowed to do that
+        * ( Title->usercan('create') == false )
+        */
        const AS_NO_CREATE_PERMISSION      = 223;
+
+       /**
+        * Status: user tried to create a blank page
+        */
        const AS_BLANK_ARTICLE             = 224;
+
+       /**
+        * Status: (non-resolvable) edit conflict
+        */
        const AS_CONFLICT_DETECTED         = 225;
+
+       /**
+        * Status: no edit summary given and the user has forceeditsummary set and the user is not
+        * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
+        */
        const AS_SUMMARY_NEEDED            = 226;
+
+       /**
+        * Status: user tried to create a new section without content
+        */
        const AS_TEXTBOX_EMPTY             = 228;
+
+       /**
+        * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
+        */
        const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
+
+       /**
+        * not used
+        */
        const AS_OK                        = 230;
+
+       /**
+        * Status: WikiPage::doEdit() was unsuccessfull
+        */
        const AS_END                       = 231;
+
+       /**
+        * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
+        */
        const AS_SPAM_ERROR                = 232;
+
+       /**
+        * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
+        */
        const AS_IMAGE_REDIRECT_ANON       = 233;
+
+       /**
+        * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
+        */
        const AS_IMAGE_REDIRECT_LOGGED     = 234;
 
        /**
@@ -84,6 +183,12 @@ class EditPage {
         */
        var $mParserOutput;
 
+       /**
+        * Has a summary been preset using GET parameter &summary= ?
+        * @var Bool
+        */
+       var $hasPresetSummary = false;
+
        var $mBaseRevision = false;
        var $mShowSummaryField = true;
 
@@ -91,7 +196,7 @@ class EditPage {
        var $save = false, $preview = false, $diff = false;
        var $minoredit = false, $watchthis = false, $recreate = false;
        var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
-       var $edittime = '', $section = '', $starttime = '';
+       var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
        var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
 
        # Placeholders for text injection by hooks (must be HTML)
@@ -113,10 +218,9 @@ class EditPage {
        public $suppressIntro = false;
 
        /**
-        * @todo document
         * @param $article Article
         */
-       public function __construct( $article ) {
+       public function __construct( Article $article ) {
                $this->mArticle = $article;
                $this->mTitle = $article->getTitle();
        }
@@ -184,7 +288,7 @@ class EditPage {
                }
 
                wfProfileIn( __METHOD__ );
-               wfDebug( __METHOD__.": enter\n" );
+               wfDebug( __METHOD__ . ": enter\n" );
 
                // If they used redlink=1 and the page exists, redirect to the main article
                if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
@@ -235,15 +339,7 @@ class EditPage {
                        return;
                }
 
-               $wgOut->addModules( array( 'mediawiki.action.edit' ) );
-
-               if ( $wgUser->getOption( 'uselivepreview', false ) ) {
-                       $wgOut->addModules( 'mediawiki.legacy.preview' );
-               }
-               // Bug #19334: textarea jumps when editing articles in IE8
-               $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
-
-               wfProfileIn( __METHOD__."-business-end" );
+               wfProfileIn( __METHOD__ . "-business-end" );
 
                $this->isConflict = false;
                // css / js subpages of user pages get a special treatment
@@ -254,36 +350,8 @@ class EditPage {
                $this->isNew                = !$this->mTitle->exists() || $this->section == 'new';
 
                # Show applicable editing introductions
-               if ( $this->formtype == 'initial' || $this->firsttime )
+               if ( $this->formtype == 'initial' || $this->firsttime ) {
                        $this->showIntro();
-
-               if ( $this->mTitle->isTalkPage() ) {
-                       $wgOut->addWikiMsg( 'talkpagetext' );
-               }
-
-               # Optional notices on a per-namespace and per-page basis
-               $editnotice_ns   = 'editnotice-'.$this->mTitle->getNamespace();
-               $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
-               if ( $editnotice_ns_message->exists() ) {
-                       $wgOut->addWikiText( $editnotice_ns_message->plain() );
-               }
-               if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
-                       $parts = explode( '/', $this->mTitle->getDBkey() );
-                       $editnotice_base = $editnotice_ns;
-                       while ( count( $parts ) > 0 ) {
-                               $editnotice_base .= '-'.array_shift( $parts );
-                               $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
-                               if ( $editnotice_base_msg->exists() ) {
-                                       $wgOut->addWikiText( $editnotice_base_msg->plain()  );
-                               }
-                       }
-               } else {
-                       # Even if there are no subpages in namespace, we still don't want / in MW ns.
-                       $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
-                       $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
-                       if ( $editnoticeMsg->exists() ) {
-                               $wgOut->addWikiText( $editnoticeMsg->plain() );
-                       }
                }
 
                # Attempt submission here.  This will check for edit conflicts,
@@ -293,7 +361,7 @@ class EditPage {
 
                if ( 'save' == $this->formtype ) {
                        if ( !$this->attemptSave() ) {
-                               wfProfileOut( __METHOD__."-business-end" );
+                               wfProfileOut( __METHOD__ . "-business-end" );
                                wfProfileOut( __METHOD__ );
                                return;
                        }
@@ -304,18 +372,18 @@ class EditPage {
                if ( 'initial' == $this->formtype || $this->firsttime ) {
                        if ( $this->initialiseForm() === false ) {
                                $this->noSuchSectionPage();
-                               wfProfileOut( __METHOD__."-business-end" );
+                               wfProfileOut( __METHOD__ . "-business-end" );
                                wfProfileOut( __METHOD__ );
                                return;
                        }
-                       if ( !$this->mTitle->getArticleId() )
+                       if ( !$this->mTitle->getArticleID() )
                                wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
                        else
                                wfRunHooks( 'EditFormInitialText', array( $this ) );
                }
 
                $this->showEditForm();
-               wfProfileOut( __METHOD__."-business-end" );
+               wfProfileOut( __METHOD__ . "-business-end" );
                wfProfileOut( __METHOD__ );
        }
 
@@ -332,7 +400,7 @@ class EditPage {
                }
                # Ignore some permissions errors when a user is just previewing/viewing diffs
                $remove = array();
-               foreach( $permErrors as $error ) {
+               foreach ( $permErrors as $error ) {
                        if ( ( $this->preview || $this->diff ) &&
                                ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
                        {
@@ -346,7 +414,7 @@ class EditPage {
        /**
         * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
         * but with the following differences:
-        * - If redlink=1, the user will be redirect to the page
+        * - If redlink=1, the user will be redirected to the page
         * - If there is content to display or the error occurs while either saving,
         *   previewing or showing the difference, it will be a
         *   "View source for ..." page displaying the source code after the error message.
@@ -371,7 +439,7 @@ class EditPage {
                # Use the normal message if there's nothing to display
                if ( $this->firsttime && $content === '' ) {
                        $action = $this->mTitle->exists() ? 'edit' :
-                               ( $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
+                               ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
                        throw new PermissionsError( $action, $permErrors );
                }
 
@@ -406,6 +474,8 @@ class EditPage {
         * @deprecated in 1.19; use displayPermissionsError() instead
         */
        function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
+               wfDeprecated( __METHOD__, '1.19' );
+
                global $wgRequest, $wgOut;
                if ( $wgRequest->getBool( 'redlink' ) ) {
                        // The edit page was reached via a red link.
@@ -437,7 +507,7 @@ class EditPage {
                        // Standard preference behaviour
                        return true;
                } elseif ( !$this->mTitle->exists() &&
-                 isset($wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]) &&
+                 isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] ) &&
                  $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
                {
                        // Categories are special
@@ -454,7 +524,7 @@ class EditPage {
         * @return bool
         */
        protected function isWrongCaseCssJsPage() {
-               if( $this->mTitle->isCssJsSubpage() ) {
+               if ( $this->mTitle->isCssJsSubpage() ) {
                        $name = $this->mTitle->getSkinFromCssJsSubpage();
                        $skins = array_merge(
                                array_keys( Skin::getSkinNames() ),
@@ -478,7 +548,7 @@ class EditPage {
        }
 
        /**
-        * @todo document
+        * This function collects the form data and uses it to populate various member variables.
         * @param $request WebRequest
         */
        function importFormData( &$request ) {
@@ -494,29 +564,39 @@ class EditPage {
                        # Also remove trailing whitespace, but don't remove _initial_
                        # whitespace from the text boxes. This may be significant formatting.
                        $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
-                       if ( !$request->getCheck('wpTextbox2') ) {
+                       if ( !$request->getCheck( 'wpTextbox2' ) ) {
                                // Skip this if wpTextbox2 has input, it indicates that we came
                                // from a conflict page with raw page text, not a custom form
                                // modified by subclasses
-                               wfProfileIn( get_class($this)."::importContentFormData" );
+                               wfProfileIn( get_class( $this ) . "::importContentFormData" );
                                $textbox1 = $this->importContentFormData( $request );
-                               if ( isset($textbox1) )
+                               if ( isset( $textbox1 ) )
                                        $this->textbox1 = $textbox1;
-                               wfProfileOut( get_class($this)."::importContentFormData" );
+                               wfProfileOut( get_class( $this ) . "::importContentFormData" );
                        }
 
                        # Truncate for whole multibyte characters. +5 bytes for ellipsis
                        $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
 
-                       # Remove extra headings from summaries and new sections.
-                       $this->summary = preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary);
+                       # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
+                       # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
+                       # section titles.
+                       $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
+
+                       # Treat sectiontitle the same way as summary.
+                       # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
+                       # currently doing double duty as both edit summary and section title. Right now this
+                       # is just to allow API edits to work around this limitation, but this should be
+                       # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
+                       $this->sectiontitle = $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 250 );
+                       $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
 
                        $this->edittime = $request->getVal( 'wpEdittime' );
                        $this->starttime = $request->getVal( 'wpStarttime' );
 
                        $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
 
-                       if ($this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null) {
+                       if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
                                // wpTextbox1 field is missing, possibly due to being "too big"
                                // according to some filter rules such as Suhosin's setting for
                                // suhosin.request.max_value_length (d'oh)
@@ -576,30 +656,38 @@ class EditPage {
                        {
                                $this->allowBlankSummary = true;
                        } else {
-                               $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary');
+                               $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary' );
                        }
 
                        $this->autoSumm = $request->getText( 'wpAutoSummary' );
                } else {
                        # Not a posted form? Start with nothing.
                        wfDebug( __METHOD__ . ": Not a posted form.\n" );
-                       $this->textbox1  = '';
-                       $this->summary   = '';
-                       $this->edittime  = '';
-                       $this->starttime = wfTimestampNow();
-                       $this->edit      = false;
-                       $this->preview   = false;
-                       $this->save      = false;
-                       $this->diff      = false;
-                       $this->minoredit = false;
-                       $this->watchthis = $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
-                       $this->recreate  = false;
-
+                       $this->textbox1     = '';
+                       $this->summary      = '';
+                       $this->sectiontitle = '';
+                       $this->edittime     = '';
+                       $this->starttime    = wfTimestampNow();
+                       $this->edit         = false;
+                       $this->preview      = false;
+                       $this->save         = false;
+                       $this->diff         = false;
+                       $this->minoredit    = false;
+                       $this->watchthis    = $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
+                       $this->recreate     = false;
+
+                       // When creating a new section, we can preload a section title by passing it as the
+                       // preloadtitle parameter in the URL (Bug 13100)
                        if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
+                               $this->sectiontitle = $request->getVal( 'preloadtitle' );
+                               // Once wpSummary isn't being use for setting section titles, we should delete this.
                                $this->summary = $request->getVal( 'preloadtitle' );
                        }
                        elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
                                $this->summary = $request->getText( 'summary' );
+                               if ( $this->summary !== '' ) {
+                                       $this->hasPresetSummary = true;
+                               }
                        }
 
                        if ( $request->getVal( 'minor' ) ) {
@@ -610,7 +698,6 @@ class EditPage {
                $this->bot = $request->getBool( 'bot', true );
                $this->nosummary = $request->getBool( 'nosummary' );
 
-               // @todo FIXME: Unused variable?
                $this->oldid = $request->getInt( 'oldid' );
 
                $this->live = $request->getCheck( 'live' );
@@ -678,91 +765,85 @@ class EditPage {
                global $wgOut, $wgRequest, $wgParser;
 
                wfProfileIn( __METHOD__ );
-               # Get variables from query string :P
-               $section = $wgRequest->getVal( 'section' );
 
-               $preload = $wgRequest->getVal( 'preload',
-                       // Custom preload text for new sections
-                       $section === 'new' ? 'MediaWiki:addsection-preload' : '' );
-               $undoafter = $wgRequest->getVal( 'undoafter' );
-               $undo = $wgRequest->getVal( 'undo' );
+               $text = false;
 
                // For message page not locally set, use the i18n message.
                // For other non-existent articles, use preload text if any.
-               if ( !$this->mTitle->exists() ) {
-                       if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
+               if ( !$this->mTitle->exists() || $this->section == 'new' ) {
+                       if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
                                # If this is a system message, get the default text.
                                $text = $this->mTitle->getDefaultMessageText();
-                               if( $text === false ) {
-                                       $text = $this->getPreloadedText( $preload );
-                               }
-                       } else {
+                       }
+                       if ( $text === false ) {
                                # If requested, preload some text.
+                               $preload = $wgRequest->getVal( 'preload',
+                                       // Custom preload text for new sections
+                                       $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
                                $text = $this->getPreloadedText( $preload );
                        }
                // For existing pages, get text based on "undo" or section parameters.
                } else {
-                       $text = $this->mArticle->getContent();
-                       if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
-                               # If they got undoafter and undo round the wrong way, switch them
-                               list( $undo, $undoafter ) = array( $undoafter, $undo );
-                       }
-                       if ( $undo > 0 && $undo > $undoafter ) {
-                               # Undoing a specific edit overrides section editing; section-editing
-                               # doesn't work with undoing.
-                               if ( $undoafter ) {
+                       if ( $this->section != '' ) {
+                               // Get section edit text (returns $def_text for invalid sections)
+                               $text = $wgParser->getSection( $this->getOriginalContent(), $this->section, $def_text );
+                       } else {
+                               $undoafter = $wgRequest->getInt( 'undoafter' );
+                               $undo = $wgRequest->getInt( 'undo' );
+
+                               if ( $undo > 0 && $undoafter > 0 ) {
+                                       if ( $undo < $undoafter ) {
+                                               # If they got undoafter and undo round the wrong way, switch them
+                                               list( $undo, $undoafter ) = array( $undoafter, $undo );
+                                       }
+
                                        $undorev = Revision::newFromId( $undo );
                                        $oldrev = Revision::newFromId( $undoafter );
-                               } else {
-                                       $undorev = Revision::newFromId( $undo );
-                                       $oldrev = $undorev ? $undorev->getPrevious() : null;
-                               }
 
-                               # Sanity check, make sure it's the right page,
-                               # the revisions exist and they were not deleted.
-                               # Otherwise, $text will be left as-is.
-                               if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
-                                       $undorev->getPage() == $oldrev->getPage() &&
-                                       $undorev->getPage() == $this->mArticle->getID() &&
-                                       !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
-                                       !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
-
-                                       $undotext = $this->mArticle->getUndoText( $undorev, $oldrev );
-                                       if ( $undotext === false ) {
-                                               # Warn the user that something went wrong
-                                               $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-failure">' .
-                                                       wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
-                                       } else {
-                                               $text = $undotext;
-                                               # Inform the user of our success and set an automatic edit summary
-                                               $this->editFormPageTop .= $wgOut->parse( '<div class="mw-undo-success">' .
-                                                       wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
-                                               $firstrev = $oldrev->getNext();
-                                               # If we just undid one rev, use an autosummary
-                                               if ( $firstrev->getId() == $undo ) {
-                                                       $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
-                                                       if ( $this->summary === '' ) {
-                                                               $this->summary = $undoSummary;
-                                                       } else {
-                                                               $this->summary = $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary;
+                                       # Sanity check, make sure it's the right page,
+                                       # the revisions exist and they were not deleted.
+                                       # Otherwise, $text will be left as-is.
+                                       if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
+                                               $undorev->getPage() == $oldrev->getPage() &&
+                                               $undorev->getPage() == $this->mTitle->getArticleID() &&
+                                               !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
+                                               !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
+
+                                               $text = $this->mArticle->getUndoText( $undorev, $oldrev );
+                                               if ( $text === false ) {
+                                                       # Warn the user that something went wrong
+                                                       $undoMsg = 'failure';
+                                               } else {
+                                                       # Inform the user of our success and set an automatic edit summary
+                                                       $undoMsg = 'success';
+
+                                                       # If we just undid one rev, use an autosummary
+                                                       $firstrev = $oldrev->getNext();
+                                                       if ( $firstrev->getId() == $undo ) {
+                                                               $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
+                                                               if ( $this->summary === '' ) {
+                                                                       $this->summary = $undoSummary;
+                                                               } else {
+                                                                       $this->summary = $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary;
+                                                               }
+                                                               $this->undidRev = $undo;
                                                        }
-                                                       $this->undidRev = $undo;
+                                                       $this->formtype = 'diff';
                                                }
-                                               $this->formtype = 'diff';
+                                       } else {
+                                               // Failed basic sanity checks.
+                                               // Older revisions may have been removed since the link
+                                               // was created, or we may simply have got bogus input.
+                                               $undoMsg = 'norev';
                                        }
-                               } else {
-                                       // Failed basic sanity checks.
-                                       // Older revisions may have been removed since the link
-                                       // was created, or we may simply have got bogus input.
-                                       $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-norev">' .
-                                               wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
+
+                                       $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
+                                       $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
+                                               wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
                                }
-                       } elseif ( $section != '' ) {
-                               if ( $section == 'new' ) {
-                                       $text = $this->getPreloadedText( $preload );
-                               } else {
-                                       // Get section edit text (returns $def_text for invalid sections)
-                                       $text = $wgParser->getSection( $text, $section, $def_text );
+
+                               if ( $text === false ) {
+                                       $text = $this->getOriginalContent();
                                }
                        }
                }
@@ -771,6 +852,48 @@ class EditPage {
                return $text;
        }
 
+       /**
+        * Get the content of the wanted revision, without section extraction.
+        *
+        * The result of this function can be used to compare user's input with
+        * section replaced in its context (using WikiPage::replaceSection())
+        * to the original text of the edit.
+        *
+        * This difers from Article::getContent() that when a missing revision is
+        * encountered the result will be an empty string and not the
+        * 'missing-article' message.
+        *
+        * @since 1.19
+        * @return string
+        */
+       private function getOriginalContent() {
+               if ( $this->section == 'new' ) {
+                       return $this->getCurrentText();
+               }
+               $revision = $this->mArticle->getRevisionFetched();
+               if ( $revision === null ) {
+                       return '';
+               }
+               return $this->mArticle->getContent();
+       }
+
+       /**
+        * Get the actual text of the page. This is basically similar to
+        * WikiPage::getRawText() except that when the page doesn't exist an empty
+        * string is returned instead of false.
+        *
+        * @since 1.19
+        * @return string
+        */
+       private function getCurrentText() {
+               $text = $this->mArticle->getRawText();
+               if ( $text === false ) {
+                       return '';
+               } else {
+                       return $text;
+               }
+       }
+
        /**
         * Use this method before edit() to preload some text into the edit box
         *
@@ -793,7 +916,7 @@ class EditPage {
                if ( !empty( $this->mPreloadText ) ) {
                        return $this->mPreloadText;
                }
-               
+
                if ( $preload === '' ) {
                        return '';
                }
@@ -867,7 +990,8 @@ class EditPage {
 
                        case self::AS_SUCCESS_NEW_ARTICLE:
                                $query = $resultDetails['redirect'] ? 'redirect=no' : '';
-                               $wgOut->redirect( $this->mTitle->getFullURL( $query ) );
+                               $anchor = isset ( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
+                               $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
                                return false;
 
                        case self::AS_SUCCESS_UPDATE:
@@ -896,7 +1020,7 @@ class EditPage {
                                return false;
 
                        case self::AS_BLOCKED_PAGE_FOR_USER:
-                               throw new UserBlockedError( $wgUser->mBlock );
+                               throw new UserBlockedError( $wgUser->getBlock() );
 
                        case self::AS_IMAGE_REDIRECT_ANON:
                        case self::AS_IMAGE_REDIRECT_LOGGED:
@@ -1100,20 +1224,34 @@ class EditPage {
                                return $status;
                        }
 
-                       # Handle the user preference to force summaries here. Check if it's not a redirect.
-                       if ( !$this->allowBlankSummary && !Title::newFromRedirect( $this->textbox1 ) ) {
-                               if ( md5( $this->summary ) == $this->autoSumm ) {
-                                       $this->missingSummary = true;
-                                       $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
-                                       $status->value = self::AS_SUMMARY_NEEDED;
-                                       wfProfileOut( __METHOD__ );
-                                       return $status;
-                               }
-                       }
-
                        $text = $this->textbox1;
-                       if ( $this->section == 'new' && $this->summary != '' ) {
-                               $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
+                       $result['sectionanchor'] = '';
+                       if ( $this->section == 'new' ) {
+                               if ( $this->sectiontitle !== '' ) {
+                                       // Insert the section title above the content.
+                                       $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle ) . "\n\n" . $text;
+
+                                       // Jump to the new section
+                                       $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
+
+                                       // If no edit summary was specified, create one automatically from the section
+                                       // title and have it link to the new section. Otherwise, respect the summary as
+                                       // passed.
+                                       if ( $this->summary === '' ) {
+                                               $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
+                                               $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
+                                       }
+                               } elseif ( $this->summary !== '' ) {
+                                       // Insert the section title above the content.
+                                       $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
+
+                                       // Jump to the new section
+                                       $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
+
+                                       // Create a link to the new section from the edit summary.
+                                       $cleanSummary = $wgParser->stripSectionName( $this->summary );
+                                       $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
+                               }
                        }
 
                        $status->value = self::AS_SUCCESS_NEW_ARTICLE;
@@ -1123,10 +1261,11 @@ class EditPage {
                        # Article exists. Check for edit conflict.
 
                        $this->mArticle->clear(); # Force reload of dates, etc.
+                       $timestamp = $this->mArticle->getTimestamp();
 
-                       wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
+                       wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
 
-                       if ( $this->mArticle->getTimestamp() != $this->edittime ) {
+                       if ( $timestamp != $this->edittime ) {
                                $this->isConflict = true;
                                if ( $this->section == 'new' ) {
                                        if ( $this->mArticle->getUserText() == $wgUser->getName() &&
@@ -1138,7 +1277,7 @@ class EditPage {
                                        } else {
                                                // New comment; suppress conflict.
                                                $this->isConflict = false;
-                                               wfDebug( __METHOD__ .": conflict suppressed; new section\n" );
+                                               wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
                                        }
                                } elseif ( $this->section == '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime ) ) {
                                        # Suppress edit conflict with self, except for section edits where merging is required.
@@ -1147,13 +1286,20 @@ class EditPage {
                                }
                        }
 
+                       // If sectiontitle is set, use it, otherwise use the summary as the section title (for
+                       // backwards compatibility with old forms/bots).
+                       if ( $this->sectiontitle !== '' ) {
+                               $sectionTitle = $this->sectiontitle;
+                       } else {
+                               $sectionTitle = $this->summary;
+                       }
+
                        if ( $this->isConflict ) {
-                               wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
-                                       $this->mArticle->getTimestamp() . "')\n" );
-                               $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
+                               wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
+                               $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle, $this->edittime );
                        } else {
                                wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
-                               $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
+                               $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle );
                        }
                        if ( is_null( $text ) ) {
                                wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
@@ -1195,7 +1341,7 @@ class EditPage {
 
                        # Handle the user preference to force summaries here, but not for null edits
                        if ( $this->section != 'new' && !$this->allowBlankSummary
-                               && 0 != strcmp( $this->mArticle->getContent(), $text )
+                               && $this->getOriginalContent() != $text
                                && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
                        {
                                if ( md5( $this->summary ) == $this->autoSumm ) {
@@ -1230,7 +1376,16 @@ class EditPage {
                                        wfProfileOut( __METHOD__ );
                                        return $status;
                                }
-                               if ( $this->summary != '' ) {
+                               if ( $this->sectiontitle !== '' ) {
+                                       $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
+                                       // If no edit summary was specified, create one automatically from the section
+                                       // title and have it link to the new section. Otherwise, respect the summary as
+                                       // passed.
+                                       if ( $this->summary === '' ) {
+                                               $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
+                                               $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
+                                       }
+                               } elseif ( $this->summary !== '' ) {
                                        $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
                                        # This is a new section, so create a link to the new section
                                        # in the revision summary.
@@ -1297,13 +1452,13 @@ class EditPage {
                global $wgUser;
                if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
                        $dbw = wfGetDB( DB_MASTER );
-                       $dbw->begin();
+                       $dbw->begin( __METHOD__ );
                        if ( $this->watchthis ) {
                                WatchAction::doWatch( $this->mTitle, $wgUser );
                        } else {
                                WatchAction::doUnwatch( $this->mTitle, $wgUser );
                        }
-                       $dbw->commit();
+                       $dbw->commit( __METHOD__ );
                }
        }
 
@@ -1318,18 +1473,18 @@ class EditPage {
         * @return bool
         */
        protected function userWasLastToEdit( $id, $edittime ) {
-               if( !$id ) return false;
+               if ( !$id ) return false;
                $dbw = wfGetDB( DB_MASTER );
                $res = $dbw->select( 'revision',
                        'rev_user',
                        array(
-                               'rev_page' => $this->mArticle->getId(),
-                               'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
+                               'rev_page' => $this->mTitle->getArticleID(),
+                               'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
                        ),
                        __METHOD__,
                        array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
                foreach ( $res as $row ) {
-                       if( $row->rev_user != $id ) {
+                       if ( $row->rev_user != $id ) {
                                return false;
                        }
                }
@@ -1344,7 +1499,7 @@ class EditPage {
         *
         * @return bool
         */
-       function mergeChangesInto( &$editText ){
+       function mergeChangesInto( &$editText ) {
                wfProfileIn( __METHOD__ );
 
                $db = wfGetDB( DB_MASTER );
@@ -1395,7 +1550,7 @@ class EditPage {
         *
         * @param $text string
         *
-        * @return string|false matching string or false
+        * @return string|bool matching string or false
         */
        public static function matchSpamRegex( $text ) {
                global $wgSpamRegex;
@@ -1409,7 +1564,7 @@ class EditPage {
         *
         * @parma $text string
         *
-        * @return string|false  matching string or false
+        * @return string|bool  matching string or false
         */
        public static function matchSummarySpamRegex( $text ) {
                global $wgSummarySpamRegex;
@@ -1423,9 +1578,9 @@ class EditPage {
         * @return bool|string
         */
        protected static function matchSpamRegexInternal( $text, $regexes ) {
-               foreach( $regexes as $regex ) {
+               foreach ( $regexes as $regex ) {
                        $matches = array();
-                       if( preg_match( $regex, $text, $matches ) ) {
+                       if ( preg_match( $regex, $text, $matches ) ) {
                                return $matches[0];
                        }
                }
@@ -1433,8 +1588,21 @@ class EditPage {
        }
 
        function setHeaders() {
-               global $wgOut;
+               global $wgOut, $wgUser;
+
+               $wgOut->addModules( 'mediawiki.action.edit' );
+
+               if ( $wgUser->getOption( 'uselivepreview', false ) ) {
+                       $wgOut->addModules( 'mediawiki.legacy.preview' );
+               }
+               // Bug #19334: textarea jumps when editing articles in IE8
+               $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
+
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
+
+               # Enabled article-related sidebar, toplinks, etc.
+               $wgOut->setArticleRelated( true );
+
                if ( $this->isConflict ) {
                        $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
                } elseif ( $this->section != '' ) {
@@ -1475,7 +1643,7 @@ class EditPage {
                        $username = $parts[0];
                        $user = User::newFromName( $username, false /* allow IP users*/ );
                        $ip = User::isIP( $username );
-                       if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
+                       if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
                                $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
                                        array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
                        } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
@@ -1509,7 +1677,7 @@ class EditPage {
                                '', array( 'lim' => 10,
                                           'conds' => array( "log_action != 'revision'" ),
                                           'showIfEmpty' => false,
-                                          'msgKey' => array( 'recreate-moveddeleted-warn') )
+                                          'msgKey' => array( 'recreate-moveddeleted-warn' ) )
                        );
                }
        }
@@ -1522,7 +1690,7 @@ class EditPage {
        protected function showCustomIntro() {
                if ( $this->editintro ) {
                        $title = Title::newFromText( $this->editintro );
-                       if ( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
+                       if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
                                global $wgOut;
                                // Added using template syntax, to take <noinclude>'s into account.
                                $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
@@ -1545,37 +1713,24 @@ class EditPage {
 
                wfProfileIn( __METHOD__ );
 
-               #need to parse the preview early so that we know which templates are used,
-               #otherwise users with "show preview after edit box" will get a blank list
-               #we parse this near the beginning so that setHeaders can do the title
-               #setting work instead of leaving it in getPreviewText
+               # need to parse the preview early so that we know which templates are used,
+               # otherwise users with "show preview after edit box" will get a blank list
+               # we parse this near the beginning so that setHeaders can do the title
+               # setting work instead of leaving it in getPreviewText
                $previewOutput = '';
                if ( $this->formtype == 'preview' ) {
                        $previewOutput = $this->getPreviewText();
                }
 
-               wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
+               wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
 
                $this->setHeaders();
 
-               # Enabled article-related sidebar, toplinks, etc.
-               $wgOut->setArticleRelated( true );
-
                if ( $this->showHeader() === false ) {
                        wfProfileOut( __METHOD__ );
                        return;
                }
 
-               $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
-
-               if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage ) {
-                       # prepare toolbar for edit buttons
-                       $toolbar = EditPage::getEditToolbar();
-               } else {
-                       $toolbar = '';
-               }
-
-
                $wgOut->addHTML( $this->editFormPageTop );
 
                if ( $wgUser->getOption( 'previewontop' ) ) {
@@ -1584,26 +1739,21 @@ class EditPage {
 
                $wgOut->addHTML( $this->editFormTextTop );
 
-               $templates = $this->getTemplates();
-               $formattedtemplates = Linker::formatTemplates( $templates, $this->preview, $this->section != '');
-
-               $hiddencats = $this->mArticle->getHiddenCategories();
-               $formattedhiddencats = Linker::formatHiddenCategories( $hiddencats );
-
-               if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
-                       $wgOut->wrapWikiMsg(
-                               "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
-                               'deletedwhileediting' );
-               } elseif ( $this->wasDeletedSinceLastEdit() ) {
-                       // Hide the toolbar and edit area, user can click preview to get it back
-                       // Add an confirmation checkbox and explanation.
-                       $toolbar = '';
-                       // @todo move this to a cleaner conditional instead of blanking a variable
+               $showToolbar = true;
+               if ( $this->wasDeletedSinceLastEdit() ) {
+                       if ( $this->formtype == 'save' ) {
+                               // Hide the toolbar and edit area, user can click preview to get it back
+                               // Add an confirmation checkbox and explanation.
+                               $showToolbar = false;
+                       } else {
+                               $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
+                                       'deletedwhileediting' );
+                       }
                }
-               $wgOut->addHTML( <<<HTML
-<form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
-HTML
-);
+
+               $wgOut->addHTML( Html::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
+                       'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
+                       'enctype' => 'multipart/form-data' ) ) );
 
                if ( is_callable( $formCallback ) ) {
                        call_user_func_array( $formCallback, array( &$wgOut ) );
@@ -1640,13 +1790,21 @@ HTML
                #####
                # For a bit more sophisticated detection of blank summaries, hash the
                # automatic one and pass that in the hidden field wpAutoSummary.
-               if ( $this->missingSummary ||
-                       ( $this->section == 'new' && $this->nosummary ) )
-                               $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
+               if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
+                       $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
+               }
+
+               if ( $this->hasPresetSummary ) {
+                       // If a summary has been preset using &summary= we dont want to prompt for
+                       // a different summary. Only prompt for a summary if the summary is blanked.
+                       // (Bug 17416)
+                       $this->autoSumm = md5( '' );
+               }
+
                $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
                $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
 
-               $wgOut->addHTML( Html::hidden( 'oldid', $this->mArticle->getOldID() ) );
+               $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
 
                if ( $this->section == 'new' ) {
                        $this->showSummaryInput( true, $this->summary );
@@ -1655,14 +1813,19 @@ HTML
 
                $wgOut->addHTML( $this->editFormTextBeforeContent );
 
-               $wgOut->addHTML( $toolbar );
+               if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
+                       $wgOut->addHTML( EditPage::getEditToolbar() );
+               }
 
                if ( $this->isConflict ) {
                        // In an edit conflict bypass the overrideable content form method
                        // and fallback to the raw wpTextbox1 since editconflicts can't be
                        // resolved between page source edits and custom ui edits using the
                        // custom edit ui.
-                       $this->showTextbox1( null, $this->getContent() );
+                       $this->textbox2 = $this->textbox1;
+                       $this->textbox1 = $this->getCurrentText();
+
+                       $this->showTextbox1();
                } else {
                        $this->showContentForm();
                }
@@ -1670,32 +1833,31 @@ HTML
                $wgOut->addHTML( $this->editFormTextAfterContent );
 
                $wgOut->addWikiText( $this->getCopywarn() );
-               if ( isset($this->editFormTextAfterWarn) && $this->editFormTextAfterWarn !== '' )
-                       $wgOut->addHTML( $this->editFormTextAfterWarn );
+
+               $wgOut->addHTML( $this->editFormTextAfterWarn );
 
                $this->showStandardInputs();
 
                $this->showFormAfterText();
 
                $this->showTosSummary();
+
                $this->showEditTools();
 
-               $wgOut->addHTML( <<<HTML
-{$this->editFormTextAfterTools}
-<div class='templatesUsed'>
-{$formattedtemplates}
-</div>
-<div class='hiddencats'>
-{$formattedhiddencats}
-</div>
-HTML
-);
+               $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
+
+               $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
+                       Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
 
-               if ( $this->isConflict )
+               $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
+                       Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
+
+               if ( $this->isConflict ) {
                        $this->showConflict();
+               }
+
+               $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
 
-               $wgOut->addHTML( $this->editFormTextBottom );
-               $wgOut->addHTML( "</form>\n" );
                if ( !$wgUser->getOption( 'previewontop' ) ) {
                        $this->displayPreviewArea( $previewOutput, false );
                }
@@ -1703,8 +1865,54 @@ HTML
                wfProfileOut( __METHOD__ );
        }
 
+       /**
+        * Extract the section title from current section text, if any.
+        *
+        * @param string $text
+        * @return Mixed|string or false
+        */
+       public static function extractSectionTitle( $text ) {
+               preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
+               if ( !empty( $matches[2] ) ) {
+                       global $wgParser;
+                       return $wgParser->stripSectionName( trim( $matches[2] ) );
+               } else {
+                       return false;
+               }
+       }
+
        protected function showHeader() {
                global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
+
+               if ( $this->mTitle->isTalkPage() ) {
+                       $wgOut->addWikiMsg( 'talkpagetext' );
+               }
+
+               # Optional notices on a per-namespace and per-page basis
+               $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
+               $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
+               if ( $editnotice_ns_message->exists() ) {
+                       $wgOut->addWikiText( $editnotice_ns_message->plain() );
+               }
+               if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
+                       $parts = explode( '/', $this->mTitle->getDBkey() );
+                       $editnotice_base = $editnotice_ns;
+                       while ( count( $parts ) > 0 ) {
+                               $editnotice_base .= '-' . array_shift( $parts );
+                               $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
+                               if ( $editnotice_base_msg->exists() ) {
+                                       $wgOut->addWikiText( $editnotice_base_msg->plain() );
+                               }
+                       }
+               } else {
+                       # Even if there are no subpages in namespace, we still don't want / in MW ns.
+                       $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
+                       $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
+                       if ( $editnoticeMsg->exists() ) {
+                               $wgOut->addWikiText( $editnoticeMsg->plain() );
+                       }
+               }
+
                if ( $this->isConflict ) {
                        $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
                        $this->edittime = $this->mArticle->getTimestamp();
@@ -1718,14 +1926,10 @@ HTML
                        }
 
                        if ( $this->section != '' && $this->section != 'new' ) {
-                               $matches = array();
                                if ( !$this->summary && !$this->preview && !$this->diff ) {
-                                       preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
-                                       if ( !empty( $matches[2] ) ) {
-                                               global $wgParser;
-                                               $this->summary = "/* " .
-                                                       $wgParser->stripSectionName(trim($matches[2])) .
-                                                       " */ ";
+                                       $sectionTitle = self::extractSectionTitle( $this->textbox1 );
+                                       if ( $sectionTitle !== false ) {
+                                               $this->summary = "/* $sectionTitle */ ";
                                        }
                                }
                        }
@@ -1750,18 +1954,27 @@ HTML
                                $wgOut->addWikiMsg( 'nonunicodebrowser' );
                        }
 
-                       if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
-                       // Let sysop know that this will make private content public if saved
+                       if ( $this->section != 'new' ) {
+                               $revision = $this->mArticle->getRevisionFetched();
+                               if ( $revision ) {
+                                       // Let sysop know that this will make private content public if saved
 
-                               if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
-                                       $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
-                               } elseif ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
-                                       $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
-                               }
+                                       if ( !$revision->userCan( Revision::DELETED_TEXT ) ) {
+                                               $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
+                                       } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
+                                               $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
+                                       }
+
+                                       if ( !$revision->isCurrent() ) {
+                                               $this->mArticle->setOldSubtitle( $revision->getId() );
+                                               $wgOut->addWikiMsg( 'editingold' );
+                                       }
+                               } elseif ( $this->mTitle->exists() ) {
+                                       // Something went wrong
 
-                               if ( !$this->mArticle->mRevision->isCurrent() ) {
-                                       $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
-                                       $wgOut->addWikiMsg( 'editingold' );
+                                       $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
+                                               array( 'missing-article', $this->mTitle->getPrefixedText(),
+                                               wfMsgNoTrans( 'missingarticle-rev', $this->oldid ) ) );
                                }
                        }
                }
@@ -1802,12 +2015,12 @@ HTML
                }
                if ( $this->mTitle->isCascadeProtected() ) {
                        # Is this page under cascading protection from some source pages?
-                       list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
+                       list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
                        $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
                        $cascadeSourcesCount = count( $cascadeSources );
                        if ( $cascadeSourcesCount > 0 ) {
                                # Explain, and list the titles responsible
-                               foreach( $cascadeSources as $page ) {
+                               foreach ( $cascadeSources as $page ) {
                                        $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
                                }
                        }
@@ -1816,7 +2029,7 @@ HTML
                }
                if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
                        LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
-                               array(  'lim' => 1,
+                               array( 'lim' => 1,
                                        'showIfEmpty' => false,
                                        'msgKey' => array( 'titleprotectedwarning' ),
                                        'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
@@ -1830,7 +2043,7 @@ HTML
                        $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
                                array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
                } else {
-                       if( !wfMessage('longpage-hint')->isDisabled() ) {
+                       if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
                                $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
                                        array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
                                );
@@ -1852,9 +2065,9 @@ HTML
         *
         * @return array An array in the format array( $label, $input )
         */
-       function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
-               //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
-               $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
+       function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
+               // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
+               $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
                        'id' => 'wpSummary',
                        'maxlength' => '200',
                        'tabindex' => '1',
@@ -1862,7 +2075,7 @@ HTML
                        'spellcheck' => 'true',
                ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
 
-               $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
+               $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
                        'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
                        'id' => "wpSummaryLabel"
                );
@@ -1900,8 +2113,8 @@ HTML
                }
                $summary = $wgContLang->recodeForEdit( $summary );
                $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
-               list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
-               $wgOut->addHTML("{$label} {$input}");
+               list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
+               $wgOut->addHTML( "{$label} {$input}" );
        }
 
        /**
@@ -1938,7 +2151,7 @@ HTML
 HTML
                );
                if ( !$this->checkUnicodeCompliantBrowser() )
-                       $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
+                       $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
        }
 
        protected function showFormAfterText() {
@@ -1975,37 +2188,43 @@ HTML
         * The $textoverride method can be used by subclasses overriding showContentForm
         * to pass back to this method.
         *
-        * @param $customAttribs An array of html attributes to use in the textarea
+        * @param $customAttribs array of html attributes to use in the textarea
         * @param $textoverride String: optional text to override $this->textarea1 with
         */
-       protected function showTextbox1($customAttribs = null, $textoverride = null) {
-               $classes = array(); // Textarea CSS
-               if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
-                       # Is the title semi-protected?
-                       if ( $this->mTitle->isSemiProtected() ) {
-                               $classes[] = 'mw-textarea-sprotected';
-                       } else {
-                               # Then it must be protected based on static groups (regular)
-                               $classes[] = 'mw-textarea-protected';
+       protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
+               if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
+                       $attribs = array( 'style' => 'display:none;' );
+               } else {
+                       $classes = array(); // Textarea CSS
+                       if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
+                               # Is the title semi-protected?
+                               if ( $this->mTitle->isSemiProtected() ) {
+                                       $classes[] = 'mw-textarea-sprotected';
+                               } else {
+                                       # Then it must be protected based on static groups (regular)
+                                       $classes[] = 'mw-textarea-protected';
+                               }
+                               # Is the title cascade-protected?
+                               if ( $this->mTitle->isCascadeProtected() ) {
+                                       $classes[] = 'mw-textarea-cprotected';
+                               }
                        }
-                       # Is the title cascade-protected?
-                       if ( $this->mTitle->isCascadeProtected() ) {
-                               $classes[] = 'mw-textarea-cprotected';
+
+                       $attribs = array( 'tabindex' => 1 );
+
+                       if ( is_array( $customAttribs ) ) {
+                               $attribs += $customAttribs;
                        }
-               }
-               $attribs = array( 'tabindex' => 1 );
-               if ( is_array($customAttribs) )
-                       $attribs += $customAttribs;
 
-               if ( $this->wasDeletedSinceLastEdit() )
-                       $attribs['type'] = 'hidden';
-               if ( !empty( $classes ) ) {
-                       if ( isset($attribs['class']) )
-                               $classes[] = $attribs['class'];
-                       $attribs['class'] = implode( ' ', $classes );
+                       if ( count( $classes ) ) {
+                               if ( isset( $attribs['class'] ) ) {
+                                       $classes[] = $attribs['class'];
+                               }
+                               $attribs['class'] = implode( ' ', $classes );
+                       }
                }
 
-               $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
+               $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
        }
 
        protected function showTextbox2() {
@@ -2016,7 +2235,7 @@ HTML
                global $wgOut, $wgUser;
 
                $wikitext = $this->safeUnicodeOutput( $content );
-               if ( strval($wikitext) !== '' ) {
+               if ( strval( $wikitext ) !== '' ) {
                        // Ensure there's a newline at the end, otherwise adding lines
                        // is awkward.
                        // But don't add a newline if the ext is empty, or Firefox in XHTML
@@ -2058,7 +2277,7 @@ HTML
 
                $wgOut->addHTML( '</div>' );
 
-               if ( $this->formtype == 'diff') {
+               if ( $this->formtype == 'diff' ) {
                        $this->showDiff();
                }
        }
@@ -2071,12 +2290,12 @@ HTML
         */
        protected function showPreview( $text ) {
                global $wgOut;
-               if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
+               if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
                        $this->mArticle->openShowCategory();
                }
                # This hook seems slightly odd here, but makes things more
                # consistent for extensions.
-               wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
+               wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
                $wgOut->addHTML( $text );
                if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
                        $this->mArticle->closeShowCategory();
@@ -2091,9 +2310,9 @@ HTML
         * save and then make a comparison.
         */
        function showDiff() {
-               global $wgUser, $wgContLang, $wgParser;
+               global $wgUser, $wgContLang, $wgParser, $wgOut;
 
-               $oldtext = $this->mArticle->fetchContent();
+               $oldtext = $this->mArticle->getRawText();
                $newtext = $this->mArticle->replaceSection(
                        $this->section, $this->textbox1, $this->summary, $this->edittime );
 
@@ -2101,9 +2320,11 @@ HTML
 
                $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
                $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle, $wgUser, $popts );
-               $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
-               $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
+
                if ( $oldtext !== false  || $newtext != '' ) {
+                       $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
+                       $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
+
                        $de = new DifferenceEngine( $this->mArticle->getContext() );
                        $de->setText( $oldtext, $newtext );
                        $difftext = $de->getDiff( $oldtitle, $newtitle );
@@ -2112,7 +2333,6 @@ HTML
                        $difftext = '';
                }
 
-               global $wgOut;
                $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
        }
 
@@ -2127,7 +2347,7 @@ HTML
        protected function showTosSummary() {
                $msg = 'editpage-tos-summary';
                wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
-               if( !wfMessage( $msg )->isDisabled() ) {
+               if ( !wfMessage( $msg )->isDisabled() ) {
                        global $wgOut;
                        $wgOut->addHTML( '<div class="mw-tos-summary">' );
                        $wgOut->addWikiMsg( $msg );
@@ -2156,7 +2376,7 @@ HTML
                wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
 
                return "<div id=\"editpage-copywarn\">\n" .
-                       call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
+                       call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
        }
 
        protected function showStandardInputs( &$tabindex = 2 ) {
@@ -2179,8 +2399,8 @@ HTML
                        $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
                }
                $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
-               $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
-                       htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
+               $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
+                       htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
                        htmlspecialchars( wfMsg( 'newwindow' ) );
                $wgOut->addHTML( "      <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
                $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
@@ -2192,8 +2412,7 @@ HTML
         */
        protected function showConflict() {
                global $wgOut;
-               $this->textbox2 = $this->textbox1;
-               $this->textbox1 = $this->getContent();
+
                if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
                        $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
 
@@ -2211,8 +2430,8 @@ HTML
         */
        public function getCancelLink() {
                $cancelParams = array();
-               if ( !$this->isConflict && $this->mArticle->getOldID() > 0 ) {
-                       $cancelParams['oldid'] = $this->mArticle->getOldID();
+               if ( !$this->isConflict && $this->oldid > 0 ) {
+                       $cancelParams['oldid'] = $this->oldid;
                }
 
                return Linker::linkKnown(
@@ -2285,10 +2504,10 @@ HTML
                        array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
                );
                // Quick paranoid permission checks...
-               if( is_object( $data ) ) {
-                       if( $data->log_deleted & LogPage::DELETED_USER )
+               if ( is_object( $data ) ) {
+                       if ( $data->log_deleted & LogPage::DELETED_USER )
                                $data->user_name = wfMsgHtml( 'rev-deleted-user' );
-                       if( $data->log_deleted & LogPage::DELETED_COMMENT )
+                       if ( $data->log_deleted & LogPage::DELETED_COMMENT )
                                $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
                }
                return $data;
@@ -2334,15 +2553,15 @@ HTML
                $parserOptions->setEditSection( false );
                $parserOptions->setTidy( true );
                $parserOptions->setIsPreview( true );
-               $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
+               $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
 
                # don't parse non-wikitext pages, show message about preview
                # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
 
                if ( $this->isCssJsSubpage || !$this->mTitle->isWikitextPage() ) {
-                       if( $this->mTitle->isCssJsSubpage() ) {
+                       if ( $this->mTitle->isCssJsSubpage() ) {
                                $level = 'user';
-                       } elseif( $this->mTitle->isCssOrJsPage() ) {
+                       } elseif ( $this->mTitle->isCssOrJsPage() ) {
                                $level = 'site';
                        } else {
                                $level = false;
@@ -2350,11 +2569,11 @@ HTML
 
                        # Used messages to make sure grep find them:
                        # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
-                       if( $level ) {
-                               if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
+                       if ( $level ) {
+                               if ( preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
                                        $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
                                        $class = "mw-code mw-css";
-                               } elseif (preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
+                               } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
                                        $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
                                        $class = "mw-code mw-js";
                                } else {
@@ -2366,36 +2585,37 @@ HTML
                        $previewHTML = $parserOutput->mText;
                        $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
                } else {
-                       $rt = Title::newFromRedirectArray( $this->textbox1 );
-                       if ( $rt ) {
-                               $previewHTML = $this->mArticle->viewRedirect( $rt, false );
-                       } else {
-                               $toparse = $this->textbox1;
+                       $toparse = $this->textbox1;
 
-                               # If we're adding a comment, we need to show the
-                               # summary as the headline
-                               if ( $this->section == "new" && $this->summary != "" ) {
-                                       $toparse = "== {$this->summary} ==\n\n" . $toparse;
-                               }
+                       # If we're adding a comment, we need to show the
+                       # summary as the headline
+                       if ( $this->section == "new" && $this->summary != "" ) {
+                               $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $toparse;
+                       }
 
-                               wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
+                       wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
 
-                               $parserOptions->enableLimitReport();
+                       $parserOptions->enableLimitReport();
 
-                               $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
-                               $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
+                       $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
+                       $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
 
+                       $rt = Title::newFromRedirectArray( $this->textbox1 );
+                       if ( $rt ) {
+                               $previewHTML = $this->mArticle->viewRedirect( $rt, false );
+                       } else {
                                $previewHTML = $parserOutput->getText();
-                               $this->mParserOutput = $parserOutput;
-                               $wgOut->addParserOutputNoText( $parserOutput );
+                       }
 
-                               if ( count( $parserOutput->getWarnings() ) ) {
-                                       $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
-                               }
+                       $this->mParserOutput = $parserOutput;
+                       $wgOut->addParserOutputNoText( $parserOutput );
+
+                       if ( count( $parserOutput->getWarnings() ) ) {
+                               $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
                        }
                }
 
-               if( $this->isConflict ) {
+               if ( $this->isConflict ) {
                        $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
                } else {
                        $conflict = '<hr />';
@@ -2407,7 +2627,7 @@ HTML
 
                $pageLang = $this->mTitle->getPageLanguage();
                $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
-                       'class' => 'mw-content-'.$pageLang->getDir() );
+                       'class' => 'mw-content-' . $pageLang->getDir() );
                $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
 
                wfProfileOut( __METHOD__ );
@@ -2423,14 +2643,14 @@ HTML
                        if ( !isset( $this->mParserOutput ) ) {
                                return $templates;
                        }
-                       foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
-                               foreach( array_keys( $template ) as $dbk ) {
-                                       $templates[] = Title::makeTitle($ns, $dbk);
+                       foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
+                               foreach ( array_keys( $template ) as $dbk ) {
+                                       $templates[] = Title::makeTitle( $ns, $dbk );
                                }
                        }
                        return $templates;
                } else {
-                       return $this->mArticle->getUsedTemplates();
+                       return $this->mTitle->getTemplateLinksFrom();
                }
        }
 
@@ -2524,7 +2744,7 @@ HTML
                                'tip'    => wfMsg( 'media_tip' ),
                                'key'    => 'M'
                        ) : false,
-                       $wgUseTeX ?     array(
+                       $wgUseTeX ? array(
                                'image'  => $wgLang->getImageFile( 'button-math' ),
                                'id'     => 'mw-editbutton-math',
                                'open'   => "<math>",
@@ -2562,7 +2782,7 @@ HTML
                        )
                );
 
-               $script = '';
+               $script = 'mw.loader.using("mediawiki.action.edit", function() {';
                foreach ( $toolarray as $tool ) {
                        if ( !$tool ) {
                                continue;
@@ -2583,6 +2803,14 @@ HTML
 
                        $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
                }
+
+               // This used to be called on DOMReady from mediawiki.action.edit, which
+               // ended up causing race conditions with the setup code above.
+               $script .= "\n" .
+                       "// Create button bar\n" .
+                       "$(function() { mw.toolbar.init(); } );\n";
+
+               $script .= '});';
                $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
 
                $toolbar = '<div id="toolbar"></div>';
@@ -2596,7 +2824,7 @@ HTML
         * Returns an array of html code of the following checkboxes:
         * minor and watch
         *
-        * @param $tabindex Current tabindex
+        * @param $tabindex int Current tabindex
         * @param $checked Array of checkbox => bool, where bool indicates the checked
         *                 status of the checkbox
         *
@@ -2647,7 +2875,7 @@ HTML
         * Returns an array of html code of the following buttons:
         * save, diff, preview and live
         *
-        * @param $tabindex Current tabindex
+        * @param $tabindex int Current tabindex
         *
         * @return array
         */
@@ -2661,9 +2889,9 @@ HTML
                        'tabindex'  => ++$tabindex,
                        'value'     => wfMsg( 'savearticle' ),
                        'accesskey' => wfMsg( 'accesskey-save' ),
-                       'title'     => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
+                       'title'     => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
                );
-               $buttons['save'] = Xml::element('input', $temp, '');
+               $buttons['save'] = Xml::element( 'input', $temp, '' );
 
                ++$tabindex; // use the same for preview and live preview
                $temp = array(
@@ -2729,9 +2957,10 @@ HTML
         * @deprecated in 1.19; throw an exception directly instead
         */
        function blockedPage() {
+               wfDeprecated( __METHOD__, '1.19' );
                global $wgUser;
 
-               throw new UserBlockedError( $wgUser->mBlock );
+               throw new UserBlockedError( $wgUser->getBlock() );
        }
 
        /**
@@ -2740,6 +2969,7 @@ HTML
         * @deprecated in 1.19; throw an exception directly instead
         */
        function userNotLoggedInPage() {
+               wfDeprecated( __METHOD__, '1.19' );
                throw new PermissionsError( 'edit' );
        }
 
@@ -2750,6 +2980,7 @@ HTML
         * @deprecated in 1.19; throw an exception directly instead
         */
        function noCreatePermission() {
+               wfDeprecated( __METHOD__, '1.19' );
                $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
                throw new PermissionsError( $permission );
        }
@@ -2773,10 +3004,12 @@ HTML
        /**
         * Produce the stock "your edit contains spam" page
         *
-        * @param $match Text which triggered one or more filters
+        * @param $match string Text which triggered one or more filters
         * @deprecated since 1.17 Use method spamPageWithContent() instead
         */
        static function spamPage( $match = false ) {
+               wfDeprecated( __METHOD__, '1.17' );
+
                global $wgOut, $wgTitle;
 
                $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
@@ -2794,7 +3027,7 @@ HTML
        /**
         * Show "your edit contains spam" page with your diff and text
         *
-        * @param $match Text which triggered one or more filters
+        * @param $match string|bool Text which triggered one or more filters
         */
        public function spamPageWithContent( $match = false ) {
                global $wgOut;
@@ -2810,9 +3043,7 @@ HTML
                $wgOut->addHTML( '</div>' );
 
                $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
-               $de = new DifferenceEngine( $this->mArticle->getContext() );
-               $de->setText( $this->getContent(), $this->textbox2 );
-               $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
+               $this->showDiff();
 
                $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
                $this->showTextbox2();
@@ -2846,7 +3077,7 @@ HTML
                }
                $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
                foreach ( $wgBrowserBlackList as $browser ) {
-                       if ( preg_match($browser, $currentbrowser) ) {
+                       if ( preg_match( $browser, $currentbrowser ) ) {
                                return false;
                        }
                }
@@ -2917,25 +3148,25 @@ HTML
                $bytesleft = 0;
                $result = "";
                $working = 0;
-               for( $i = 0; $i < strlen( $invalue ); $i++ ) {
+               for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
                        $bytevalue = ord( $invalue[$i] );
-                       if ( $bytevalue <= 0x7F ) { //0xxx xxxx
+                       if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
                                $result .= chr( $bytevalue );
                                $bytesleft = 0;
-                       } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
+                       } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
                                $working = $working << 6;
-                               $working += ($bytevalue & 0x3F);
+                               $working += ( $bytevalue & 0x3F );
                                $bytesleft--;
                                if ( $bytesleft <= 0 ) {
                                        $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
                                }
-                       } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
+                       } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
                                $working = $bytevalue & 0x1F;
                                $bytesleft = 1;
-                       } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
+                       } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
                                $working = $bytevalue & 0x0F;
                                $bytesleft = 2;
-                       } else { //1111 0xxx
+                       } else { // 1111 0xxx
                                $working = $bytevalue & 0x07;
                                $bytesleft = 3;
                        }
@@ -2954,20 +3185,20 @@ HTML
         */
        function unmakesafe( $invalue ) {
                $result = "";
-               for( $i = 0; $i < strlen( $invalue ); $i++ ) {
-                       if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+3] != '0' ) ) {
+               for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
+                       if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
                                $i += 3;
                                $hexstring = "";
                                do {
                                        $hexstring .= $invalue[$i];
                                        $i++;
-                               } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
+                               } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
 
                                // Do some sanity checks. These aren't needed for reversability,
                                // but should help keep the breakage down if the editor
                                // breaks one of the entities whilst editing.
-                               if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
-                                       $codepoint = hexdec($hexstring);
+                               if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
+                                       $codepoint = hexdec( $hexstring );
                                        $result .= codepointToUtf8( $codepoint );
                                } else {
                                        $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );