* Removed Parser::doExponent(), unused
[lhc/web/wiklou.git] / includes / Parser.php
index 2dbc4e9..8747b09 100644 (file)
@@ -8,6 +8,7 @@
 
 /** */
 require_once( 'Sanitizer.php' );
+require_once( 'HttpFunctions.php' );
 
 /**
  * Update this version number when the ParserOutput format
@@ -46,24 +47,23 @@ define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
 define( 'UNIQ_PREFIX', 'NaodW29');
 
 # Constants needed for external link processing
-define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
-define( 'HTTP_PROTOCOLS', 'http|https' );
+define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
 # Everything except bracket, space, or control characters
 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
 # Including space
 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
-define( 'EXT_LINK_BRACKETED',  '/\[(\b('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
+define( 'EXT_LINK_BRACKETED',  '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
 define( 'EXT_IMAGE_REGEX',
-       '/^('.HTTP_PROTOCOLS.':)'.  # Protocol
+       '/^('.HTTP_PROTOCOLS.')'.  # Protocol
        '('.EXT_LINK_URL_CLASS.'+)\\/'.  # Hostname and path
        '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
 );
 
 /**
  * PHP Parser
- * 
+ *
  * Processes wiki markup
  *
  * <pre>
@@ -110,15 +110,16 @@ class Parser
            $mTemplatePath;     // stores an unsorted hash of all the templates already loaded
                                // in this path. Used for loop detection.
 
+       var $mIWTransData = array();
+
        /**#@-*/
 
        /**
         * Constructor
-        * 
+        *
         * @access public
         */
        function Parser() {
-               global $wgContLang;
                $this->mTemplates = array();
                $this->mTemplatePath = array();
                $this->mTagHooks = array();
@@ -151,6 +152,7 @@ class Parser
                        'texts' => array(),
                        'titles' => array()
                );
+               $this->mRevisionId = null;
        }
 
        /**
@@ -163,9 +165,10 @@ class Parser
         * @param array $options
         * @param boolean $linestart
         * @param boolean $clearState
+        * @param int $revid number to pass in {{REVISIONID}}
         * @return ParserOutput a ParserOutput
         */
-       function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
+       function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
                global $wgUseTidy, $wgContLang;
                $fname = 'Parser::parse';
                wfProfileIn( $fname );
@@ -176,20 +179,23 @@ class Parser
 
                $this->mOptions = $options;
                $this->mTitle =& $title;
+               $this->mRevisionId = $revid;
                $this->mOutputType = OT_HTML;
 
                $this->mStripState = NULL;
-               
+
                //$text = $this->strip( $text, $this->mStripState );
                // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
                $x =& $this->mStripState;
+
+               wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
                $text = $this->strip( $text, $x );
+               wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
 
                $text = $this->internalParse( $text );
 
-               
                $text = $this->unstrip( $text, $this->mStripState );
-               
+
                # Clean up special characters, only run once, next-to-last before doBlockLevels
                $fixtags = array(
                        # french spaces, last one Guillemet-left
@@ -197,30 +203,33 @@ class Parser
                        '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
                        # french spaces, Guillemet-right
                        '/(\\302\\253) /' => '\\1&nbsp;',
-                       '/<center *>/i' => '<div class="center">',
-                       '/<\\/center *>/i' => '</div>',
+                       '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
                );
                $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
-               
+
                # only once and last
                $text = $this->doBlockLevels( $text, $linestart );
 
                $this->replaceLinkHolders( $text );
 
-               # the position of the convert() call should not be changed. it 
-               # assumes that the links are all replaces and the only thing left 
+               # the position of the convert() call should not be changed. it
+               # assumes that the links are all replaces and the only thing left
                # is the <nowiki> mark.
                $text = $wgContLang->convert($text);
                $this->mOutput->setTitleText($wgContLang->getParsedTitle());
 
                $text = $this->unstripNoWiki( $text, $this->mStripState );
-               
+
+               wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
+
                $text = Sanitizer::normalizeCharReferences( $text );
-               global $wgUseTidy;
+               
                if ($wgUseTidy) {
                        $text = Parser::tidy($text);
                }
 
+               wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
+
                $this->mOutput->setText( $text );
                wfProfileOut( $fname );
                return $this->mOutput;
@@ -236,12 +245,12 @@ class Parser
                return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
        }
 
-       /** 
+       /**
         * Replaces all occurrences of <$tag>content</$tag> in the text
         * with a random marker and returns the new text. the output parameter
         * $content will be an associative array filled with data on the form
         * $unique_marker => content.
-        * 
+        *
         * If $content is already set, the additional entries will be appended
         * If $tag is set to STRIP_COMMENTS, the function will extract
         * <!-- HTML comments -->
@@ -256,45 +265,52 @@ class Parser
                }
                $n = 1;
                $stripped = '';
-       
+
                if ( !$tags ) {
                        $tags = array( );
                }
-               
+
                if ( !$params ) {
                        $params = array( );
                }
 
                if( $tag == STRIP_COMMENTS ) {
-                       $start = '/<!--()/';
+                       $start = '/<!--()()/';
                        $end   = '/-->/';
                } else {
-                       $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
+                       $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
                        $end   = "/<\\/$tag\\s*>/i";
                }
 
                while ( '' != $text ) {
                        $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
                        $stripped .= $p[0];
-                       if( count( $p ) < 3 ) {
+                       if( count( $p ) < 4 ) {
                                break;
                        }
                        $attributes = $p[1];
-                       $inside     = $p[2];
-                       
+                       $empty      = $p[2];
+                       $inside     = $p[3];
+
                        $marker = $rnd . sprintf('%08X', $n++);
                        $stripped .= $marker;
-                       
-                       $tags[$marker] = "<$tag$attributes>";
+
+                       $tags[$marker] = "<$tag$attributes$empty>";
                        $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
-                       
-                       $q = preg_split( $end, $inside, 2 );
-                       $content[$marker] = $q[0];
-                       if( count( $q ) < 1 ) {
-                               # No end tag -- let it run out to the end of the text.
-                               break;
+
+                       if ( $empty === '/' ) {
+                               // Empty element tag, <tag />
+                               $content[$marker] = null;
+                               $text = $inside;
                        } else {
-                               $text = $q[1];
+                               $q = preg_split( $end, $inside, 2 );
+                               $content[$marker] = $q[0];
+                               if( count( $q ) < 2 ) {
+                                       # No end tag -- let it run out to the end of the text.
+                                       break;
+                               } else {
+                                       $text = $q[1];
+                               }
                        }
                }
                return $stripped;
@@ -311,11 +327,11 @@ class Parser
        function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
                $dummy_tags = array();
                $dummy_params = array();
-               
+
                return Parser::extractTagsAndParams( $tag, $text, $content,
                        $dummy_tags, $dummy_params, $uniq_prefix );
        }
-       
+
        /**
         * Strips and renders nowiki, pre, math, hiero
         * If $render is set, performs necessary rendering operations on plugins
@@ -370,16 +386,14 @@ class Parser
                }
 
                # math
-               $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
-               foreach( $math_content as $marker => $content ){
-                       if( $render ) {
-                               if( $this->mOptions->getUseTeX() ) {
+               if( $this->mOptions->getUseTeX() ) {
+                       $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
+                       foreach( $math_content as $marker => $content ){
+                               if( $render ) {
                                        $math_content[$marker] = renderMath( $content );
                                } else {
-                                       $math_content[$marker] = '&lt;math&gt;'.$content.'&lt;math&gt;';
+                                       $math_content[$marker] = '<math>'.$content.'</math>';
                                }
-                       } else {
-                               $math_content[$marker] = '<math>'.$content.'</math>';
                        }
                }
 
@@ -420,10 +434,15 @@ class Parser
                        foreach( $ext_content[$tag] as $marker => $content ) {
                                $full_tag = $ext_tags[$tag][$marker];
                                $params = $ext_params[$tag][$marker];
-                               if ( $render ) {
-                                       $ext_content[$tag][$marker] = $callback( $content, $params );
-                               } else {
-                                       $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
+                               if ( $render )
+                                       $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, $this ) );
+                               else {
+                                       if ( is_null( $content ) ) {
+                                               // Empty element tag
+                                               $ext_content[$tag][$marker] = $full_tag;
+                                       } else {
+                                               $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
+                                       }
                                }
                        }
                }
@@ -462,12 +481,15 @@ class Parser
         * @access private
         */
        function unstrip( $text, &$state ) {
+               if ( !is_array( $state ) ) {
+                       return $text;
+               }
+               
                # Must expand in reverse order, otherwise nested tags will be corrupted
-               $contentDict = end( $state );
-               for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
-                       if( key($state) != 'nowiki' && key($state) != 'html') {
-                               for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
-                                       $text = str_replace( key( $contentDict ), $content, $text );
+               foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
+                       if( $tag != 'nowiki' && $tag != 'html' ) {
+                               foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
+                                       $text = str_replace( $uniq, $content, $text );
                                }
                        }
                }
