Deprecated Title::userIsWatching(); use User::isWatched() instead.
[lhc/web/wiklou.git] / includes / EditPage.php
index 088eae8..1f526cc 100644 (file)
@@ -1,6 +1,22 @@
 <?php
 /**
- * Contains the EditPage class
+ * Page edition user interface.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
  * @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;
-       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;
 
+       /**
+        * HTML id and name for the beginning of the edit form.
+        */
+       const EDITFORM_ID                  = 'editform';
+
        /**
         * @var Article
         */
@@ -84,6 +199,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;
 
@@ -113,10 +234,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 +304,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 +355,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 +366,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 +377,7 @@ class EditPage {
 
                if ( 'save' == $this->formtype ) {
                        if ( !$this->attemptSave() ) {
-                               wfProfileOut( __METHOD__."-business-end" );
+                               wfProfileOut( __METHOD__ . "-business-end" );
                                wfProfileOut( __METHOD__ );
                                return;
                        }
@@ -304,18 +388,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 +416,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 +430,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 +455,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 );
                }
 
@@ -407,7 +491,7 @@ class EditPage {
         */
        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.
@@ -439,7 +523,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
@@ -456,7 +540,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() ),
@@ -496,15 +580,15 @@ 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
@@ -514,7 +598,7 @@ class EditPage {
                        # 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
@@ -588,7 +672,7 @@ 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' );
@@ -607,7 +691,7 @@ class EditPage {
                        $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' ) ) {
@@ -617,6 +701,9 @@ class EditPage {
                        }
                        elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
                                $this->summary = $request->getText( 'summary' );
+                               if ( $this->summary !== '' ) {
+                                       $this->hasPresetSummary = true;
+                               }
                        }
 
                        if ( $request->getVal( 'minor' ) ) {
@@ -627,7 +714,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' );
@@ -670,7 +756,7 @@ class EditPage {
                } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
                        # Watch creations
                        $this->watchthis = true;
-               } elseif ( $this->mTitle->userIsWatching() ) {
+               } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
                        # Already watched
                        $this->watchthis = true;
                }
@@ -695,91 +781,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 && $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();
                                }
                        }
                }
@@ -788,6 +868,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
         *
@@ -810,7 +932,7 @@ class EditPage {
                if ( !empty( $this->mPreloadText ) ) {
                        return $this->mPreloadText;
                }
-               
+
                if ( $preload === '' ) {
                        return '';
                }
@@ -862,7 +984,6 @@ class EditPage {
                $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
                $status = $this->internalAttemptSave( $resultDetails, $bot );
                // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
-
                if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
                        $this->didSave = true;
                }
@@ -879,7 +1000,6 @@ class EditPage {
                                return true;
 
                        case self::AS_HOOK_ERROR:
-                       case self::AS_FILTERING:
                                return false;
 
                        case self::AS_SUCCESS_NEW_ARTICLE:
@@ -914,7 +1034,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:
@@ -934,8 +1054,15 @@ class EditPage {
                                $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
                                throw new PermissionsError( $permission );
 
+                       default:
+                               // We don't recognize $status->value. The only way that can happen
+                               // is if an extension hook aborted from inside ArticleSave.
+                               // Render the status object into $this->hookError
+                               // FIXME this sucks, we should just use the Status object throughout
+                               $this->hookError = '<div class="error">' . $status->getWikitext() .
+                                       '</div>';
+                               return true;
                }
-               return false;
        }
 
        /**
@@ -951,8 +1078,7 @@ class EditPage {
         * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
         */
        function internalAttemptSave( &$result, $bot = false ) {
-               global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
-               global $wgMaxArticleSize;
+               global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
 
                $status = Status::newGood();
 
@@ -998,13 +1124,6 @@ class EditPage {
                        wfProfileOut( __METHOD__ );
                        return $status;
                }
-               if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
-                       # Error messages or other handling should be performed by the filter function
-                       $status->setResult( false, self::AS_FILTERING );
-                       wfProfileOut( __METHOD__ . '-checks' );
-                       wfProfileOut( __METHOD__ );
-                       return $status;
-               }
                if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
                        # Error messages etc. could be handled within the hook...
                        $status->fatal( 'hookaborted' );
@@ -1082,9 +1201,10 @@ class EditPage {
 
                wfProfileOut( __METHOD__ . '-checks' );
 
-               # If article is new, insert it.
-               $aid = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
-               $new = ( $aid == 0 );
+               // Use SELECT FOR UPDATE here to avoid transaction collision in
+               // WikiPage::updateRevisionOn() and ending in the self::AS_END case.
+               $this->mArticle->loadPageData( 'forupdate' );
+               $new = !$this->mArticle->exists();
 
                if ( $new ) {
                        // Late check for create permission, just in case *PARANOIA*
@@ -1118,27 +1238,16 @@ 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;
                        $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.
@@ -1149,7 +1258,7 @@ class EditPage {
                                } 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 );
 
@@ -1164,12 +1273,10 @@ class EditPage {
                } else {
 
                        # Article exists. Check for edit conflict.
+                       $timestamp = $this->mArticle->getTimestamp();
+                       wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
 
-                       $this->mArticle->clear(); # Force reload of dates, etc.
-
-                       wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, 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() &&
@@ -1181,7 +1288,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.
@@ -1189,7 +1296,7 @@ class EditPage {
                                        $this->isConflict = false;
                                }
                        }
-                       
+
                        // If sectiontitle is set, use it, otherwise use the summary as the section title (for
                        // backwards compatibility with old forms/bots).
                        if ( $this->sectiontitle !== '' ) {
@@ -1197,10 +1304,9 @@ class EditPage {
                        } else {
                                $sectionTitle = $this->summary;
                        }
-                       
+
                        if ( $this->isConflict ) {
-                               wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
-                                       $this->mArticle->getTimestamp() . "')\n" );
+                               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" );
@@ -1246,7 +1352,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 ) {
@@ -1343,8 +1449,17 @@ class EditPage {
                        wfProfileOut( __METHOD__ );
                        return $status;
                } else {
-                       $this->isConflict = true;
-                       $doEditStatus->value = self::AS_END; // Destroys data doEdit() put in $status->value but who cares
+                       // Failure from doEdit()
+                       // Show the edit conflict page for certain recognized errors from doEdit(),
+                       // but don't show it for errors from extension hooks
+                       $errors = $doEditStatus->getErrorsArray();
+                       if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
+                               'edit-already-exists' ) ) )
+                       {
+                               $this->isConflict = true;
+                               // Destroys data doEdit() put in $status->value but who cares
+                               $doEditStatus->value = self::AS_END;
+                       }
                        wfProfileOut( __METHOD__ );
                        return $doEditStatus;
                }
