* s~\t+$~~
[lhc/web/wiklou.git] / includes / Parser.php
index 4cc0c7d..727c0a4 100644 (file)
@@ -15,7 +15,7 @@ require_once( 'HttpFunctions.php' );
  * changes in an incompatible way, so the parser cache
  * can automatically discard old data.
  */
-define( 'MW_PARSER_VERSION', '1.5.0' );
+define( 'MW_PARSER_VERSION', '1.6.0' );
 
 /**
  * Variable substitution O(N^2) attack
@@ -43,18 +43,15 @@ define( 'OT_MSG' , 3 );
 # may want to use in wikisyntax
 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
 
-# prefix for escaping, used in two functions at least
-define( 'UNIQ_PREFIX', 'NaodW29');
-
 # Constants needed for external link processing
 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
 # Everything except bracket, space, or control characters
-define( '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]' );
 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
-define( 'EXT_LINK_BRACKETED',  '/\[(\b('.$wgUrlProtocols.')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
+define( 'EXT_LINK_BRACKETED',  '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
 define( 'EXT_IMAGE_REGEX',
        '/^('.HTTP_PROTOCOLS.')'.  # Protocol
        '('.EXT_LINK_URL_CLASS.'+)\\/'.  # Hostname and path
@@ -76,7 +73,7 @@ define( 'EXT_IMAGE_REGEX',
  *   performs brace substitution on MediaWiki messages
  *
  * Globals used:
- *    objects:   $wgLang, $wgLinkCache
+ *    objects:   $wgLang
  *
  * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
  *
@@ -101,16 +98,18 @@ class Parser
        # Cleared with clearState():
        var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
        var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
-       var $mInterwikiLinkHolders, $mLinkHolders;
+       var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
 
        # Temporary:
-       var $mOptions, $mTitle, $mOutputType,
+       var $mOptions,      // ParserOptions object
+               $mTitle,        // Title context, used for self-link rendering and similar things
+               $mOutputType,   // Output type, one of the OT_xxx constants
            $mTemplates,        // cache of already loaded templates, avoids
                                // multiple SQL queries for the same string
-           $mTemplatePath;     // stores an unsorted hash of all the templates already loaded
+           $mTemplatePath,     // stores an unsorted hash of all the templates already loaded
                                // in this path. Used for loop detection.
-
-       var $mIWTransData = array();
+               $mIWTransData = array(),
+               $mRevisionId;   // ID to display in {{REVISIONID}} tags
 
        /**#@-*/
 
@@ -152,11 +151,15 @@ class Parser
                        'texts' => array(),
                        'titles' => array()
                );
+               $this->mRevisionId = null;
+               $this->mUniqPrefix = 'UNIQ' . Parser::getRandomString();
+
+               wfRunHooks( 'ParserClearState', array( &$this ) );
        }
 
        /**
-        * First pass--just handle <nowiki> sections, pass the rest off
-        * to internalParse() which does all the real work.
+        * Convert wikitext to HTML
+        * Do not call this function recursively.
         *
         * @access private
         * @param string $text Text we want to parse
@@ -164,9 +167,15 @@ class Parser
         * @param array $options
         * @param boolean $linestart
         * @param boolean $clearState
+        * @param int $revid number to pass in {{REVISIONID}}
         * @return ParserOutput a ParserOutput
         */
-       function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
+       function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
+               /**
+                * First pass--just handle <nowiki> sections, pass the rest off
+                * to internalParse() which does all the real work.
+                */
+
                global $wgUseTidy, $wgContLang;
                $fname = 'Parser::parse';
                wfProfileIn( $fname );
@@ -177,6 +186,7 @@ class Parser
 
                $this->mOptions = $options;
                $this->mTitle =& $title;
+               $this->mRevisionId = $revid;
                $this->mOutputType = OT_HTML;
 
                $this->mStripState = NULL;
@@ -189,6 +199,12 @@ class Parser
                $text = $this->strip( $text, $x );
                wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
 
+               # Hook to suspend the parser in this state
+               if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
+                       wfProfileOut( $fname );
+                       return $text ;
+               }
+
                $text = $this->internalParse( $text );
 
                $text = $this->unstrip( $text, $this->mStripState );
@@ -220,7 +236,7 @@ class Parser
                wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
 
                $text = Sanitizer::normalizeCharReferences( $text );
-               
+
                if ($wgUseTidy) {
                        $text = Parser::tidy($text);
                }
@@ -229,6 +245,7 @@ class Parser
 
                $this->mOutput->setText( $text );
                wfProfileOut( $fname );
+
                return $this->mOutput;
        }
 