@@ -481,6 +503,10 @@ class Parser
         * @access private
         */
        function unstripNoWiki( $text, &$state ) {
+               if ( !is_array( $state ) ) {
+                       return $text;
+               }
+
                # Must expand in reverse order, otherwise nested tags will be corrupted
                for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
                        $text = str_replace( key( $state['nowiki'] ), $content, $text );
@@ -510,7 +536,9 @@ class Parser
                          'html' => array(),
                          'nowiki' => array(),
                          'math' => array(),
-                         'pre' => array()
+                         'pre' => array(),
+                         'comment' => array(),
+                         'gallery' => array(),
                        );
                }
                $state['item'][$rnd] = $text;
@@ -547,7 +575,7 @@ class Parser
                }
                return $correctedtext;
        }
-       
+
        /**
         * Spawn an external HTML tidy process and get corrected markup back from it.
         *
@@ -604,7 +632,7 @@ class Parser
                global $wgTidyConf;
                $fname = 'Parser::internalTidy';
                wfProfileIn( $fname );
-               
+
                tidy_load_config( $wgTidyConf );
                tidy_set_encoding( 'utf8' );
                tidy_parse_string( $text );
@@ -641,8 +669,11 @@ class Parser
                        $fc = substr ( $x , 0 , 1 ) ;
                        if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
                                $indent_level = strlen( $matches[1] );
+                               
+                               $attributes = $this->unstripForHTML( $matches[2] );
+
                                $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
-                                       '<table' . Sanitizer::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
+                                       '<table' . Sanitizer::fixTagAttributes ( $attributes, 'table' ) . '>' ;
                                array_push ( $td , false ) ;
                                array_push ( $ltd , '' ) ;
                                array_push ( $tr , false ) ;
@@ -669,7 +700,8 @@ class Parser
                                array_push ( $tr , false ) ;
                                array_push ( $td , false ) ;
                                array_push ( $ltd , '' ) ;
-                               array_push ( $ltr , Sanitizer::fixTagAttributes ( $x, 'tr' ) ) ;
+                               $attributes = $this->unstripForHTML( $x );
+                               array_push ( $ltr , Sanitizer::fixTagAttributes ( $attributes, 'tr' ) ) ;
                        }
                        else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
                                # $x is a table row
@@ -711,7 +743,10 @@ class Parser
                                        }
                                        if ( count ( $y ) == 1 )
                                                $y = "{$z}<{$l}>{$y[0]}" ;
-                                       else $y = $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($y[0], $l).">{$y[1]}" ;
+                                       else {
+                                               $attributes = $this->unstripForHTML( $y[0] );
+                                               $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($attributes, $l).">{$y[1]}" ;
+                                       }
                                        $t[$k] .= $y ;
                                        array_push ( $td , true ) ;
                                }
@@ -744,7 +779,12 @@ class Parser
                $fname = 'Parser::internalParse';
                wfProfileIn( $fname );
 
-               $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ) );
+               # Remove <noinclude> tags and <includeonly> sections
+               $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
+               $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
+               $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
+
+               $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
                $text = $this->replaceVariables( $text, $args );
 
                $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
@@ -756,20 +796,28 @@ class Parser
                }
                $text = $this->doAllQuotes( $text );
                $text = $this->replaceInternalLinks( $text );
-               $text = $this->replaceExternalLinks( $text );           
-               
+               $text = $this->replaceExternalLinks( $text );
+
                # replaceInternalLinks may sometimes leave behind
                # absolute URLs, which have to be masked to hide them from replaceExternalLinks
-               $text = str_replace("http-noparse://","http://",$text);
-               
+               $text = str_replace(UNIQ_PREFIX."NOPARSE", "", $text);
+
                $text = $this->doMagicLinks( $text );
                $text = $this->doTableStuff( $text );
                $text = $this->formatHeadings( $text, $isMain );
 
+               $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
+               $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
+
                wfProfileOut( $fname );
                return $text;
        }
 
+       function scarySubstitution($matches) {
+#              return "[[".$matches[0]."]]";
+               return $this->mIWTransData[(int)$matches[0]];
+       }
+
        /**
         * Replace special strings like "ISBN xxx" and "RFC xxx" with
         * magic external links.
@@ -783,19 +831,6 @@ class Parser
                return $text;
        }
 
-       /**
-        * Parse ^^ tokens and return html
-        *
-        * @access private
-        */
-       function doExponent( $text ) {
-               $fname = 'Parser::doExponent';
-               wfProfileIn( $fname );
-               $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
-               wfProfileOut( $fname );
-               return $text;
-       }
-
        /**
         * Parse headers and return html
         *
@@ -805,7 +840,7 @@ class Parser
                $fname = 'Parser::doHeadings';
                wfProfileIn( $fname );
                for ( $i = 6; $i >= 1; --$i ) {
-                       $h = substr( '======', 0, $i );
+                       $h = str_repeat( '=', $i );
                        $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
                          "<h{$i}>\\1</h{$i}>\\2", $text );
                }
@@ -1010,7 +1045,7 @@ class Parser
                wfProfileIn( $fname );
 
                $sk =& $this->mOptions->getSkin();
-               
+
                $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
 
                $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
@@ -1045,7 +1080,7 @@ class Parser
                        # No link text, e.g. [http://domain.tld/some.link]
                        if ( $text == '' ) {
                                # Autonumber if allowed
-                               if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
+                               if ( strpos( HTTP_PROTOCOLS, str_replace('/','\/', $protocol) ) !== false ) {
                                        $text = '[' . ++$this->mAutonumber . ']';
                                        $linktype = 'autonumber';
                                } else {
@@ -1090,8 +1125,8 @@ class Parser
                global $wgContLang;
                $fname = 'Parser::replaceFreeExternalLinks';
                wfProfileIn( $fname );
-               
-               $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
+
+               $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
                $s = array_shift( $bits );
                $i = 0;
 
@@ -1143,18 +1178,22 @@ class Parser
                                $s .= $protocol . $remainder;
                        }
                }
-               wfProfileOut();
+               wfProfileOut( $fname );
                return $s;
        }
 
        /**
-        * make an image if it's allowed
+        * make an image if it's allowed, either through the global
+        * option or through the exception
         * @access private
         */
        function maybeMakeExternalImage( $url ) {
                $sk =& $this->mOptions->getSkin();
+               $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
+               $imagesexception = !empty($imagesfrom);
                $text = false;
-               if ( $this->mOptions->getAllowExternalImages() ) {
+               if ( $this->mOptions->getAllowExternalImages() 
+                    || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
                        if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
                                # Image found
                                $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
@@ -1162,7 +1201,7 @@ class Parser
                }
                return $text;
        }
-       
+
        /**
         * Process [[ ]] wikilinks
         *
@@ -1178,7 +1217,7 @@ class Parser
                static $tc = FALSE;
                # the % is needed to support urlencoded titles as well
                if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
-               
+
                $sk =& $this->mOptions->getSkin();
 
                #split the entire text string on occurences of [[
@@ -1195,7 +1234,7 @@ class Parser
                if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
                # Match the end of a line for a word that's not followed by whitespace,
                # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
-               static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
+               $e2 = wfMsgForContent( 'linkprefix' );
 
                $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
 
@@ -1207,7 +1246,6 @@ class Parser
                if ( $useLinkPrefixExtension ) {
                        if ( preg_match( $e2, $s, $m ) ) {
                                $first_prefix = $m[2];
-                               $s = $m[1];
                        } else {
                                $first_prefix = false;
                        }
@@ -1220,7 +1258,7 @@ class Parser
 
                $checkVariantLink = sizeof($wgContLang->getVariants())>1;
                $useSubpages = $this->areSubpagesAllowed();
-               
+
                # Loop for each link
                for ($k = 0; isset( $a[$k] ); $k++) {
                        $line = $a[$k];
@@ -1241,7 +1279,7 @@ class Parser
                        }
 
                        $might_be_img = false;
-                       
+
                        if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
                                $text = $m[2];
                                # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
@@ -1272,7 +1310,7 @@ class Parser
                        # Don't allow internal links to pages containing
                        # PROTO: where PROTO is a valid URL protocol; these
                        # should be external links.
-                       if (preg_match('/^(\b(?:'.URL_PROTOCOLS.'):)/', $m[1])) {
+                       if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
                                $s .= $prefix . '[[' . $line ;
                                continue;
                        }
@@ -1289,8 +1327,8 @@ class Parser
                                # Strip off leading ':'
                                $link = substr($link, 1);
                        }
-                       
-                       $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
+
+                       $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
                        if( !$nt ) {
                                $s .= $prefix . '[[' . $line;
                                continue;
@@ -1305,13 +1343,14 @@ class Parser
 
                        $ns = $nt->getNamespace();
                        $iw = $nt->getInterWiki();
-                       
+
                        if ($might_be_img) { # if this is actually an invalid link
                                if ($ns == NS_IMAGE && $noforce) { #but might be an image
                                        $found = false;
                                        while (isset ($a[$k+1]) ) {
                                                #look at the next 'line' to see if we can close it there
-                                               $next_line =  array_shift(array_splice( $a, $k + 1, 1) );
+                                               $spliced = array_splice( $a, $k + 1, 1 );
+                                               $next_line = array_shift( $spliced );
                                                if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
                                                # the first ]] closes the inner link, the second the image
                                                        $found = true;
@@ -1345,7 +1384,7 @@ class Parser
                        $wasblank = ( '' == $text );
                        if( $wasblank ) $text = $link;
 
-                       
+
                        # Link not escaped by : , create the various objects
                        if( $noforce ) {
 
@@ -1356,7 +1395,7 @@ class Parser
                                        $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
                                        continue;
                                }
-                               
+
                                if ( $ns == NS_IMAGE ) {
                                        wfProfileIn( "$fname-image" );
                                        if ( !wfIsBadImage( $nt->getDBkey() ) ) {
@@ -1365,21 +1404,21 @@ class Parser
                                                # but it might be hard to fix that, and it doesn't matter ATM
                                                $text = $this->replaceExternalLinks($text);
                                                $text = $this->replaceInternalLinks($text);
-                                               
+
                                                # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
-                                               $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
+                                               $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', UNIQ_PREFIX."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
                                                $wgLinkCache->addImageLinkObj( $nt );
-                                               
+
                                                wfProfileOut( "$fname-image" );
                                                continue;
                                        }
                                        wfProfileOut( "$fname-image" );
 
                                }
-                               
+
                                if ( $ns == NS_CATEGORY ) {
                                        wfProfileIn( "$fname-category" );
-                                       $t = $wgContLang->convert($nt->getText());
+                                       $t = $wgContLang->convertHtml( $nt->getText() );
                                        $s = rtrim($s . "\n"); # bug 87
 
                                        $wgLinkCache->suspend(); # Don't save in links/brokenlinks
@@ -1398,13 +1437,13 @@ class Parser
                                        $sortkey = $wgContLang->convertCategoryKey( $sortkey );
                                        $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
                                        $this->mOutput->addCategoryLink( $t );
-                                       
+
                                        /**
                                         * Strip the whitespace Category links produce, see bug 87
                                         * @todo We might want to use trim($tmp, "\n") here.
                                         */
                                        $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
-                                       
+
                                        wfProfileOut( "$fname-category" );
                                        continue;
                                }
