Tell regexp parser to use extra analysis on external link regexp;
[lhc/web/wiklou.git] / includes / Parser.php
index 42b71df..433487a 100644 (file)
@@ -7,6 +7,13 @@
  * @version $Id$
  */
 
+/**
+ * Update this version number when the ParserOutput format
+ * changes in an incompatible way, so the parser cache
+ * can automatically discard old data.
+ */
+define( 'MW_PARSER_VERSION', '1.4.0' );
+
 /**
  * Variable substitution O(N^2) attack
  *
  * Hence, we limit the number of inclusions of any given page, thus bringing any
  * attack back to O(N).
  */
+
 define( 'MAX_INCLUDE_REPEAT', 100 );
 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
 
+define( 'RLH_FOR_UPDATE', 1 );
+
 # Allowed values for $mOutputType
 define( 'OT_HTML', 1 );
 define( 'OT_WIKI', 2 );
@@ -37,8 +47,7 @@ define( 'UNIQ_PREFIX', 'NaodW29');
 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
 define( 'HTTP_PROTOCOLS', 'http|https' );
 # Everything except bracket, space, or control characters
-define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
-define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
+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]' );
@@ -65,7 +74,7 @@ define( 'EXT_IMAGE_REGEX',
  *   performs brace substitution on MediaWiki messages
  *
  * Globals used:
- *    objects:   $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
+ *    objects:   $wgLang, $wgDateFormatter, $wgLinkCache
  *
  * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
  *
@@ -137,7 +146,7 @@ class Parser
         * @return ParserOutput a ParserOutput
         */
        function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
-               global $wgUseTidy;
+               global $wgUseTidy, $wgContLang;
                $fname = 'Parser::parse';
                wfProfileIn( $fname );
 
@@ -151,6 +160,7 @@ class Parser
 
                $stripState = NULL;
                $text = $this->strip( $text, $this->mStripState );
+
                $text = $this->internalParse( $text, $linestart );
                $text = $this->unstrip( $text, $this->mStripState );
                # Clean up special characters, only run once, next-to-last before doBlockLevels
@@ -183,7 +193,16 @@ class Parser
                }
                # only once and last
                $text = $this->doBlockLevels( $text, $linestart );
+
+               $this->replaceLinkHolders( $text );
+               $text = $wgContLang->convert($text);
+
                $text = $this->unstripNoWiki( $text, $this->mStripState );
+               global $wgUseTidy;
+               if ($wgUseTidy) {
+                       $text = Parser::tidy($text);
+               }
+
                $this->mOutput->setText( $text );
                wfProfileOut( $fname );
                return $this->mOutput;
@@ -265,6 +284,7 @@ class Parser
                $pre_content = array();
                $comment_content = array();
                $ext_content = array();
+               $gallery_content = array();
 
                # Replace any instances of the placeholders
                $uniq_prefix = UNIQ_PREFIX;
@@ -318,6 +338,17 @@ class Parser
                        }
                }
 
+               # gallery
+               $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
+               foreach( $gallery_content as $marker => $content ) {
+                       require_once( 'ImageGallery.php' );
+                       if ( $render ) {
+                               $gallery_content[$marker] = Parser::renderImageGallery( $content );
+                       } else {
+                               $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
+                       }
+               }
+
                # Comments
                if($stripcomments) {
                        $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
@@ -346,6 +377,7 @@ class Parser
                        $state['math'] = $state['math'] + $math_content;
                        $state['pre'] = $state['pre'] + $pre_content;
                        $state['comment'] = $state['comment'] + $comment_content;
+                       $state['gallery'] = $state['gallery'] + $gallery_content;
 
                        foreach( $ext_content as $tag => $array ) {
                                if ( array_key_exists( $tag, $state ) ) {
@@ -359,13 +391,14 @@ class Parser
                          'math' => $math_content,
                          'pre' => $pre_content,
                          'comment' => $comment_content,
+                         'gallery' => $gallery_content,
                        ) + $ext_content;
                }
                return $text;
        }
 
        /**
-        * restores pre, math, and heiro removed by strip()
+        * restores pre, math, and hiero removed by strip()
         *
         * always call unstripNoWiki() after this one
         * @access private
@@ -584,6 +617,7 @@ class Parser
                                array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
                        }
                        else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
+                               # $x is a table row
                                if ( '|+' == substr ( $x , 0 , 2 ) ) {
                                        $fc = '+' ;
                                        $x = substr ( $x , 1 ) ;
@@ -592,6 +626,8 @@ class Parser
                                if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
                                $after = explode ( '||' , $after ) ;
                                $t[$k] = '' ;
+
+                               # Loop through each table cell
                                foreach ( $after AS $theline )
                                {
                                        $z = '' ;
@@ -610,8 +646,16 @@ class Parser
                                        else if ( $fc == '+' ) $l = 'caption' ;
                                        else $l = '' ;
                                        array_push ( $ltd , $l ) ;
+
+                                       # Cell parameters
                                        $y = explode ( '|' , $theline , 2 ) ;
-                                       if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
+                                       # Note that a '|' inside an invalid link should not
+                                       # be mistaken as delimiting cell parameters
+                                       if ( strpos( $y[0], '[[' ) !== false ) {
+                                               $y = array ($theline);
+                                       }
+                                       if ( count ( $y ) == 1 )
+                                               $y = "{$z}<{$l}>{$y[0]}" ;
                                        else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
                                        $t[$k] .= $y ;
                                        array_push ( $td , true ) ;
@@ -640,7 +684,7 @@ class Parser
         * @access private
         */
        function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