@@ -1355,15 +1470,15 @@ class EditPage {
         */
        protected function commitWatch() {
                global $wgUser;
-               if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
+               if ( $wgUser->isLoggedIn() && $this->watchthis != $wgUser->isWatched( $this->mTitle ) ) {
                        $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__ );
                }
        }
 
@@ -1378,18 +1493,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;
                        }
                }
@@ -1404,7 +1519,7 @@ class EditPage {
         *
         * @return bool
         */
-       function mergeChangesInto( &$editText ){
+       function mergeChangesInto( &$editText ) {
                wfProfileIn( __METHOD__ );
 
                $db = wfGetDB( DB_MASTER );
@@ -1455,7 +1570,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;
@@ -1469,7 +1584,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;
@@ -1483,9 +1598,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];
                        }
                }
@@ -1493,23 +1608,36 @@ 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 );
+
+               $contextTitle = $this->getContextTitle();
                if ( $this->isConflict ) {
-                       $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
-               } elseif ( $this->section != '' ) {
+                       $msg = 'editconflict';
+               } elseif ( $contextTitle->exists() && $this->section != '' ) {
                        $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
-                       $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
                } else {
-                       # Use the title defined by DISPLAYTITLE magic word when present
-                       if ( isset( $this->mParserOutput )
-                        && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
-                               $title = $dt;
-                       } else {
-                               $title = $this->getContextTitle()->getPrefixedText();
-                       }
-                       $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
+                       $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
+                               'editing' : 'creating';
+               }
+               # Use the title defined by DISPLAYTITLE magic word when present
+               $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
+               if ( $displayTitle === false ) {
+                       $displayTitle = $contextTitle->getPrefixedText();
                }
+               $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
        }
 
        /**
@@ -1526,6 +1654,24 @@ class EditPage {
                if ( $namespace == NS_MEDIAWIKI ) {
                        # Show a warning if editing an interface message
                        $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
+               } else if( $namespace == NS_FILE ) {
+                       # Show a hint to shared repo
+                       $file = wfFindFile( $this->mTitle );
+                       if( $file && !$file->isLocal() ) {
+                               $descUrl = $file->getDescriptionUrl();
+                               # there must be a description url to show a hint to shared repo
+                               if( $descUrl ) {
+                                       if( !$this->mTitle->exists() ) {
+                                               $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
+                                                                       'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
+                                               ) );
+                                       } else {
+                                               $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
+                                                                       'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
+                                               ) );
+                                       }
+                               }
+                       }
                }
 
                # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
@@ -1535,7 +1681,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
@@ -1569,7 +1715,7 @@ class EditPage {
                                '', array( 'lim' => 10,
                                           'conds' => array( "log_action != 'revision'" ),
                                           'showIfEmpty' => false,
-                                          'msgKey' => array( 'recreate-moveddeleted-warn') )
+                                          'msgKey' => array( 'recreate-moveddeleted-warn' ) )
                        );
                }
        }
@@ -1605,37 +1751,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' ) ) {
@@ -1644,26 +1777,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' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
+                       'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
+                       'enctype' => 'multipart/form-data' ) ) );
 
                if ( is_callable( $formCallback ) ) {
                        call_user_func_array( $formCallback, array( &$wgOut ) );
@@ -1693,6 +1821,11 @@ HTML
                        );
                }
 
+               # When the summary is hidden, also hide them on preview/show changes
+               if( $this->nosummary ) {
+                       $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
+               }
+
                # If a blank edit summary was previously provided, and the appropriate
                # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
                # user being bounced back more than once in the event that a summary
@@ -1700,13 +1833,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 );
@@ -1715,14 +1856,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();
                }
@@ -1730,32 +1876,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 );
                }
@@ -1770,10 +1915,10 @@ HTML
         * @return Mixed|string or false
         */
        public static function extractSectionTitle( $text ) {
-               preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
+               preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
                if ( !empty( $matches[2] ) ) {
                        global $wgParser;
-                       return $wgParser->stripSectionName(trim($matches[2]));
+                       return $wgParser->stripSectionName( trim( $matches[2] ) );
                } else {
                        return false;
                }
@@ -1781,6 +1926,36 @@ HTML
 
        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 );
+               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 );
+                               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 );
+                       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();
@@ -1794,7 +1969,6 @@ HTML
                        }
 
                        if ( $this->section != '' && $this->section != 'new' ) {
-                               $matches = array();
                                if ( !$this->summary && !$this->preview && !$this->diff ) {
                                        $sectionTitle = self::extractSectionTitle( $this->textbox1 );
                                        if ( $sectionTitle !== false ) {
@@ -1823,18 +1997,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 ) ) );
                                }
                        }
                }
@@ -1875,12 +2058,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";
                                }
                        }
@@ -1889,7 +2072,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>" ) );
@@ -1903,7 +2086,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 ) )
                                );
@@ -1925,9 +2108,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',
@@ -1935,7 +2118,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"
                );
@@ -1973,8 +2156,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}" );
        }
 
        /**
@@ -2011,7 +2194,7 @@ HTML
 HTML
                );
                if ( !$this->checkUnicodeCompliantBrowser() )
-                       $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
+                       $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
        }
 
        protected function showFormAfterText() {
@@ -2048,37 +2231,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() {
@@ -2089,7 +2278,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
@@ -2100,6 +2289,7 @@ HTML
                $attribs = $customAttribs + array(
                        'accesskey' => ',',
                        'id'   => $name,
+                       'cols' => $wgUser->getIntOption( 'cols' ),
                        'rows' => $wgUser->getIntOption( 'rows' ),
                        'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
                );
@@ -2130,7 +2320,7 @@ HTML
 
                $wgOut->addHTML( '</div>' );
 
-               if ( $this->formtype == 'diff') {
+               if ( $this->formtype == 'diff' ) {
                        $this->showDiff();
                }
        }
@@ -2143,12 +2333,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();
@@ -2163,9 +2353,18 @@ HTML
         * save and then make a comparison.
         */
        function showDiff() {
-               global $wgUser, $wgContLang, $wgParser;
+               global $wgUser, $wgContLang, $wgParser, $wgOut;
 
-               $oldtext = $this->mArticle->fetchContent();
+               $oldtitlemsg = 'currentrev';
+               # if message does not exist, show diff against the preloaded default
+               if( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
+                       $oldtext = $this->mTitle->getDefaultMessageText();
+                       if( $oldtext !== false ) {
+                               $oldtitlemsg = 'defaultmessagetext';
+                       }
+               } else {
+                       $oldtext = $this->mArticle->getRawText();
+               }
                $newtext = $this->mArticle->replaceSection(
                        $this->section, $this->textbox1, $this->summary, $this->edittime );
 
@@ -2173,9 +2372,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( $oldtitlemsg, array( 'parseinline' ) );
+                       $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
+
                        $de = new DifferenceEngine( $this->mArticle->getContext() );
                        $de->setText( $oldtext, $newtext );
                        $difftext = $de->getDiff( $oldtitle, $newtitle );
@@ -2184,7 +2385,6 @@ HTML
                        $difftext = '';
                }
 
-               global $wgOut;
                $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
        }
 
@@ -2199,7 +2399,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 );
@@ -2214,7 +2414,16 @@ HTML
                        '</div>' );
        }
 