@@ -1426,22 +1465,7 @@ class Parser
                                $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
                                continue;
                        }
-                       if( !$nt->isExternal() && $nt->isAlwaysKnown() ) {
-                               /**
-                                * Skip lookups for special pages and self-links.
-                                * External interwiki links are not included here because
-                                * the HTTP urls would break output in the next parse step;
-                                * they will have placeholders kept.
-                                */
-                               $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
-                       } else {
-                               /**
-                                * Add a link placeholder
-                                * Later, this will be replaced by a real link, after the existence or 
-                                * non-existence of all the links is known
-                                */
-                               $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
-                       }
+                       $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
                }
                wfProfileOut( $fname );
                return $s;
@@ -1449,8 +1473,8 @@ class Parser
 
        /**
         * Make a link placeholder. The text returned can be later resolved to a real link with
-        * replaceLinkHolders(). This is done for two reasons: firstly to avoid further 
-        * parsing of interwiki links, and secondly to allow all extistence checks and 
+        * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
+        * parsing of interwiki links, and secondly to allow all extistence checks and
         * article length checks (for stub links) to be bundled into a single query.
         *
         */
@@ -1461,7 +1485,7 @@ class Parser
                } else {
                        # Separate the link trail from the rest of the link
                        list( $inside, $trail ) = Linker::splitTrail( $trail );
-                       
+
                        if ( $nt->isExternal() ) {
                                $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
                                $this->mInterwikiLinkHolders['titles'][] = $nt;
@@ -1488,7 +1512,7 @@ class Parser
                global $wgNamespacesWithSubpages;
                return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
        }
-       
+
        /**
         * Handle link to subpage if necessary
         * @param string $target the source of the link
@@ -1508,10 +1532,10 @@ class Parser
                $fname = 'Parser::maybeDoSubpageLink';
                wfProfileIn( $fname );
                $ret = $target; # default return value is no change
-                       
-               # Some namespaces don't allow subpages, 
+
+               # Some namespaces don't allow subpages,
                # so only perform processing if subpages are allowed
-               if( $this->areSubpagesAllowed() ) {             
+               if( $this->areSubpagesAllowed() ) {
                        # Look at the first character
                        if( $target != '' && $target{0} == '/' ) {
                                # / at end means we don't want the slash to be shown
@@ -1521,7 +1545,7 @@ class Parser
                                } else {
                                        $noslash = substr( $target, 1 );
                                }
-                               
+
                                $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
                                if( '' === $text ) {
                                        $text = $target;
@@ -1734,7 +1758,7 @@ class Parser
                                if ( $openmatch or $closematch ) {
                                        $paragraphStack = false;
                                        $output .= $this->closeParagraph();
-                                       if($preOpenMatch and !$preCloseMatch) {
+                                       if ( $preOpenMatch and !$preCloseMatch ) {
                                                $this->mInPre = true;
                                        }
                                        if ( $closematch ) {
@@ -1781,6 +1805,10 @@ class Parser
                                }
                                wfProfileOut( "$fname-paragraph" );
                        }
+                       // somewhere above we forget to get out of pre block (bug 785)
+                       if($preCloseMatch && $this->mInPre) {
+                               $this->mInPre = false;
+                       }
                        if ($paragraphStack === false) {
                                $output .= $t."\n";
                        }
@@ -1844,45 +1872,55 @@ class Parser
         * @access private
         */
        function getVariableValue( $index ) {
-               global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
-               
+               global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
+
                /**
                 * Some of these require message or data lookups and can be
                 * expensive to check many times.
                 */
                static $varCache = array();
-               if( isset( $varCache[$index] ) ) return $varCache[$index];
-               
+               if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
+                       if ( isset( $varCache[$index] ) )
+                               return $varCache[$index];
+
+               $ts = time();
+               wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
+
                switch ( $index ) {
                        case MAG_CURRENTMONTH:
-                               return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
                        case MAG_CURRENTMONTHNAME:
-                               return $varCache[$index] = $wgContLang->getMonthName( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
                        case MAG_CURRENTMONTHNAMEGEN:
-                               return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
                        case MAG_CURRENTMONTHABBREV:
-                               return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
                        case MAG_CURRENTDAY:
-                               return $varCache[$index] = $wgContLang->formatNum( date('j') );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
                        case MAG_PAGENAME:
                                return $this->mTitle->getText();
                        case MAG_PAGENAMEE:
                                return $this->mTitle->getPartialURL();
+                       case MAG_FULLPAGENAME:
+                               return $this->mTitle->getPrefixedText();
+                       case MAG_FULLPAGENAMEE:
+                               return wfUrlencode( $this->mTitle->getPrefixedText() );
                        case MAG_REVISIONID:
-                               return $wgArticle->getRevIdFetched();
+                               return $this->mRevisionId;
                        case MAG_NAMESPACE:
-                               # return Namespace::getCanonicalName($this->mTitle->getNamespace());
-                               return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
+                               return $wgContLang->getNsText( $this->mTitle->getNamespace() );
+                       case MAG_NAMESPACEE:
+                               return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
                        case MAG_CURRENTDAYNAME:
-                               return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
+                               return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
                        case MAG_CURRENTYEAR:
-                               return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
                        case MAG_CURRENTTIME:
-                               return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
+                               return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
                        case MAG_CURRENTWEEK:
-                               return $varCache[$index] = $wgContLang->formatNum( date('W') );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
                        case MAG_CURRENTDOW:
-                               return $varCache[$index] = $wgContLang->formatNum( date('w') );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
                        case MAG_NUMBEROFARTICLES:
                                return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
                        case MAG_NUMBEROFFILES:
@@ -1896,7 +1934,11 @@ class Parser
                        case MAG_SCRIPTPATH:
                                return $wgScriptPath;
                        default:
-                               return NULL;
+                               $ret = null;
+                               if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
+                                       return $ret;
+                               else
+                                       return null;
                }
        }
 
@@ -1917,6 +1959,180 @@ class Parser
                wfProfileOut( $fname );
        }
 
+       /**
+        * parse any parentheses in format ((title|part|part))
+        * and call callbacks to get a replacement text for any found piece
+        *
+        * @param string $text The text to parse
+        * @param array $callbacks rules in form:
+        *     '{' => array(                            # opening parentheses
+        *                                      'end' => '}',   # closing parentheses
+        *                                      'cb' => array(2 => callback,    # replacement callback to call if {{..}} is found
+        *                                                                4 => callback         # replacement callback to call if {{{{..}}}} is found
+        *                                                                )
+        *                                      )
+        * @access private
+        */
+       function replace_callback ($text, $callbacks) {
+               $openingBraceStack = array();   # this array will hold a stack of parentheses which are not closed yet
+               $lastOpeningBrace = -1;                 # last not closed parentheses
+
+               for ($i = 0; $i < strlen($text); $i++) {
+                       # check for any opening brace
+                       $rule = null;
+                       $nextPos = -1;
+                       foreach ($callbacks as $key => $value) {
+                               $pos = strpos ($text, $key, $i);
+                               if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
+                                       $rule = $value;
+                                       $nextPos = $pos;
+                               }
+                       }
+
+                       if ($lastOpeningBrace >= 0) {
+                               $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
+                       
+                               if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
+                                       $rule = null;
+                                       $nextPos = $pos;
+                               }
+
+                               $pos = strpos ($text, '|', $i);
+                               
+                               if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
+                                       $rule = null;
+                                       $nextPos = $pos;
+                               }
+                       }
+
+                       if ($nextPos == -1)
+                               break;
+
+                       $i = $nextPos;
+
+                       # found openning brace, lets add it to parentheses stack
+                       if (null != $rule) {
+                               $piece = array('brace' => $text[$i],
+                                                          'braceEnd' => $rule['end'],
+                                                          'count' => 1,
+                                                          'title' => '',
+                                                          'parts' => null);
+
+                               # count openning brace characters 
+                               while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
+                                       $piece['count']++;
+                                       $i++;
+                               }
+
+                               $piece['startAt'] = $i+1; 
+                               $piece['partStart'] = $i+1; 
+
+                               # we need to add to stack only if openning brace count is enough for any given rule
+                               foreach ($rule['cb'] as $cnt => $fn) {
+                                       if ($piece['count'] >= $cnt) {
+                                               $lastOpeningBrace ++;
+                                               $openingBraceStack[$lastOpeningBrace] = $piece;
+                                               break;
+                                       }
+                               }
+
+                               continue;
+                       }
+                       else if ($lastOpeningBrace >= 0) {
+                               # first check if it is a closing brace
+                               if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
+                                       # lets check if it is enough characters for closing brace
+                                       $count = 1;
+                                       while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
+                                               $count++;
+
+                                       # if there are more closing parentheses than opening ones, we parse less
+                                       if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
+                                               $count = $openingBraceStack[$lastOpeningBrace]['count'];
+
+                                       # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
+                                       $matchingCount = 0;
+                                       $matchingCallback = null;
+                                       foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
+                                               if ($count >= $cnt && $matchingCount < $cnt) {
+                                                       $matchingCount = $cnt;
+                                                       $matchingCallback = $fn;
+                                               }
+                                       }
+                                       
+                                       if ($matchingCount == 0) {
+                                               $i += $count - 1;
+                                               continue;
+                                       }
+
+                                       # lets set a title or last part (if '|' was found)
+                                       if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
+                                               $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
+                                       else
+                                               $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
+
+                                       $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
+                                       $pieceEnd = $i + $matchingCount;
+                                       
+                                       if( is_callable( $matchingCallback ) ) {
+                                               $cbArgs = array (
+                                                                                'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
+                                                                                'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
+                                                                                'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
+                                                                                'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
+                                                                                );
+                                               # finally we can call a user callback and replace piece of text
+                                               $replaceWith = call_user_func( $matchingCallback, $cbArgs );
+                                               $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
+                                               $i = $pieceStart + strlen($replaceWith) - 1;
+                                       }
+                                       else {
+                                               # null value for callback means that parentheses should be parsed, but not replaced
+                                               $i += $matchingCount - 1;
+                                       }
+
+                                       # reset last openning parentheses, but keep it in case there are unused characters
+                                       $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
+                                                                  'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
+                                                                  'count' => $openingBraceStack[$lastOpeningBrace]['count'],
+                                                                  'title' => '',
+                                                                  'parts' => null,
+                                                                  'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
+                                       $openingBraceStack[$lastOpeningBrace--] = null;
+
+                                       if ($matchingCount < $piece['count']) {
+                                               $piece['count'] -= $matchingCount;
+                                               $piece['startAt'] -= $matchingCount;
+                                               $piece['partStart'] = $piece['startAt'];
+                                               # do we still qualify for any callback with remaining count?
+                                               foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
+                                                       if ($piece['count'] >= $cnt) {
+                                                               $lastOpeningBrace ++;
+                                                               $openingBraceStack[$lastOpeningBrace] = $piece;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+                                       continue;
+                               }
+
+                               # lets set a title if it is a first separator, or next part otherwise
+                               if ($text[$i] == '|') {
+                                       if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
+                                               $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
+                                               $openingBraceStack[$lastOpeningBrace]['parts'] = array();
+                                       }
+                                       else
+                                               $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
+                                       
+                                       $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
+                               }
+                       }
+               }
+
+               return $text;
+       }
+
        /**
         * Replace magic variables, templates, and template arguments
         * with the appropriate text. Templates are substituted recursively,
@@ -1926,13 +2142,12 @@ class Parser
         *  OT_WIKI: only {{subst:}} templates
         *  OT_MSG: only magic variables
         *  OT_HTML: all templates and magic variables
-        * 
+        *
         * @param string $tex The text to transform
         * @param array $args Key-value pairs representing template parameters to substitute
         * @access private
         */
        function replaceVariables( $text, $args = array() ) {
-
                # Prevent too big inclusions
                if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
                        return $text;
@@ -1941,21 +2156,18 @@ class Parser
                $fname = 'Parser::replaceVariables';
                wfProfileIn( $fname );
 
-               $titleChars = Title::legalChars();
-
                # This function is called recursively. To keep track of arguments we need a stack:
                array_push( $this->mArgStack, $args );
 
-               # Variable substitution
-               $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
-               
+               $braceCallbacks = array();
+               $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
                if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
-                       # Argument substitution
-                       $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
+                       $braceCallbacks[3] = array( &$this, 'argSubstitution' );
                }