-        global $wgContLang;
+               global $wgContLang;
 
                $fname = 'Parser::internalParse';
                wfProfileIn( $fname );
@@ -648,8 +692,6 @@ class Parser
                $text = $this->removeHTMLtags( $text );
                $text = $this->replaceVariables( $text, $args );
 
-               $text = $wgContLang->convert($text);
-
                $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
 
                $text = $this->doHeadings( $text );
@@ -659,9 +701,12 @@ class Parser
                }
                $text = $this->doAllQuotes( $text );
                $text = $this->replaceInternalLinks ( $text );
-               # Another call to replace links and images inside captions of images
-               $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 = $this->doMagicLinks( $text );
                $text = $this->doTableStuff( $text );
                $text = $this->formatHeadings( $text, $isMain );
@@ -684,7 +729,8 @@ class Parser
                if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
                        $text = $this->magicGEO( $text );
                }
-               $text = $this->magicRFC( $text );
+               $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
+               $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
                return $text;
        }
 
@@ -693,11 +739,11 @@ class Parser
         *
         * @access private
         */
-       function doExponent ( $text ) {
+       function doExponent( $text ) {
                $fname = 'Parser::doExponent';
-               wfProfileIn( $fname);
+               wfProfileIn( $fname );
                $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
-               wfProfileOut( $fname);
+               wfProfileOut( $fname );
                return $text;
        }
 
@@ -741,8 +787,8 @@ class Parser
         * @access private
         */
        function doQuotes( $text ) {
-               $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
-               if (count ($arr) == 1)
+               $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
+               if ( count( $arr ) == 1 )
                        return $text;
                else
                {
@@ -752,29 +798,29 @@ class Parser
                        $i = 0;
                        $numbold = 0;
                        $numitalics = 0;
-                       foreach ($arr as $r)
+                       foreach ( $arr as $r )
                        {
-                               if (($i % 2) == 1)
+                               if ( ( $i % 2 ) == 1 )
                                {
                                        # If there are ever four apostrophes, assume the first is supposed to
                                        # be text, and the remaining three constitute mark-up for bold text.
-                                       if (strlen ($arr[$i]) == 4)
+                                       if ( strlen( $arr[$i] ) == 4 )
                                        {
                                                $arr[$i-1] .= "'";
                                                $arr[$i] = "'''";
                                        }
                                        # If there are more than 5 apostrophes in a row, assume they're all
                                        # text except for the last 5.
-                                       else if (strlen ($arr[$i]) > 5)
+                                       else if ( strlen( $arr[$i] ) > 5 )
                                        {
-                                               $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
+                                               $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
                                                $arr[$i] = "'''''";
                                        }
                                        # Count the number of occurrences of bold and italics mark-ups.
                                        # We are not counting sequences of five apostrophes.
-                                       if (strlen ($arr[$i]) == 2) $numitalics++;  else
-                                       if (strlen ($arr[$i]) == 3) $numbold++;     else
-                                       if (strlen ($arr[$i]) == 5) { $numitalics++; $numbold++; }
+                                       if ( strlen( $arr[$i] ) == 2 ) $numitalics++;  else
+                                       if ( strlen( $arr[$i] ) == 3 ) $numbold++;     else
+                                       if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
                                }
                                $i++;
                        }
@@ -783,15 +829,15 @@ class Parser
                        # that one of the bold ones was meant to be an apostrophe followed
                        # by italics. Which one we cannot know for certain, but it is more
                        # likely to be one that has a single-letter word before it.
-                       if (($numbold % 2 == 1) && ($numitalics % 2 == 1))
+                       if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
                        {
                                $i = 0;
                                $firstsingleletterword = -1;
                                $firstmultiletterword = -1;
                                $firstspace = -1;
-                               foreach ($arr as $r)
+                               foreach ( $arr as $r )
                                {
-                                       if (($i % 2 == 1) and (strlen ($r) == 3))
+                                       if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
                                        {
                                                $x1 = substr ($arr[$i-1], -1);
                                                $x2 = substr ($arr[$i-1], -2, 1);
@@ -904,9 +950,8 @@ class Parser
        /**
         * Replace external links
         *
-        * Note: we have to do external links before the internal ones,
-        * and otherwise take great care in the order of things here, so
-        * that we don't end up interpreting some URLs twice.
+        * Note: this is all very hackish and the order of execution matters a lot.
+        * Make sure to run maintenance/parserTests.php if you change this code.
         *
         * @access private
         */
@@ -927,6 +972,14 @@ class Parser
                        $text = $bits[$i++];
                        $trail = $bits[$i++];
 
+                       # The characters '<' and '>' (which were escaped by
+                       # removeHTMLtags()) should not be included in
+                       # URLs, per RFC 2396.
+                       if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
+                               $text = substr($url, $m2[0][1]) . ' ' . $text;
+                               $url = substr($url, 0, $m2[0][1]);
+                       }
+
                        # If the link text is an image URL, replace it with an <img> tag
                        # This happened by accident in the original parser, but some people used it extensively
                        $img = $this->maybeMakeImageLink( $text );
@@ -971,13 +1024,11 @@ class Parser
                        # replacing any non-bracketed links
                        $trail = $this->replaceFreeExternalLinks( $trail );
 
-                       $la = $sk->getExternalLinkAttributes( $url, $text );
-
                        # Use the encoded URL
                        # This means that users can paste URLs directly into the text
                        # Funny characters like &ouml; aren't valid in URLs anyway
                        # This was changed in August 2004
-                       $s .= "<a href=\"{$url}\"{$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
+                       $s .= $sk->makeExternalLink( $url, $text, false ) . $dtrail. $paren . $trail;
                }
 
                wfProfileOut( $fname );
@@ -989,7 +1040,10 @@ class Parser
         * @access private
         */
        function replaceFreeExternalLinks( $text ) {
-               $bits = preg_split( '/((?:'.URL_PROTOCOLS.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
+               $fname = 'Parser::replaceFreeExternalLinks';
+               wfProfileIn( $fname );
+               
+               $bits = preg_split( '/((?:'.URL_PROTOCOLS.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
                $s = array_shift( $bits );
                $i = 0;
 
@@ -1004,6 +1058,14 @@ class Parser
                                $url = $protocol . $m[1];
                                $trail = $m[2];
 
+                               # The characters '<' and '>' (which were escaped by
+                               # removeHTMLtags()) should not be included in
+                               # URLs, per RFC 2396.
+                               if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
+                                       $trail = substr($url, $m2[0][1]) . $trail;
+                                       $url = substr($url, 0, $m2[0][1]);
+                               }
+
                                # Move trailing punctuation to $trail
                                $sep = ',;\.:!?';
                                # If there is no left bracket, then consider right brackets fair game too
@@ -1017,7 +1079,9 @@ class Parser
                                        $url = substr( $url, 0, -$numSepChars );
                                }
 
-                               # Replace &amp; from obsolete syntax with &
+                               # Replace &amp; from obsolete syntax with &.
+                               # All HTML entities will be escaped by makeExternalLink()
+                               # or maybeMakeImageLink()
                                $url = str_replace( '&amp;', '&', $url );
 
                                # Is this an external image?
@@ -1031,6 +1095,7 @@ class Parser
                                $s .= $protocol . $remainder;
                        }
                }
+               wfProfileOut();
                return $s;
        }
 
@@ -1055,32 +1120,44 @@ class Parser
         *
         * @access private
         */
+
        function replaceInternalLinks( $s ) {
                global $wgLang, $wgContLang, $wgLinkCache;
+               global $wgDisableLangConversion;
                static $fname = 'Parser::replaceInternalLinks' ;
+
                wfProfileIn( $fname );
 
                wfProfileIn( $fname.'-setup' );
                static $tc = FALSE;
                # the % is needed to support urlencoded titles as well
                if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
+               
                $sk =& $this->mOptions->getSkin();
+               global $wgUseOldExistenceCheck;
+               # "Post-parse link colour check" works only on wiki text since it's now
+               # in Parser. Enable it, then disable it when we're done.
+               $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
 
                $redirect = MagicWord::get ( MAG_REDIRECT ) ;
 
+               #split the entire text string on occurences of [[
                $a = explode( '[[', ' ' . $s );
+               #get the first element (all text up to first [[), and remove the space we added
                $s = array_shift( $a );
                $s = substr( $s, 1 );
 
                # Match a link having the form [[namespace:link|alternate]]trail
                static $e1 = FALSE;
                if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
+               # Match cases where there is no "]]", which might still be images
+               static $e1_img = FALSE;
+               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';
 
                $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
-               # Special and Media are pseudo-namespaces; no pages actually exist in them
 
                $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
 
@@ -1095,12 +1172,15 @@ class Parser
                        $prefix = '';
                }
 
+               $selflink = $this->mTitle->getPrefixedText();
                wfProfileOut( $fname.'-setup' );
 
-               # start procedeeding each line
-               foreach ( $a as $line ) {
-                       wfProfileIn( $fname.'-prefixhandling' );
+               $checkVariantLink = sizeof($wgContLang->getVariants())>1;
+               # Loop for each link
+               for ($k = 0; isset( $a[$k] ); $k++) {
+                       $line = $a[$k];
                        if ( $useLinkPrefixExtension ) {
+                               wfProfileIn( $fname.'-prefixhandling' );
                                if ( preg_match( $e2, $s, $m ) ) {
                                        $prefix = $m[2];
                                        $s = $m[1];
@@ -1112,14 +1192,21 @@ class Parser
                                        $prefix = $first_prefix;
                                        $first_prefix = false;
                                }
+                               wfProfileOut( $fname.'-prefixhandling' );
                        }
-                       wfProfileOut( $fname.'-prefixhandling' );
 
+                       $might_be_img = false;
+                       
                        if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
                                $text = $m[2];
                                # fix up urlencoded title texts
                                if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
                                $trail = $m[3];
+                       } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
+                               $might_be_img = true;
+                               $text = $m[2];
+                               if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
+                               $trail = "";
                        } else { # Invalid form; output directly
                                $s .= $prefix . '[[' . $line ;
                                continue;
@@ -1128,7 +1215,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('/((?:'.URL_PROTOCOLS.'):)/', $m[1])) {
+                       if (preg_match('/^((?:'.URL_PROTOCOLS.'):)/', $m[1])) {
                                $s .= $prefix . '[[' . $line ;
                                continue;
                        }
@@ -1142,18 +1229,62 @@ class Parser
                                $link = substr($link, 1);
                        }
                        
-                       $wasblank = ( '' == $text );
-                       if( $wasblank ) $text = $link;
-
-                       $nt = Title::newFromText( $link );
+                       $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
                        if( !$nt ) {
                                $s .= $prefix . '[[' . $line;
                                continue;
                        }
-                       
+
+                       #check other language variants of the link
+                       #if the article does not exist
+                       if( $checkVariantLink
+                           && $nt->getArticleID() == 0 ) {
+                               $wgContLang->findVariantLink($link, $nt);
+                       }
+
                        $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) );
+                                               if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
+                                               # the first ]] closes the inner link, the second the image
+                                                       $found = true;
+                                                       $text .= '[[' . $m[1];
+                                                       $trail = $m[2];
+                                                       break;
+                                               } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
+                                                       #if there's exactly one ]] that's fine, we'll keep looking
+                                                       $text .= '[[' . $m[0];
+                                               } else {
+                                                       #if $next_line is invalid too, we need look no further
+                                                       $text .= '[[' . $next_line;
+                                                       break;
+                                               }
+                                       }
+                                       if ( !$found ) {
+                                               # we couldn't find the end of this imageLink, so output it raw
+                                               #but don't ignore what might be perfectly normal links in the text we've examined
+                                               $text = $this->replaceInternalLinks($text);
+                                               $s .= $prefix . '[[' . $link . '|' . $text;
+                                               # note: no $trail, because without an end, there *is* no trail
+                                               continue;
+                                       }
+                               } else { #it's not an image, so output it raw
+                                       $s .= $prefix . '[[' . $link . '|' . $text;
+                                       # note: no $trail, because without an end, there *is* no trail
+                                       continue;
+                               }
+                       }
+
+                       $wasblank = ( '' == $text );
+                       if( $wasblank ) $text = $link;
+
+                       
                        # Link not escaped by : , create the various objects
                        if( $noforce ) {
 
@@ -1166,19 +1297,30 @@ class Parser
                                }
                                
                                if ( $ns == NS_IMAGE ) {
-                                       $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
+                                       wfProfileIn( "$fname-image" );
+                                       
+                                       # recursively parse links inside the image caption
+                                       # actually, this will parse them in any other parameters, too,
+                                       # but it might be hard to fix that, and it doesn't matter ATM
+                                       $text = $this->replaceExternalLinks($text);
+                                       $text = $this->replaceInternalLinks($text);
+                                       
+                                       # replace the image with a link-holder so that replaceExternalLinks() can't mess with it
+                                       $s .= $prefix . $this->insertStripItem( $sk->makeImageLinkObj( $nt, $text ), $this->mStripState ) . $trail;
                                        $wgLinkCache->addImageLinkObj( $nt );
+                                       
+                                       wfProfileOut( "$fname-image" );
                                        continue;
                                }
                                
                                if ( $ns == NS_CATEGORY ) {
-                                       $t = $nt->getText() ;
-                                       $nnt = Title::newFromText ( Namespace::getCanonicalName(NS_CATEGORY).':'.$t ) ;
+                                       wfProfileIn( "$fname-category" );
+                                       $t = $nt->getText();
 
                                        $wgLinkCache->suspend(); # Don't save in links/brokenlinks
                                        $pPLC=$sk->postParseLinkColour();
                                        $sk->postParseLinkColour( false );
-                                       $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
+                                       $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
                                        $sk->postParseLinkColour( $pPLC );
                                        $wgLinkCache->resume();
 
@@ -1192,21 +1334,24 @@ class Parser
                                                $sortkey = $text;
                                        }
                                        $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
-                                       $this->mOutput->mCategoryLinks[] = $t ;
+                                       $this->mOutput->addCategoryLink( $t );
                                        $s .= $prefix . $trail ;
+                                       
+                                       wfProfileOut( "$fname-category" );
                                        continue;
                                }
                        }
-                       
-                       if( ( $nt->getPrefixedText() === $this->mTitle->getPrefixedText() ) &&
-                           ( strpos( $link, '#' ) === FALSE ) ) {
+
+                       if( ( $nt->getPrefixedText() === $selflink ) &&
+                           ( $nt->getFragment() === '' ) ) {
                                # Self-links are handled specially; generally de-link and change to bold.
                                $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
                                continue;
                        }
 
+                       # Special and Media are pseudo-namespaces; no pages actually exist in them
                        if( $ns == NS_MEDIA ) {
-                               $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
+                               $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
                                $wgLinkCache->addImageLinkObj( $nt );
                                continue;
                        } elseif( $ns == NS_SPECIAL ) {
@@ -1215,14 +1360,15 @@ class Parser
                        }
                        $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
                }
+               $sk->postParseLinkColour( $saveParseColour );
                wfProfileOut( $fname );
                return $s;
        }
 
        /**
         * Handle link to subpage if necessary
-        * @param $target string the source of the link
-        * @param &$text the link text, modified as necessary
+        * @param string $target the source of the link
+        * @param string &$text the link text, modified as necessary
         * @return string the full name of the link
         * @access private
         */
@@ -1234,6 +1380,8 @@ class Parser
                # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
                global $wgNamespacesWithSubpages;
 
+               $fname = 'Parser::maybeDoSubpageLink';
+               wfProfileIn( $fname );
                # Look at the first character
                if( $target{0} == '/' ) {
                        # / at end means we don't want the slash to be shown
@@ -1260,6 +1408,7 @@ class Parser
                        $ret = $target;
                }
 
+               wfProfileOut( $fname );
                return $ret;
        }
 
@@ -1394,11 +1543,9 @@ class Parser
                                        # ; title : definition text
                                        # So we check for : in the remainder text to split up the
                                        # title and definition, without b0rking links.