+       /**
+        * Get the copyright warning
+        *
+        * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
+        */
        protected function getCopywarn() {
+               return self::getCopyrightWarning( $this->mTitle );
+       }
+
+       public static function getCopyrightWarning( $title ) {
                global $wgRightsText;
                if ( $wgRightsText ) {
                        $copywarnMsg = array( 'copyrightwarning',
@@ -2225,10 +2434,10 @@ HTML
                                '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
                }
                // Allow for site and per-namespace customization of contribution/copyright notice.
-               wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
+               wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$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 ) {
@@ -2251,8 +2460,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" );
@@ -2264,8 +2473,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" );
 
@@ -2283,8 +2491,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(
@@ -2357,10 +2565,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;
@@ -2371,7 +2579,7 @@ HTML
         * @return string
         */
        function getPreviewText() {
-               global $wgOut, $wgUser, $wgParser, $wgRawHtml;
+               global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
 
                wfProfileIn( __METHOD__ );
 
@@ -2399,22 +2607,21 @@ HTML
                } elseif ( $this->incompleteForm ) {
                        $note = wfMsg( 'edit_form_incomplete' );
                } else {
-                       $note = wfMsg( 'previewnote' );
+                       $note = wfMsg( 'previewnote' ) .
+                               ' [[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' . wfMsg( 'continue-editing' ) . ']]';
                }
 
                $parserOptions = ParserOptions::newFromUser( $wgUser );
                $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() || !$this->mTitle->isWikitextPage() ) {
+                       if ( $this->mTitle->isCssJsSubpage() ) {
                                $level = 'user';
-                       } elseif( $this->mTitle->isCssOrJsPage() ) {
+                       } elseif ( $this->mTitle->isCssOrJsPage() ) {
                                $level = 'site';
                        } else {
                                $level = false;
@@ -2422,52 +2629,56 @@ HTML
 
                        # Used messages to make sure grep find them:
                        # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
-                       if( $level ) {
-                               if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
+                       $class = 'mw-code';
+                       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() ) ) {
+                                       $class .= " mw-css";
+                               } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
                                        $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
-                                       $class = "mw-code mw-js";
+                                       $class .= " mw-js";
                                } else {
                                        throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
                                }
+                               $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
+                               $previewHTML = $parserOutput->getText();
+                       } else {
+                               $previewHTML = '';
                        }
 
-                       $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
-                       $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 />';
@@ -2479,7 +2690,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__ );
@@ -2495,14 +2706,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();
                }
        }
 
@@ -2596,7 +2807,7 @@ HTML
                                'tip'    => wfMsg( 'media_tip' ),
                                'key'    => 'M'
                        ) : false,
-                       $wgUseTeX ?     array(
+                       $wgUseTeX ? array(
                                'image'  => $wgLang->getImageFile( 'button-math' ),
                                'id'     => 'mw-editbutton-math',
                                'open'   => "<math>",
@@ -2634,7 +2845,7 @@ HTML
                        )
                );
 
-               $script = '';
+               $script = 'mw.loader.using("mediawiki.action.edit", function() {';
                foreach ( $toolarray as $tool ) {
                        if ( !$tool ) {
                                continue;
@@ -2655,6 +2866,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>';
@@ -2668,7 +2887,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
         *
@@ -2719,7 +2938,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
         */
@@ -2733,9 +2952,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(
@@ -2804,7 +3023,7 @@ HTML
                wfDeprecated( __METHOD__, '1.19' );
                global $wgUser;
 
-               throw new UserBlockedError( $wgUser->mBlock );
+               throw new UserBlockedError( $wgUser->getBlock() );
        }
 
        /**
@@ -2848,12 +3067,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' ) );
@@ -2871,12 +3090,15 @@ HTML
        /**
         * Show "your edit contains spam" page with your diff and text
         *
-        * @param $match Text which triggered one or more filters
+        * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
         */
        public function spamPageWithContent( $match = false ) {
-               global $wgOut;
+               global $wgOut, $wgLang;
                $this->textbox2 = $this->textbox1;
 
+               if( is_array( $match ) ){
+                       $match = $wgLang->listToText( $match );
+               }
                $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
 
                $wgOut->addHTML( '<div id="spamprotected">' );
@@ -2887,9 +3109,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();
@@ -2923,7 +3143,7 @@ HTML
                }
                $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
                foreach ( $wgBrowserBlackList as $browser ) {
-                       if ( preg_match($browser, $currentbrowser) ) {
+                       if ( preg_match( $browser, $currentbrowser ) ) {
                                return false;
                        }
                }
@@ -2994,25 +3214,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;
                        }
@@ -3031,20 +3251,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 );