-               # Template substitution
-               $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
-               $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
+               $callbacks = array();
+               $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
+               $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
+               $text = $this->replace_callback ($text, $callbacks);
 
                array_pop( $this->mArgStack );
 
@@ -2007,7 +2219,7 @@ class Parser
                # merged with the next arg because the '|' character between belongs
                # to the link syntax and not the template parameter syntax.
                $argc = count($args);
-               
+
                for ( $i = 0; $i < $argc-1; $i++ ) {
                        if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
                                $args[$i] .= '|'.$args[$i+1];
@@ -2024,44 +2236,44 @@ class Parser
         * Return the text of a template, after recursively
         * replacing any variables or templates within the template.
         *
-        * @param array $matches The parts of the template
-        *  $matches[1]: the title, i.e. the part before the |
-        *  $matches[2]: the parameters (including a leading |), if  any
+        * @param array $piece The parts of the template
+        *  $piece['text']: matched text
+        *  $piece['title']: the title, i.e. the part before the |
+        *  $piece['parts']: the parameter array
         * @return string the text of the template
         * @access private
         */
-       function braceSubstitution( $matches ) {
+       function braceSubstitution( $piece ) {
                global $wgLinkCache, $wgContLang;
                $fname = 'Parser::braceSubstitution';
                wfProfileIn( $fname );
-               
+
                $found = false;
                $nowiki = false;
                $noparse = false;
 
                $title = NULL;
 
-               # Need to know if the template comes at the start of a line,
-               # to treat the beginning of the template like the beginning
-               # of a line for tables and block-level elements.
-               $linestart = $matches[1];
+               $linestart = '';
 
                # $part1 is the bit before the first |, and must contain only title characters
                # $args is a list of arguments, starting from index 0, not including $part1
 
-               $part1 = $matches[2];
+               $part1 = $piece['title'];
                # If the third subpattern matched anything, it will start with |
 
-               $args = $this->getTemplateArgs($matches[3]);
-               $argc = count( $args );
-
-               # Don't parse {{{}}} because that's only for template arguments
-               if ( $linestart === '{' ) {
-                       $text = $matches[0];
-                       $found = true;
-                       $noparse = true;
+               if (null == $piece['parts']) {
+                       $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
+                       if ($replaceWith != $piece['text']) {
+                               $text = $replaceWith;
+                               $found = true;
+                               $noparse = true;
+                       }
                }
 
+               $args = (null == $piece['parts']) ? array() : $piece['parts'];
+               $argc = count( $args );
+
                # SUBST
                if ( !$found ) {
                        $mwSubst =& MagicWord::get( MAG_SUBST );
@@ -2070,7 +2282,7 @@ class Parser
                                # 1) Found SUBST but not in the PST phase
                                # 2) Didn't find SUBST and in the PST phase
                                # In either case, return without further processing
-                               $text = $matches[0];
+                               $text = $piece['text'];
                                $found = true;
                                $noparse = true;
                        }
@@ -2116,20 +2328,48 @@ class Parser
                        }
                }
 
-               # LOCALURL and LOCALURLE
+               # LCFIRST, UCFIRST, LC and UC
+               if ( !$found ) {
+                       $lcfirst =& MagicWord::get( MAG_LCFIRST );
+                       $ucfirst =& MagicWord::get( MAG_UCFIRST );
+                       $lc =& MagicWord::get( MAG_LC );
+                       $uc =& MagicWord::get( MAG_UC );
+                       if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
+                               $text = $linestart . $wgContLang->lcfirst( $part1 );
+                               $found = true;
+                       } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
+                               $text = $linestart . $wgContLang->ucfirst( $part1 );
+                               $found = true;
+                       } else if ( $lc->matchStartAndRemove( $part1 ) ) {
+                               $text = $linestart . $wgContLang->lc( $part1 );
+                               $found = true;
+                       } else if ( $uc->matchStartAndRemove( $part1 ) ) {
+                                $text = $linestart . $wgContLang->uc( $part1 );
+                                $found = true;
+                       }
+               }
+
+               # LOCALURL and FULLURL
                if ( !$found ) {
-                       $mwLocal = MagicWord::get( MAG_LOCALURL );
-                       $mwLocalE = MagicWord::get( MAG_LOCALURLE );
+                       $mwLocal =& MagicWord::get( MAG_LOCALURL );
+                       $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
+                       $mwFull =& MagicWord::get( MAG_FULLURL );
+                       $mwFullE =& MagicWord::get( MAG_FULLURLE );
+                       
 
                        if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
                                $func = 'getLocalURL';
                        } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
                                $func = 'escapeLocalURL';
