* Use local context to get messages
[lhc/web/wiklou.git] / includes / EditPage.php
index c895048..8f4761c 100644 (file)
  * headaches, which may be fatal.
  */
 class EditPage {
+
+       /**
+        * Status: Article successfully updated
+        */
        const AS_SUCCESS_UPDATE            = 200;
+
+       /**
+        * Status: Article successfully created
+        */
        const AS_SUCCESS_NEW_ARTICLE       = 201;
+
+       /**
+        * Status: Article update aborted by a hook function
+        */
        const AS_HOOK_ERROR                = 210;
+
+       /**
+        * Status: The filter function set in $wgFilterCallback returned true (= block it)
+        */
        const AS_FILTERING                 = 211;
+
+       /**
+        * Status: A hook function returned an error
+        */
        const AS_HOOK_ERROR_EXPECTED       = 212;
+
+       /**
+        * Status: User is blocked from editting this page
+        */
        const AS_BLOCKED_PAGE_FOR_USER     = 215;
+
+       /**
+        * Status: Content too big (> $wgMaxArticleSize)
+        */
        const AS_CONTENT_TOO_BIG           = 216;
+
+       /**
+        * Status: User cannot edit? (not used)
+        */
        const AS_USER_CANNOT_EDIT          = 217;
+
+       /**
+        * Status: this anonymous user is not allowed to edit this page
+        */
        const AS_READ_ONLY_PAGE_ANON       = 218;
+
+       /**
+        * Status: this logged in user is not allowed to edit this page
+        */
        const AS_READ_ONLY_PAGE_LOGGED     = 219;
+
+       /**
+        * Status: wiki is in readonly mode (wfReadOnly() == true)
+        */
        const AS_READ_ONLY_PAGE            = 220;
+
+       /**
+        * Status: rate limiter for action 'edit' was tripped
+        */
        const AS_RATE_LIMITED              = 221;
+
+       /**
+        * Status: article was deleted while editting and param wpRecreate == false or form
+        * was not posted
+        */
        const AS_ARTICLE_WAS_DELETED       = 222;
+
+       /**
+        * Status: user tried to create this page, but is not allowed to do that
+        * ( Title->usercan('create') == false )
+        */
        const AS_NO_CREATE_PERMISSION      = 223;
+
+       /**
+        * Status: user tried to create a blank page
+        */
        const AS_BLANK_ARTICLE             = 224;
+
+       /**
+        * Status: (non-resolvable) edit conflict
+        */
        const AS_CONFLICT_DETECTED         = 225;
+
+       /**
+        * Status: no edit summary given and the user has forceeditsummary set and the user is not
+        * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
+        */
        const AS_SUMMARY_NEEDED            = 226;
+
+       /**
+        * Status: user tried to create a new section without content
+        */
        const AS_TEXTBOX_EMPTY             = 228;
+
+       /**
+        * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
+        */
        const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
+
+       /**
+        * not used
+        */
        const AS_OK                        = 230;
+
+       /**
+        * Status: WikiPage::doEdit() was unsuccessfull
+        */
        const AS_END                       = 231;
+
+       /**
+        * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
+        */
        const AS_SPAM_ERROR                = 232;
+
+       /**
+        * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
+        */
        const AS_IMAGE_REDIRECT_ANON       = 233;
+
+       /**
+        * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
+        */
        const AS_IMAGE_REDIRECT_LOGGED     = 234;
 
        /**
@@ -84,6 +183,12 @@ class EditPage {
         */
        var $mParserOutput;
 
+       /**
+        * Has a summary been preset using GET parameter &summary= ?
+        * @var Bool
+        */
+       var $hasPresetSummary = false;
+
        var $mBaseRevision = false;
        var $mShowSummaryField = true;
 
@@ -113,10 +218,9 @@ class EditPage {
        public $suppressIntro = false;
 
        /**
-        * @todo document
         * @param $article Article
         */
-       public function __construct( $article ) {
+       public function __construct( Article $article ) {
                $this->mArticle = $article;
                $this->mTitle = $article->getTitle();
        }
@@ -184,7 +288,7 @@ class EditPage {
                }
 
                wfProfileIn( __METHOD__ );
-               wfDebug( __METHOD__.": enter\n" );
+               wfDebug( __METHOD__ . ": enter\n" );
 
                // If they used redlink=1 and the page exists, redirect to the main article
                if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
@@ -235,15 +339,7 @@ class EditPage {
                        return;
                }
 
-               $wgOut->addModules( array( 'mediawiki.action.edit' ) );
-
-               if ( $wgUser->getOption( 'uselivepreview', false ) ) {
-                       $wgOut->addModules( 'mediawiki.legacy.preview' );
-               }
-               // Bug #19334: textarea jumps when editing articles in IE8
-               $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
-
-               wfProfileIn( __METHOD__."-business-end" );
+               wfProfileIn( __METHOD__ . "-business-end" );
 
                $this->isConflict = false;
                // css / js subpages of user pages get a special treatment
@@ -254,36 +350,8 @@ class EditPage {
                $this->isNew                = !$this->mTitle->exists() || $this->section == 'new';
 
                # Show applicable editing introductions
-               if ( $this->formtype == 'initial' || $this->firsttime )
+               if ( $this->formtype == 'initial' || $this->firsttime ) {
                        $this->showIntro();
-
-               if ( $this->mTitle->isTalkPage() ) {
-                       $wgOut->addWikiMsg( 'talkpagetext' );
-               }
-
-               # Optional notices on a per-namespace and per-page basis
-               $editnotice_ns   = 'editnotice-'.$this->mTitle->getNamespace();
-               $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
-               if ( $editnotice_ns_message->exists() ) {
-                       $wgOut->addWikiText( $editnotice_ns_message->plain() );
-               }
-               if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
-                       $parts = explode( '/', $this->mTitle->getDBkey() );
-                       $editnotice_base = $editnotice_ns;
-                       while ( count( $parts ) > 0 ) {
-                               $editnotice_base .= '-'.array_shift( $parts );
-                               $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
-                               if ( $editnotice_base_msg->exists() ) {
-                                       $wgOut->addWikiText( $editnotice_base_msg->plain()  );
-                               }
-                       }
-               } else {
-                       # Even if there are no subpages in namespace, we still don't want / in MW ns.
-                       $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
-                       $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
-                       if ( $editnoticeMsg->exists() ) {
-                               $wgOut->addWikiText( $editnoticeMsg->plain() );
-                       }
                }
 
                # Attempt submission here.  This will check for edit conflicts,
@@ -293,7 +361,7 @@ class EditPage {
 
                if ( 'save' == $this->formtype ) {
                        if ( !$this->attemptSave() ) {
-                               wfProfileOut( __METHOD__."-business-end" );
+                               wfProfileOut( __METHOD__ . "-business-end" );
                                wfProfileOut( __METHOD__ );
                                return;
                        }
@@ -304,18 +372,18 @@ class EditPage {
                if ( 'initial' == $this->formtype || $this->firsttime ) {
                        if ( $this->initialiseForm() === false ) {
                                $this->noSuchSectionPage();
-                               wfProfileOut( __METHOD__."-business-end" );
+                               wfProfileOut( __METHOD__ . "-business-end" );
                                wfProfileOut( __METHOD__ );
                                return;
                        }
-                       if ( !$this->mTitle->getArticleId() )
+                       if ( !$this->mTitle->getArticleID() )
                                wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
                        else
                                wfRunHooks( 'EditFormInitialText', array( $this ) );
                }
 
                $this->showEditForm();
-               wfProfileOut( __METHOD__."-business-end" );
+               wfProfileOut( __METHOD__ . "-business-end" );
                wfProfileOut( __METHOD__ );
        }
 
@@ -332,7 +400,7 @@ class EditPage {
                }
                # Ignore some permissions errors when a user is just previewing/viewing diffs
                $remove = array();
-               foreach( $permErrors as $error ) {
+               foreach ( $permErrors as $error ) {
                        if ( ( $this->preview || $this->diff ) &&
                                ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
                        {
@@ -346,7 +414,7 @@ class EditPage {
        /**
         * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
         * but with the following differences:
-        * - If redlink=1, the user will be redirect to the page
+        * - If redlink=1, the user will be redirected to the page
         * - If there is content to display or the error occurs while either saving,
         *   previewing or showing the difference, it will be a
         *   "View source for ..." page displaying the source code after the error message.
@@ -407,7 +475,7 @@ class EditPage {
         */
        function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
                wfDeprecated( __METHOD__, '1.19' );
-               
+
                global $wgRequest, $wgOut;
                if ( $wgRequest->getBool( 'redlink' ) ) {
                        // The edit page was reached via a red link.
@@ -439,7 +507,7 @@ class EditPage {
                        // Standard preference behaviour
                        return true;
                } elseif ( !$this->mTitle->exists() &&
-                 isset($wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]) &&
+                 isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] ) &&
                  $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
                {
                        // Categories are special
@@ -456,7 +524,7 @@ class EditPage {
         * @return bool
         */
        protected function isWrongCaseCssJsPage() {
-               if( $this->mTitle->isCssJsSubpage() ) {
+               if ( $this->mTitle->isCssJsSubpage() ) {
                        $name = $this->mTitle->getSkinFromCssJsSubpage();
                        $skins = array_merge(
                                array_keys( Skin::getSkinNames() ),
@@ -496,15 +564,15 @@ class EditPage {
                        # Also remove trailing whitespace, but don't remove _initial_
                        # whitespace from the text boxes. This may be significant formatting.
                        $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
-                       if ( !$request->getCheck('wpTextbox2') ) {
+                       if ( !$request->getCheck( 'wpTextbox2' ) ) {
                                // Skip this if wpTextbox2 has input, it indicates that we came
                                // from a conflict page with raw page text, not a custom form
                                // modified by subclasses
-                               wfProfileIn( get_class($this)."::importContentFormData" );
+                               wfProfileIn( get_class( $this ) . "::importContentFormData" );
                                $textbox1 = $this->importContentFormData( $request );
-                               if ( isset($textbox1) )
+                               if ( isset( $textbox1 ) )
                                        $this->textbox1 = $textbox1;
-                               wfProfileOut( get_class($this)."::importContentFormData" );
+                               wfProfileOut( get_class( $this ) . "::importContentFormData" );
                        }
 
                        # Truncate for whole multibyte characters. +5 bytes for ellipsis
@@ -514,7 +582,7 @@ class EditPage {
                        # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
                        # section titles.
                        $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
-                       
+
                        # Treat sectiontitle the same way as summary.
                        # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
                        # currently doing double duty as both edit summary and section title. Right now this
@@ -588,7 +656,7 @@ class EditPage {
                        {
                                $this->allowBlankSummary = true;
                        } else {
-                               $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary');
+                               $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary' );
                        }
 
                        $this->autoSumm = $request->getText( 'wpAutoSummary' );
@@ -607,7 +675,7 @@ class EditPage {
                        $this->minoredit    = false;
                        $this->watchthis    = $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
                        $this->recreate     = false;
-                       
+
                        // When creating a new section, we can preload a section title by passing it as the
                        // preloadtitle parameter in the URL (Bug 13100)
                        if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
@@ -617,6 +685,9 @@ class EditPage {
                        }
                        elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
                                $this->summary = $request->getText( 'summary' );
+                               if ( $this->summary !== '' ) {
+                                       $this->hasPresetSummary = true;
+                               }
                        }
 
                        if ( $request->getVal( 'minor' ) ) {
@@ -734,7 +805,7 @@ class EditPage {
                                        # Otherwise, $text will be left as-is.
                                        if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
                                                $undorev->getPage() == $oldrev->getPage() &&
-                                               $undorev->getPage() == $this->mTitle->getArticleId() &&
+                                               $undorev->getPage() == $this->mTitle->getArticleID() &&
                                                !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
                                                !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
 
@@ -766,7 +837,8 @@ class EditPage {
                                                $undoMsg = 'norev';
                                        }
 
-                                       $this->editFormPageTop .= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
+                                       $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
+                                       $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
                                                wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
                                }
 
@@ -844,7 +916,7 @@ class EditPage {
                if ( !empty( $this->mPreloadText ) ) {
                        return $this->mPreloadText;
                }
-               
+
                if ( $preload === '' ) {
                        return '';
                }
@@ -948,7 +1020,7 @@ class EditPage {
                                return false;
 
                        case self::AS_BLOCKED_PAGE_FOR_USER:
-                               throw new UserBlockedError( $wgUser->mBlock );
+                               throw new UserBlockedError( $wgUser->getBlock() );
 
                        case self::AS_IMAGE_REDIRECT_ANON:
                        case self::AS_IMAGE_REDIRECT_LOGGED:
@@ -1152,27 +1224,16 @@ class EditPage {
                                return $status;
                        }
 
-                       # Handle the user preference to force summaries here. Check if it's not a redirect.
-                       if ( !$this->allowBlankSummary && !Title::newFromRedirect( $this->textbox1 ) ) {
-                               if ( md5( $this->summary ) == $this->autoSumm ) {
-                                       $this->missingSummary = true;
-                                       $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
-                                       $status->value = self::AS_SUMMARY_NEEDED;
-                                       wfProfileOut( __METHOD__ );
-                                       return $status;
-                               }
-                       }
-
                        $text = $this->textbox1;
                        $result['sectionanchor'] = '';
                        if ( $this->section == 'new' ) {
                                if ( $this->sectiontitle !== '' ) {
                                        // Insert the section title above the content.
                                        $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle ) . "\n\n" . $text;
-                                       
+
                                        // Jump to the new section
                                        $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
-                                       
+
                                        // If no edit summary was specified, create one automatically from the section
                                        // title and have it link to the new section. Otherwise, respect the summary as
                                        // passed.
@@ -1183,7 +1244,7 @@ class EditPage {
                                } elseif ( $this->summary !== '' ) {
                                        // Insert the section title above the content.
                                        $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
-                                       
+
                                        // Jump to the new section
                                        $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
 
@@ -1216,7 +1277,7 @@ class EditPage {
                                        } else {
                                                // New comment; suppress conflict.
                                                $this->isConflict = false;
-                                               wfDebug( __METHOD__ .": conflict suppressed; new section\n" );
+                                               wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
                                        }
                                } elseif ( $this->section == '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime ) ) {
                                        # Suppress edit conflict with self, except for section edits where merging is required.
@@ -1224,7 +1285,7 @@ class EditPage {
                                        $this->isConflict = false;
                                }
                        }
-                       
+
                        // If sectiontitle is set, use it, otherwise use the summary as the section title (for
                        // backwards compatibility with old forms/bots).
                        if ( $this->sectiontitle !== '' ) {
@@ -1232,7 +1293,7 @@ class EditPage {
                        } else {
                                $sectionTitle = $this->summary;
                        }
-                       
+
                        if ( $this->isConflict ) {
                                wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
                                $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle, $this->edittime );
@@ -1391,13 +1452,13 @@ class EditPage {
                global $wgUser;
                if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
                        $dbw = wfGetDB( DB_MASTER );
-                       $dbw->begin();
+                       $dbw->begin( __METHOD__ );
                        if ( $this->watchthis ) {
                                WatchAction::doWatch( $this->mTitle, $wgUser );
                        } else {
                                WatchAction::doUnwatch( $this->mTitle, $wgUser );
                        }
-                       $dbw->commit();
+                       $dbw->commit( __METHOD__ );
                }
        }
 
@@ -1412,18 +1473,18 @@ class EditPage {
         * @return bool
         */
        protected function userWasLastToEdit( $id, $edittime ) {
-               if( !$id ) return false;
+               if ( !$id ) return false;
                $dbw = wfGetDB( DB_MASTER );
                $res = $dbw->select( 'revision',
                        'rev_user',
                        array(
-                               'rev_page' => $this->mTitle->getArticleId(),
-                               'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
+                               'rev_page' => $this->mTitle->getArticleID(),
+                               'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
                        ),
                        __METHOD__,
                        array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
                foreach ( $res as $row ) {
-                       if( $row->rev_user != $id ) {
+                       if ( $row->rev_user != $id ) {
                                return false;
                        }
                }
@@ -1438,7 +1499,7 @@ class EditPage {
         *
         * @return bool
         */
-       function mergeChangesInto( &$editText ){
+       function mergeChangesInto( &$editText ) {
                wfProfileIn( __METHOD__ );
 
                $db = wfGetDB( DB_MASTER );
@@ -1489,7 +1550,7 @@ class EditPage {
         *
         * @param $text string
         *
-        * @return string|false matching string or false
+        * @return string|bool matching string or false
         */
        public static function matchSpamRegex( $text ) {
                global $wgSpamRegex;
@@ -1503,7 +1564,7 @@ class EditPage {
         *
         * @parma $text string
         *
-        * @return string|false  matching string or false
+        * @return string|bool  matching string or false
         */
        public static function matchSummarySpamRegex( $text ) {
                global $wgSummarySpamRegex;
@@ -1517,9 +1578,9 @@ class EditPage {
         * @return bool|string
         */
        protected static function matchSpamRegexInternal( $text, $regexes ) {
-               foreach( $regexes as $regex ) {
+               foreach ( $regexes as $regex ) {
                        $matches = array();
-                       if( preg_match( $regex, $text, $matches ) ) {
+                       if ( preg_match( $regex, $text, $matches ) ) {
                                return $matches[0];
                        }
                }
@@ -1527,8 +1588,21 @@ class EditPage {
        }
 
        function setHeaders() {
-               global $wgOut;
+               global $wgOut, $wgUser;
+
+               $wgOut->addModules( 'mediawiki.action.edit' );
+
+               if ( $wgUser->getOption( 'uselivepreview', false ) ) {
+                       $wgOut->addModules( 'mediawiki.legacy.preview' );
+               }
+               // Bug #19334: textarea jumps when editing articles in IE8
+               $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
+
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
+
+               # Enabled article-related sidebar, toplinks, etc.
+               $wgOut->setArticleRelated( true );
+
                if ( $this->isConflict ) {
                        $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
                } elseif ( $this->section != '' ) {
@@ -1569,7 +1643,7 @@ class EditPage {
                        $username = $parts[0];
                        $user = User::newFromName( $username, false /* allow IP users*/ );
                        $ip = User::isIP( $username );
-                       if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
+                       if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
                                $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
                                        array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
                        } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
@@ -1603,7 +1677,7 @@ class EditPage {
                                '', array( 'lim' => 10,
                                           'conds' => array( "log_action != 'revision'" ),
                                           'showIfEmpty' => false,
-                                          'msgKey' => array( 'recreate-moveddeleted-warn') )
+                                          'msgKey' => array( 'recreate-moveddeleted-warn' ) )
                        );
                }
        }
@@ -1639,22 +1713,19 @@ class EditPage {
 
                wfProfileIn( __METHOD__ );
 
-               #need to parse the preview early so that we know which templates are used,
-               #otherwise users with "show preview after edit box" will get a blank list
-               #we parse this near the beginning so that setHeaders can do the title
-               #setting work instead of leaving it in getPreviewText
+               # need to parse the preview early so that we know which templates are used,
+               # otherwise users with "show preview after edit box" will get a blank list
+               # we parse this near the beginning so that setHeaders can do the title
+               # setting work instead of leaving it in getPreviewText
                $previewOutput = '';
                if ( $this->formtype == 'preview' ) {
                        $previewOutput = $this->getPreviewText();
                }
 
-               wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
+               wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
 
                $this->setHeaders();
 
-               # Enabled article-related sidebar, toplinks, etc.
-               $wgOut->setArticleRelated( true );
-
                if ( $this->showHeader() === false ) {
                        wfProfileOut( __METHOD__ );
                        return;
@@ -1723,6 +1794,13 @@ class EditPage {
                        $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
                }
 
+               if ( $this->hasPresetSummary ) {
+                       // If a summary has been preset using &summary= we dont want to prompt for
+                       // a different summary. Only prompt for a summary if the summary is blanked.
+                       // (Bug 17416)
+                       $this->autoSumm = md5( '' );
+               }
+
                $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
                $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
 
@@ -1794,10 +1872,10 @@ class EditPage {
         * @return Mixed|string or false
         */
        public static function extractSectionTitle( $text ) {
-               preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
+               preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
                if ( !empty( $matches[2] ) ) {
                        global $wgParser;
-                       return $wgParser->stripSectionName(trim($matches[2]));
+                       return $wgParser->stripSectionName( trim( $matches[2] ) );
                } else {
                        return false;
                }
@@ -1805,6 +1883,36 @@ class EditPage {
 
        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();
@@ -1907,12 +2015,12 @@ class EditPage {
                }
                if ( $this->mTitle->isCascadeProtected() ) {
                        # Is this page under cascading protection from some source pages?
-                       list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
+                       list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
                        $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
                        $cascadeSourcesCount = count( $cascadeSources );
                        if ( $cascadeSourcesCount > 0 ) {
                                # Explain, and list the titles responsible
-                               foreach( $cascadeSources as $page ) {
+                               foreach ( $cascadeSources as $page ) {
                                        $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
                                }
                        }
@@ -1921,7 +2029,7 @@ class EditPage {
                }
                if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
                        LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
-                               array(  'lim' => 1,
+                               array( 'lim' => 1,
                                        'showIfEmpty' => false,
                                        'msgKey' => array( 'titleprotectedwarning' ),
                                        'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
@@ -1935,7 +2043,7 @@ class EditPage {
                        $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
                                array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
                } else {
-                       if( !wfMessage('longpage-hint')->isDisabled() ) {
+                       if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
                                $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
                                        array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
                                );
@@ -1957,9 +2065,9 @@ class EditPage {
         *
         * @return array An array in the format array( $label, $input )
         */
-       function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
-               //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
-               $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
+       function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
+               // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
+               $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
                        'id' => 'wpSummary',
                        'maxlength' => '200',
                        'tabindex' => '1',
@@ -1967,7 +2075,7 @@ class EditPage {
                        'spellcheck' => 'true',
                ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
 
-               $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
+               $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
                        'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
                        'id' => "wpSummaryLabel"
                );
@@ -2005,8 +2113,8 @@ class EditPage {
                }
                $summary = $wgContLang->recodeForEdit( $summary );
                $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
-               list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
-               $wgOut->addHTML("{$label} {$input}");
+               list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
+               $wgOut->addHTML( "{$label} {$input}" );
        }
 
        /**
@@ -2043,7 +2151,7 @@ class EditPage {
 HTML
                );
                if ( !$this->checkUnicodeCompliantBrowser() )
-                       $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
+                       $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
        }
 
        protected function showFormAfterText() {
@@ -2080,7 +2188,7 @@ HTML
         * The $textoverride method can be used by subclasses overriding showContentForm
         * to pass back to this method.
         *
-        * @param $customAttribs An array of html attributes to use in the textarea
+        * @param $customAttribs array of html attributes to use in the textarea
         * @param $textoverride String: optional text to override $this->textarea1 with
         */
        protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
@@ -2127,7 +2235,7 @@ HTML
                global $wgOut, $wgUser;
 
                $wikitext = $this->safeUnicodeOutput( $content );
-               if ( strval($wikitext) !== '' ) {
+               if ( strval( $wikitext ) !== '' ) {
                        // Ensure there's a newline at the end, otherwise adding lines
                        // is awkward.
                        // But don't add a newline if the ext is empty, or Firefox in XHTML
@@ -2138,6 +2246,7 @@ HTML
                $attribs = $customAttribs + array(
                        'accesskey' => ',',
                        'id'   => $name,
+                       'cols' => $wgUser->getIntOption( 'cols' ),
                        'rows' => $wgUser->getIntOption( 'rows' ),
                        'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
                );
@@ -2168,7 +2277,7 @@ HTML
 
                $wgOut->addHTML( '</div>' );
 
-               if ( $this->formtype == 'diff') {
+               if ( $this->formtype == 'diff' ) {
                        $this->showDiff();
                }
        }
@@ -2181,12 +2290,12 @@ HTML
         */
        protected function showPreview( $text ) {
                global $wgOut;
-               if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
+               if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
                        $this->mArticle->openShowCategory();
                }
                # This hook seems slightly odd here, but makes things more
                # consistent for extensions.
-               wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
+               wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
                $wgOut->addHTML( $text );
                if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
                        $this->mArticle->closeShowCategory();
@@ -2203,7 +2312,7 @@ HTML
        function showDiff() {
                global $wgUser, $wgContLang, $wgParser, $wgOut;
 
-               $oldtext = $this->getOriginalContent();
+               $oldtext = $this->mArticle->getRawText();
                $newtext = $this->mArticle->replaceSection(
                        $this->section, $this->textbox1, $this->summary, $this->edittime );
 
@@ -2238,7 +2347,7 @@ HTML
        protected function showTosSummary() {
                $msg = 'editpage-tos-summary';
                wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
-               if( !wfMessage( $msg )->isDisabled() ) {
+               if ( !wfMessage( $msg )->isDisabled() ) {
                        global $wgOut;
                        $wgOut->addHTML( '<div class="mw-tos-summary">' );
                        $wgOut->addWikiMsg( $msg );
@@ -2267,7 +2376,7 @@ HTML
                wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
 
                return "<div id=\"editpage-copywarn\">\n" .
-                       call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
+                       call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
        }
 
        protected function showStandardInputs( &$tabindex = 2 ) {
@@ -2290,8 +2399,8 @@ HTML
                        $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
                }
                $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
-               $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
-                       htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
+               $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
+                       htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
                        htmlspecialchars( wfMsg( 'newwindow' ) );
                $wgOut->addHTML( "      <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
                $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
@@ -2395,10 +2504,10 @@ HTML
                        array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
                );
                // Quick paranoid permission checks...
-               if( is_object( $data ) ) {
-                       if( $data->log_deleted & LogPage::DELETED_USER )
+               if ( is_object( $data ) ) {
+                       if ( $data->log_deleted & LogPage::DELETED_USER )
                                $data->user_name = wfMsgHtml( 'rev-deleted-user' );
-                       if( $data->log_deleted & LogPage::DELETED_COMMENT )
+                       if ( $data->log_deleted & LogPage::DELETED_COMMENT )
                                $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
                }
                return $data;
@@ -2444,15 +2553,15 @@ HTML
                $parserOptions->setEditSection( false );
                $parserOptions->setTidy( true );
                $parserOptions->setIsPreview( true );
-               $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
+               $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
 
                # don't parse non-wikitext pages, show message about preview
                # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
 
                if ( $this->isCssJsSubpage || !$this->mTitle->isWikitextPage() ) {
-                       if( $this->mTitle->isCssJsSubpage() ) {
+                       if ( $this->mTitle->isCssJsSubpage() ) {
                                $level = 'user';
-                       } elseif( $this->mTitle->isCssOrJsPage() ) {
+                       } elseif ( $this->mTitle->isCssOrJsPage() ) {
                                $level = 'site';
                        } else {
                                $level = false;
@@ -2460,11 +2569,11 @@ HTML
 
                        # Used messages to make sure grep find them:
                        # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
-                       if( $level ) {
-                               if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
+                       if ( $level ) {
+                               if ( preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
                                        $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
                                        $class = "mw-code mw-css";
-                               } elseif (preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
+                               } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
                                        $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
                                        $class = "mw-code mw-js";
                                } else {
@@ -2476,36 +2585,37 @@ HTML
                        $previewHTML = $parserOutput->mText;
                        $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
                } else {
-                       $rt = Title::newFromRedirectArray( $this->textbox1 );
-                       if ( $rt ) {
-                               $previewHTML = $this->mArticle->viewRedirect( $rt, false );
-                       } else {
-                               $toparse = $this->textbox1;
+                       $toparse = $this->textbox1;
 
-                               # If we're adding a comment, we need to show the
-                               # summary as the headline
-                               if ( $this->section == "new" && $this->summary != "" ) {
-                                       $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $toparse;
-                               }
+                       # If we're adding a comment, we need to show the
+                       # summary as the headline
+                       if ( $this->section == "new" && $this->summary != "" ) {
+                               $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $toparse;
+                       }
 
-                               wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
+                       wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
 
-                               $parserOptions->enableLimitReport();
+                       $parserOptions->enableLimitReport();
 
-                               $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
-                               $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
+                       $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
+                       $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
 
+                       $rt = Title::newFromRedirectArray( $this->textbox1 );
+                       if ( $rt ) {
+                               $previewHTML = $this->mArticle->viewRedirect( $rt, false );
+                       } else {
                                $previewHTML = $parserOutput->getText();
-                               $this->mParserOutput = $parserOutput;
-                               $wgOut->addParserOutputNoText( $parserOutput );
+                       }
 
-                               if ( count( $parserOutput->getWarnings() ) ) {
-                                       $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
-                               }
+                       $this->mParserOutput = $parserOutput;
+                       $wgOut->addParserOutputNoText( $parserOutput );
+
+                       if ( count( $parserOutput->getWarnings() ) ) {
+                               $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
                        }
                }
 
-               if( $this->isConflict ) {
+               if ( $this->isConflict ) {
                        $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
                } else {
                        $conflict = '<hr />';
@@ -2517,7 +2627,7 @@ HTML
 
                $pageLang = $this->mTitle->getPageLanguage();
                $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
-                       'class' => 'mw-content-'.$pageLang->getDir() );
+                       'class' => 'mw-content-' . $pageLang->getDir() );
                $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
 
                wfProfileOut( __METHOD__ );
@@ -2533,9 +2643,9 @@ HTML
                        if ( !isset( $this->mParserOutput ) ) {
                                return $templates;
                        }
-                       foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
-                               foreach( array_keys( $template ) as $dbk ) {
-                                       $templates[] = Title::makeTitle($ns, $dbk);
+                       foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
+                               foreach ( array_keys( $template ) as $dbk ) {
+                                       $templates[] = Title::makeTitle( $ns, $dbk );
                                }
                        }
                        return $templates;
@@ -2634,7 +2744,7 @@ HTML
                                'tip'    => wfMsg( 'media_tip' ),
                                'key'    => 'M'
                        ) : false,
-                       $wgUseTeX ?     array(
+                       $wgUseTeX ? array(
                                'image'  => $wgLang->getImageFile( 'button-math' ),
                                'id'     => 'mw-editbutton-math',
                                'open'   => "<math>",
@@ -2672,7 +2782,7 @@ HTML
                        )
                );
 
-               $script = '';
+               $script = 'mw.loader.using("mediawiki.action.edit", function() {';
                foreach ( $toolarray as $tool ) {
                        if ( !$tool ) {
                                continue;
@@ -2693,6 +2803,14 @@ HTML
 
                        $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
                }
+
+               // This used to be called on DOMReady from mediawiki.action.edit, which
+               // ended up causing race conditions with the setup code above.
+               $script .= "\n" .
+                       "// Create button bar\n" .
+                       "$(function() { mw.toolbar.init(); } );\n";
+
+               $script .= '});';
                $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
 
                $toolbar = '<div id="toolbar"></div>';
@@ -2706,7 +2824,7 @@ HTML
         * Returns an array of html code of the following checkboxes:
         * minor and watch
         *
-        * @param $tabindex Current tabindex
+        * @param $tabindex int Current tabindex
         * @param $checked Array of checkbox => bool, where bool indicates the checked
         *                 status of the checkbox
         *
@@ -2757,7 +2875,7 @@ HTML
         * Returns an array of html code of the following buttons:
         * save, diff, preview and live
         *
-        * @param $tabindex Current tabindex
+        * @param $tabindex int Current tabindex
         *
         * @return array
         */
@@ -2771,9 +2889,9 @@ HTML
                        'tabindex'  => ++$tabindex,
                        'value'     => wfMsg( 'savearticle' ),
                        'accesskey' => wfMsg( 'accesskey-save' ),
-                       'title'     => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
+                       'title'     => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
                );
-               $buttons['save'] = Xml::element('input', $temp, '');
+               $buttons['save'] = Xml::element( 'input', $temp, '' );
 
                ++$tabindex; // use the same for preview and live preview
                $temp = array(
@@ -2842,7 +2960,7 @@ HTML
                wfDeprecated( __METHOD__, '1.19' );
                global $wgUser;
 
-               throw new UserBlockedError( $wgUser->mBlock );
+               throw new UserBlockedError( $wgUser->getBlock() );
        }
 
        /**
@@ -2886,12 +3004,12 @@ HTML
        /**
         * Produce the stock "your edit contains spam" page
         *
-        * @param $match Text which triggered one or more filters
+        * @param $match string Text which triggered one or more filters
         * @deprecated since 1.17 Use method spamPageWithContent() instead
         */
        static function spamPage( $match = false ) {
                wfDeprecated( __METHOD__, '1.17' );
-               
+
                global $wgOut, $wgTitle;
 
                $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
@@ -2909,7 +3027,7 @@ HTML
        /**
         * Show "your edit contains spam" page with your diff and text
         *
-        * @param $match Text which triggered one or more filters
+        * @param $match string|bool Text which triggered one or more filters
         */
        public function spamPageWithContent( $match = false ) {
                global $wgOut;
@@ -2925,9 +3043,7 @@ HTML
                $wgOut->addHTML( '</div>' );
 
                $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
-               $de = new DifferenceEngine( $this->mArticle->getContext() );
-               $de->setText( $this->getCurrentText(), $this->textbox2 );
-               $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
+               $this->showDiff();
 
                $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
                $this->showTextbox2();
@@ -2961,7 +3077,7 @@ HTML
                }
                $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
                foreach ( $wgBrowserBlackList as $browser ) {
-                       if ( preg_match($browser, $currentbrowser) ) {
+                       if ( preg_match( $browser, $currentbrowser ) ) {
                                return false;
                        }
                }
@@ -3032,25 +3148,25 @@ HTML
                $bytesleft = 0;
                $result = "";
                $working = 0;
-               for( $i = 0; $i < strlen( $invalue ); $i++ ) {
+               for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
                        $bytevalue = ord( $invalue[$i] );
-                       if ( $bytevalue <= 0x7F ) { //0xxx xxxx
+                       if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
                                $result .= chr( $bytevalue );
                                $bytesleft = 0;
-                       } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
+                       } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
                                $working = $working << 6;
-                               $working += ($bytevalue & 0x3F);
+                               $working += ( $bytevalue & 0x3F );
                                $bytesleft--;
                                if ( $bytesleft <= 0 ) {
                                        $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
                                }
-                       } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
+                       } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
                                $working = $bytevalue & 0x1F;
                                $bytesleft = 1;
-                       } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
+                       } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
                                $working = $bytevalue & 0x0F;
                                $bytesleft = 2;
-                       } else { //1111 0xxx
+                       } else { // 1111 0xxx
                                $working = $bytevalue & 0x07;
                                $bytesleft = 3;
                        }
@@ -3069,20 +3185,20 @@ HTML
         */
        function unmakesafe( $invalue ) {
                $result = "";
-               for( $i = 0; $i < strlen( $invalue ); $i++ ) {
-                       if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+3] != '0' ) ) {
+               for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
+                       if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
                                $i += 3;
                                $hexstring = "";
                                do {
                                        $hexstring .= $invalue[$i];
                                        $i++;
-                               } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
+                               } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
 
                                // Do some sanity checks. These aren't needed for reversability,
                                // but should help keep the breakage down if the editor
                                // breaks one of the entities whilst editing.
-                               if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
-                                       $codepoint = hexdec($hexstring);
+                               if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
+                                       $codepoint = hexdec( $hexstring );
                                        $result .= codepointToUtf8( $codepoint );
                                } else {
                                        $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );