Reset password throttles on login
[lhc/web/wiklou.git] / includes / EditPage.php
index 409034e..3492a24 100644 (file)
@@ -1,6 +1,7 @@
 <?php
 /**
  * Contains the EditPage class
+ * @file
  */
 
 /**
@@ -43,6 +44,7 @@ class EditPage {
 
        var $mArticle;
        var $mTitle;
+       var $action;
        var $mMetaData = '';
        var $isConflict = false;
        var $isCssJsSubpage = false;
@@ -60,7 +62,9 @@ class EditPage {
        var $allowBlankSummary = false;
        var $autoSumm = '';
        var $hookError = '';
-       var $mPreviewTemplates;
+       #var $mPreviewTemplates;
+       var $mParserOutput;
+       var $mBaseRevision = false;
 
        # Form values
        var $save = false, $preview = false, $diff = false;
@@ -77,10 +81,10 @@ class EditPage {
        public $editFormTextAfterWarn;
        public $editFormTextAfterTools;
        public $editFormTextBottom;
-       
+
        /* $didSave should be set to true whenever an article was succesfully altered. */
        public $didSave = false;
-       
+
        public $suppressIntro = false;
 
        /**
@@ -90,6 +94,7 @@ class EditPage {
        function EditPage( $article ) {
                $this->mArticle =& $article;
                $this->mTitle = $article->getTitle();
+               $this->action = 'submit';
 
                # Placeholders for text injection by hooks (empty per default)
                $this->editFormPageTop =
@@ -99,7 +104,7 @@ class EditPage {
                $this->editFormTextAfterTools =
                $this->editFormTextBottom = "";
        }
-       
+
        /**
         * Fetch initial editing page content.
         * @private
@@ -119,8 +124,8 @@ class EditPage {
                if( !$this->mTitle->exists() ) {
                        if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
                                $wgMessageCache->loadAllMessages();
-                               # If this is a system message, get the default text. 
-                               $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
+                               # If this is a system message, get the default text.
+                               $text = wfMsgWeirdKey( $this->mTitle->getText() ) ;
                        } else {
                                # If requested, preload some text.
                                $text = $this->getPreloadedText( $preload );
@@ -153,39 +158,43 @@ class EditPage {
                                        $oldrev = $undorev ? $undorev->getPrevious() : null;
                                }
 
-                               #Sanity check, make sure it's the right page.
+                               # 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() ) {
+                               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 ) ) {
                                        $undorev_text = $undorev->getText();
                                        $oldrev_text = $oldrev->getText();
                                        $currev_text = $text;
 
-                                       #No use doing a merge if it's just a straight revert.
                                        if ( $currev_text != $undorev_text ) {
-                                               $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
+                                               $result = wfMerge( $undorev_text, $oldrev_text, $currev_text, $text );
                                        } else {
+                                               # No use doing a merge if it's just a straight revert.
                                                $text = $oldrev_text;
                                                $result = true;
                                        }
+                                       if( $result ) {
+                                               # Inform the user of our success and set an automatic edit summary
+                                               $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
+                                               $firstrev = $oldrev->getNext();
+                                               # If we just undid one rev, use an autosummary
+                                               if( $firstrev->mId == $undo ) {
+                                                       $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
+                                               }
+                                               $this->formtype = 'diff';
+                                       } else {
+                                               # Warn the user that something went wrong
+                                               $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
+                                       }
                                } else {
                                        // Failed basic sanity checks.
                                        // Older revisions may have been removed since the link
                                        // was created, or we may simply have got bogus input.
-                                       $result = false;
-                               }
-
-                               if( $result ) {
-                                       # Inform the user of our success and set an automatic edit summary
-                                       $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
-                                       $firstrev = $oldrev->getNext();
-                                       # If we just undid one rev, use an autosummary
-                                       if ( $firstrev->mId == $undo ) {
-                                               $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
-                                       }
-                                       $this->formtype = 'diff';
-                               } else {
-                                       # Warn the user that something went wrong
-                                       $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
+                                       $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-norev' ) );
                                }
                        } else if( $section != '' ) {
                                if( $section == 'new' ) {
@@ -206,7 +215,7 @@ class EditPage {
         * @param $preload String: the title of the page.
         * @return string The contents of the page.
         */