+                       } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
+                               $func = 'getFullURL';
+                       } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
+                               $func = 'escapeFullURL';
                        } else {
-                               $func = '';
+                               $func = false;
                        }
 
-                       if ( $func !== '' ) {
+                       if ( $func !== false ) {
                                $title = Title::newFromText( $part1 );
                                if ( !is_null( $title ) ) {
                                        if ( $argc > 0 ) {
@@ -2151,6 +2391,16 @@ class Parser
                        }
                }
 
+               # PLURAL
+               if ( !$found && $argc >= 2 ) {
+                       $mwPluralForm =& MagicWord::get( MAG_PLURAL );
+                       if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
+                               if ($argc==2) {$args[2]=$args[1];}
+                               $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
+                               $found = true;
+                       }
+               }
+
                # Template table test
 
                # Did we encounter this template already? If yes, it is in the cache
@@ -2183,6 +2433,14 @@ class Parser
                                $ns = $this->mTitle->getNamespace();
                        }
                        $title = Title::newFromText( $part1, $ns );
+
+                       if ($title) {
+                               $interwiki = Title::getInterwikiLink($title->getInterwiki());
+                               if ($interwiki != '' && $title->isTrans()) {
+                                       return $this->scarytransclude($title, $interwiki);
+                               }
+                       }
+
                        if ( !is_null( $title ) && !$title->isExternal() ) {
                                # Check for excessive inclusion
                                $dbk = $title->getPrefixedDBkey();
@@ -2190,15 +2448,15 @@ class Parser
                                        if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
                                                # Capture special page output
                                                $text = SpecialPage::capturePath( $title );
-                                               if ( $text && !is_object( $text ) ) {
+                                               if ( is_string( $text ) ) {
                                                        $found = true;
                                                        $noparse = true;
                                                        $isHTML = true;
-                                                       $this->mOutput->setCacheTime( -1 );
+                                                       $this->disableCache();
                                                }
                                        } else {
                                                $article = new Article( $title );
-                                               $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
+                                               $articleContent = $article->fetchContent(0, false);
                                                if ( $articleContent !== false ) {
                                                        $found = true;
                                                        $text = $articleContent;
@@ -2248,7 +2506,19 @@ class Parser
                        # Add a new element to the templace recursion path
                        $this->mTemplatePath[$part1] = 1;
 
+                       # If there are any <onlyinclude> tags, only include them
+                       if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
+                               preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
+                               $text = '';
+                               foreach ($m[1] as $piece)
+                                       $text .= $this->trimOnlyinclude( $piece );
+                       }
+                       # Remove <noinclude> sections and <includeonly> tags
+                       $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
+                       $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
+                       
                        if( $this->mOutputType == OT_HTML ) {
+                               # Strip <nowiki>, <pre>, etc.
                                $text = $this->strip( $text, $this->mStripState );
                                $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
                        }
@@ -2261,20 +2531,20 @@ class Parser
 
                        # If the template begins with a table or block-level
                        # element, it should be treated as beginning a new line.
-                       if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
+                       if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
                                $text = "\n" . $text;
                        }
                }
                # Prune lower levels off the recursion check path
                $this->mTemplatePath = $lastPathLevel;