@@ -272,35 +289,42 @@ class Parser
                }
 
                if( $tag == STRIP_COMMENTS ) {
-                       $start = '/<!--()/';
+                       $start = '/<!--()()/';
                        $end   = '/-->/';
                } else {
-                       $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
+                       $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
                        $end   = "/<\\/$tag\\s*>/i";
                }
 
                while ( '' != $text ) {
                        $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
                        $stripped .= $p[0];
-                       if( count( $p ) < 3 ) {
+                       if( count( $p ) < 4 ) {
                                break;
                        }
                        $attributes = $p[1];
-                       $inside     = $p[2];
+                       $empty      = $p[2];
+                       $inside     = $p[3];
 
                        $marker = $rnd . sprintf('%08X', $n++);
                        $stripped .= $marker;
 
-                       $tags[$marker] = "<$tag$attributes>";
+                       $tags[$marker] = "<$tag$attributes$empty>";
                        $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
 
-                       $q = preg_split( $end, $inside, 2 );
-                       $content[$marker] = $q[0];
-                       if( count( $q ) < 2 ) {
-                               # No end tag -- let it run out to the end of the text.
-                               break;
+                       if ( $empty === '/' ) {
+                               // Empty element tag, <tag />
+                               $content[$marker] = null;
+                               $text = $inside;
                        } else {
-                               $text = $q[1];
+                               $q = preg_split( $end, $inside, 2 );
+                               $content[$marker] = $q[0];
+                               if( count( $q ) < 2 ) {
+                                       # No end tag -- let it run out to the end of the text.
+                                       break;
+                               } else {
+                                       $text = $q[1];
+                               }
                        }
                }
                return $stripped;
@@ -348,7 +372,7 @@ class Parser
                $gallery_content = array();
 
                # Replace any instances of the placeholders
-               $uniq_prefix = UNIQ_PREFIX;
+               $uniq_prefix = $this->mUniqPrefix;
                #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
 
                # html
@@ -402,7 +426,7 @@ class Parser
                foreach( $gallery_content as $marker => $content ) {
                        require_once( 'ImageGallery.php' );
                        if ( $render ) {
-                               $gallery_content[$marker] = Parser::renderImageGallery( $content );
+                               $gallery_content[$marker] = $this->renderImageGallery( $content );
                        } else {
                                $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
                        }
@@ -424,10 +448,15 @@ class Parser
                        foreach( $ext_content[$tag] as $marker => $content ) {
                                $full_tag = $ext_tags[$tag][$marker];
                                $params = $ext_params[$tag][$marker];
-                               if ( $render ) {
-                                       $ext_content[$tag][$marker] = $callback( $content, $params, $this );
-                               } else {
-                                       $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
+                               if ( $render )
+                                       $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
+                               else {
+                                       if ( is_null( $content ) ) {
+                                               // Empty element tag
+                                               $ext_content[$tag][$marker] = $full_tag;
+                                       } else {
+                                               $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
+                                       }
                                }
                        }
                }
@@ -469,13 +498,12 @@ class Parser
                if ( !is_array( $state ) ) {
                        return $text;
                }
-               
+
                # Must expand in reverse order, otherwise nested tags will be corrupted
-               $contentDict = end( $state );
-               for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
-                       if( key($state) != 'nowiki' && key($state) != 'html') {
-                               for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
-                                       $text = str_replace( key( $contentDict ), $content, $text );
+               foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
+                       if( $tag != 'nowiki' && $tag != 'html' ) {
+                               foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
+                                       $text = str_replace( $uniq, $content, $text );
                                }
                        }
                }
@@ -516,7 +544,7 @@ class Parser
         * @access private
         */
        function insertStripItem( $text, &$state ) {
-               $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
+               $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
                if ( !$state ) {
                        $state = array(
                          'html' => array(),
@@ -655,7 +683,7 @@ class Parser
                        $fc = substr ( $x , 0 , 1 ) ;
                        if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
                                $indent_level = strlen( $matches[1] );
-                               
+
                                $attributes = $this->unstripForHTML( $matches[2] );
 
                                $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
@@ -786,7 +814,7 @@ class Parser
 
                # replaceInternalLinks may sometimes leave behind
                # absolute URLs, which have to be masked to hide them from replaceExternalLinks
-               $text = str_replace(UNIQ_PREFIX."NOPARSE", "", $text);
+               $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
 
                $text = $this->doMagicLinks( $text );
                $text = $this->doTableStuff( $text );
@@ -817,19 +845,6 @@ class Parser
                return $text;
        }
 
-       /**
-        * Parse ^^ tokens and return html
-        *
-        * @access private
-        */
-       function doExponent( $text ) {
-               $fname = 'Parser::doExponent';
-               wfProfileIn( $fname );
-               $text = preg_replace('/\^\^(.*?)\^\^/','<small><sup>\\1</sup></small>', $text);
-               wfProfileOut( $fname );
-               return $text;
-       }
-
        /**
         * Parse headers and return html
         *
@@ -839,7 +854,7 @@ class Parser
                $fname = 'Parser::doHeadings';
                wfProfileIn( $fname );
                for ( $i = 6; $i >= 1; --$i ) {
-                       $h = substr( '======', 0, $i );
+                       $h = str_repeat( '=', $i );
                        $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
                          "<h{$i}>\\1</h{$i}>\\2", $text );
                }
@@ -1121,12 +1136,11 @@ class Parser
         * @access private
         */
        function replaceFreeExternalLinks( $text ) {
-               global $wgUrlProtocols;
                global $wgContLang;
                $fname = 'Parser::replaceFreeExternalLinks';
                wfProfileIn( $fname );
 
-               $bits = preg_split( '/(\b(?:'.$wgUrlProtocols.'))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
+               $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
                $s = array_shift( $bits );
                $i = 0;
 
@@ -1192,7 +1206,7 @@ class Parser
                $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
                $imagesexception = !empty($imagesfrom);
                $text = false;
-               if ( $this->mOptions->getAllowExternalImages() 
+               if ( $this->mOptions->getAllowExternalImages()
                     || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
                        if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
                                # Image found
@@ -1208,7 +1222,7 @@ class Parser
         * @access private
         */
        function replaceInternalLinks( $s ) {
-               global $wgContLang, $wgLinkCache, $wgUrlProtocols;
+               global $wgContLang;
                static $fname = 'Parser::replaceInternalLinks' ;
 
                wfProfileIn( $fname );
@@ -1310,7 +1324,7 @@ class Parser
                        # Don't allow internal links to pages containing
                        # PROTO: where PROTO is a valid URL protocol; these
                        # should be external links.
-                       if (preg_match('/^(\b(?:'.$wgUrlProtocols.'))/', $m[1])) {
+                       if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
                                $s .= $prefix . '[[' . $line ;
                                continue;
                        }
@@ -1390,7 +1404,7 @@ class Parser
 
                                # Interwikis
                                if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
-                                       array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
+                                       $this->mOutput->addLanguageLink( $nt->getFullText() );
                                        $s = rtrim($s . "\n");
                                        $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
                                        continue;
@@ -1406,8 +1420,8 @@ class Parser
                                                $text = $this->replaceInternalLinks($text);
 
                                                # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
-                                               $s .= $prefix . preg_replace("/\b($wgUrlProtocols)/", UNIQ_PREFIX."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
-                                               $wgLinkCache->addImageLinkObj( $nt );
+                                               $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
+                                               $this->mOutput->addImage( $nt->getDBkey() );
 
                                                wfProfileOut( "$fname-image" );
                                                continue;
@@ -1418,13 +1432,8 @@ class Parser
 
                                if ( $ns == NS_CATEGORY ) {
                                        wfProfileIn( "$fname-category" );
-                                       $t = $wgContLang->convertHtml( $nt->getText() );
                                        $s = rtrim($s . "\n"); # bug 87
 
-                                       $wgLinkCache->suspend(); # Don't save in links/brokenlinks
-                                       $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
-                                       $wgLinkCache->resume();
-
                                        if ( $wasblank ) {
                                                if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
                                                        $sortkey = $this->mTitle->getText();
@@ -1434,9 +1443,9 @@ class Parser
                                        } else {
                                                $sortkey = $text;
                                        }
+                                       $sortkey = Sanitizer::decodeCharReferences( $sortkey );
                                        $sortkey = $wgContLang->convertCategoryKey( $sortkey );
-                                       $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
-                                       $this->mOutput->addCategoryLink( $t );
+                                       $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
 
                                        /**
                                         * Strip the whitespace Category links produce, see bug 87
@@ -1458,12 +1467,23 @@ class Parser
 
                        # Special and Media are pseudo-namespaces; no pages actually exist in them
                        if( $ns == NS_MEDIA ) {
-                               $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
-                               $wgLinkCache->addImageLinkObj( $nt );
+                               $link = $sk->makeMediaLinkObj( $nt, $text );
+                               # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
+                               $s .= $prefix . $this->armorLinks( $link ) . $trail;
+                               $this->mOutput->addImage( $nt->getDBkey() );
                                continue;
                        } elseif( $ns == NS_SPECIAL ) {
-                               $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
+                               $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
                                continue;
+                       } elseif( $ns == NS_IMAGE ) {
+                               $img = Image::newFromTitle( $nt );
+                               if( $img->exists() ) {
+                                       // Force a blue link if the file exists; may be a remote
+                                       // upload on the shared repository, and we want to see its
+                                       // auto-generated page.
+                                       $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
+                                       continue;
+                               }
                        }
                        $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
                }
@@ -1503,6 +1523,44 @@ class Parser
                return $retVal;
        }
 
+       /**
+        * Render a forced-blue link inline; protect against double expansion of
+        * URLs if we're in a mode that prepends full URL prefixes to internal links.
+        * Since this little disaster has to split off the trail text to avoid
+        * breaking URLs in the following text without breaking trails on the
+        * wiki links, it's been made into a horrible function.
+        *
+        * @param Title $nt
+        * @param string $text
+        * @param string $query
+        * @param string $trail
+        * @param string $prefix
+        * @return string HTML-wikitext mix oh yuck
+        */
+       function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
+               list( $inside, $trail ) = Linker::splitTrail( $trail );
+               $sk =& $this->mOptions->getSkin();
+               $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
+               return $this->armorLinks( $link ) . $trail;
+       }
+
+       /**
+        * Insert a NOPARSE hacky thing into any inline links in a chunk that's
+        * going to go through further parsing steps before inline URL expansion.
+        *
+        * In particular this is important when using action=render, which causes
+        * full URLs to be included.
+        *
+        * Oh man I hate our multi-layer parser!
+        *
+        * @param string more-or-less HTML
+        * @return string less-or-more HTML with NOPARSE bits
+        */
+       function armorLinks( $text ) {
+               return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
+                       "{$this->mUniqPrefix}NOPARSE$1", $text );
+       }
+
        /**
         * Return true if subpage links should be expanded on this page.
         * @return bool
@@ -1749,12 +1807,11 @@ class Parser
                        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)/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)/iS', $t );
+                                       '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul)/iS', $t );
                                if ( $openmatch or $closematch ) {
                                        $paragraphStack = false;
                                        $output .= $this->closeParagraph();
@@ -1872,45 +1929,55 @@ class Parser
         * @access private
         */
        function getVariableValue( $index ) {
-               global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
+               global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
 
                /**
                 * Some of these require message or data lookups and can be
                 * expensive to check many times.
                 */
                static $varCache = array();
-               if( isset( $varCache[$index] ) ) return $varCache[$index];
+               if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
+                       if ( isset( $varCache[$index] ) )
+                               return $varCache[$index];
+
+               $ts = time();
+               wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
 
                switch ( $index ) {
                        case MAG_CURRENTMONTH:
-                               return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
                        case MAG_CURRENTMONTHNAME:
-                               return $varCache[$index] = $wgContLang->getMonthName( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
                        case MAG_CURRENTMONTHNAMEGEN:
-                               return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
                        case MAG_CURRENTMONTHABBREV:
-                               return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
+                               return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
                        case MAG_CURRENTDAY:
-                               return $varCache[$index] = $wgContLang->formatNum( date('j') );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
                        case MAG_PAGENAME:
                                return $this->mTitle->getText();
                        case MAG_PAGENAMEE:
                                return $this->mTitle->getPartialURL();
+                       case MAG_FULLPAGENAME:
+                               return $this->mTitle->getPrefixedText();
+                       case MAG_FULLPAGENAMEE:
+                               return $this->mTitle->getPrefixedURL();
                        case MAG_REVISIONID:
-                               return $wgArticle->getRevIdFetched();
+                               return $this->mRevisionId;
                        case MAG_NAMESPACE:
-                               # return Namespace::getCanonicalName($this->mTitle->getNamespace());
-                               return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
+                               return $wgContLang->getNsText( $this->mTitle->getNamespace() );
+                       case MAG_NAMESPACEE:
+                               return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
                        case MAG_CURRENTDAYNAME:
-                               return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
+                               return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
                        case MAG_CURRENTYEAR:
-                               return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
                        case MAG_CURRENTTIME:
-                               return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
+                               return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
                        case MAG_CURRENTWEEK:
-                               return $varCache[$index] = $wgContLang->formatNum( date('W') );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
                        case MAG_CURRENTDOW:
-                               return $varCache[$index] = $wgContLang->formatNum( date('w') );
+                               return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
                        case MAG_NUMBEROFARTICLES:
                                return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
                        case MAG_NUMBEROFFILES:
@@ -1924,7 +1991,11 @@ class Parser
                        case MAG_SCRIPTPATH:
                                return $wgScriptPath;
                        default:
-                               return NULL;
+                               $ret = null;
+                               if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
+                                       return $ret;
+                               else
+                                       return null;
                }
        }
 
@@ -1977,14 +2048,14 @@ class Parser
 
                        if ($lastOpeningBrace >= 0) {
                                $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
-                       
+
                                if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
                                        $rule = null;
                                        $nextPos = $pos;
                                }
 
                                $pos = strpos ($text, '|', $i);
-                               
+
                                if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
                                        $rule = null;
                                        $nextPos = $pos;
@@ -2004,14 +2075,14 @@ class Parser
                                                           'title' => '',
                                                           'parts' => null);
 
-                               # count openning brace characters 
+                               # count openning brace characters
                                while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
                                        $piece['count']++;
                                        $i++;
                                }
 
-                               $piece['startAt'] = $i+1; 
-                               $piece['partStart'] = $i+1; 
+                               $piece['startAt'] = $i+1;
+                               $piece['partStart'] = $i+1;
 
                                # we need to add to stack only if openning brace count is enough for any given rule
                                foreach ($rule['cb'] as $cnt => $fn) {
@@ -2045,7 +2116,7 @@ class Parser
                                                        $matchingCallback = $fn;
                                                }
                                        }
-                                       
+
                                        if ($matchingCount == 0) {
                                                $i += $count - 1;
                                                continue;
@@ -2059,7 +2130,7 @@ class Parser
 
                                        $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
                                        $pieceEnd = $i + $matchingCount;
-                                       
+
                                        if( is_callable( $matchingCallback ) ) {
                                                $cbArgs = array (
                                                                                 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
@@ -2110,7 +2181,7 @@ class Parser
                                        }
                                        else
                                                $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
-                                       
+
                                        $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
                                }
                        }
@@ -2142,8 +2213,6 @@ class Parser
                $fname = 'Parser::replaceVariables';
                wfProfileIn( $fname );
 
-               $titleChars = Title::legalChars();
-
                # This function is called recursively. To keep track of arguments we need a stack:
                array_push( $this->mArgStack, $args );
 
@@ -2168,7 +2237,7 @@ class Parser
         * @access private
         */
        function variableSubstitution( $matches ) {
-               $fname = 'parser::variableSubstitution';
+               $fname = 'Parser::variableSubstitution';
                $varname = $matches[1];
                wfProfileIn( $fname );
                if ( !$this->mVariables ) {
@@ -2232,7 +2301,7 @@ class Parser
         * @access private
         */
        function braceSubstitution( $piece ) {
-               global $wgLinkCache, $wgContLang;
+               global $wgContLang;
                $fname = 'Parser::braceSubstitution';
                wfProfileIn( $fname );
 
@@ -2343,7 +2412,7 @@ class Parser
                        $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
                        $mwFull =& MagicWord::get( MAG_FULLURL );
                        $mwFullE =& MagicWord::get( MAG_FULLURLE );
-                       
+
 
                        if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
                                $func = 'getLocalURL';
@@ -2401,7 +2470,7 @@ class Parser
                                $noparse = true;
                                $found = true;
                                $text = $linestart .
-                                       "\{\{$part1}}" .
+                                       '{{' . $part1 . '}}' .
                                        '<!-- WARNING: template loop detected -->';
                                wfDebug( "$fname: template loop broken at '$part1'\n" );
                        } else {
@@ -2450,6 +2519,8 @@ class Parser
                                                        $text = $articleContent;
                                                        $replaceHeadings = true;
                                                }
+                                               # Register a template reference whether or not the template exists
+                                               $this->mOutput->addTemplate( $title, $article->getID() );
                                        }
                                }
 
@@ -2494,27 +2565,24 @@ class Parser
                        # Add a new element to the templace recursion path
                        $this->mTemplatePath[$part1] = 1;
 
+                       # If there are any <onlyinclude> tags, only include them
+                       if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
+                               preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
+                               $text = '';
+                               foreach ($m[1] as $piece)
+                                       $text .= $piece;
+                       }
+                       # Remove <noinclude> sections and <includeonly> tags
+                       $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
+                       $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
+
                        if( $this->mOutputType == OT_HTML ) {
-                               if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
-                                       preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
-                                       $text = '';
-                                       foreach ($m[1] as $piece)
-                                               $text .= $piece;
-                               }
-                               # Remove <noinclude> sections and <includeonly> tags
-                               $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
-                               $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
                                # Strip <nowiki>, <pre>, etc.
                                $text = $this->strip( $text, $this->mStripState );
                                $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
                        }
                        $text = $this->replaceVariables( $text, $assocArgs );
 
-                       # Resume the link cache and register the inclusion as a link
-                       if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
-                               $wgLinkCache->addLinkObj( $title );
-                       }
-
                        # If the template begins with a table or block-level
                        # element, it should be treated as beginning a new line.
                        if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
@@ -2666,7 +2734,7 @@ class Parser
         * @access private
         */
        function formatHeadings( $text, $isMain=true ) {
-               global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
+               global $wgMaxTocLevel, $wgContLang;
 
                $doNumberHeadings = $this->mOptions->getNumberHeadings();
                $doShowToc = true;
@@ -2829,12 +2897,7 @@ class Parser
                        # strip out HTML
                        $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
                        $tocline = trim( $canonized_headline );
-                       $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
-                       $replacearray = array(
-                               '%3A' => ':',
-                               '%' => '.'
-                       );
-                       $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
+                       $canonized_headline = Sanitizer::escapeId( $tocline );
                        $refers[$headlineCount] = $canonized_headline;
 
                        # count how many in assoc. array so we can track dupes in anchors
@@ -3054,7 +3117,7 @@ class Parser
                        "\r\n" => "\n",
                );
                $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
-               $text = $this->strip( $text, $stripState, false );
+               $text = $this->strip( $text, $stripState, true );
                $text = $this->pstPass2( $text, $user );
                $text = $this->unstrip( $text, $stripState );
                $text = $this->unstripNoWiki( $text, $stripState );
@@ -3074,38 +3137,33 @@ class Parser
 
                # Signatures
                #
-               $n = $user->getName();
-               $k = $user->getOption( 'nickname' );
-               if ( '' == $k ) { $k = $n; }
-               if ( isset( $wgLocaltimezone ) ) {
-                       $oldtz = getenv( 'TZ' );
-                       putenv( 'TZ='.$wgLocaltimezone );
-               }
+               $sigText = $this->getUserSig( $user );
 
                /* Note: This is the timestamp saved as hardcoded wikitext to
                 * the database, we use $wgContLang here in order to give
                 * everyone the same signiture and use the default one rather
                 * than the one selected in each users preferences.
                 */
+               if ( isset( $wgLocaltimezone ) ) {
+                       $oldtz = getenv( 'TZ' );
+                       putenv( 'TZ='.$wgLocaltimezone );
+               }
                $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
                  ' (' . date( 'T' ) . ')';
                if ( isset( $wgLocaltimezone ) ) {
                        putenv( 'TZ='.$oldtz );
                }
 
-               if( $user->getOption( 'fancysig' ) ) {
-                       $sigText = $k;
-               } else {
-                       $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
-               }
                $text = preg_replace( '/~~~~~/', $d, $text );
                $text = preg_replace( '/~~~~/', "$sigText $d", $text );
                $text = preg_replace( '/~~~/', $sigText, $text );
 
                # Context links: [[|name]] and [[name (context)|]]
                #
-               $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
-               $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
+               global $wgLegalTitleChars;
+               $tc = "[$wgLegalTitleChars]";
+               $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
+
                $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
                $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
 
@@ -3138,6 +3196,62 @@ class Parser
                return $text;
        }
 
+       /**
+        * Fetch the user's signature text, if any, and normalize to
+        * validated, ready-to-insert wikitext.
+        *
+        * @param User $user
+        * @return string
+        * @access private
+        */
+       function getUserSig( &$user ) {
+               $name = $user->getName();
+               $nick = trim( $user->getOption( 'nickname' ) );
+               if ( '' == $nick ) {
+                       $nick = $name;
+               }
+
+               if( $user->getOption( 'fancysig' ) ) {
+                       // A wikitext signature.
+                       $valid = $this->validateSig( $nick );
+                       if( $valid === false ) {
+                               // Fall back to default sig
+                               $nick = $name;
+                               wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
+                       } else {
+                               return $nick;
+                       }
+               }
+
+               // Plain text linking to the user's homepage
+               global $wgContLang;
+               $page = $user->getUserPage();
+               return '[[' .
+                       $page->getPrefixedText() .
+                       "|" .
+                       wfEscapeWikIText( $nick ) .
+                       "]]";
+       }
+
+       /**
+        * We want to enforce two rules on wikitext sigs here:
+        * 1) Expand any templates at save time (forced subst:)
+        * 2) Check for unbalanced XML tags, and reject if so.
+        *
+        * @param string $text
+        * @return mixed An expanded string, or false if invalid.
+        *
+        * @todo Run brace substitutions
+        * @todo ?? Check for unbalanced '' and ''' quotes, etc
+        */
+       function validateSig( $text ) {
+               if( wfIsWellFormedXmlFragment( $text ) ) {
+                       return $text;
+               } else {
+                       return false;
+               }
+       }
+
        /**
         * Set up some variables which are usually set up in parse()
         * so that an external function can call some class members with confidence
@@ -3184,11 +3298,18 @@ class Parser
         * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
         * Callback will be called with the text within
         * Transform and return the text within
+        *
         * @access public
+        *
+        * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
+        * @param mixed $callback The callback function (and object) to use for the tag
+        *
+        * @return The old value of the mTagHooks array associated with the hook
         */
        function setHook( $tag, $callback ) {
                $oldVal = @$this->mTagHooks[$tag];
                $this->mTagHooks[$tag] = $callback;
+
                return $oldVal;
        }
 
@@ -3202,7 +3323,7 @@ class Parser
         * $options is a bit field, RLH_FOR_UPDATE to select for update
         */
        function replaceLinkHolders( &$text, $options = 0 ) {
-               global $wgUser, $wgLinkCache;
+               global $wgUser;
                global $wgOutputReplace;
 
                $fname = 'Parser::replaceLinkHolders';
@@ -3210,7 +3331,8 @@ class Parser
 
                $pdbks = array();
                $colours = array();
-               $sk = $this->mOptions->getSkin();
+               $sk =& $this->mOptions->getSkin();
+               $linkCache =& LinkCache::singleton();
 
                if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
                        wfProfileIn( $fname.'-check' );
@@ -3223,7 +3345,7 @@ class Parser
 
                        # Generate query
                        $query = false;
-                       foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
+                       foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
                                # Make title object
                                $title = $this->mLinkHolders['titles'][$key];
 
@@ -3234,23 +3356,26 @@ class Parser
                                }
                                $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
 
-                               # Check if it's in the link cache already
-                               if ( $title->isAlwaysKnown() || $wgLinkCache->getGoodLinkID( $pdbk ) ) {
+                               # Check if it's a static known link, e.g. interwiki
+                               if ( $title->isAlwaysKnown() ) {
                                        $colours[$pdbk] = 1;
-                               } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
+                               } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
+                                       $colours[$pdbk] = 1;
+                                       $this->mOutput->addLink( $title, $id );
+                               } elseif ( $linkCache->isBadLink( $pdbk ) ) {
                                        $colours[$pdbk] = 0;
                                } else {
                                        # Not in the link cache, add it to the query
                                        if ( !isset( $current ) ) {
-                                               $current = $val;
+                                               $current = $ns;
                                                $query =  "SELECT page_id, page_namespace, page_title";
                                                if ( $threshold > 0 ) {
                                                        $query .= ', page_len, page_is_redirect';
                                                }
-                                               $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
-                                       } elseif ( $current != $val ) {
-                                               $current = $val;
-                                               $query .= ")) OR (page_namespace=$val AND page_title IN(";
+                                               $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
+                                       } elseif ( $current != $ns ) {
+                                               $current = $ns;
+                                               $query .= ")) OR (page_namespace=$ns AND page_title IN(";
                                        } else {
                                                $query .= ', ';
                                        }
@@ -3273,7 +3398,8 @@ class Parser
                                while ( $s = $dbr->fetchObject($res) ) {
                                        $title = Title::makeTitle( $s->page_namespace, $s->page_title );
                                        $pdbk = $title->getPrefixedDBkey();
-                                       $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
+                                       $linkCache->addGoodLinkObj( $s->page_id, $title );
+                                       $this->mOutput->addLink( $title, $s->page_id );
 
                                        if ( $threshold >  0 ) {
                                                $size = $s->page_len;
@@ -3297,8 +3423,9 @@ class Parser
                                $searchkey = "<!--LINK $key-->";
                                $title = $this->mLinkHolders['titles'][$key];
                                if ( empty( $colours[$pdbk] ) ) {
-                                       $wgLinkCache->addBadLinkObj( $title );
+                                       $linkCache->addBadLinkObj( $title );
                                        $colours[$pdbk] = 0;
+                                       $this->mOutput->addLink( $title, 0 );
                                        $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
                                                                        $this->mLinkHolders['texts'][$key],
                                                                        $this->mLinkHolders['queries'][$key] );
@@ -3354,7 +3481,7 @@ class Parser
         * @return string
         */
        function replaceLinkHoldersText( $text ) {
-               global $wgUser, $wgLinkCache;
+               global $wgUser;
                global $wgOutputReplace;
 
                $fname = 'Parser::replaceLinkHoldersText';
@@ -3397,16 +3524,12 @@ class Parser
         * given as text will return the HTML of a gallery with two images,
         * labeled 'The number "1"' and
         * 'A tree'.
-        *
-        * @static
         */
        function renderImageGallery( $text ) {
                # Setup the parser
-               global $wgUser, $wgTitle;
-               $parserOptions = ParserOptions::newFromUser( $wgUser );
+               $parserOptions = new ParserOptions;
                $localParser = new Parser();
 
-               global $wgLinkCache;
                $ig = new ImageGallery();
                $ig->setShowBytes( false );
                $ig->setShowFilename( false );
@@ -3420,7 +3543,7 @@ class Parser
                        if ( count( $matches ) == 0 ) {
                                continue;
                        }
-                       $nt = Title::newFromURL( $matches[1] );
+                       $nt =& Title::newFromText( $matches[1] );
                        if( is_null( $nt ) ) {
                                # Bogus title. Ignore these so we don't bomb out later.
                                continue;
@@ -3431,11 +3554,11 @@ class Parser
                                $label = '';
                        }
 
-                       $html = $localParser->parse( $label , $wgTitle, $parserOptions );
-                       $html = $html->mText;
+                       $pout = $localParser->parse( $label , $this->mTitle, $parserOptions );
+                       $html = $pout->getText();
 
                        $ig->add( new Image( $nt ), $html );
-                       $wgLinkCache->addImageLinkObj( $nt );
+                       $this->mOutput->addImage( $nt->getDBkey() );
                }
                return $ig->toHTML();
        }
@@ -3444,8 +3567,7 @@ class Parser
         * Parse image options text and use it to make an image
         */
        function makeImage( &$nt, $options ) {
-               global $wgContLang, $wgUseImageResize;
-               global $wgUser, $wgThumbLimits;
+               global $wgContLang, $wgUseImageResize, $wgUser;
 
                $align = '';
 
@@ -3518,13 +3640,13 @@ class Parser
        }
 
        /**
-        * Set a flag in the output object indicating that the content is dynamic and 
+        * Set a flag in the output object indicating that the content is dynamic and
         * shouldn't be cached.
         */
        function disableCache() {
                $this->mOutput->mCacheTime = -1;
        }
-       
+
        /**
         * Callback from the Sanitizer for expanding items found in HTML attribute
         * values, so they can be safely tested and escaped.
@@ -3538,12 +3660,16 @@ class Parser
                $text = $this->unstripForHTML( $text );
                return $text;
        }
-       
+
        function unstripForHTML( $text ) {
                $text = $this->unstrip( $text, $this->mStripState );
                $text = $this->unstripNoWiki( $text, $this->mStripState );
                return $text;
        }
+
+       function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
+       function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
+       function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
 }
 
 /**
@@ -3552,43 +3678,81 @@ class Parser
  */
 class ParserOutput
 {
-       var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
-       var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
-       var $mVersion;   # Compatibility check
-       var $mTitleText; # title text of the chosen language variant
+       var $mText,             # The output text
+               $mLanguageLinks,    # List of the full text of language links, in the order they appear
+               $mCategories,       # Map of category names to sort keys
+               $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
+               $mCacheTime,        # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
+               $mVersion,          # Compatibility check
+               $mTitleText,        # title text of the chosen language variant
+               $mLinks,            # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
+               $mTemplates,        # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
+               $mImages;           # DB keys of the images used, in the array key only
 
        function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
                $containsOldMagic = false, $titletext = '' )
        {
                $this->mText = $text;
                $this->mLanguageLinks = $languageLinks;
-               $this->mCategoryLinks = $categoryLinks;
+               $this->mCategories = $categoryLinks;
                $this->mContainsOldMagic = $containsOldMagic;
                $this->mCacheTime = '';
                $this->mVersion = MW_PARSER_VERSION;
                $this->mTitleText = $titletext;
+               $this->mLinks = array();
+               $this->mTemplates = array();
+               $this->mImages = array();
        }
 
        function getText()                   { return $this->mText; }
        function getLanguageLinks()          { return $this->mLanguageLinks; }
-       function getCategoryLinks()          { return array_keys( $this->mCategoryLinks ); }
+       function getCategoryLinks()          { return array_keys( $this->mCategories ); }
+       function &getCategories()            { return $this->mCategories; }
        function getCacheTime()              { return $this->mCacheTime; }
        function getTitleText()              { return $this->mTitleText; }
+       function &getLinks()                 { return $this->mLinks; }
+       function &getTemplates()             { return $this->mTemplates; }
+       function &getImages()                { return $this->mImages; }
+
        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 setCategoryLinks( $cl )     { return wfSetVar( $this->mCategories, $cl ); }
        function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
        function setCacheTime( $t )          { return wfSetVar( $this->mCacheTime, $t ); }
        function setTitleText( $t )          { return wfSetVar ($this->mTitleText, $t); }
 
-       function addCategoryLink( $c )       { $this->mCategoryLinks[$c] = 1; }
+       function addCategory( $c, $sort )    { $this->mCategories[$c] = $sort; }
+       function addImage( $name )           { $this->mImages[$name] = 1; }
+       function addLanguageLink( $t )       { $this->mLanguageLinks[] = $t; }
 
+       function addLink( $title, $id ) {
+               $ns = $title->getNamespace();
+               $dbk = $title->getDBkey();
+               if ( !isset( $this->mLinks[$ns] ) ) {
+                       $this->mLinks[$ns] = array();
+               }
+               $this->mLinks[$ns][$dbk] = $id;
+       }
+
+       function addTemplate( $title, $id ) {
+               $ns = $title->getNamespace();
+               $dbk = $title->getDBkey();
+               if ( !isset( $this->mTemplates[$ns] ) ) {
+                       $this->mTemplates[$ns] = array();
+               }
+               $this->mTemplates[$ns][$dbk] = $id;
+       }
+
+       /**
+        * @deprecated
+        */
+       /*
        function merge( $other ) {
                $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
-               $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
+               $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
                $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
-       }
+       }*/
 
        /**
         * Return true if this cached output object predates the global or
@@ -3602,7 +3766,7 @@ class ParserOutput
        function expired( $touched ) {
                global $wgCacheEpoch;
                return $this->getCacheTime() == -1 || // parser says it's uncacheable
-                      $this->getCacheTime() <= $touched ||
+                      $this->getCacheTime() < $touched ||
                       $this->getCacheTime() <= $wgCacheEpoch ||
                       !isset( $this->mVersion ) ||
                       version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
@@ -3731,7 +3895,7 @@ function wfNumberOfFiles() {
 
 /**
  * Get various statistics from the database
- * @private
+ * @access private
  */
 function wfLoadSiteStats() {
        global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
@@ -3755,7 +3919,7 @@ function wfLoadSiteStats() {
 
 /**
  * Escape html tags
- * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
+ * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
  *
  * @param string $in Text that might contain HTML tags
  * @return string Escaped string