-       private function getPreloadedText($preload) {
+       protected function getPreloadedText($preload) {
                if ( $preload === '' )
                        return '';
                else {
@@ -319,11 +328,11 @@ class EditPage {
                $this->mArticle->mContent = $t ;
                $this->mMetaData = $s ;
        }
-       
+
        protected function wasDeletedSinceLastEdit() {
                /* Note that we rely on the logging table, which hasn't been always there,
                 * but that doesn't matter, because this only applies to brand new
-                * deletes. 
+                * deletes.
                 */
                if ( $this->deletedSinceEdit )
                        return true;
@@ -364,7 +373,7 @@ class EditPage {
                wfDebug( __METHOD__.": enter\n" );
 
                // this is not an article
-               $wgOut->setArticleFlag(false);
+               $wgOut->setArticleFlag( false );
 
                $this->importFormData( $wgRequest );
                $this->firsttime = false;
@@ -374,17 +383,28 @@ class EditPage {
                        wfProfileOut( __METHOD__ );
                        return;
                }
-               
+
                if( wfReadOnly() ) {
-                       $this->readOnlyPage( $this->getContent() );
-                       wfProfileOut( __METHOD__ );
-                       return;
+                       if( $this->save ){
+                               // Force preview
+                               $this->save = false;
+                               $this->preview = true;
+                       } elseif( $this->preview || $this->diff ){
+                               // A warning will be displayed instead
+                       } else {
+                               $this->readOnlyPage( $this->getContent() );
+                               wfProfileOut( __METHOD__ );
+                               return;
+                       }
                }
 
-               $permErrors = $this->mTitle->getUserPermissionsErrors('edit', $wgUser);
+               $wgOut->addScriptFile( 'edit.js' );
+
+               $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
+               
                if( !$this->mTitle->exists() ) {
-                       $permErrors = array_merge( $permErrors, 
-                               wfArrayDiff2( $this->mTitle->getUserPermissionsErrors('create', $wgUser), $permErrors ) );
+                       $permErrors = array_merge( $permErrors,
+                               wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
                }
 
                # Ignore some permissions errors.
@@ -396,27 +416,18 @@ class EditPage {
                                // Don't worry about blocks when previewing/diffing
                                $remove[] = $error;
                        }
-
-                       if ($error[0] == 'readonlytext')
-                       {
-                               if ($this->edit) {
-                                       $this->formtype = 'preview';
-                               } elseif ($this->save || $this->preview || $this->diff) {
-                                       $remove[] = $error;
-                               }
-                       }
                }
                $permErrors = wfArrayDiff2( $permErrors, $remove );
-
+               
                if ( $permErrors ) {
                        wfDebug( __METHOD__.": User can't edit\n" );
-                       $this->readOnlyPage( $this->getContent(), true, $permErrors );
+                       $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
                        wfProfileOut( __METHOD__ );
                        return;
                } else {
                        if ( $this->save ) {
                                $this->formtype = 'save';
-                       } else if ( $this->preview ) {
+                       } else if( $this->preview ) {
                                $this->formtype = 'preview';
                        } else if ( $this->diff ) {
                                $this->formtype = 'diff';
@@ -441,11 +452,30 @@ class EditPage {
                # Show applicable editing introductions
                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_page = $editnotice_ns.'-'.$this->mTitle->getDBkey();
+               if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
+                       $wgOut->addWikiText( wfMsgForContent( $editnotice_ns )  );
+               }
+               if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
+                       $parts = explode( '/', $this->mTitle->getDBkey() );
+                       $editnotice_base = $editnotice_ns;
+                       while ( count( $parts ) > 0 ) {
+                               $editnotice_base .= '-'.array_shift( $parts );
+                               if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
+                                       $wgOut->addWikiText( wfMsgForContent( $editnotice_base )  );
+                               }
+                       }
+               } else if ( !wfEmptyMsg( $editnotice_page, wfMsgForContent( $editnotice_page ) ) ) {
+                       $wgOut->addWikiText( wfMsgForContent( $editnotice_page ) );
+               }
+
                # Attempt submission here.  This will check for edit conflicts,
                # and redundantly check for locked database, blocked IPs, etc.
                # that edit() already checked just in case someone tries to sneak
@@ -468,7 +498,7 @@ class EditPage {
                                wfProfileOut( __METHOD__ );
                                return;
                        }
-                       if( !$this->mTitle->getArticleId() ) 
+                       if( !$this->mTitle->getArticleId() )
                                wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
                }
 
@@ -482,15 +512,15 @@ class EditPage {
         * Parameters are the same as OutputPage:readOnlyPage()
         * Redirect to the article page if redlink=1
         */
-       function readOnlyPage( $source = null, $protected = false, $reasons = array() ) {
+       function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
                global $wgRequest, $wgOut;
                if ( $wgRequest->getBool( 'redlink' ) ) {
                        // The edit page was reached via a red link.
-                       // Redirect to the article page and let them click the edit tab if 
+                       // Redirect to the article page and let them click the edit tab if
                        // they really want a permission error.
                        $wgOut->redirect( $this->mTitle->getFullUrl() );
                } else {
-                       $wgOut->readOnlyPage( $source, $protected, $reasons );
+                       $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
                }
        }
 
@@ -499,7 +529,7 @@ class EditPage {
         *
         * @return bool
         */
-       private function previewOnOpen() {
+       protected function previewOnOpen() {
                global $wgRequest, $wgUser;
                if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
                        // Explicit override from request
@@ -539,12 +569,12 @@ class EditPage {
                        # whitespace from the text boxes. This may be significant formatting.
                        $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
                        $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
-                       $this->mMetaData = rtrim( $request->getText( 'metadata'   ) );
+                       $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
                        # Truncate for whole multibyte characters. +5 bytes for ellipsis
-                       $this->summary   = $wgLang->truncate( $request->getText( 'wpSummary'  ), 250 );
-                       
-                       # Remove extra headings and whitespace from summaries and new sections.
-                       $this->summary = trim(preg_replace('/^=+(.*?)=+$/', '$1', trim($this->summary)));
+                       $this->summary = $wgLang->truncate( $request->getText( 'wpSummary'  ), 250 );
+
+                       # Remove extra headings from summaries and new sections.
+                       $this->summary = preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary);
 
                        $this->edittime = $request->getVal( 'wpEdittime' );
                        $this->starttime = $request->getVal( 'wpStarttime' );
@@ -581,7 +611,7 @@ class EditPage {
                                        $this->preview = true;
                                }
                        }
-                       $this->save    = ! ( $this->preview OR $this->diff );
+                       $this->save = !$this->preview && !$this->diff;
                        if( !preg_match( '/^\d{14}$/', $this->edittime )) {
                                $this->edittime = null;
                        }
@@ -602,7 +632,7 @@ class EditPage {
                                $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
                        }
 
-                       $this->autoSumm = $request->getText( 'wpAutoSummary' ); 
+                       $this->autoSumm = $request->getText( 'wpAutoSummary' );
                } else {
                        # Not a posted form? Start with nothing.
                        wfDebug( "$fname: Not a posted form.\n" );
@@ -651,7 +681,7 @@ class EditPage {
        /**
         * Show all applicable editing introductions
         */
-       private function showIntro() {
+       protected function showIntro() {
                global $wgOut, $wgUser;
                if( $this->suppressIntro )
                        return;
@@ -664,7 +694,7 @@ class EditPage {
                        $ip = User::isIP( $username );
 
                        if ( $id == 0 && !$ip ) {
-                               $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>', 
+                               $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
                                        array( 'userpage-userdoesnotexist', $username ) );
                        }
                }
@@ -684,7 +714,7 @@ class EditPage {
         *
         * @return bool
         */
-       private function showCustomIntro() {
+       protected function showCustomIntro() {
                if( $this->editintro ) {
                        $title = Title::newFromText( $this->editintro );
                        if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
@@ -705,7 +735,7 @@ class EditPage {
         * @return one of the constants describing the result
         */
        function internalAttemptSave( &$result, $bot = false ) {
-               global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
+               global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
                global $wgMaxArticleSize;
 
                $fname = 'EditPage::attemptSave';
@@ -734,20 +764,27 @@ class EditPage {
                $this->mMetaData = '' ;
 
                # Check for spam
-               $matches = array();
-               if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
-                       $result['spam'] = $matches[0];
+               $match = self::matchSpamRegex( $this->summary );
+               if( $match === false ) {
+                       $match = self::matchSpamRegex( $this->textbox1 );
+               }
+               if( $match !== false ) {
+                       $result['spam'] = $match;
+                       $ip = wfGetIP();
+                       $pdbk = $this->mTitle->getPrefixedDBkey();
+                       $match = str_replace( "\n", '', $match );
+                       wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
                        wfProfileOut( "$fname-checks" );
                        wfProfileOut( $fname );
                        return self::AS_SPAM_ERROR;
                }
-               if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
+               if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
                        # Error messages or other handling should be performed by the filter function
                        wfProfileOut( "$fname-checks" );
                        wfProfileOut( $fname );
                        return self::AS_FILTERING;
                }
-               if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
+               if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
                        # Error messages etc. could be handled within the hook...
                        wfProfileOut( "$fname-checks" );
                        wfProfileOut( $fname );
@@ -825,14 +862,14 @@ class EditPage {
                        }
 
                        // Run post-section-merge edit filter
-                       if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError ) ) ) {
+                       if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
                                # Error messages etc. could be handled within the hook...
                                wfProfileOut( $fname );
                                return self::AS_HOOK_ERROR;
                        }
 
                        $isComment = ( $this->section == 'new' );
-                       
+
                        $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
                                $this->minoredit, $this->watchthis, false, $isComment, $bot);
 
@@ -863,7 +900,7 @@ class EditPage {
                                }
                        }
                }
-               $userid = $wgUser->getID();
+               $userid = $wgUser->getId();
 
                if ( $this->isConflict) {
                        wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
@@ -908,15 +945,18 @@ class EditPage {
                $oldtext = $this->mArticle->getContent();
 
                // Run post-section-merge edit filter
-               if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError ) ) ) {
+               if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
                        # Error messages etc. could be handled within the hook...
                        wfProfileOut( $fname );
                        return self::AS_HOOK_ERROR;
                }
 
                # Handle the user preference to force summaries here, but not for null edits
-               if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
-                       &&  0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
+               if( $this->section != 'new' && !$this->allowBlankSummary &&  $wgUser->getOption( 'forceeditsummary') && 
+                       0 != strcmp($oldtext, $text) && 
+                       !is_object( Title::newFromRedirect( $text ) ) # check if it's not a redirect
+               ) {
+
                        if( md5( $this->summary ) == $this->autoSumm ) {
                                $this->missingSummary = true;
                                wfProfileOut( $fname );
@@ -924,7 +964,7 @@ class EditPage {
                        }
                }
 
-               #And a similar thing for new sections
+               # And a similar thing for new sections
                if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
                        if (trim($this->summary) == '') {
                                $this->missingSummary = true;
@@ -987,6 +1027,25 @@ class EditPage {
                wfProfileOut( $fname );
                return self::AS_END;
        }
+       
+       /**
+        * Check given input text against $wgSpamRegex, and return the text of the first match.
+        * @return mixed -- matching string or false
+        */
+       public static function matchSpamRegex( $text ) {
+               global $wgSpamRegex;
+               if( $wgSpamRegex ) {
+                       // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
+                       $regexes = (array)$wgSpamRegex;
+                       foreach( $regexes as $regex ) {
+                               $matches = array();
+                               if ( preg_match( $regex, $text, $matches ) ) {
+                                       return $matches[0];
+                               }
+                       }
+               }
+               return false;
+       }
 
        /**
         * Initialise form fields in the object
@@ -1003,6 +1062,29 @@ class EditPage {
                return true;
        }
 
+       function setHeaders() {
+               global $wgOut, $wgTitle;
+               $wgOut->setRobotPolicy( 'noindex,nofollow' );
+               if ( $this->formtype == 'preview' ) {
+                       $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
+               }
+               if ( $this->isConflict ) {
+                       $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
+               } elseif( $this->section != '' ) {
+                       $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
+                       $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->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 = $wgTitle->getPrefixedText();
+                       }
+                       $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
+               }
+       }
+
        /**
         * Send the edit form and related headers to $wgOut
         * @param $formCallback Optional callable that takes an OutputPage
@@ -1011,7 +1093,7 @@ class EditPage {
         */
        function showEditForm( $formCallback=null ) {
                global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
-               
+
                # If $wgTitle is null, that means we're in API mode.
                # Some hook probably called this function  without checking
                # for is_null($wgTitle) first. Bail out right here so we don't
@@ -1026,46 +1108,41 @@ class EditPage {
 
                wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
 
-               $wgOut->setRobotpolicy( 'noindex,nofollow' );
+               #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();
+               }
+
+               $this->setHeaders();
 
                # Enabled article-related sidebar, toplinks, etc.
                $wgOut->setArticleRelated( true );
 
-               if ( $this->formtype == 'preview' ) {
-                       $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
-               }
-
                if ( $this->isConflict ) {
-                       $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
-                       $wgOut->setPageTitle( $s );
                        $wgOut->addWikiMsg( 'explainconflict' );
 
                        $this->textbox2 = $this->textbox1;
                        $this->textbox1 = $this->getContent();
                        $this->edittime = $this->mArticle->getTimestamp();
                } else {
-                       if( $this->section != '' ) {
-                               if( $this->section == 'new' ) {
-                                       $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
-                               } else {
-                                       $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
-                                       $matches = array();
-                                       if( !$this->summary && !$this->preview && !$this->diff ) {
-                                               preg_match( "/^(=+)(.+)\\1/mi",
-                                                       $this->textbox1,
-                                                       $matches );
-                                               if( !empty( $matches[2] ) ) {
-                                                       global $wgParser;
-                                                       $this->summary = "/* " . 
-                                                               $wgParser->stripSectionName(trim($matches[2])) . 
-                                                               " */ ";
-                                               }
+                       if( $this->section != '' && $this->section != 'new' ) {
+                               $matches = array();
+                               if( !$this->summary && !$this->preview && !$this->diff ) {
+                                       preg_match( "/^(=+)(.+)\\1/mi",
+                                               $this->textbox1,
+                                               $matches );
+                                       if( !empty( $matches[2] ) ) {
+                                               global $wgParser;
+                                               $this->summary = "/* " .
+                                                       $wgParser->stripSectionName(trim($matches[2])) .
+                                                       " */ ";
                                        }
                                }
-                       } else {
-                               $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
                        }
-                       $wgOut->setPageTitle( $s );
 
                        if ( $this->missingComment ) {
                                $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>',  'missingcommenttext' );
@@ -1088,13 +1165,13 @@ class EditPage {
                        }
                        if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
                        // Let sysop know that this will make private content public if saved
-                               
+
                                if( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
                                        $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
                                } else if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
                                        $wgOut->addWikiMsg( 'rev-deleted-text-view' );
                                }
-                               
+
                                if( !$this->mArticle->mRevision->isCurrent() ) {
                                        $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
                                        $wgOut->addWikiMsg( 'editingold' );
@@ -1103,9 +1180,9 @@ class EditPage {
                }
 
                if( wfReadOnly() ) {
-                       $wgOut->addHTML( '<div id="mw-read-only-warning">'.wfMsgWikiHTML( 'readonlywarning' ).'</div>' );
+                       $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
                } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
-                       $wgOut->addHTML( '<div id="mw-anon-edit-warning">'.wfMsgWikiHTML( 'anoneditwarning' ).'</div>' );
+                       $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
                } else {
                        if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
                                # Check the skin exists
@@ -1128,7 +1205,9 @@ class EditPage {
                                # Then it must be protected based on static groups (regular)
                                $noticeMsg = 'protectedpagewarning';
                        }
+                       $wgOut->addHTML( "<div id='mw-edit-$noticeMsg'>\n" );
                        $wgOut->addWikiMsg( $noticeMsg );
+                       $wgOut->addHTML( "</div>\n" );
                }
                if ( $this->mTitle->isCascadeProtected() ) {
                        # Is this page under cascading protection from some source pages?
@@ -1150,30 +1229,22 @@ class EditPage {
                        $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
                }
                if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
-                       $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize );
+                       $wgOut->addHTML( "<div id='mw-edit-longpageerror'>\n" );
+                       $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) );
+                       $wgOut->addHTML( "</div>\n" );
                } elseif( $this->kblength > 29 ) {
+                       $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
                        $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
+                       $wgOut->addHTML( "</div>\n" );
                }
 
-               #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
-               if ( $this->formtype == 'preview' ) {
-                       $previewOutput = $this->getPreviewText();
-               }
-
-               $rows = $wgUser->getIntOption( 'rows' );
-               $cols = $wgUser->getIntOption( 'cols' );
-
-               $ew = $wgUser->getOption( 'editwidth' );
-               if ( $ew ) $ew = " style=\"width:100%\"";
-               else $ew = '';
-
-               $q = 'action=submit';
+               $q = 'action='.$this->action;
                #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
                $action = $wgTitle->escapeLocalURL( $q );
 
-               $summary = wfMsg('summary');
-               $subject = wfMsg('subject');
+               $colonSep = wfMsg( 'colon-separator' );
+               $summary = wfMsg( 'summary' ) . $colonSep;
+               $subject = wfMsg( 'subject' ) . $colonSep;
 
                $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
                                wfMsgExt('cancel', array('parseinline')) );
@@ -1184,17 +1255,17 @@ class EditPage {
 
                global $wgRightsText;
                if ( $wgRightsText ) {
-                       $copywarnMsg = array( 'copyrightwarning', 
+                       $copywarnMsg = array( 'copyrightwarning',
                                '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
                                $wgRightsText );
                } else {
-                       $copywarnMsg = array( 'copyrightwarning2', 
+                       $copywarnMsg = array( 'copyrightwarning2',
                                '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
                }
 
                if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
                        # prepare toolbar for edit buttons
-                       $toolbar = $this->getEditToolbar();
+                       $toolbar = EditPage::getEditToolbar();
                } else {
                        $toolbar = '';
                }
@@ -1219,16 +1290,9 @@ class EditPage {
                $wgOut->addHTML( $this->editFormPageTop );
 
                if ( $wgUser->getOption( 'previewontop' ) ) {
-
-                       if ( 'preview' == $this->formtype ) {
-                               $this->showPreview( $previewOutput );
-                       } else {
-                               $wgOut->addHTML( '<div id="wikiPreview"></div>' );
-                       }
-
-                       if ( 'diff' == $this->formtype ) {
-                               $this->showDiff();
-                       }
+                       $this->displayPreviewArea( $previewOutput );
+                       // Spacer for the edit toolbar
+                       $wgOut->addHTML( '<p><br /></p>' );
                }
 
 
@@ -1237,7 +1301,7 @@ class EditPage {
                # if this is a comment, show a subject line at the top, which is also the edit summary.
                # Otherwise, show a summary field at the bottom
                $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
-               
+
                # 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
@@ -1246,18 +1310,20 @@ class EditPage {
                # For a bit more sophisticated detection of blank summaries, hash the
                # automatic one and pass that in the hidden field wpAutoSummary.
                $summaryhiddens =  '';
-               if( $this->missingSummary ) $summaryhiddens .= wfHidden( 'wpIgnoreBlankSummary', true );
+               if( $this->missingSummary ) $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true );
                $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
-               $summaryhiddens .= wfHidden( 'wpAutoSummary', $autosumm );
+               $summaryhiddens .= Xml::hidden( 'wpAutoSummary', $autosumm );
                if( $this->section == 'new' ) {
-                       $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
-                       $editsummary = '';
-                       $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
+                       $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}</label></span>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
+                       $editsummary = "<div class='editOptions'>\n";
+                       global $wgParser;
+                       $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) );
+                       $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').$colonSep.$sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : '';
                        $summarypreview = '';
                } else {
                        $commentsubject = '';
-                       $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
-                       $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
+                       $editsummary="<div class='editOptions'>\n<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}</label></span>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
+                       $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').$colonSep.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
                        $subjectpreview = '';
                }
 
@@ -1265,7 +1331,7 @@ class EditPage {
                if( !$this->preview && !$this->diff ) {
                        $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
                }
-               $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
+               $templates = $this->getTemplates();
                $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
 
                $hiddencats = $this->mArticle->getHiddenCategories();
@@ -1276,11 +1342,15 @@ class EditPage {
                        $metadata = $this->mMetaData ;
                        $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
                        $top = wfMsgWikiHtml( 'metadata_help' );
+                       /* ToDo: Replace with clean code */
+                       $ew = $wgUser->getOption( 'editwidth' );
+                       if ( $ew ) $ew = " style=\"width:100%\"";
+                       else $ew = '';
+                       /* /ToDo */
                        $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
                }
                else $metadata = "" ;
 
-               $hidden = '';
                $recreate = '';
                if ($this->wasDeletedSinceLastEdit()) {
                        if ( 'save' != $this->formtype ) {
@@ -1289,7 +1359,6 @@ class EditPage {
                                // Hide the toolbar and edit area, use can click preview to get it back
                                // Add an confirmation checkbox and explanation.
                                $toolbar = '';
-                               $hidden = 'type="hidden" style="display:none;"';
                                $recreate = $wgOut->parse( wfMsg( 'confirmrecreate',  $this->lastDelete->user_name , $this->lastDelete->log_comment ));
                                $recreate .=
                                        "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
@@ -1323,34 +1392,27 @@ END
                wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
 
                // Put these up at the top to ensure they aren't lost on early form submission
-               $wgOut->addHTML( "
-<input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
-<input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
-<input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
-<input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
+               $this->showFormBeforeText();
 
                $wgOut->addHTML( <<<END
-$recreate
+{$recreate}
 {$commentsubject}
 {$subjectpreview}
 {$this->editFormTextBeforeContent}
-<textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
-cols='{$cols}'{$ew} $hidden>
 END
-. htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
-"
-</textarea>
-               " );
+);
+               $this->showTextbox1();
 
                $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
-               $wgOut->addHTML( $this->editFormTextAfterWarn );
-               $wgOut->addHTML( "
+               $wgOut->addHTML( <<<END
+{$this->editFormTextAfterWarn}
 {$metadata}
 {$editsummary}
 {$summarypreview}
 {$checkboxhtml}
 {$safemodehtml}
-");
+END
+);
 
                $wgOut->addHTML(
 "<div class='editButtons'>
@@ -1374,22 +1436,20 @@ END
                $token = htmlspecialchars( $wgUser->editToken() );
                $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
 
-               $wgOut->addHtml( '<div class="mw-editTools">' );
-               $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
-               $wgOut->addHtml( '</div>' );
-
-               $wgOut->addHTML( $this->editFormTextAfterTools );
+               $this->showEditTools();
 
-               $wgOut->addHTML( "
+               $wgOut->addHTML( <<<END
+{$this->editFormTextAfterTools}
 <div class='templatesUsed'>
 {$formattedtemplates}
 </div>
 <div class='hiddencats'>
 {$formattedhiddencats}
 </div>
-");
+END
+);
 
-               if ( $this->isConflict ) {
+               if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
                        $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
 
                        $de = new DifferenceEngine( $this->mTitle );
@@ -1397,26 +1457,77 @@ END
                        $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
 
                        $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
-                       $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
-                               . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
+                       $this->showTextbox2();
                }
                $wgOut->addHTML( $this->editFormTextBottom );
                $wgOut->addHTML( "</form>\n" );
                if ( !$wgUser->getOption( 'previewontop' ) ) {
+                       $this->displayPreviewArea( $previewOutput );
+               }
 
-                       if ( $this->formtype == 'preview') {
-                               $this->showPreview( $previewOutput );
-                       } else {
-                               $wgOut->addHTML( '<div id="wikiPreview"></div>' );
-                       }
+               wfProfileOut( $fname );
+       }
 
-                       if ( $this->formtype == 'diff') {
-                               $this->showDiff();
-                       }
+       protected function showFormBeforeText() {
+               global $wgOut;
+               $wgOut->addHTML( "
+<input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
+<input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
+<input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
+<input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
+       }
+       
+       protected function showTextbox1() {
+               $attribs = array( 'tabindex' => 1 );
+               
+               if( $this->wasDeletedSinceLastEdit() )
+                       $attribs['type'] = 'hidden';
+               
+               $this->showTextbox( $this->textbox1, 'wpTextbox1', $attribs );
+       }
+       
+       protected function showTextbox2() {
+               $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) );
+       }
+       
+       protected function showTextbox( $content, $name, $attribs = array() ) {
+               global $wgOut, $wgUser;
+               
+               $wikitext = $this->safeUnicodeOutput( $content );
+               if( $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
+                       // mode will show an extra newline. A bit annoying.
+                       $wikitext .= "\n";
+               }
+               
+               $attribs = array(
+                       'accesskey' => ',',
+                       'id'        => $name,
+               );
+               
+               if( $wgUser->getOption( 'editwidth' ) )
+                       $attribs['style'] = 'width: 100%';
+               
+               $wgOut->addHTML( Xml::textarea(
+                       $name,
+                       $wikitext,
+                       $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
+                       $attribs ) );
+       }
 
+       protected function displayPreviewArea( $previewOutput ) {
+               global $wgOut;
+               if ( $this->formtype == 'preview') {
+                       $this->showPreview( $previewOutput );
+               } else {
+                       $wgOut->addHTML( '<div id="wikiPreview"></div>' );
                }
 
-               wfProfileOut( $fname );
+               if ( $this->formtype == 'diff') {
+                       $this->showDiff();
+               }
        }
 
        /**
@@ -1425,7 +1536,7 @@ END
         *
         * @param string $text The HTML to be output for the preview.
         */
-       private function showPreview( $text ) {
+       protected function showPreview( $text ) {
                global $wgOut;
 
                $wgOut->addHTML( '<div id="wikiPreview">' );
@@ -1451,16 +1562,21 @@ END
         * of the preview button
         */
        function doLivePreviewScript() {
-               global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
-               $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
-                       htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
-                       '"></script>' . "\n" );
-               $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
+               global $wgOut, $wgTitle;
+               $wgOut->addScriptFile( 'preview.js' );
+               $liveAction = $wgTitle->getLocalUrl( "action={$this->action}&wpPreview=true&live=true" );
                return "return !lpDoPreview(" .
                        "editform.wpTextbox1.value," .
                        '"' . $liveAction . '"' . ")";
        }
 
+       protected function showEditTools() {
+               global $wgOut;
+               $wgOut->addHtml( '<div class="mw-editTools">' );
+               $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
+               $wgOut->addHtml( '</div>' );
+       }
+
        function getLastDelete() {
                $dbr = wfGetDB( DB_SLAVE );
                $fname = 'EditPage::getLastDelete';
@@ -1494,13 +1610,13 @@ END
        }
 
        /**
-        * @todo document
+        * Get the rendered text for previewing.
+        * @return string
         */
        function getPreviewText() {
                global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
 
-               $fname = 'EditPage::getPreviewText';
-               wfProfileIn( $fname );
+               wfProfileIn( __METHOD__ );
 
                if ( $this->mTriedSave && !$this->mTokenOk ) {
                        if ( $this->mTokenOkExceptSuffix ) {
@@ -1534,8 +1650,10 @@ END
                        }
                        $parserOptions->setTidy(true);
                        $parserOutput = $wgParser->parse( $previewtext , $this->mTitle, $parserOptions );
-                       $wgOut->addHTML( $parserOutput->mText );
+                       //$wgOut->addHTML( $parserOutput->mText );
                        $previewHTML = '';
+               } elseif( $rt = Title::newFromRedirect( $this->textbox1 ) ) {
+                       $previewHTML = $this->mArticle->viewRedirect( $rt, false );
                } else {
                        $toparse = $this->textbox1;
 
@@ -1567,23 +1685,12 @@ END
 
                        $parserOptions->setTidy(true);
                        $parserOptions->enableLimitReport();
-                       $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
+                       $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
                                        $this->mTitle, $parserOptions );
 
                        $previewHTML = $parserOutput->getText();
+                       $this->mParserOutput = $parserOutput;
                        $wgOut->addParserOutputNoText( $parserOutput );
-                       
-                       # ParserOutput might have altered the page title, so reset it
-                       # Also, use the title defined by DISPLAYTITLE magic word when present
-                       if( ( $dt = $parserOutput->getDisplayTitle() ) !== false ) {
-                               $wgOut->setPageTitle( wfMsg( 'editing', $dt ) );
-                       } else {
-                               $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );                        
-                       }
-
-                       foreach ( $parserOutput->getTemplates() as $ns => $template)
-                               foreach ( array_keys( $template ) as $dbk)
-                                       $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
 
                        if ( count( $parserOutput->getWarnings() ) ) {
                                $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
@@ -1593,12 +1700,27 @@ END
                $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
                        "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
                if ( $this->isConflict ) {
-                       $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
+                       $previewhead .='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
                }
 
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $previewhead . $previewHTML;
        }
+       
+       function getTemplates() {
+               if( $this->preview || $this->section != '' ) {
+                       $templates = array();
+                       if( !isset($this->mParserOutput) ) return $templates;
+                       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();
+               }
+       }
 
        /**
         * Call the stock "user is blocked" page
@@ -1618,12 +1740,14 @@ END
 
                # Spit out the source or the user's modified version
                if( $source !== false ) {
-                       $rows = $wgUser->getOption( 'rows' );
-                       $cols = $wgUser->getOption( 'cols' );
+                       $rows = $wgUser->getIntOption( 'rows' );
+                       $cols = $wgUser->getIntOption( 'cols' );
                        $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
                        $wgOut->addHtml( '<hr />' );
                        $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
-                       $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
+                       # Why we don't use Xml::element here?
+                       # Is it because if $source is '', it returns <textarea />?
+                       $wgOut->addHtml( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
                }
        }
 
@@ -1675,7 +1799,7 @@ END
                $wgOut->addHtml( '<div id="spamprotected">' );
                $wgOut->addWikiMsg( 'spamprotectiontext' );
                if ( $match )
-                       $wgOut->addWikiMsg( 'spamprotectionmatch',wfEscapeWikiText( $match ) );
+                       $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
                $wgOut->addHtml( '</div>' );
 
                $wgOut->returnToMain( false, $wgTitle );
@@ -1692,8 +1816,7 @@ END
                $db = wfGetDB( DB_MASTER );
 
                // This is the revision the editor started from
-               $baseRevision = Revision::loadFromTimestamp(
-                       $db, $this->mTitle, $this->edittime );
+               $baseRevision = $this->getBaseRevision();
                if( is_null( $baseRevision ) ) {
                        wfProfileOut( $fname );
                        return false;
@@ -1764,10 +1887,12 @@ END
        /**
         * Shows a bulletin board style toolbar for common editing functions.
         * It can be disabled in the user preferences.
-        * The necessary JavaScript code can be found in style/wikibits.js.
+        * The necessary JavaScript code can be found in skins/common/edit.js.
+        * 
+        * @return string
         */
-       function getEditToolbar() {
-               global $wgStylePath, $wgContLang, $wgJsMimeType;
+       static function getEditToolbar() {
+               global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
 
                /**
                 * toolarray an array of arrays which each include the filename of
@@ -1781,93 +1906,104 @@ END
                 * sure these keys are not defined on the edit page.
                 */
                $toolarray = array(
-                       array(  'image' => 'button_bold.png',
-                               'id'    => 'mw-editbutton-bold',
-                               'open'  => '\'\'\'',
-                               'close' => '\'\'\'',
-                               'sample'=> wfMsg('bold_sample'),
-                               'tip'   => wfMsg('bold_tip'),
-                               'key'   => 'B'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-bold'),
+                               'id'     => 'mw-editbutton-bold',
+                               'open'   => '\'\'\'',
+                               'close'  => '\'\'\'',
+                               'sample' => wfMsg('bold_sample'),
+                               'tip'    => wfMsg('bold_tip'),
+                               'key'    => 'B'
                        ),
-                       array(  'image' => 'button_italic.png',
-                               'id'    => 'mw-editbutton-italic',
-                               'open'  => '\'\'',
-                               'close' => '\'\'',
-                               'sample'=> wfMsg('italic_sample'),
-                               'tip'   => wfMsg('italic_tip'),
-                               'key'   => 'I'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-italic'),
+                               'id'     => 'mw-editbutton-italic',
+                               'open'   => '\'\'',
+                               'close'  => '\'\'',
+                               'sample' => wfMsg('italic_sample'),
+                               'tip'    => wfMsg('italic_tip'),
+                               'key'    => 'I'
                        ),
-                       array(  'image' => 'button_link.png',
-                               'id'    => 'mw-editbutton-link',
-                               'open'  => '[[',
-                               'close' => ']]',
-                               'sample'=> wfMsg('link_sample'),
-                               'tip'   => wfMsg('link_tip'),
-                               'key'   => 'L'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-link'),
+                               'id'     => 'mw-editbutton-link',
+                               'open'   => '[[',
+                               'close'  => ']]',
+                               'sample' => wfMsg('link_sample'),
+                               'tip'    => wfMsg('link_tip'),
+                               'key'    => 'L'
                        ),
-                       array(  'image' => 'button_extlink.png',
-                               'id'    => 'mw-editbutton-extlink',
-                               'open'  => '[',
-                               'close' => ']',
-                               'sample'=> wfMsg('extlink_sample'),
-                               'tip'   => wfMsg('extlink_tip'),
-                               'key'   => 'X'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-extlink'),
+                               'id'     => 'mw-editbutton-extlink',
+                               'open'   => '[',
+                               'close'  => ']',
+                               'sample' => wfMsg('extlink_sample'),
+                               'tip'    => wfMsg('extlink_tip'),
+                               'key'    => 'X'
                        ),
-                       array(  'image' => 'button_headline.png',
-                               'id'    => 'mw-editbutton-headline',
-                               'open'  => "\n== ",
-                               'close' => " ==\n",
-                               'sample'=> wfMsg('headline_sample'),
-                               'tip'   => wfMsg('headline_tip'),
-                               'key'   => 'H'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-headline'),
+                               'id'     => 'mw-editbutton-headline',
+                               'open'   => "\n== ",
+                               'close'  => " ==\n",
+                               'sample' => wfMsg('headline_sample'),
+                               'tip'    => wfMsg('headline_tip'),
+                               'key'    => 'H'
                        ),
-                       array(  'image' => 'button_image.png',
-                               'id'    => 'mw-editbutton-image',
-                               'open'  => '[['.$wgContLang->getNsText(NS_IMAGE).":",
-                               'close' => ']]',
-                               'sample'=> wfMsg('image_sample'),
-                               'tip'   => wfMsg('image_tip'),
-                               'key'   => 'D'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-image'),
+                               'id'     => 'mw-editbutton-image',
+                               'open'   => '[['.$wgContLang->getNsText(NS_IMAGE).':',
+                               'close'  => ']]',
+                               'sample' => wfMsg('image_sample'),
+                               'tip'    => wfMsg('image_tip'),
+                               'key'    => 'D'
                        ),
-                       array(  'image' => 'button_media.png',
-                               'id'    => 'mw-editbutton-media',
-                               'open'  => '[['.$wgContLang->getNsText(NS_MEDIA).':',
-                               'close' => ']]',
-                               'sample'=> wfMsg('media_sample'),
-                               'tip'   => wfMsg('media_tip'),
-                               'key'   => 'M'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-media'),
+                               'id'     => 'mw-editbutton-media',
+                               'open'   => '[['.$wgContLang->getNsText(NS_MEDIA).':',
+                               'close'  => ']]',
+                               'sample' => wfMsg('media_sample'),
+                               'tip'    => wfMsg('media_tip'),
+                               'key'    => 'M'
                        ),
-                       array(  'image' => 'button_math.png',
-                               'id'    => 'mw-editbutton-math',
-                               'open'  => "<math>",
-                               'close' => "</math>",
-                               'sample'=> wfMsg('math_sample'),
-                               'tip'   => wfMsg('math_tip'),
-                               'key'   => 'C'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-math'),
+                               'id'     => 'mw-editbutton-math',
+                               'open'   => "<math>",
+                               'close'  => "</math>",
+                               'sample' => wfMsg('math_sample'),
+                               'tip'    => wfMsg('math_tip'),
+                               'key'    => 'C'
                        ),
-                       array(  'image' => 'button_nowiki.png',
-                               'id'    => 'mw-editbutton-nowiki',
-                               'open'  => "<nowiki>",
-                               'close' => "</nowiki>",
-                               'sample'=> wfMsg('nowiki_sample'),
-                               'tip'   => wfMsg('nowiki_tip'),
-                               'key'   => 'N'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-nowiki'),
+                               'id'     => 'mw-editbutton-nowiki',
+                               'open'   => "<nowiki>",
+                               'close'  => "</nowiki>",
+                               'sample' => wfMsg('nowiki_sample'),
+                               'tip'    => wfMsg('nowiki_tip'),
+                               'key'    => 'N'
                        ),
-                       array(  'image' => 'button_sig.png',
-                               'id'    => 'mw-editbutton-signature',
-                               'open'  => '--~~~~',
-                               'close' => '',
-                               'sample'=> '',
-                               'tip'   => wfMsg('sig_tip'),
-                               'key'   => 'Y'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-sig'),
+                               'id'     => 'mw-editbutton-signature',
+                               'open'   => '--~~~~',
+                               'close'  => '',
+                               'sample' => '',
+                               'tip'    => wfMsg('sig_tip'),
+                               'key'    => 'Y'
                        ),
-                       array(  'image' => 'button_hr.png',
-                               'id'    => 'mw-editbutton-hr',
-                               'open'  => "\n----\n",
-                               'close' => '',
-                               'sample'=> '',
-                               'tip'   => wfMsg('hr_tip'),
-                               'key'   => 'R'
+                       array(
+                               'image'  => $wgLang->getImageFile('button-hr'),
+                               'id'     => 'mw-editbutton-hr',
+                               'open'   => "\n----\n",
+                               'close'  => '',
+                               'sample' => '',
+                               'tip'    => wfMsg('hr_tip'),
+                               'key'    => 'R'
                        )
                );
                $toolbar = "<div id='toolbar'>\n";
@@ -1886,7 +2022,7 @@ END
                                $sample = $tool['sample'],
                                $cssId = $tool['id'],
                        );
-                       
+
                        $paramList = implode( ',',
                                array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
                        $toolbar.="addButton($paramList);\n";
@@ -1923,7 +2059,7 @@ END
                        );
                        $checkboxes['minor'] =
                                Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
-                               "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
+                               "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
                }
 
                $watchLabel = wfMsgExt('watchthis', array('parseinline'));
@@ -1936,7 +2072,7 @@ END
                        );
                        $checkboxes['watch'] =
                                Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
-                               "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
+                               "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
                }
                return $checkboxes;
        }
@@ -1963,7 +2099,7 @@ END
                        'accesskey' => wfMsg('accesskey-save'),
                        'title'     => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
                );
-               $buttons['save'] = wfElement('input', $temp, '');
+               $buttons['save'] = Xml::element('input', $temp, '');
 
                ++$tabindex; // use the same for preview and live preview
                if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
@@ -1977,7 +2113,7 @@ END
                                'title'     => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
                                'style'     => 'display: none;',
                        );
-                       $buttons['preview'] = wfElement('input', $temp, '');
+                       $buttons['preview'] = Xml::element('input', $temp, '');
 
                        $temp = array(
                                'id'        => 'wpLivePreview',
@@ -1989,7 +2125,7 @@ END
                                'title'     => '',
                                'onclick'   => $this->doLivePreviewScript(),
                        );
-                       $buttons['live'] = wfElement('input', $temp, '');
+                       $buttons['live'] = Xml::element('input', $temp, '');
                } else {
                        $temp = array(
                                'id'        => 'wpPreview',
@@ -2000,7 +2136,7 @@ END
                                'accesskey' => wfMsg('accesskey-preview'),
                                'title'     => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
                        );
-                       $buttons['preview'] = wfElement('input', $temp, '');
+                       $buttons['preview'] = Xml::element('input', $temp, '');
                        $buttons['live'] = '';
                }
 
@@ -2013,8 +2149,8 @@ END
                        'accesskey' => wfMsg('accesskey-diff'),
                        'title'     => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
                );
-               $buttons['diff'] = wfElement('input', $temp, '');
-               
+               $buttons['diff'] = Xml::element('input', $temp, '');
+
                wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
                return $buttons;
        }
@@ -2197,16 +2333,16 @@ END
                $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
                $wgOut->addWikiMsg( 'nocreatetext' );
        }
-       
+
        /**
         * If there are rows in the deletion log for this page, show them,
         * along with a nice little note for the user
         *
         * @param OutputPage $out
         */
-       private function showDeletionLog( $out ) {
+       protected function showDeletionLog( $out ) {
                global $wgUser;
-               $loglist = new LogEventsList( $wgUser->getSkin() );
+               $loglist = new LogEventsList( $wgUser->getSkin(), $out );
                $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
                if( $pager->getNumRows() > 0 ) {
                        $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
@@ -2229,7 +2365,7 @@ END
 
                $resultDetails = false;
                $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
-               
+
                if( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
                        $this->didSave = true;
                }
@@ -2279,7 +2415,7 @@ END
                        case self::AS_NO_CREATE_PERMISSION;
                                $this->noCreatePermission();
                                return;
-                       
+
                        case self::AS_BLANK_ARTICLE:
                                $wgOut->redirect( $wgTitle->getFullURL() );
                                return false;
@@ -2289,4 +2425,15 @@ END
                                return false;
                }
        }
+       
+       function getBaseRevision() {
+               if ($this->mBaseRevision == false) {
+                       $db = wfGetDB( DB_MASTER );
+                       $baseRevision = Revision::loadFromTimestamp(
+                               $db, $this->mTitle, $this->edittime );
+                       return $this->mBaseRevision = $baseRevision;
+               } else {
+                       return $this->mBaseRevision;
+               }
+       }
 }