messing with wfMerge
[lhc/web/wiklou.git] / includes / EditPage.php
index eeabe03..91d2be4 100644 (file)
  * headaches, which may be fatal.
  */
 class EditPage {
+
+       /**
+        * Status: Article successfully updated
+        */
        const AS_SUCCESS_UPDATE            = 200;
+
+       /**
+        * Status: Article successfully created
+        */
        const AS_SUCCESS_NEW_ARTICLE       = 201;
+
+       /**
+        * Status: Article update aborted by a hook function
+        */
        const AS_HOOK_ERROR                = 210;
+
+       /**
+        * Status: The filter function set in $wgFilterCallback returned true (= block it) 
+        */
        const AS_FILTERING                 = 211;
+
+       /**
+        * Status: A hook function returned an error
+        */
        const AS_HOOK_ERROR_EXPECTED       = 212;
+
+       /**
+        * Status: User is blocked from editting this page
+        */
        const AS_BLOCKED_PAGE_FOR_USER     = 215;
+
+       /**
+        * Status: Content too big (> $wgMaxArticleSize)
+        */
        const AS_CONTENT_TOO_BIG           = 216;
+
+       /**
+        * Status: User cannot edit? (not used)
+        */
        const AS_USER_CANNOT_EDIT          = 217;
+
+       /**
+        * Status: this anonymous user is not allowed to edit this page
+        */
        const AS_READ_ONLY_PAGE_ANON       = 218;
+
+       /**
+        * Status: this logged in user is not allowed to edit this page
+        */
        const AS_READ_ONLY_PAGE_LOGGED     = 219;
+
+       /**
+        * Status: wiki is in readonly mode (wfReadOnly() == true)
+        */
        const AS_READ_ONLY_PAGE            = 220;
+
+       /**
+        * Status: rate limiter for action 'edit' was tripped
+        */
        const AS_RATE_LIMITED              = 221;
+
+       /**
+        * Status: article was deleted while editting and param wpRecreate == false or form
+        * was not posted
+        */
        const AS_ARTICLE_WAS_DELETED       = 222;
+
+       /**
+        * Status: user tried to create this page, but is not allowed to do that
+        * ( Title->usercan('create') == false )
+        */
        const AS_NO_CREATE_PERMISSION      = 223;
+
+       /**
+        * Status: user tried to create a blank page
+        */
        const AS_BLANK_ARTICLE             = 224;
+
+       /**
+        * Status: (non-resolvable) edit conflict
+        */
        const AS_CONFLICT_DETECTED         = 225;
+
+       /**
+        * Status: no edit summary given and the user has forceeditsummary set and the user is not
+        * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
+        */
        const AS_SUMMARY_NEEDED            = 226;
+
+       /**
+        * Status: user tried to create a new section without content
+        */
        const AS_TEXTBOX_EMPTY             = 228;
+
+       /**
+        * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
+        */
        const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
+
+       /**
+        * not used
+        */
        const AS_OK                        = 230;
+
+       /**
+        * Status: WikiPage::doEdit() was unsuccessfull
+        */
        const AS_END                       = 231;
+
+       /**
+        * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
+        */
        const AS_SPAM_ERROR                = 232;
+
+       /**
+        * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
+        */
        const AS_IMAGE_REDIRECT_ANON       = 233;
+
+       /**
+        * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
+        */
        const AS_IMAGE_REDIRECT_LOGGED     = 234;
 
        /**
@@ -113,10 +212,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();
        }
@@ -235,14 +333,6 @@ 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" );
 
                $this->isConflict = false;
@@ -254,36 +344,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,
@@ -346,7 +408,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 +433,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 );
                }
 
@@ -627,7 +689,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' );
@@ -695,91 +756,84 @@ class EditPage {
                global $wgOut, $wgRequest, $wgParser;
 
                wfProfileIn( __METHOD__ );
-               # Get variables from query string :P
-               $section = $wgRequest->getVal( 'section' );
 
-               $preload = $wgRequest->getVal( 'preload',
-                       // Custom preload text for new sections
-                       $section === 'new' ? 'MediaWiki:addsection-preload' : '' );
-               $undoafter = $wgRequest->getVal( 'undoafter' );
-               $undo = $wgRequest->getVal( 'undo' );
+               $text = false;
 
                // For message page not locally set, use the i18n message.
                // For other non-existent articles, use preload text if any.
-               if ( !$this->mTitle->exists() ) {
-                       if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
+               if ( !$this->mTitle->exists() || $this->section == 'new' ) {
+                       if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
                                # If this is a system message, get the default text.
                                $text = $this->mTitle->getDefaultMessageText();
-                               if( $text === false ) {
-                                       $text = $this->getPreloadedText( $preload );
-                               }
-                       } else {
+                       }
+                       if ( $text === false ) {
                                # If requested, preload some text.
+                               $preload = $wgRequest->getVal( 'preload',
+                                       // Custom preload text for new sections
+                                       $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
                                $text = $this->getPreloadedText( $preload );
                        }
                // For existing pages, get text based on "undo" or section parameters.
                } else {
-                       $text = $this->mArticle->getContent();
-                       if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
-                               # If they got undoafter and undo round the wrong way, switch them
-                               list( $undo, $undoafter ) = array( $undoafter, $undo );
-                       }
-                       if ( $undo > 0 && $undo > $undoafter ) {
-                               # Undoing a specific edit overrides section editing; section-editing
-                               # doesn't work with undoing.
-                               if ( $undoafter ) {
+                       if ( $this->section != '' ) {
+                               // Get section edit text (returns $def_text for invalid sections)
+                               $text = $wgParser->getSection( $this->getOriginalContent(), $this->section, $def_text );
+                       } else {
+                               $undoafter = $wgRequest->getInt( 'undoafter' );
+                               $undo = $wgRequest->getInt( 'undo' );
+
+                               if ( $undo > 0 && $undoafter > 0 ) {
+                                       if ( $undo < $undoafter ) {
+                                               # If they got undoafter and undo round the wrong way, switch them
+                                               list( $undo, $undoafter ) = array( $undoafter, $undo );
+                                       }
+
                                        $undorev = Revision::newFromId( $undo );
                                        $oldrev = Revision::newFromId( $undoafter );
-                               } else {
-                                       $undorev = Revision::newFromId( $undo );
-                                       $oldrev = $undorev ? $undorev->getPrevious() : null;
-                               }
 
-                               # Sanity check, make sure it's the right page,
-                               # the revisions exist and they were not deleted.
-                               # Otherwise, $text will be left as-is.
-                               if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
-                                       $undorev->getPage() == $oldrev->getPage() &&
-                                       $undorev->getPage() == $this->mArticle->getID() &&
-                                       !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
-                                       !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
-
-                                       $undotext = $this->mArticle->getUndoText( $undorev, $oldrev );
-                                       if ( $undotext === false ) {
-                                               # Warn the user that something went wrong
-                                               $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-failure">' .
-                                                       wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
-                                       } else {
-                                               $text = $undotext;
-                                               # Inform the user of our success and set an automatic edit summary
-                                               $this->editFormPageTop .= $wgOut->parse( '<div class="mw-undo-success">' .
-                                                       wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
-                                               $firstrev = $oldrev->getNext();
-                                               # If we just undid one rev, use an autosummary
-                                               if ( $firstrev->getId() == $undo ) {
-                                                       $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
-                                                       if ( $this->summary === '' ) {
-                                                               $this->summary = $undoSummary;
-                                                       } else {
-                                                               $this->summary = $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary;
+                                       # Sanity check, make sure it's the right page,
+                                       # the revisions exist and they were not deleted.
+                                       # Otherwise, $text will be left as-is.
+                                       if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
+                                               $undorev->getPage() == $oldrev->getPage() &&
+                                               $undorev->getPage() == $this->mTitle->getArticleId() &&
+                                               !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
+                                               !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
+
+                                               $text = $this->mArticle->getUndoText( $undorev, $oldrev );
+                                               if ( $text === false ) {
+                                                       # Warn the user that something went wrong
+                                                       $undoMsg = 'failure';
+                                               } else {
+                                                       # Inform the user of our success and set an automatic edit summary
+                                                       $undoMsg = 'success';
+
+                                                       # If we just undid one rev, use an autosummary
+                                                       $firstrev = $oldrev->getNext();
+                                                       if ( $firstrev->getId() == $undo ) {
+                                                               $undoSummary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
+                                                               if ( $this->summary === '' ) {
+                                                                       $this->summary = $undoSummary;
+                                                               } else {
+                                                                       $this->summary = $undoSummary . wfMsgForContent( 'colon-separator' ) . $this->summary;
+                                                               }
+                                                               $this->undidRev = $undo;
                                                        }
-                                                       $this->undidRev = $undo;
+                                                       $this->formtype = 'diff';
                                                }
-                                               $this->formtype = 'diff';
+                                       } else {
+                                               // Failed basic sanity checks.
+                                               // Older revisions may have been removed since the link
+                                               // was created, or we may simply have got bogus input.
+                                               $undoMsg = 'norev';
                                        }
-                               } else {
-                                       // Failed basic sanity checks.
-                                       // Older revisions may have been removed since the link
-                                       // was created, or we may simply have got bogus input.
-                                       $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-norev">' .
-                                               wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
+
+                                       $this->editFormPageTop .= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
+                                               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 +842,50 @@ 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 '';
+               }
+
+        $content = $this->mArticle->getContentObject();
+               return $content->getRawData(); # this editor is for editing the raw text. so use the raw text.
+       }
+
+       /**
+        * 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
         *
@@ -804,7 +902,7 @@ class EditPage {
         * @param $preload String: representing the title to preload from.
         * @return String
         */
-       protected function getPreloadedText( $preload ) {
+       protected function getPreloadedText( $preload ) { #FIXME: change to getPreloadedContent()
                global $wgUser, $wgParser;
 
                if ( !empty( $this->mPreloadText ) ) {
@@ -832,7 +930,7 @@ class EditPage {
                }
 
                $parserOptions = ParserOptions::newFromUser( $wgUser );
-               return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
+               return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions ); #FIXME: create Content::getPreloadCopy
        }
 
        /**
@@ -1132,7 +1230,7 @@ class EditPage {
                        $text = $this->textbox1;
                        $result['sectionanchor'] = '';
                        if ( $this->section == 'new' ) {
-                               if ( $this->sectiontitle != '' ) {
+                               if ( $this->sectiontitle !== '' ) {
                                        // Insert the section title above the content.
                                        $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle ) . "\n\n" . $text;
                                        
@@ -1142,11 +1240,11 @@ class EditPage {
                                        // If no edit summary was specified, create one automatically from the section
                                        // title and have it link to the new section. Otherwise, respect the summary as
                                        // passed.
-                                       if ( $this->summary == '' ) {
+                                       if ( $this->summary === '' ) {
                                                $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
                                                $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
                                        }
-                               } elseif ( $this->summary != '' ) {
+                               } elseif ( $this->summary !== '' ) {
                                        // Insert the section title above the content.
                                        $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
                                        
@@ -1166,10 +1264,11 @@ class EditPage {
                        # Article exists. Check for edit conflict.
 
                        $this->mArticle->clear(); # Force reload of dates, etc.
+                       $timestamp = $this->mArticle->getTimestamp();
 
-                       wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
+                       wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
 
-                       if ( $this->mArticle->getTimestamp() != $this->edittime ) {
+                       if ( $timestamp != $this->edittime ) {
                                $this->isConflict = true;
                                if ( $this->section == 'new' ) {
                                        if ( $this->mArticle->getUserText() == $wgUser->getName() &&
@@ -1189,14 +1288,23 @@ 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 !== '' ) {
+                               $sectionTitle = $this->sectiontitle;
+                       } else {
+                               $sectionTitle = $this->summary;
+                       }
+                       
                        if ( $this->isConflict ) {
-                               wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
-                                       $this->mArticle->getTimestamp() . "')\n" );
-                               $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
+                               wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
+                               $cnt = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle, $this->edittime );
+                $text = ContentHandler::getContentText($cnt); #FIXME: use Content object throughout, make edit form aware of content model and serialization format
                        } else {
                                wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
-                               $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
+                $cnt = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle );
+                $text = ContentHandler::getContentText($cnt); #FIXME: use Content object throughout, make edit form aware of content model and serialization format
                        }
                        if ( is_null( $text ) ) {
                                wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
@@ -1204,7 +1312,7 @@ class EditPage {
                                $text = $this->textbox1; // do not try to merge here!
                        } elseif ( $this->isConflict ) {
                                # Attempt merge
-                               if ( $this->mergeChangesInto( $text ) ) {
+                               if ( $this->mergeChangesInto( $text ) ) { #FIXME: passe/receive Content object
                                        // Successful merge! Maybe we should tell the user the good news?
                                        $this->isConflict = false;
                                        wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
@@ -1238,7 +1346,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 ) {
@@ -1273,7 +1381,16 @@ class EditPage {
                                        wfProfileOut( __METHOD__ );
                                        return $status;
                                }
-                               if ( $this->summary != '' ) {
+                               if ( $this->sectiontitle !== '' ) {
+                                       $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
+                                       // If no edit summary was specified, create one automatically from the section
+                                       // title and have it link to the new section. Otherwise, respect the summary as
+                                       // passed.
+                                       if ( $this->summary === '' ) {
+                                               $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
+                                               $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
+                                       }
+                               } elseif ( $this->summary !== '' ) {
                                        $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
                                        # This is a new section, so create a link to the new section
                                        # in the revision summary.
@@ -1366,7 +1483,7 @@ class EditPage {
                $res = $dbw->select( 'revision',
                        'rev_user',
                        array(
-                               'rev_page' => $this->mArticle->getId(),
+                               'rev_page' => $this->mTitle->getArticleId(),
                                'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
                        ),
                        __METHOD__,
@@ -1398,7 +1515,7 @@ class EditPage {
                        wfProfileOut( __METHOD__ );
                        return false;
                }
-               $baseText = $baseRevision->getText();
+               $baseContent = $baseRevision->getContent();
 
                // The current state, we want to merge updates into it
                $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
@@ -1406,11 +1523,14 @@ class EditPage {
                        wfProfileOut( __METHOD__ );
                        return false;
                }
-               $currentText = $currentRevision->getText();
+               $currentContent = $currentRevision->getContent();
+
+        $handler = ContentHandler::getForModelName( $baseContent->getModelName() );
+        $editContent = $handler->unserialize( $editText ); #FIXME: supply serialization fomrat from edit form!
 
-               $result = '';
-               if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
-                       $editText = $result;
+               $result = $handler->merge3( $baseContent, $editContent, $currentContent );
+               if ( $result ) {
+                       $editText = ContentHandler::getContentText($result);  #FIXME: supply serialization fomrat from edit form!
                        wfProfileOut( __METHOD__ );
                        return true;
                } else {
@@ -1476,8 +1596,21 @@ class EditPage {
        }
 
        function setHeaders() {
-               global $wgOut;
+               global $wgOut, $wgUser;
+
+               $wgOut->addModules( 'mediawiki.action.edit' );
+
+               if ( $wgUser->getOption( 'uselivepreview', false ) ) {
+                       $wgOut->addModules( 'mediawiki.legacy.preview' );
+               }
+               // Bug #19334: textarea jumps when editing articles in IE8
+               $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
+
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
+
+               # Enabled article-related sidebar, toplinks, etc.
+               $wgOut->setArticleRelated( true );
+
                if ( $this->isConflict ) {
                        $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
                } elseif ( $this->section != '' ) {
@@ -1601,24 +1734,11 @@ class EditPage {
 
                $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' ) ) {
@@ -1627,26 +1747,21 @@ class EditPage {
 
                $wgOut->addHTML( $this->editFormTextTop );
 
-               $templates = $this->getTemplates();
-               $formattedtemplates = Linker::formatTemplates( $templates, $this->preview, $this->section != '');
-
-               $hiddencats = $this->mArticle->getHiddenCategories();
-               $formattedhiddencats = Linker::formatHiddenCategories( $hiddencats );
-
-               if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
-                       $wgOut->wrapWikiMsg(
-                               "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
-                               'deletedwhileediting' );
-               } elseif ( $this->wasDeletedSinceLastEdit() ) {
-                       // Hide the toolbar and edit area, user can click preview to get it back
-                       // Add an confirmation checkbox and explanation.
-                       $toolbar = '';
-                       // @todo move this to a cleaner conditional instead of blanking a variable
+               $showToolbar = true;
+               if ( $this->wasDeletedSinceLastEdit() ) {
+                       if ( $this->formtype == 'save' ) {
+                               // Hide the toolbar and edit area, user can click preview to get it back
+                               // Add an confirmation checkbox and explanation.
+                               $showToolbar = false;
+                       } else {
+                               $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
+                                       'deletedwhileediting' );
+                       }
                }
-               $wgOut->addHTML( <<<HTML
-<form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
-HTML
-);
+
+               $wgOut->addHTML( Html::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
+                       'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
+                       'enctype' => 'multipart/form-data' ) ) );
 
                if ( is_callable( $formCallback ) ) {
                        call_user_func_array( $formCallback, array( &$wgOut ) );
@@ -1683,13 +1798,14 @@ 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 ) );
+               }
+
                $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 );
@@ -1698,14 +1814,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();
                }
@@ -1713,32 +1834,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 != '' ) ) );
+
+               $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
+                       Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
 
-               if ( $this->isConflict )
+               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 );
                }
@@ -1764,6 +1884,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 )->inContentLanguage();
+               if ( $editnotice_ns_message->exists() ) {
+                       $wgOut->addWikiText( $editnotice_ns_message->plain() );
+               }
+               if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
+                       $parts = explode( '/', $this->mTitle->getDBkey() );
+                       $editnotice_base = $editnotice_ns;
+                       while ( count( $parts ) > 0 ) {
+                               $editnotice_base .= '-'.array_shift( $parts );
+                               $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
+                               if ( $editnotice_base_msg->exists() ) {
+                                       $wgOut->addWikiText( $editnotice_base_msg->plain()  );
+                               }
+                       }
+               } else {
+                       # Even if there are no subpages in namespace, we still don't want / in MW ns.
+                       $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
+                       $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
+                       if ( $editnoticeMsg->exists() ) {
+                               $wgOut->addWikiText( $editnoticeMsg->plain() );
+                       }
+               }
+
                if ( $this->isConflict ) {
                        $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
                        $this->edittime = $this->mArticle->getTimestamp();
@@ -1777,7 +1927,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 ) {
@@ -1806,18 +1955,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 ) ) );
                                }
                        }
                }
@@ -2034,34 +2192,40 @@ HTML
         * @param $customAttribs An 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() {
@@ -2147,9 +2311,9 @@ HTML
         * save and then make a comparison.
         */
        function showDiff() {
-               global $wgUser, $wgContLang, $wgParser;
+               global $wgUser, $wgContLang, $wgParser, $wgOut;
 
-               $oldtext = $this->mArticle->fetchContent();
+               $oldtext = $this->getOriginalContent();
                $newtext = $this->mArticle->replaceSection(
                        $this->section, $this->textbox1, $this->summary, $this->edittime );
 
@@ -2157,9 +2321,11 @@ HTML
 
                $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
                $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle, $wgUser, $popts );
-               $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
-               $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
+
                if ( $oldtext !== false  || $newtext != '' ) {
+                       $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
+                       $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
+
                        $de = new DifferenceEngine( $this->mArticle->getContext() );
                        $de->setText( $oldtext, $newtext );
                        $difftext = $de->getDiff( $oldtitle, $newtitle );
@@ -2168,7 +2334,6 @@ HTML
                        $difftext = '';
                }
 
-               global $wgOut;
                $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
        }
 
@@ -2248,8 +2413,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" );
 
@@ -2267,8 +2431,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(
@@ -2395,6 +2559,7 @@ HTML
                # 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?
 
+        #FIXME: get appropriate content handler!
                if ( $this->isCssJsSubpage || !$this->mTitle->isWikitextPage() ) {
                        if( $this->mTitle->isCssJsSubpage() ) {
                                $level = 'user';
@@ -2407,6 +2572,7 @@ HTML
                        # Used messages to make sure grep find them:
                        # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
                        if( $level ) {
+                           #FIXME: move this crud into ContentHandler class!
                                if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
                                        $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
                                        $class = "mw-code mw-css";
@@ -2431,7 +2597,7 @@ HTML
                                # 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;
+                                       $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $toparse;
                                }
 
                                wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
@@ -2486,7 +2652,7 @@ HTML
                        }
                        return $templates;
                } else {
-                       return $this->mArticle->getUsedTemplates();
+                       return $this->mTitle->getTemplateLinksFrom();
                }
        }
 
@@ -2618,7 +2784,7 @@ HTML
                        )
                );
 
-               $script = '';
+               $script = 'mw.loader.using("mediawiki.action.edit", function() {';
                foreach ( $toolarray as $tool ) {
                        if ( !$tool ) {
                                continue;
@@ -2639,6 +2805,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>';
@@ -2872,7 +3046,7 @@ HTML
 
                $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
                $de = new DifferenceEngine( $this->mArticle->getContext() );
-               $de->setText( $this->getContent(), $this->textbox2 );
+               $de->setText( $this->getCurrentText(), $this->textbox2 );
                $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
 
                $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );