Tell regexp parser to use extra analysis on external link regexp;
[lhc/web/wiklou.git] / includes / Parser.php
index 80dd1a7..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
  *
@@ -277,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;
@@ -330,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);
@@ -358,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 ) ) {
@@ -371,6 +391,7 @@ class Parser
                          'math' => $math_content,
                          'pre' => $pre_content,
                          'comment' => $comment_content,
+                         'gallery' => $gallery_content,
                        ) + $ext_content;
                }
                return $text;
@@ -679,8 +700,13 @@ class Parser
                        $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
                }
                $text = $this->doAllQuotes( $text );
-               $text = $this->replaceExternalLinks( $text );           
                $text = $this->replaceInternalLinks ( $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 );
@@ -703,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;
        }
 
@@ -712,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;
        }
 
@@ -760,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
                {
@@ -771,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++;
                        }
@@ -802,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);
@@ -923,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
         */
@@ -1014,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;
 
@@ -1066,6 +1095,7 @@ class Parser
                                $s .= $protocol . $remainder;
                        }
                }
+               wfProfileOut();
                return $s;
        }
 
@@ -1142,14 +1172,15 @@ class Parser
                        $prefix = '';
                }
 
+               $selflink = $this->mTitle->getPrefixedText();
                wfProfileOut( $fname.'-setup' );
 
                $checkVariantLink = sizeof($wgContLang->getVariants())>1;
                # Loop for each link
                for ($k = 0; isset( $a[$k] ); $k++) {
                        $line = $a[$k];
-                       wfProfileIn( $fname.'-prefixhandling' );
                        if ( $useLinkPrefixExtension ) {
+                               wfProfileIn( $fname.'-prefixhandling' );
                                if ( preg_match( $e2, $s, $m ) ) {
                                        $prefix = $m[2];
                                        $s = $m[1];
@@ -1161,8 +1192,8 @@ class Parser
                                        $prefix = $first_prefix;
                                        $first_prefix = false;
                                }
+                               wfProfileOut( $fname.'-prefixhandling' );
                        }
-                       wfProfileOut( $fname.'-prefixhandling' );
 
                        $might_be_img = false;
                        
@@ -1184,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;
                        }
@@ -1198,7 +1229,7 @@ class Parser
                                $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;
@@ -1206,8 +1237,8 @@ class Parser
 
                        #check other language variants of the link
                        #if the article does not exist
-                       if( $nt->getArticleID() == 0
-                               && $checkVariantLink ) {
+                       if( $checkVariantLink
+                           && $nt->getArticleID() == 0 ) {
                                $wgContLang->findVariantLink($link, $nt);
                        }
 
@@ -1266,6 +1297,8 @@ class Parser
                                }
                                
                                if ( $ns == NS_IMAGE ) {
+                                       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
@@ -1275,11 +1308,14 @@ class Parser
                                        # 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() ;
+                                       wfProfileIn( "$fname-category" );
+                                       $t = $nt->getText();
 
                                        $wgLinkCache->suspend(); # Don't save in links/brokenlinks
                                        $pPLC=$sk->postParseLinkColour();
@@ -1298,13 +1334,15 @@ 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() ) &&
+                       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 );
@@ -1313,7 +1351,7 @@ class Parser
 
                        # 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 ) {
@@ -1538,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();
@@ -1593,6 +1632,7 @@ class Parser
                                                }
                                        }
                                }
+                               wfProfileOut( "$fname-paragraph" );
                        }
                        if ($paragraphStack === false) {
                                $output .= $t."\n";
@@ -1658,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:
@@ -1676,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:
@@ -1727,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 );
@@ -2065,6 +2113,7 @@ class Parser
 
                # Empties the template path
                $this->mTemplatePath = array();
+               
                if ( !$found ) {
                        return $matches[0];
                } else {
@@ -2460,7 +2509,7 @@ class Parser
                                if( $istemplate )
                                        $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
                                else
-                                       $headline = $sk->editSectionScript($this->title, $sectionCount+1,$headline);
+                                       $headline = $sk->editSectionScript($this->mTitle, $sectionCount+1,$headline);
                        }
 
                        # give headline the correct <h#> tag
@@ -2614,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} == ' ' ) {
@@ -2645,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;
        }
@@ -2697,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 );
@@ -2729,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 );
 
@@ -2842,6 +2890,8 @@ class Parser
         */
        function replaceLinkHolders( &$text, $options = 0 ) {
                global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
+               global $wgInterwikiLinkHolders;
+               global $outputReplace;
                
                if ( $wgUseOldExistenceCheck ) {
                        return array();
@@ -2934,7 +2984,6 @@ class Parser
                        
                        # Construct search and replace arrays
                        wfProfileIn( $fname.'-construct' );
-                       global $outputReplace;
                        $outputReplace = array();
                        foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
                                $pdbk = $pdbks[$key];
@@ -2966,20 +3015,57 @@ class Parser
                                "outputReplaceMatches",
                                $text);
                        wfProfileOut( $fname.'-replace' );
+               }
 
+               if ( !empty( $wgInterwikiLinkHolders ) ) {
                        wfProfileIn( $fname.'-interwiki' );
-                       global $wgInterwikiLinkHolders;
                        $outputReplace = $wgInterwikiLinkHolders;
                        $text = preg_replace_callback(
                                '/<!--IWLINK (.*?)-->/',
                                "outputReplaceMatches",
-                               $text);
+                               $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();
+       }
 }
 
 /**
@@ -2990,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 )
@@ -2999,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 );
@@ -3018,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" );
+       }
 }
 
 /**
@@ -3072,7 +3177,6 @@ class ParserOptions
        # Get user options
        function initialiseFromUser( &$userInput ) {
                global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
-               
                $fname = 'ParserOptions::initialiseFromUser';
                wfProfileIn( $fname );
                if ( !$userInput ) {
@@ -3104,7 +3208,7 @@ class ParserOptions
  * Callback function used by Parser::replaceLinkHolders()
  * to substitute link placeholders.
  */
-function &outputReplaceMatches($matches) {
+function &outputReplaceMatches( $matches ) {
        global $outputReplace;
        return $outputReplace[$matches[1]];
 }
@@ -3129,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
        );