-                                       # FIXME: This is not foolproof. Something better in Tokenizer might help.
-                                       if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
-                                               $term = $match[1];
+                                       if ($this->findColonNoLinks($t, $term, $t2) !== false) {
+                                               $t = $t2;
                                                $output .= $term . $this->nextItem( ':' );
-                                               $t = $match[2];
                                        }
                                }
                        } elseif( $prefixLength || $lastPrefixLength ) {
@@ -1419,10 +1566,9 @@ class Parser
 
                                        if ( ';' == $char ) {
                                                # FIXME: This is dupe of code above
-                                               if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
-                                                       $term = $match[1];
+                                               if ($this->findColonNoLinks($t, $term, $t2) !== false) {
+                                                       $t = $t2;
                                                        $output .= $term . $this->nextItem( ':' );
-                                                       $t = $match[2];
                                                }
                                        }
                                        ++$commonPrefixLength;
@@ -1430,13 +1576,14 @@ class Parser
                                $lastPrefix = $pref2;
                        }
                        if( 0 == $prefixLength ) {
+                               wfProfileIn( "$fname-paragraph" );
                                # No prefix (not in list)--go to paragraph mode
                                $uniq_prefix = UNIQ_PREFIX;
                                // XXX: use a stack for nestable elements like span, table and div
-                               $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
+                               $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
                                $closematch = preg_match(
                                        '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
-                                       '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
+                                       '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
                                if ( $openmatch or $closematch ) {
                                        $paragraphStack = false;
                                        $output .= $this->closeParagraph();
@@ -1485,6 +1632,7 @@ class Parser
                                                }
                                        }
                                }
+                               wfProfileOut( "$fname-paragraph" );
                        }
                        if ($paragraphStack === false) {
                                $output .= $t."\n";
@@ -1503,6 +1651,46 @@ class Parser
                return $output;
        }
 
+       /**
+        * Split up a string on ':', ignoring any occurences inside
+        * <a>..</a> or <span>...</span>
+        * @param string $str the string to split
+        * @param string &$before set to everything before the ':'
+        * @param string &$after set to everything after the ':'
+        * return string the position of the ':', or false if none found
+        */
+       function findColonNoLinks($str, &$before, &$after) {
+               # I wonder if we should make this count all tags, not just <a>
+               # and <span>. That would prevent us from matching a ':' that
+               # comes in the middle of italics other such formatting....
+               # -- Wil
+               $fname = 'Parser::findColonNoLinks';
+               wfProfileIn( $fname );
+               $pos = 0;
+               do {
+                       $colon = strpos($str, ':', $pos);
+
+                       if ($colon !== false) {
+                               $before = substr($str, 0, $colon);
+                               $after = substr($str, $colon + 1);
+
+                               # Skip any ':' within <a> or <span> pairs
+                               $a = substr_count($before, '<a');
+                               $s = substr_count($before, '<span');
+                               $ca = substr_count($before, '</a>');
+                               $cs = substr_count($before, '</span>');
+
+                               if ($a <= $ca and $s <= $cs) {
+                                       # Tags are balanced before ':'; ok
+                                       break;
+                               }
+                               $pos = $colon + 1;
+                       }
+               } while ($colon !== false);
+               wfProfileOut( $fname );
+               return $colon;
+       }
+
        /**
         * Return value of a magic variable (like PAGENAME)
         *
@@ -1510,16 +1698,23 @@ class Parser
         */
        function getVariableValue( $index ) {
                global $wgContLang, $wgSitename, $wgServer;
-
+               
+               /**
+                * 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];
+               
                switch ( $index ) {
                        case MAG_CURRENTMONTH:
-                               return $wgContLang->formatNum( date( 'm' ) );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
                        case MAG_CURRENTMONTHNAME:
-                               return $wgContLang->getMonthName( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthName( date('n') );
                        case MAG_CURRENTMONTHNAMEGEN:
-                               return $wgContLang->getMonthNameGen( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
                        case MAG_CURRENTDAY:
-                               return $wgContLang->formatNum( date('j') );
+                               return $varCache[$index] = $wgContLang->formatNum( date('j') );
                        case MAG_PAGENAME:
                                return $this->mTitle->getText();
                        case MAG_PAGENAMEE:
@@ -1528,13 +1723,13 @@ class Parser
                                # return Namespace::getCanonicalName($this->mTitle->getNamespace());
                                return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
                        case MAG_CURRENTDAYNAME:
-                               return $wgContLang->getWeekdayName( date('w')+1 );
+                               return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
                        case MAG_CURRENTYEAR:
-                               return $wgContLang->formatNum( date( 'Y' ) );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
                        case MAG_CURRENTTIME:
-                               return $wgContLang->time( wfTimestampNow(), false );
+                               return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
                        case MAG_NUMBEROFARTICLES:
-                               return $wgContLang->formatNum( wfNumberOfArticles() );
+                               return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
                        case MAG_SITENAME:
                                return $wgSitename;
                        case MAG_SERVER:
@@ -1550,7 +1745,7 @@ class Parser
         * @access private
         */
        function initialiseVariables() {
-               $fname = 'Parser::initialiseVaraibles';
+               $fname = 'Parser::initialiseVariables';
                wfProfileIn( $fname );
                global $wgVariableIDs;
                $this->mVariables = array();
@@ -1558,7 +1753,6 @@ class Parser
                        $mw =& MagicWord::get( $id );
                        $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
                }
-               $fname = 'Parser::initialiseVaraibles';
                wfProfileOut( $fname );
        }
 
@@ -1580,8 +1774,9 @@ class Parser
                global $wgLang, $wgScript, $wgArticlePath;
 
                # Prevent too big inclusions
-               if(strlen($text)> MAX_INCLUDE_SIZE)
-               return $text;
+               if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
+                       return $text;
+               }
 
                $fname = 'Parser::replaceVariables';
                wfProfileIn( $fname );
@@ -1591,19 +1786,16 @@ class Parser
                # This function is called recursively. To keep track of arguments we need a stack:
                array_push( $this->mArgStack, $args );
 
-               # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
-               $GLOBALS['wgCurParser'] =& $this;
-
                # Variable substitution
-               $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", 'wfVariableSubstitution', $text );
+               $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
                
                if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
                        # Argument substitution
-                       $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
+                       $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
                }
                # Template substitution
                $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
-               $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
+               $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
 
                array_pop( $this->mArgStack );
 
@@ -1921,6 +2113,7 @@ class Parser
 
                # Empties the template path
                $this->mTemplatePath = array();
+               
                if ( !$found ) {
                        return $matches[0];
                } else {
@@ -2308,7 +2501,7 @@ class Parser
                                if( $istemplate )
                                        $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
                                else
-                                       $head[$headlineCount] .= $sk->editSectionLink($sectionCount+1);
+                                       $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
                        }
 
                        # Add the edit section span
@@ -2316,7 +2509,7 @@ class Parser
                                if( $istemplate )
                                        $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
                                else
-                                       $headline = $sk->editSectionScript($sectionCount+1,$headline);
+                                       $headline = $sk->editSectionScript($this->mTitle, $sectionCount+1,$headline);
                        }
 
                        # give headline the correct <h#> tag
@@ -2470,30 +2663,34 @@ class Parser
         * @access private
         * @param string $text text to be processed
         */
-       function magicRFC( $text ) {
+       function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl'  ) {
                global $wgLang;
                
                $valid = '0123456789';
                $internal = false;
 
-               $a = split( 'RFC ', ' '.$text );
-               if ( count ( $a ) < 2 ) return $text;
+               $a = split( $keyword, ' '.$text );
+               if ( count ( $a ) < 2 ) {
+                       return $text;
+               }
                $text = substr( array_shift( $a ), 1);
                
-               /* Check if RFC keyword is preceed by [[.
+               /* 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.
                 */
-               if(substr($text, -2) == '[[') { $internal = true; }
+               if ( substr( $text, -2 ) == '[[' ) {
+                       $internal = true;
+               }
 
                foreach ( $a as $x ) {
                        /* token might be empty if we have RFC RFC 1234 */
-                       if($x=='') {
-                               $text.='RFC ';
+                       if ( $x=='' ) {
+                               $text.=$keyword;
                                continue;
                                }
 
-                       $rfc = $blank = '' ;
+                       $id = $blank = '' ;
 
                        /** remove and save whitespaces in $blank */
                        while ( $x{0} == ' ' ) {
@@ -2501,29 +2698,29 @@ class Parser
                                $x = substr( $x, 1 );
                        }
 
-                       /** remove and save the rfc number in $rfc */
+                       /** remove and save the rfc number in $id */
                        while ( strstr( $valid, $x{0} ) != false ) {
-                               $rfc .= $x{0};
+                               $id .= $x{0};
                                $x = substr( $x, 1 );
                        }
 
-                       if ( $rfc == '') {
+                       if ( $id == '' ) {
                                /* call back stripped spaces*/
-                               $text .= "RFC $blank$x";
-                       } elseif( $internal) {
+                               $text .= $keyword.$blank.$x;
+                       } elseif( $internal ) {
                                /* normal link */
-                               $text .= "RFC $rfc$x";
+                               $text .= $keyword.$id.$x;
                        } else {
                                /* build the external link*/
-                               $url = wfmsg( 'rfcurl' );
-                               $url = str_replace( '$1', $rfc, $url);
+                               $url = wfmsg( $urlmsg );
+                               $url = str_replace( '$1', $id, $url);
                                $sk =& $this->mOptions->getSkin();
-                               $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
-                               $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
+                               $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) == '[[');
+                       $internal = ( substr($x,-2) == '[[' );
                }
                return $text;
        }
@@ -2553,15 +2750,7 @@ class Parser
                $pairs = array(
                        "\r\n" => "\n",
                        );
-               $text = str_replace(array_keys($pairs), array_values($pairs), $text);
-               // now with regexes
-               /*
-               $pairs = array(
-                       "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
-                       "/<br *?>/i" => "<br />",
-               );
-               $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
-               */
+               $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
                $text = $this->strip( $text, $stripState, false );
                $text = $this->pstPass2( $text, $user );
                $text = $this->unstrip( $text, $stripState );
@@ -2574,7 +2763,7 @@ class Parser
         * @access private
         */
        function pstPass2( $text, &$user ) {
-               global $wgLang, $wgContLang, $wgLocaltimezone, $wgCurParser;
+               global $wgLang, $wgContLang, $wgLocaltimezone;
 
                # Variable replacement
                # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
@@ -2585,15 +2774,18 @@ class Parser
                $n = $user->getName();
                $k = $user->getOption( 'nickname' );
                if ( '' == $k ) { $k = $n; }
-               if(isset($wgLocaltimezone)) {
-                       $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
+               if ( isset( $wgLocaltimezone ) ) {
+                       $oldtz = getenv( 'TZ' );
+                       putenv( 'TZ='.$wgLocaltimezone );
                }
                /* Note: this is an ugly timezone hack for the European wikis */
                $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
                  ' (' . date( 'T' ) . ')';
-               if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
+               if ( isset( $wgLocaltimezone ) ) {
+                       putenv( 'TZ='.$oldtzs );
+               }
 
-               $text = preg_replace( '/~~~~~/', $d, $text );
+               $text = preg_replace( '/~~~~~~/', $d, $text );
                $text = preg_replace( '/~~~~/', '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]] $d", $text );
                $text = preg_replace( '/~~~/', '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]", $text );
 
@@ -2686,6 +2878,194 @@ class Parser
                $this->mTagHooks[$tag] = $callback;
                return $oldVal;
        }
+
+       /**
+        * Replace <!--LINK--> link placeholders with actual links, in the buffer
+        * Placeholders created in Skin::makeLinkObj()
+        * Returns an array of links found, indexed by PDBK:
+        *  0 - broken
+        *  1 - normal link
+        *  2 - stub
+        * $options is a bit field, RLH_FOR_UPDATE to select for update
+        */
+       function replaceLinkHolders( &$text, $options = 0 ) {
+               global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
+               global $wgInterwikiLinkHolders;
+               global $outputReplace;
+               
+               if ( $wgUseOldExistenceCheck ) {
+                       return array();
+               }
+
+               $fname = 'Parser::replaceLinkHolders';
+               wfProfileIn( $fname );
+
+               $pdbks = array();
+               $colours = array();
+               
+               #if ( !empty( $tmpLinks[0] ) ) { #TODO
+               if ( !empty( $wgLinkHolders['namespaces'] ) ) {
+                       wfProfileIn( $fname.'-check' );
+                       $dbr =& wfGetDB( DB_SLAVE );
+                       $cur = $dbr->tableName( 'cur' );
+                       $sk = $wgUser->getSkin();
+                       $threshold = $wgUser->getOption('stubthreshold');
+                       
+                       # Sort by namespace
+                       asort( $wgLinkHolders['namespaces'] );
+       
+                       # Generate query
+                       $query = false;
+                       foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
+                               # Make title object
+                               $title = $wgLinkHolders['titles'][$key];
+
+                               # Skip invalid entries.
+                               # Result will be ugly, but prevents crash.
+                               if ( is_null( $title ) ) {
+                                       continue;
+                               }
+                               $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
+
+                               # Check if it's in the link cache already
+                               if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
+                                       $colours[$pdbk] = 1;
+                               } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
+                                       $colours[$pdbk] = 0;
+                               } else {
+                                       # Not in the link cache, add it to the query
+                                       if ( !isset( $current ) ) {
+                                               $current = $val;
+                                               $query =  "SELECT cur_id, cur_namespace, cur_title";
+                                               if ( $threshold > 0 ) {
+                                                       $query .= ", LENGTH(cur_text) AS cur_len, cur_is_redirect";
+                                               } 
+                                               $query .= " FROM $cur WHERE (cur_namespace=$val AND cur_title IN(";
+                                       } elseif ( $current != $val ) {
+                                               $current = $val;
+                                               $query .= ")) OR (cur_namespace=$val AND cur_title IN(";
+                                       } else {
+                                               $query .= ', ';
+                                       }
+                               
+                                       $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
+                               }
+                       }
+                       if ( $query ) {
+                               $query .= '))';
+                               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
+                               # 2 = stub
+                               while ( $s = $dbr->fetchObject($res) ) {
+                                       $title = Title::makeTitle( $s->cur_namespace, $s->cur_title );
+                                       $pdbk = $title->getPrefixedDBkey();
+                                       $wgLinkCache->addGoodLink( $s->cur_id, $pdbk );
+                                       
+                                       if ( $threshold >  0 ) {
+                                               $size = $s->cur_len;
+                                               if ( $s->cur_is_redirect || $s->cur_namespace != 0 || $length < $threshold ) {
+                                                       $colours[$pdbk] = 1;
+                                               } else {
+                                                       $colours[$pdbk] = 2;
+                                               }
+                                       } else {
+                                               $colours[$pdbk] = 1;
+                                       }
+                               }
+                       }
+                       wfProfileOut( $fname.'-check' );
+                       
+                       # Construct search and replace arrays
+                       wfProfileIn( $fname.'-construct' );
+                       $outputReplace = array();
+                       foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
+                               $pdbk = $pdbks[$key];
+                               $searchkey = '<!--LINK '.$key.'-->';
+                               $title = $wgLinkHolders['titles'][$key];
+                               if ( empty( $colours[$pdbk] ) ) {
+                                       $wgLinkCache->addBadLink( $pdbk );
+                                       $colours[$pdbk] = 0;
+                                       $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
+                                                                       $wgLinkHolders['texts'][$key],
+                                                                       $wgLinkHolders['queries'][$key] );
+                               } elseif ( $colours[$pdbk] == 1 ) {
+                                       $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
+                                                                       $wgLinkHolders['texts'][$key],
+                                                                       $wgLinkHolders['queries'][$key] );
+                               } elseif ( $colours[$pdbk] == 2 ) {
+                                       $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
+                                                                       $wgLinkHolders['texts'][$key],
+                                                                       $wgLinkHolders['queries'][$key] );
+                               }
+                       }
+                       wfProfileOut( $fname.'-construct' );
+
+                       # Do the thing
+                       wfProfileIn( $fname.'-replace' );
+                       
+                       $text = preg_replace_callback(
+                               '/(<!--LINK .*?-->)/',
+                               "outputReplaceMatches",
+                               $text);
+                       wfProfileOut( $fname.'-replace' );
+               }
+
+               if ( !empty( $wgInterwikiLinkHolders ) ) {
+                       wfProfileIn( $fname.'-interwiki' );
+                       $outputReplace = $wgInterwikiLinkHolders;
+                       $text = preg_replace_callback(
+                               '/<!--IWLINK (.*?)-->/',
+                               "outputReplaceMatches",
+                               $text );
+                       wfProfileOut( $fname.'-interwiki' );
+               }
+
+               wfProfileOut( $fname );
+               return $colours;
+       }
+
+       /**
+        * Renders an image gallery from a text with one line per image.
+        * text labels may be given by using |-style alternative text. E.g.
+        *   Image:one.jpg|The number "1"
+        *   Image:tree.jpg|A tree
+        * given as text will return the HTML of a gallery with two images,
+        * labeled 'The number "1"' and
+        * 'A tree'.
+        */
+       function renderImageGallery( $text ) {
+               global $wgLinkCache;
+               $ig = new ImageGallery();
+               $ig->setShowBytes( false );
+               $ig->setShowFilename( false );
+               $lines = explode( "\n", $text );
+
+               foreach ( $lines as $line ) {
+                       # match lines like these:
+                       # Image:someimage.jpg|This is some image
+                       preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
+                       # Skip empty lines
+                       if ( count( $matches ) == 0 ) {
+                               continue;
+                       }
+                       $nt = Title::newFromURL( $matches[1] );
+                       if ( isset( $matches[3] ) ) {
+                               $label = $matches[3];
+                       } else {
+                               $label = '';
+                       }
+                       $ig->add( Image::newFromTitle( $nt ), $label );
+                       $wgLinkCache->addImageLinkObj( $nt );
+               }
+               return $ig->toHTML();
+       }
 }
 
 /**
@@ -2696,6 +3076,7 @@ class ParserOutput
 {
        var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
        var $mCacheTime; # Used in ParserCache
+       var $mVersion;   # Compatibility check
 
        function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
                $containsOldMagic = false )
@@ -2705,18 +3086,20 @@ class ParserOutput
                $this->mCategoryLinks = $categoryLinks;
                $this->mContainsOldMagic = $containsOldMagic;
                $this->mCacheTime = '';
+               $this->mVersion = MW_PARSER_VERSION;
        }
 
-       function getText() { return $this->mText; }
-       function getLanguageLinks() { return $this->mLanguageLinks; }
-       function getCategoryLinks() { return $this->mCategoryLinks; }
-       function getCacheTime() { return $this->mCacheTime; }
-       function containsOldMagic() { return $this->mContainsOldMagic; }
-       function setText( $text ) { return wfSetVar( $this->mText, $text ); }
-       function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
-       function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
+       function getText()                   { return $this->mText; }
+       function getLanguageLinks()          { return $this->mLanguageLinks; }
+       function getCategoryLinks()          { return array_keys( $this->mCategoryLinks ); }
+       function getCacheTime()              { return $this->mCacheTime; }
+       function containsOldMagic()          { return $this->mContainsOldMagic; }
+       function setText( $text )            { return wfSetVar( $this->mText, $text ); }
+       function setLanguageLinks( $ll )     { return wfSetVar( $this->mLanguageLinks, $ll ); }
+       function setCategoryLinks( $cl )     { return wfSetVar( $this->mCategoryLinks, $cl ); }
        function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
-       function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
+       function setCacheTime( $t )          { return wfSetVar( $this->mCacheTime, $t ); }
+       function addCategoryLink( $c )       { $this->mCategoryLinks[$c] = 1; }
 
        function merge( $other ) {
                $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
@@ -2724,6 +3107,22 @@ class ParserOutput
                $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
        }
 
+       /**
+        * Return true if this cached output object predates the global or
+        * per-article cache invalidation timestamps, or if it comes from
+        * an incompatible older version.
+        *
+        * @param string $touched the affected article's last touched timestamp
+        * @return bool
+        * @access public
+        */
+       function expired( $touched ) {
+               global $wgCacheEpoch;
+               return $this->getCacheTime() <= $touched ||
+                      $this->getCacheTime() <= $wgCacheEpoch ||
+                      !isset( $this->mVersion ) ||
+                      version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
+       }
 }
 
 /**
@@ -2778,7 +3177,6 @@ class ParserOptions
        # Get user options
        function initialiseFromUser( &$userInput ) {
                global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
-               
                $fname = 'ParserOptions::initialiseFromUser';
                wfProfileIn( $fname );
                if ( !$userInput ) {
@@ -2806,20 +3204,13 @@ class ParserOptions
 
 }
 
-# Regex callbacks, used in Parser::replaceVariables
-function wfBraceSubstitution( $matches ) {
-       global $wgCurParser;
-       return $wgCurParser->braceSubstitution( $matches );
-}
-
-function wfArgSubstitution( $matches ) {
-       global $wgCurParser;
-       return $wgCurParser->argSubstitution( $matches );
-}
-
-function wfVariableSubstitution( $matches ) {
-       global $wgCurParser;
-       return $wgCurParser->variableSubstitution( $matches );
+/**
+ * Callback function used by Parser::replaceLinkHolders()
+ * to substitute link placeholders.
+ */
+function &outputReplaceMatches( $matches ) {
+       global $outputReplace;
+       return $outputReplace[$matches[1]];
 }
 
 /**
@@ -2842,7 +3233,7 @@ function wfLoadSiteStats() {
 
        if ( -1 != $wgNumberOfArticles ) return;
        $dbr =& wfGetDB( DB_SLAVE );
-       $s = $dbr->getArray( 'site_stats',
+       $s = $dbr->selectRow( 'site_stats',
                array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
                array( 'ss_row_id' => 1 ), $fname
        );