-               
+
                if ( !$found ) {
                        wfProfileOut( $fname );
-                       return $matches[0];
+                       return $piece['text'];
                } else {
                        if ( $isHTML ) {
                                # Replace raw HTML by a placeholder
-                               # Add a blank line preceding, to prevent it from mucking up 
+                               # Add a blank line preceding, to prevent it from mucking up
                                # immediately preceding headings
                                $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
                        } else {
@@ -2300,36 +2570,94 @@ class Parser
                                                preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
                                                $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
                                                        . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
-                                               
+
                                                $nsec++;
                                        }
                                }
                        }
                }
-               
+
                # Prune lower levels off the recursion check path
                $this->mTemplatePath = $lastPathLevel;
-               
+
                if ( !$found ) {
                        wfProfileOut( $fname );
-                       return $matches[0];
+                       return $piece['text'];
                } else {
                        wfProfileOut( $fname );
                        return $text;
                }
        }
+       
+       /**
+        * Trim the first and last newlines of a string, this is not equivalent
+        * to trim( $str, "\n" ) which would trim them all.
+        *
+        * @param string $str The string to trim
+        * @return string
+        */
+       function trimOnlyinclude( $str ) {
+               $str = preg_replace( "/^\n/", '', $str );
+               $str = preg_replace( "/\n$/", '', $str );
+               return $str;
+       }
+
+       /**
+        * Translude an interwiki link.
+        */
+       function scarytransclude($title, $interwiki) {
+               global $wgEnableScaryTranscluding;
+
+               if (!$wgEnableScaryTranscluding)
+                       return wfMsg('scarytranscludedisabled');
+
+               $articlename = "Template:" . $title->getDBkey();
+               $url = str_replace('$1', urlencode($articlename), $interwiki);
+               if (strlen($url) > 255)
+                       return wfMsg('scarytranscludetoolong');
+               $text = $this->fetchScaryTemplateMaybeFromCache($url);
+               $this->mIWTransData[] = $text;
+               return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData) - 1)."-->";
+       }
+
+       function fetchScaryTemplateMaybeFromCache($url) {
+               $dbr =& wfGetDB(DB_SLAVE);
+               $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
+                               array('tc_url' => $url));
+               if ($obj) {
+                       $time = $obj->tc_time;
+                       $text = $obj->tc_contents;
+                       if ($time && $time < (time() + (60*60))) {
+                               return $text;
+                       }
+               }
+
+               $text = wfGetHTTP($url . '?action=render');
+               if (!$text)
+                       return wfMsg('scarytranscludefailed', $url);
+
+               $dbw =& wfGetDB(DB_MASTER);
+               $dbw->replace('transcache', array(), array(
+                       'tc_url' => $url,
+                       'tc_time' => time(),
+                       'tc_contents' => $text));
+               return $text;
+       }
+
 
        /**
         * Triple brace replacement -- used for template arguments
         * @access private
         */
        function argSubstitution( $matches ) {
-               $arg = trim( $matches[1] );
-               $text = $matches[0];
+               $arg = trim( $matches['title'] );
+               $text = $matches['text'];
                $inputArgs = end( $this->mArgStack );
 
                if ( array_key_exists( $arg, $inputArgs ) ) {
                        $text = $inputArgs[$arg];
+               } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
+                       $text = $matches['parts'][0];
                }
 
                return $text;
@@ -2356,10 +2684,10 @@ class Parser
         * 2) Add an [edit] link to sections for logged in users who have enabled the option
         * 3) Add a Table of contents on the top for users who have enabled the option
         * 4) Auto-anchor headings
-        *      
+        *
         * It loops through all headlines, collects the necessary data, then splits up the
         * string and re-inserts the newly formatted headlines.
-        * 
+        *
         * @param string $text
         * @param boolean $isMain
         * @access private
@@ -2456,9 +2784,9 @@ class Parser
                                $prevtoclevel = $toclevel;
                        }
                        $level = $matches[1][$headlineCount];
-                       
+
                        if( $doNumberHeadings || $doShowToc ) {
-                               
+
                                if ( $level > $prevlevel ) {
                                        # Increase TOC level
                                        $toclevel++;
@@ -2492,7 +2820,7 @@ class Parser
                                        # No change in level, end TOC line
                                        $toc .= $sk->tocLineEnd();
                                }
-                               
+
                                $levelCount[$toclevel] = $level;
 
                                # count number of headlines for each level
@@ -2516,7 +2844,7 @@ class Parser
 
                        # Remove link placeholders by the link text.
                        #     <!--LINK number-->
-                       # turns into 
+                       # turns into
                        #     link text with suffix
                        $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
                                                            "\$this->mLinkHolders['texts'][\$1]",
@@ -2668,7 +2996,7 @@ class Parser
         * @return string
         */
        function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl'  ) {
-               
+
                $valid = '0123456789';
                $internal = false;
 
@@ -2677,7 +3005,7 @@ class Parser
                        return $text;
                }
                $text = substr( array_shift( $a ), 1);
-               
+
                /* Check if keyword is preceed by [[.
                 * This test is made here cause of the array_shift above
                 * that prevent the test to be done in the foreach.
@@ -2720,7 +3048,7 @@ class Parser
                                $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
                                $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
                        }
-                       
+
                        /* Check if the next RFC keyword is preceed by [[ */
                        $internal = ( substr($x,-2) == '[[' );
                }
@@ -2753,7 +3081,7 @@ class Parser
                        "\r\n" => "\n",
                );
                $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
-               $text = $this->strip( $text, $stripState, false );
+               $text = $this->strip( $text, $stripState, true );
                $text = $this->pstPass2( $text, $user );
                $text = $this->unstrip( $text, $stripState );
                $text = $this->unstripNoWiki( $text, $stripState );
@@ -2773,30 +3101,23 @@ class Parser
 
                # Signatures
                #
-               $n = $user->getName();
-               $k = $user->getOption( 'nickname' );
-               if ( '' == $k ) { $k = $n; }
-               if ( isset( $wgLocaltimezone ) ) {
-                       $oldtz = getenv( 'TZ' );
-                       putenv( 'TZ='.$wgLocaltimezone );
-               }
+               $sigText = $this->getUserSig( $user );
 
                /* Note: This is the timestamp saved as hardcoded wikitext to
                 * the database, we use $wgContLang here in order to give
                 * everyone the same signiture and use the default one rather
                 * than the one selected in each users preferences.
                 */
-               $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
+               if ( isset( $wgLocaltimezone ) ) {
+                       $oldtz = getenv( 'TZ' );
+                       putenv( 'TZ='.$wgLocaltimezone );
+               }
+               $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
                  ' (' . date( 'T' ) . ')';
                if ( isset( $wgLocaltimezone ) ) {
                        putenv( 'TZ='.$oldtz );
                }
 
-               if( $user->getOption( 'fancysig' ) ) {
-                       $sigText = $k;
-               } else {
-                       $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
-               }
                $text = preg_replace( '/~~~~~/', $d, $text );
                $text = preg_replace( '/~~~~/', "$sigText $d", $text );
                $text = preg_replace( '/~~~/', $sigText, $text );
@@ -2836,6 +3157,62 @@ class Parser
 
                return $text;
        }
+       
+       /**
+        * Fetch the user's signature text, if any, and normalize to
+        * validated, ready-to-insert wikitext.
+        *
+        * @param User $user
+        * @return string
+        * @access private
+        */
+       function getUserSig( &$user ) {
+               $name = $user->getName();
+               $nick = trim( $user->getOption( 'nickname' ) );
+               if ( '' == $nick ) {
+                       $nick = $name;
+               }
+               
+               if( $user->getOption( 'fancysig' ) ) {
+                       // A wikitext signature.
+                       $valid = $this->validateSig( $nick );
+                       if( $valid === false ) {
+                               // Fall back to default sig
+                               $nick = $name;
+                               wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
+                       } else {
+                               return $nick;
+                       }
+               }
+               
+               // Plain text linking to the user's homepage
+               global $wgContLang;
+               $page = $user->getUserPage();
+               return '[[' .
+                       $page->getPrefixedText() .
+                       "|" .
+                       wfEscapeWikIText( $nick ) .
+                       "]]";
+       }
+       
+       /**
+        * We want to enforce two rules on wikitext sigs here:
+        * 1) Expand any templates at save time (forced subst:)
+        * 2) Check for unbalanced XML tags, and reject if so.
+        *
+        * @param string $text
+        * @return mixed An expanded string, or false if invalid.
+        *
+        * @todo Run brace substitutions
+        * @todo ?? Check for unbalanced '' and ''' quotes, etc
+        */
+       function validateSig( $text ) {
+               if( wfIsWellFormedXmlFragment( $text ) ) {
+                       return $text;
+               } else {
+                       return false;
+               }
+       }
 
        /**
         * Set up some variables which are usually set up in parse()
@@ -2853,7 +3230,7 @@ class Parser
 
        /**
         * Transform a MediaWiki message by replacing magic variables.
-        * 
+        *
         * @param string $text the text to transform
         * @param ParserOptions $options  options
         * @return string the text with variables substituted
@@ -2883,11 +3260,18 @@ class Parser
         * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
         * Callback will be called with the text within
         * Transform and return the text within
+        *
         * @access public
+        *
+        * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
+        * @param mixed $callback The callback function (and object) to use for the tag
+        *
+        * @return The old value of the mTagHooks array associated with the hook
         */
        function setHook( $tag, $callback ) {
                $oldVal = @$this->mTagHooks[$tag];
                $this->mTagHooks[$tag] = $callback;
+               
                return $oldVal;
        }
 
@@ -2910,16 +3294,16 @@ class Parser
                $pdbks = array();
                $colours = array();
                $sk = $this->mOptions->getSkin();
-               
+
                if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
                        wfProfileIn( $fname.'-check' );
                        $dbr =& wfGetDB( DB_SLAVE );
                        $page = $dbr->tableName( 'page' );
                        $threshold = $wgUser->getOption('stubthreshold');
-                       
+
                        # Sort by namespace
                        asort( $this->mLinkHolders['namespaces'] );
-       
+
                        # Generate query
                        $query = false;
                        foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
@@ -2934,7 +3318,7 @@ class Parser
                                $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
 
                                # Check if it's in the link cache already
-                               if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
+                               if ( $title->isAlwaysKnown() || $wgLinkCache->getGoodLinkID( $pdbk ) ) {
                                        $colours[$pdbk] = 1;
                                } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
                                        $colours[$pdbk] = 0;
@@ -2953,7 +3337,7 @@ class Parser
                                        } else {
                                                $query .= ', ';
                                        }
-                               
+
                                        $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
                                }
                        }
@@ -2962,9 +3346,9 @@ class Parser
                                if ( $options & RLH_FOR_UPDATE ) {
                                        $query .= ' FOR UPDATE';
                                }
-                       
+
                                $res = $dbr->query( $query, $fname );
-                               
+
                                # Fetch data and form into an associative array
                                # non-existent = broken
                                # 1 = known
@@ -2973,7 +3357,7 @@ class Parser
                                        $title = Title::makeTitle( $s->page_namespace, $s->page_title );
                                        $pdbk = $title->getPrefixedDBkey();
                                        $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
-                                       
+
                                        if ( $threshold >  0 ) {
                                                $size = $s->page_len;
                                                if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
@@ -2987,7 +3371,7 @@ class Parser
                                }
                        }
                        wfProfileOut( $fname.'-check' );
-                       
+
                        # Construct search and replace arrays
                        wfProfileIn( $fname.'-construct' );
                        $wgOutputReplace = array();
@@ -3015,7 +3399,7 @@ class Parser
 
                        # Do the thing
                        wfProfileIn( $fname.'-replace' );
-                       
+
                        $text = preg_replace_callback(
                                '/(<!--LINK .*?-->)/',
                                "wfOutputReplaceMatches",
@@ -3034,18 +3418,18 @@ class Parser
                                $title = $this->mInterwikiLinkHolders['titles'][$key];
                                $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
                        }
-                       
+
                        $text = preg_replace_callback(
                                '/<!--IWLINK (.*?)-->/',
                                "wfOutputReplaceMatches",
                                $text );
                        wfProfileOut( $fname.'-interwiki' );
                }
-               
+
                wfProfileOut( $fname );
                return $colours;
        }
-       
+
        /**
         * Replace <!--LINK--> link placeholders with plain text of links
         * (not HTML-formatted).
@@ -3063,11 +3447,11 @@ class Parser
                        '/<!--(LINK|IWLINK) (.*?)-->/',
                        array( &$this, 'replaceLinkHoldersTextCallback' ),
                        $text );
-               
+
                wfProfileOut( $fname );
                return $text;
        }
-       
+
        /**
         * @param array $matches
         * @return string
@@ -3104,7 +3488,7 @@ class Parser
                global $wgUser, $wgTitle;
                $parserOptions = ParserOptions::newFromUser( $wgUser );
                $localParser = new Parser();
-               
+
                global $wgLinkCache;
                $ig = new ImageGallery();
                $ig->setShowBytes( false );
@@ -3129,10 +3513,10 @@ class Parser
                        } else {
                                $label = '';
                        }
-                       
+
                        $html = $localParser->parse( $label , $wgTitle, $parserOptions );
                        $html = $html->mText;
-                       
+
                        $ig->add( new Image( $nt ), $html );
                        $wgLinkCache->addImageLinkObj( $nt );
                }
@@ -3145,7 +3529,7 @@ class Parser
        function makeImage( &$nt, $options ) {
                global $wgContLang, $wgUseImageResize;
                global $wgUser, $wgThumbLimits;
-               
+
                $align = '';
 
                # Check if the options text is of the form "options|alt text"
@@ -3161,6 +3545,7 @@ class Parser
                $part = explode( '|', $options);
 
                $mwThumb  =& MagicWord::get( MAG_IMG_THUMBNAIL );
+               $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
                $mwLeft   =& MagicWord::get( MAG_IMG_LEFT );
                $mwRight  =& MagicWord::get( MAG_IMG_RIGHT );
                $mwNone   =& MagicWord::get( MAG_IMG_NONE );
@@ -3173,14 +3558,12 @@ class Parser
                $manual_thumb = '' ;
 
                foreach( $part as $key => $val ) {
-                       $val_parts = explode ( '=' , $val , 2 ) ;
-                       $left_part = array_shift ( $val_parts ) ;
                        if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
                                $thumb=true;
-                       } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
+                       } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
                                # use manually specified thumbnail
                                $thumb=true;
-                               $manual_thumb = array_shift ( $val_parts ) ;
+                               $manual_thumb = $match;
                        } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
                                # remember to set an alignment, don't render immediately
                                $align = 'right';
@@ -3216,6 +3599,34 @@ class Parser
                $sk =& $this->mOptions->getSkin();
                return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
        }
+
+       /**
+        * Set a flag in the output object indicating that the content is dynamic and 
+        * shouldn't be cached.
+        */
+       function disableCache() {
+               $this->mOutput->mCacheTime = -1;
+       }
+       
+       /**
+        * Callback from the Sanitizer for expanding items found in HTML attribute
+        * values, so they can be safely tested and escaped.
+        * @param string $text
+        * @param array $args
+        * @return string
+        * @access private
+        */
+       function attributeStripCallback( &$text, $args ) {
+               $text = $this->replaceVariables( $text, $args );
+               $text = $this->unstripForHTML( $text );
+               return $text;
+       }
+       
+       function unstripForHTML( $text ) {
+               $text = $this->unstrip( $text, $this->mStripState );
+               $text = $this->unstripNoWiki( $text, $this->mStripState );
+               return $text;
+       }
 }
 
 /**
@@ -3274,7 +3685,7 @@ class ParserOutput
        function expired( $touched ) {
                global $wgCacheEpoch;
                return $this->getCacheTime() == -1 || // parser says it's uncacheable
-                      $this->getCacheTime() <= $touched ||
+                      $this->getCacheTime() < $touched ||
                       $this->getCacheTime() <= $wgCacheEpoch ||
                       !isset( $this->mVersion ) ||
                       version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
@@ -3293,6 +3704,7 @@ class ParserOptions
        var $mUseDynamicDates;           # Use DateFormatter to format dates
        var $mInterwikiMagic;            # Interlanguage links are removed and returned in an array
        var $mAllowExternalImages;       # Allow external images inline
+       var $mAllowExternalImagesFrom;   # If not, any exception?
        var $mSkin;                      # Reference to the preferred skin
        var $mDateFormat;                # Date format index
        var $mEditSection;               # Create "edit section" links
@@ -3303,7 +3715,8 @@ class ParserOptions
        function getUseDynamicDates()               { return $this->mUseDynamicDates; }
        function getInterwikiMagic()                { return $this->mInterwikiMagic; }
        function getAllowExternalImages()           { return $this->mAllowExternalImages; }
-       function getSkin()                          { return $this->mSkin; }
+       function getAllowExternalImagesFrom()       { return $this->mAllowExternalImagesFrom; }
+       function &getSkin()                         { return $this->mSkin; }
        function getDateFormat()                    { return $this->mDateFormat; }
        function getEditSection()                   { return $this->mEditSection; }
        function getNumberHeadings()                { return $this->mNumberHeadings; }
@@ -3314,6 +3727,7 @@ class ParserOptions
        function setUseDynamicDates( $x )           { return wfSetVar( $this->mUseDynamicDates, $x ); }
        function setInterwikiMagic( $x )            { return wfSetVar( $this->mInterwikiMagic, $x ); }
        function setAllowExternalImages( $x )       { return wfSetVar( $this->mAllowExternalImages, $x ); }
+       function setAllowExternalImagesFrom( $x )   { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
        function setDateFormat( $x )                { return wfSetVar( $this->mDateFormat, $x ); }
        function setEditSection( $x )               { return wfSetVar( $this->mEditSection, $x ); }
        function setNumberHeadings( $x )            { return wfSetVar( $this->mNumberHeadings, $x ); }
@@ -3338,8 +3752,8 @@ class ParserOptions
 
        /** Get user options */
        function initialiseFromUser( &$userInput ) {
-               global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages, 
-                      $wgAllowSpecialInclusion;
+               global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
+                      $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
                $fname = 'ParserOptions::initialiseFromUser';
                wfProfileIn( $fname );
                if ( !$userInput ) {
@@ -3353,11 +3767,12 @@ class ParserOptions
                $this->mUseDynamicDates = $wgUseDynamicDates;
                $this->mInterwikiMagic = $wgInterwikiMagic;
                $this->mAllowExternalImages = $wgAllowExternalImages;
+               $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
                wfProfileIn( $fname.'-skin' );
                $this->mSkin =& $user->getSkin();
                wfProfileOut( $fname.'-skin' );
                $this->mDateFormat = $user->getOption( 'date' );
-               $this->mEditSection = $user->getOption( 'editsection' );
+               $this->mEditSection = true;
                $this->mNumberHeadings = $user->getOption( 'numberheadings' );
                $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
                wfProfileOut( $fname );
@@ -3388,12 +3803,12 @@ function wfNumberOfArticles() {
  */
 function wfNumberOfFiles() {
        $fname = 'Parser::wfNumberOfFiles';
-       
+
        wfProfileIn( $fname );
        $dbr =& wfGetDB( DB_SLAVE );
        $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
        wfProfileOut( $fname );
-       
+
        return $res;
 }
 
@@ -3424,7 +3839,7 @@ function wfLoadSiteStats() {
 /**
  * Escape html tags
  * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
- *  
+ *
  * @param string $in Text that might contain HTML tags
  * @return string Escaped string
  */