# Persistent:
var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
$mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
- $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
+ $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf,
+ $mFunctionTagHooks;
# Cleared with clearState():
var $mTplExpandCache; // empty-frame expansion cache
var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
var $mExpensiveFunctionCount; // number of expensive parser function calls
- var $mFileCache;
# Temporary
# These are variables reset at least once per parse regardless of $clearState
$this->mTagHooks = array();
$this->mTransparentTagHooks = array();
$this->mFunctionHooks = array();
+ $this->mFunctionTagHooks = array();
$this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
$this->mDefaultStripList = $this->mStripList = array( 'nowiki', 'gallery' );
$this->mUrlProtocols = wfUrlProtocols();
$this->mLinkHolders = new LinkHolderArray( $this );
$this->mLinkID = 0;
$this->mRevisionTimestamp = $this->mRevisionId = null;
+ $this->mVarCache = array();
/**
* Prefix for temporary replacement strings for the multipass parser.
$this->mHeadings = array();
$this->mDoubleUnderscores = array();
$this->mExpensiveFunctionCount = 0;
- $this->mFileCache = array();
# Fix cloning
if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
$text = Sanitizer::normalizeCharReferences( $text );
- if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
- $text = self::tidy($text);
+ if ( ( $wgUseTidy && $this->mOptions->mTidy ) || $wgAlwaysUseTidy ) {
+ $text = MWTidy::tidy( $text );
} else {
# attempt to sanitize at least some nesting problems
# (bug #2702 and quite a few others)
/**
* Recursive parser entry point that can be called from an extension tag
* hook.
+ *
+ * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
+ *
+ * @param $text String: text extension wants to have parsed
+ * @param PPFrame $frame: The frame to use for expanding any template variables
*/
- function recursiveTagParse( $text ) {
+ function recursiveTagParse( $text, $frame=false ) {
wfProfileIn( __METHOD__ );
wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
- $text = $this->internalParse( $text );
+ $text = $this->internalParse( $text, false, $frame );
wfProfileOut( __METHOD__ );
return $text;
}
$matches = array();
$taglist = implode( '|', $elements );
- $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
+ $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
while ( '' != $text ) {
$p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
$this->mStripState->general->setPair( $rnd, $text );
return $rnd;
}
-
- /**
- * Interface with html tidy, used if $wgUseTidy = true.
- * If tidy isn't able to correct the markup, the original will be
- * returned in all its glory with a warning comment appended.
- *
- * Either the external tidy program or the in-process tidy extension
- * will be used depending on availability. Override the default
- * $wgTidyInternal setting to disable the internal if it's not working.
- *
- * @param string $text Hideous HTML input
- * @return string Corrected HTML output
- * @public
- * @static
- */
- function tidy( $text ) {
- global $wgTidyInternal;
-
- $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
-' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
-'<head><title>test</title></head><body>'.$text.'</body></html>';
-
- # Tidy is known to clobber tabs; convert 'em to entities
- $wrappedtext = str_replace("\t", '	', $wrappedtext);
-
- if( $wgTidyInternal ) {
- $correctedtext = self::internalTidy( $wrappedtext );
- } else {
- $correctedtext = self::externalTidy( $wrappedtext );
- }
- if( is_null( $correctedtext ) ) {
- wfDebug( "Tidy error detected!\n" );
- return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
- }
-
- # Convert the tabs back from entities
- $correctedtext = str_replace('	', "\t", $correctedtext);
-
- return $correctedtext;
- }
-
- /**
- * Spawn an external HTML tidy process and get corrected markup back from it.
- *
- * @private
- * @static
- */
- function externalTidy( $text ) {
- global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
- wfProfileIn( __METHOD__ );
-
- $cleansource = '';
- $opts = ' -utf8';
-
- $descriptorspec = array(
- 0 => array('pipe', 'r'),
- 1 => array('pipe', 'w'),
- 2 => array('file', wfGetNull(), 'a')
- );
- $pipes = array();
- if( function_exists('proc_open') ) {
- $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
- if (is_resource($process)) {
- // Theoretically, this style of communication could cause a deadlock
- // here. If the stdout buffer fills up, then writes to stdin could
- // block. This doesn't appear to happen with tidy, because tidy only
- // writes to stdout after it's finished reading from stdin. Search
- // for tidyParseStdin and tidySaveStdout in console/tidy.c
- fwrite($pipes[0], $text);
- fclose($pipes[0]);
- while (!feof($pipes[1])) {
- $cleansource .= fgets($pipes[1], 1024);
- }
- fclose($pipes[1]);
- proc_close($process);
- }
- }
-
- wfProfileOut( __METHOD__ );
-
- if( $cleansource == '' && $text != '') {
- // Some kind of error happened, so we couldn't get the corrected text.
- // Just give up; we'll use the source text and append a warning.
- return null;
- } else {
- return $cleansource;
- }
- }
-
+
/**
- * Use the HTML tidy PECL extension to use the tidy library in-process,
- * saving the overhead of spawning a new process.
- *
- * 'pear install tidy' should be able to compile the extension module.
- *
- * @private
- * @static
+ * Interface with html tidy
+ * @deprecated Use MWTidy::tidy()
*/
- function internalTidy( $text ) {
- global $wgTidyConf, $IP, $wgDebugTidy;
- wfProfileIn( __METHOD__ );
-
- $tidy = new tidy;
- $tidy->parseString( $text, $wgTidyConf, 'utf8' );
- $tidy->cleanRepair();
- if( $tidy->getStatus() == 2 ) {
- // 2 is magic number for fatal error
- // http://www.php.net/manual/en/function.tidy-get-status.php
- $cleansource = null;
- } else {
- $cleansource = tidy_get_output( $tidy );
- }
- if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
- $cleansource .= "<!--\nTidy reports:\n" .
- str_replace( '-->', '-->', $tidy->errorBuffer ) .
- "\n-->";
- }
-
- wfProfileOut( __METHOD__ );
- return $cleansource;
+ public static function tidy( $text ) {
+ wfDeprecated( __METHOD__ );
+ return MWTidy::tidy( $text );
}
/**
*
* @private
*/
- function internalParse( $text ) {
- $isMain = true;
+ function internalParse( $text, $isMain = true, $frame=false ) {
wfProfileIn( __METHOD__ );
+
+ $origText = $text;
# Hook to suspend the parser in this state
if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
return $text ;
}
- $text = $this->replaceVariables( $text );
+ // if $frame is provided, then use $frame for replacing any variables
+ if ($frame) {
+ // use frame depth to infer how include/noinclude tags should be handled
+ // depth=0 means this is the top-level document; otherwise it's an included document
+ if( !$frame->depth )
+ $flag = 0;
+ else
+ $flag = Parser::PTD_FOR_INCLUSION;
+ $dom = $this->preprocessToDom( $text, $flag );
+ $text = $frame->expand( $dom );
+ }
+ // if $frame is not provided, then use old-style replaceVariables
+ else {
+ $text = $this->replaceVariables( $text );
+ }
+
$text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
$text = $this->doDoubleUnderscore( $text );
$text = $this->doHeadings( $text );
- if($this->mOptions->getUseDynamicDates()) {
+ if( $this->mOptions->getUseDynamicDates() ) {
$df = DateFormatter::getInstance();
$text = $df->reformat( $this->mOptions->getDateFormat(), $text );
}
# replaceInternalLinks may sometimes leave behind
# absolute URLs, which have to be masked to hide them from replaceExternalLinks
- $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
+ $text = str_replace($this->mUniqPrefix.'NOPARSE', '', $text);
$text = $this->doMagicLinks( $text );
- $text = $this->formatHeadings( $text, $isMain );
+ $text = $this->formatHeadings( $text, $origText, $isMain );
wfProfileOut( __METHOD__ );
return $text;
}
function magicLinkCallback( $m ) {
- if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
+ if ( isset( $m[1] ) && $m[1] !== '' ) {
# Skip anchor
return $m[0];
- } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
+ } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
# Skip HTML element
return $m[0];
- } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
+ } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
# Free external link
return $this->makeFreeExternalLink( $m[0] );
- } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
+ } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
# RFC or PMID
+ $CssClass = '';
if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
$keyword = 'RFC';
$urlmsg = 'rfcurl';
+ $CssClass = 'mw-magiclink-rfc';
$id = $m[4];
} elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
$keyword = 'PMID';
$urlmsg = 'pubmedurl';
+ $CssClass = 'mw-magiclink-pmid';
$id = $m[4];
} else {
throw new MWException( __METHOD__.': unrecognised match type "' .
}
$url = wfMsg( $urlmsg, $id);
$sk = $this->mOptions->getSkin();
- $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
+ $la = $sk->getExternalLinkAttributes( "external $CssClass" );
return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
- } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
+ } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
# ISBN
$isbn = $m[5];
$num = strtr( $isbn, array(
$titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
return'<a href="' .
$titleObj->escapeLocalUrl() .
- "\" class=\"internal\">ISBN $isbn</a>";
+ "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
} else {
return $m[0];
}
# 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(?:' . wfUrlProtocols() . ')/', $m[1])) {
+ if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
$s .= $prefix . '[[' . $line ;
wfProfileOut( __METHOD__."-misc" );
continue;
}
# Make subpage if necessary
- if( $useSubpages ) {
+ if ( $useSubpages ) {
$link = $this->maybeDoSubpageLink( $m[1], $text );
} else {
$link = $m[1];
}
- $noforce = (substr($m[1], 0, 1) !== ':');
+ $noforce = (substr( $m[1], 0, 1 ) !== ':');
if (!$noforce) {
# Strip off leading ':'
- $link = substr($link, 1);
+ $link = substr( $link, 1 );
}
wfProfileOut( __METHOD__."-misc" );
wfProfileIn( __METHOD__."-title" );
- $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
- if( !$nt ) {
+ $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
+ if ( $nt === NULL ) {
$s .= $prefix . '[[' . $line;
wfProfileOut( __METHOD__."-title" );
continue;
$iw = $nt->getInterWiki();
wfProfileOut( __METHOD__."-title" );
- if ($might_be_img) { # if this is actually an invalid link
+ if ( $might_be_img ) { # if this is actually an invalid link
wfProfileIn( __METHOD__."-might_be_img" );
- if ($ns == NS_FILE && $noforce) { #but might be an image
+ if ( $ns == NS_FILE && $noforce ) { #but might be an image
$found = false;
while ( true ) {
#look at the next 'line' to see if we can close it there
}
$wasblank = ( '' == $text );
- if( $wasblank ) $text = $link;
+ if ( $wasblank ) $text = $link;
# Link not escaped by : , create the various objects
- if( $noforce ) {
+ if ( $noforce ) {
# Interwikis
wfProfileIn( __METHOD__."-interwiki" );
- if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
+ if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
$this->mOutput->addLanguageLink( $nt->getFullText() );
$s = rtrim($s . $prefix);
$s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
if ( $ns == NS_FILE ) {
wfProfileIn( __METHOD__."-image" );
if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
- # recursively parse links inside the image caption
- # actually, this will parse them in any other parameters, too,
- # but it might be hard to fix that, and it doesn't matter ATM
- $text = $this->replaceExternalLinks($text);
- $holders->merge( $this->replaceInternalLinks2( $text ) );
-
+ if ( $wasblank ) {
+ # if no parameters were passed, $text
+ # becomes something like "File:Foo.png",
+ # which we don't want to pass on to the
+ # image generator
+ $text = '';
+ } else {
+ # recursively parse links inside the image caption
+ # actually, this will parse them in any other parameters, too,
+ # but it might be hard to fix that, and it doesn't matter ATM
+ $text = $this->replaceExternalLinks($text);
+ $holders->merge( $this->replaceInternalLinks2( $text ) );
+ }
# cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
$s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
}
# NS_MEDIA is a pseudo-namespace for linking directly to a file
# FIXME: Should do batch file existence checks, see comment below
if( $ns == NS_MEDIA ) {
+ wfProfileIn( __METHOD__."-media" );
# Give extensions a chance to select the file revision for us
$skip = $time = false;
wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
# Cloak with NOPARSE to avoid replacement in replaceExternalLinks
$s .= $prefix . $this->armorLinks( $link ) . $trail;
$this->mOutput->addImage( $nt->getDBkey() );
+ wfProfileOut( __METHOD__."-media" );
continue;
}
+ wfProfileIn( __METHOD__."-always_known" );
# Some titles, such as valid special pages or files in foreign repos, should
# be shown as bluelinks even though they're not included in the page table
#
# Links will be added to the output link list after checking
$s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
}
+ wfProfileOut( __METHOD__."-always_known" );
}
wfProfileOut( __METHOD__ );
return $holders;
function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
list( $inside, $trail ) = Linker::splitTrail( $trail );
$sk = $this->mOptions->getSkin();
+ // FIXME: use link() instead of deprecated makeKnownLinkObj()
$link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
return $this->armorLinks( $link ) . $trail;
}
* @private
*/
function maybeDoSubpageLink($target, &$text) {
- # Valid link forms:
- # Foobar -- normal
- # :Foobar -- override special treatment of prefix (images, language links)
- # /Foobar -- convert to CurrentPage/Foobar
- # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
- # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
- # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
-
- wfProfileIn( __METHOD__ );
- $ret = $target; # default return value is no change
-
- # Some namespaces don't allow subpages,
- # so only perform processing if subpages are allowed
- if( $this->areSubpagesAllowed() ) {
- $hash = strpos( $target, '#' );
- if( $hash !== false ) {
- $suffix = substr( $target, $hash );
- $target = substr( $target, 0, $hash );
- } else {
- $suffix = '';
- }
- # bug 7425
- $target = trim( $target );
- # Look at the first character
- if( $target != '' && $target{0} === '/' ) {
- # / at end means we don't want the slash to be shown
- $m = array();
- $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
- if( $trailingSlashes ) {
- $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
- } else {
- $noslash = substr( $target, 1 );
- }
-
- $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
- if( '' === $text ) {
- $text = $target . $suffix;
- } # this might be changed for ugliness reasons
- } else {
- # check for .. subpage backlinks
- $dotdotcount = 0;
- $nodotdot = $target;
- while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
- ++$dotdotcount;
- $nodotdot = substr( $nodotdot, 3 );
- }
- if($dotdotcount > 0) {
- $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
- if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
- $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
- # / at the end means don't show full path
- if( substr( $nodotdot, -1, 1 ) === '/' ) {
- $nodotdot = substr( $nodotdot, 0, -1 );
- if( '' === $text ) {
- $text = $nodotdot . $suffix;
- }
- }
- $nodotdot = trim( $nodotdot );
- if( $nodotdot != '' ) {
- $ret .= '/' . $nodotdot;
- }
- $ret .= $suffix;
- }
- }
- }
- }
-
- wfProfileOut( __METHOD__ );
- return $ret;
+ return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
}
/**#@+
$result = $this->closeParagraph();
if ( '*' === $char ) { $result .= '<ul><li>'; }
- else if ( '#' === $char ) { $result .= '<ol><li>'; }
- else if ( ':' === $char ) { $result .= '<dl><dd>'; }
- else if ( ';' === $char ) {
+ elseif ( '#' === $char ) { $result .= '<ol><li>'; }
+ elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
+ elseif ( ';' === $char ) {
$result .= '<dl><dt>';
$this->mDTopen = true;
}
/* private */ function nextItem( $char ) {
if ( '*' === $char || '#' === $char ) { return '</li><li>'; }
- else if ( ':' === $char || ';' === $char ) {
+ elseif ( ':' === $char || ';' === $char ) {
$close = '</dd>';
if ( $this->mDTopen ) { $close = '</dt>'; }
if ( ';' === $char ) {
/* private */ function closeList( $char ) {
if ( '*' === $char ) { $text = '</li></ul>'; }
- else if ( '#' === $char ) { $text = '</li></ol>'; }
- else if ( ':' === $char ) {
+ elseif ( '#' === $char ) { $text = '</li></ol>'; }
+ elseif ( ':' === $char ) {
if ( $this->mDTopen ) {
$this->mDTopen = false;
$text = '</dt></dl>';
/**
* Make lists from lines starting with ':', '*', '#', etc. (DBL)
*
+ * @param $linestart bool whether or not this is at the start of a line.
* @private
* @return string the lists rendered as HTML
*/
$linestart = true;
continue;
}
+ // * = ul
+ // # = ol
+ // ; = dt
+ // : = dd
$lastPrefixLength = strlen( $lastPrefix );
$preCloseMatch = preg_match('/<\\/pre/i', $oLine );
$preOpenMatch = preg_match('/<pre/i', $oLine );
+ // If not in a <pre> element, scan for and figure out what prefixes are there.
if ( !$this->mInPre ) {
# Multiple prefixes may abut each other for nested lists.
$prefixLength = strspn( $oLine, '*#:;' );
$prefix = substr( $oLine, 0, $prefixLength );
# eh?
+ // ; and : are both from definition-lists, so they're equivalent
+ // for the purposes of determining whether or not we need to open/close
+ // elements.
$prefix2 = str_replace( ';', ':', $prefix );
$t = substr( $oLine, $prefixLength );
$this->mInPre = (bool)$preOpenMatch;
}
}
} elseif( $prefixLength || $lastPrefixLength ) {
+ // We need to open or close prefixes, or both.
+
# Either open or close a level...
$commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
$paragraphStack = false;
+ // Close all the prefixes which aren't shared.
while( $commonPrefixLength < $lastPrefixLength ) {
$output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
--$lastPrefixLength;
}
+
+ // Continue the current prefix if appropriate.
if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
$output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
}
+
+ // Open prefixes where appropriate.
while ( $prefixLength > $commonPrefixLength ) {
$char = substr( $prefix, $commonPrefixLength, 1 );
$output .= $this->openList( $char );
}
$lastPrefix = $prefix2;
}
+
+ // If we have no prefixes, go to paragraph mode.
if( 0 == $prefixLength ) {
wfProfileIn( __METHOD__."-paragraph" );
# No prefix (not in list)--go to paragraph mode
$inBlockElem = true;
}
} else if ( !$inBlockElem && !$this->mInPre ) {
- if ( ' ' == $t{0} and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
+ if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
// pre
if ($this->mLastSection !== 'pre') {
$paragraphStack = false;
*
* @private
*/
- function getVariableValue( $index ) {
- global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
+ function getVariableValue( $index, $frame=false ) {
+ global $wgContLang, $wgSitename, $wgServer, $wgServerName;
+ global $wgScriptPath, $wgStylePath;
/**
* Some of these require message or data lookups and can be
wfSuppressWarnings(); // E_STRICT system time bitching
$localTimestamp = date( 'YmdHis', $ts );
$localMonth = date( 'm', $ts );
+ $localMonth1 = date( 'n', $ts );
$localMonthName = date( 'n', $ts );
$localDay = date( 'j', $ts );
$localDay2 = date( 'd', $ts );
switch ( $index ) {
case 'currentmonth':
- return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
+ $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
+ break;
+ case 'currentmonth1':
+ $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
+ break;
case 'currentmonthname':
- return $this->mVarCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
+ $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
+ break;
case 'currentmonthnamegen':
- return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
+ $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
+ break;
case 'currentmonthabbrev':
- return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
+ $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
+ break;
case 'currentday':
- return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
+ $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
+ break;
case 'currentday2':
- return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
+ $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
+ break;
case 'localmonth':
- return $this->mVarCache[$index] = $wgContLang->formatNum( $localMonth );
+ $value = $wgContLang->formatNum( $localMonth );
+ break;
+ case 'localmonth1':
+ $value = $wgContLang->formatNum( $localMonth1 );
+ break;
case 'localmonthname':
- return $this->mVarCache[$index] = $wgContLang->getMonthName( $localMonthName );
+ $value = $wgContLang->getMonthName( $localMonthName );
+ break;
case 'localmonthnamegen':
- return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
+ $value = $wgContLang->getMonthNameGen( $localMonthName );
+ break;
case 'localmonthabbrev':
- return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
+ $value = $wgContLang->getMonthAbbreviation( $localMonthName );
+ break;
case 'localday':
- return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay );
+ $value = $wgContLang->formatNum( $localDay );
+ break;
case 'localday2':
- return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay2 );
+ $value = $wgContLang->formatNum( $localDay2 );
+ break;
case 'pagename':
- return wfEscapeWikiText( $this->mTitle->getText() );
+ $value = wfEscapeWikiText( $this->mTitle->getText() );
+ break;
case 'pagenamee':
- return $this->mTitle->getPartialURL();
+ $value = $this->mTitle->getPartialURL();
+ break;
case 'fullpagename':
- return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
+ $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
+ break;
case 'fullpagenamee':
- return $this->mTitle->getPrefixedURL();
+ $value = $this->mTitle->getPrefixedURL();
+ break;
case 'subpagename':
- return wfEscapeWikiText( $this->mTitle->getSubpageText() );
+ $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
+ break;
case 'subpagenamee':
- return $this->mTitle->getSubpageUrlForm();
+ $value = $this->mTitle->getSubpageUrlForm();
+ break;
case 'basepagename':
- return wfEscapeWikiText( $this->mTitle->getBaseText() );
+ $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
+ break;
case 'basepagenamee':
- return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
+ $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
+ break;
case 'talkpagename':
if( $this->mTitle->canTalk() ) {
$talkPage = $this->mTitle->getTalkPage();
- return wfEscapeWikiText( $talkPage->getPrefixedText() );
+ $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
} else {
- return '';
+ $value = '';
}
+ break;
case 'talkpagenamee':
if( $this->mTitle->canTalk() ) {
$talkPage = $this->mTitle->getTalkPage();
- return $talkPage->getPrefixedUrl();
+ $value = $talkPage->getPrefixedUrl();
} else {
- return '';
+ $value = '';
}
+ break;
case 'subjectpagename':
$subjPage = $this->mTitle->getSubjectPage();
- return wfEscapeWikiText( $subjPage->getPrefixedText() );
+ $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
+ break;
case 'subjectpagenamee':
$subjPage = $this->mTitle->getSubjectPage();
- return $subjPage->getPrefixedUrl();
+ $value = $subjPage->getPrefixedUrl();
+ break;
case 'revisionid':
// Let the edit saving system know we should parse the page
// *after* a revision ID has been assigned.
$this->mOutput->setFlag( 'vary-revision' );
wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
- return $this->mRevisionId;
+ $value = $this->mRevisionId;
+ break;
case 'revisionday':
// Let the edit saving system know we should parse the page
// *after* a revision ID has been assigned. This is for null edits.
$this->mOutput->setFlag( 'vary-revision' );
wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
- return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
+ $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
+ break;
case 'revisionday2':
// Let the edit saving system know we should parse the page
// *after* a revision ID has been assigned. This is for null edits.
$this->mOutput->setFlag( 'vary-revision' );
wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
- return substr( $this->getRevisionTimestamp(), 6, 2 );
+ $value = substr( $this->getRevisionTimestamp(), 6, 2 );
+ break;
case 'revisionmonth':
// Let the edit saving system know we should parse the page
// *after* a revision ID has been assigned. This is for null edits.
$this->mOutput->setFlag( 'vary-revision' );
wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
- return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
+ $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
+ break;
case 'revisionyear':
// Let the edit saving system know we should parse the page
// *after* a revision ID has been assigned. This is for null edits.
$this->mOutput->setFlag( 'vary-revision' );
wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
- return substr( $this->getRevisionTimestamp(), 0, 4 );
+ $value = substr( $this->getRevisionTimestamp(), 0, 4 );
+ break;
case 'revisiontimestamp':
// Let the edit saving system know we should parse the page
// *after* a revision ID has been assigned. This is for null edits.
$this->mOutput->setFlag( 'vary-revision' );
wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
- return $this->getRevisionTimestamp();
+ $value = $this->getRevisionTimestamp();
+ break;
+ case 'revisionuser':
+ // Let the edit saving system know we should parse the page
+ // *after* a revision ID has been assigned. This is for null edits.
+ $this->mOutput->setFlag( 'vary-revision' );
+ wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
+ $value = $this->getRevisionUser();
+ break;
case 'namespace':
- return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
+ $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
+ break;
case 'namespacee':
- return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
+ $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
+ break;
case 'talkspace':
- return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
+ $value = $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
+ break;
case 'talkspacee':
- return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
+ $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
+ break;
case 'subjectspace':
- return $this->mTitle->getSubjectNsText();
+ $value = $this->mTitle->getSubjectNsText();
+ break;
case 'subjectspacee':
- return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
+ $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
+ break;
case 'currentdayname':
- return $this->mVarCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
+ $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
+ break;
case 'currentyear':
- return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
+ $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
+ break;
case 'currenttime':
- return $this->mVarCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
+ $value = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
+ break;
case 'currenthour':
- return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
+ $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
+ break;
case 'currentweek':
// @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
// int to remove the padding
- return $this->mVarCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
+ $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
+ break;
case 'currentdow':
- return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
+ $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
+ break;
case 'localdayname':
- return $this->mVarCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
+ $value = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
+ break;
case 'localyear':
- return $this->mVarCache[$index] = $wgContLang->formatNum( $localYear, true );
+ $value = $wgContLang->formatNum( $localYear, true );
+ break;
case 'localtime':
- return $this->mVarCache[$index] = $wgContLang->time( $localTimestamp, false, false );
+ $value = $wgContLang->time( $localTimestamp, false, false );
+ break;
case 'localhour':
- return $this->mVarCache[$index] = $wgContLang->formatNum( $localHour, true );
+ $value = $wgContLang->formatNum( $localHour, true );
+ break;
case 'localweek':
// @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
// int to remove the padding
- return $this->mVarCache[$index] = $wgContLang->formatNum( (int)$localWeek );
+ $value = $wgContLang->formatNum( (int)$localWeek );
+ break;
case 'localdow':
- return $this->mVarCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
+ $value = $wgContLang->formatNum( $localDayOfWeek );
+ break;
case 'numberofarticles':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
+ $value = $wgContLang->formatNum( SiteStats::articles() );
+ break;
case 'numberoffiles':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::images() );
+ $value = $wgContLang->formatNum( SiteStats::images() );
+ break;
case 'numberofusers':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::users() );
+ $value = $wgContLang->formatNum( SiteStats::users() );
+ break;
+ case 'numberofactiveusers':
+ $value = $wgContLang->formatNum( SiteStats::activeUsers() );
+ break;
case 'numberofpages':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
+ $value = $wgContLang->formatNum( SiteStats::pages() );
+ break;
case 'numberofadmins':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
+ $value = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
+ break;
case 'numberofedits':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
+ $value = $wgContLang->formatNum( SiteStats::edits() );
+ break;
case 'numberofviews':
- return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::views() );
+ $value = $wgContLang->formatNum( SiteStats::views() );
+ break;
case 'currenttimestamp':
- return $this->mVarCache[$index] = wfTimestamp( TS_MW, $ts );
+ $value = wfTimestamp( TS_MW, $ts );
+ break;
case 'localtimestamp':
- return $this->mVarCache[$index] = $localTimestamp;
+ $value = $localTimestamp;
+ break;
case 'currentversion':
- return $this->mVarCache[$index] = SpecialVersion::getVersion();
+ $value = SpecialVersion::getVersion();
+ break;
case 'sitename':
return $wgSitename;
case 'server':
return $wgContLanguageCode;
default:
$ret = null;
- if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret ) ) )
+ if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) )
return $ret;
else
return null;
}
+
+ if ( $index )
+ $this->mVarCache[$index] = $value;
+
+ return $value;
}
/**
* @private
*/
function replaceVariables( $text, $frame = false, $argsOnly = false ) {
- # Prevent too big inclusions
- if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
+ # Is there any text? Also, Prevent too big inclusions!
+ if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
return $text;
}
-
wfProfileIn( __METHOD__ );
if ( $frame === false ) {
* exceeded, provide the values (optional)
*/
function limitationWarn( $limitationType, $current=null, $max=null) {
- $msgName = $limitationType . '-warning';
//does no harm if $current and $max are present but are unnecessary for the message
- $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
+ $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
$this->mOutput->addWarning( $warning );
- $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
- if ( $cat ) {
- $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
- }
+ $this->addTrackingCategory( "$limitationType-category" );
}
/**
* @private
*/
function braceSubstitution( $piece, $frame ) {
- global $wgContLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
+ global $wgContLang, $wgNonincludableNamespaces;
wfProfileIn( __METHOD__ );
wfProfileIn( __METHOD__.'-setup' );
if ( !$found && $args->getLength() == 0 ) {
$id = $this->mVariables->matchStartToEnd( $part1 );
if ( $id !== false ) {
- $text = $this->getVariableValue( $id );
+ $text = $this->getVariableValue( $id, $frame );
if (MagicWord::getCacheTTL($id)>-1)
$this->mOutput->mContainsOldMagic = true;
$found = true;
$function = $this->mFunctionSynonyms[1][$function];
} else {
# Case insensitive functions
- $function = strtolower( $function );
+ $function = $wgContLang->lc( $function );
if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
$function = $this->mFunctionSynonyms[0][$function];
} else {
# Workaround for PHP bug 35229 and similar
if ( !is_callable( $callback ) ) {
+ wfProfileOut( __METHOD__ . '-pfunc' );
+ wfProfileOut( __METHOD__ );
throw new MWException( "Tag hook for $function is not callable\n" );
}
$result = call_user_func_array( $callback, $allArgs );
if($wgContLang->hasVariants() && $title->getArticleID() == 0){
$wgContLang->findVariantLink( $part1, $title, true );
}
- # Do infinite loop check
- if ( !$frame->loopCheck( $title ) ) {
- $found = true;
- $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
- wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
- }
# Do recursion depth check
$limit = $this->mOptions->getMaxTemplateDepth();
if ( $frame->depth >= $limit ) {
}
$found = true;
}
+
+ # Do infinite loop check
+ # This has to be done after redirect resolution to avoid infinite loops via redirects
+ if ( !$frame->loopCheck( $title ) ) {
+ $found = true;
+ $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
+ wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
+ }
wfProfileOut( __METHOD__ . '-loadtpl' );
}
$marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
- if ( $this->ot['html'] ) {
+ $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
+ ( $this->ot['html'] || $this->ot['pre'] );
+ if ( $this->ot['html'] || $isFunctionTag ) {
$name = strtolower( $name );
-
$attributes = Sanitizer::decodeTagAttributes( $attrText );
if ( isset( $params['attributes'] ) ) {
$attributes = $attributes + $params['attributes'];
$content = strtr($content, array('-{' => '-{', '}-' => '}-'));
$output = Xml::escapeTagsOnly( $content );
break;
- case 'math':
- $output = $wgContLang->armourMath(
- MathRenderer::renderMath( $content, $attributes ) );
- break;
case 'gallery':
$output = $this->renderImageGallery( $content, $attributes );
break;
+ case 'math':
+ if ( $this->mOptions->getUseTeX() ) {
+ $output = $wgContLang->armourMath(
+ MathRenderer::renderMath( $content, $attributes ) );
+ break;
+ }
+ /* else let a tag hook handle it (bug 21222) */
default:
if( isset( $this->mTagHooks[$name] ) ) {
# Workaround for PHP bug 35229 and similar
throw new MWException( "Tag hook for $name is not callable\n" );
}
$output = call_user_func_array( $this->mTagHooks[$name],
- array( $content, $attributes, $this ) );
+ array( $content, $attributes, $this, $frame ) );
+ } elseif( isset( $this->mFunctionTagHooks[$name] ) ) {
+ list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
+ if( !is_callable( $callback ) )
+ throw new MWException( "Tag hook for $name is not callable\n" );
+
+ $output = call_user_func_array( $callback,
+ array( &$this, $frame, $content, $attributes ) );
} else {
$output = '<span class="error">Invalid tag extension name: ' .
htmlspecialchars( $name ) . '</span>';
}
}
- if ( $name === 'html' || $name === 'nowiki' ) {
+ if( $isFunctionTag ) {
+ return $output;
+ } elseif ( $name === 'html' || $name === 'nowiki' ) {
$this->mStripState->nowiki->setPair( $marker, $output );
} else {
$this->mStripState->general->setPair( $marker, $output );
* Fills $this->mDoubleUnderscores, returns the modified text
*/
function doDoubleUnderscore( $text ) {
+ wfProfileIn( __METHOD__ );
// The position of __TOC__ needs to be recorded
$mw = MagicWord::get( 'toc' );
if( $mw->match( $text ) ) {
}
if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
$this->mOutput->setProperty( 'hiddencat', 'y' );
-
- $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
- if ( $containerCategory ) {
- $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
- } else {
- wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
- }
- }
- if ( isset( $this->mDoubleUnderscores['ignoreunused'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
- $this->mOutput->setProperty( 'ignoreunused', 'y' );
+ $this->addTrackingCategory( 'hidden-category-category' );
}
# (bug 8068) Allow control over whether robots index a page.
#
# FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
# is not desirable, the last one on the page should win.
- if( isset( $this->mDoubleUnderscores['noindex'] ) ) {
+ if( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
$this->mOutput->setIndexPolicy( 'noindex' );
- } elseif( isset( $this->mDoubleUnderscores['index'] ) ) {
+ $this->addTrackingCategory( 'noindex-category' );
+ }
+ if( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ){
$this->mOutput->setIndexPolicy( 'index' );
+ $this->addTrackingCategory( 'index-category' );
}
-
+ wfProfileOut( __METHOD__ );
return $text;
+ }
+
+ /**
+ * Add a tracking category, getting the title from a system message,
+ * or print a debug message if the title is invalid.
+ * @param $msg String message key
+ * @return Bool whether the addition was successful
+ */
+ protected function addTrackingCategory( $msg ){
+ $cat = wfMsgForContent( $msg );
+
+ # Allow tracking categories to be disabled by setting them to "-"
+ if( $cat === '-' ) return false;
+
+ $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
+ if ( $containerCategory ) {
+ $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
+ return true;
+ } else {
+ wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
+ return false;
+ }
}
/**
* string and re-inserts the newly formatted headlines.
*
* @param string $text
+ * @param string $origText Original, untouched wikitext
* @param boolean $isMain
* @private
*/
- function formatHeadings( $text, $isMain=true ) {
+ function formatHeadings( $text, $origText, $isMain=true ) {
global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
$doNumberHeadings = $this->mOptions->getNumberHeadings();
}
# Inhibit editsection links if requested in the page
- if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
+ if ( isset( $this->mDoubleUnderscores['noeditsection'] ) || $this->mOptions->getIsPrintable() ) {
$showEditLink = 0;
}
$this->mOutput->setNewSection( true );
}
+ # Allow user to remove the "new section"
+ # link via __NONEWSECTIONLINK__
+ if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
+ $this->mOutput->hideNewSection( true );
+ }
+
# if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
# override above conditions and always show TOC above first header
if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
$prevtoclevel = 0;
$markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
$baseTitleText = $this->mTitle->getPrefixedDBkey();
+ $oldType = $this->mOutputType;
+ $this->setOutputType( self::OT_WIKI );
+ $frame = $this->getPreprocessor()->newFrame();
+ $root = $this->preprocessToDom( $origText );
+ $node = $root->getFirstChild();
+ $byteOffset = 0;
$tocraw = array();
foreach( $matches[3] as $headline ) {
}
$level = $matches[1][$headlineCount];
- if( $doNumberHeadings || $enoughToc ) {
-
- if ( $level > $prevlevel ) {
- # Increase TOC level
- $toclevel++;
- $sublevelCount[$toclevel] = 0;
- if( $toclevel<$wgMaxTocLevel ) {
- $prevtoclevel = $toclevel;
- $toc .= $sk->tocIndent();
- $numVisible++;
- }
+ if ( $level > $prevlevel ) {
+ # Increase TOC level
+ $toclevel++;
+ $sublevelCount[$toclevel] = 0;
+ if( $toclevel<$wgMaxTocLevel ) {
+ $prevtoclevel = $toclevel;
+ $toc .= $sk->tocIndent();
+ $numVisible++;
}
- elseif ( $level < $prevlevel && $toclevel > 1 ) {
- # Decrease TOC level, find level to jump to
+ }
+ elseif ( $level < $prevlevel && $toclevel > 1 ) {
+ # Decrease TOC level, find level to jump to
- if ( $toclevel == 2 && $level <= $levelCount[1] ) {
- # Can only go down to level 1
- $toclevel = 1;
- } else {
- for ($i = $toclevel; $i > 0; $i--) {
- if ( $levelCount[$i] == $level ) {
- # Found last matching level
- $toclevel = $i;
- break;
- }
- elseif ( $levelCount[$i] < $level ) {
- # Found first matching level below current level
- $toclevel = $i + 1;
- break;
- }
- }
+ for ($i = $toclevel; $i > 0; $i--) {
+ if ( $levelCount[$i] == $level ) {
+ # Found last matching level
+ $toclevel = $i;
+ break;
}
- if( $toclevel<$wgMaxTocLevel ) {
- if($prevtoclevel < $wgMaxTocLevel) {
- # Unindent only if the previous toc level was shown :p
- $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
- $prevtoclevel = $toclevel;
- } else {
- $toc .= $sk->tocLineEnd();
- }
+ elseif ( $levelCount[$i] < $level ) {
+ # Found first matching level below current level
+ $toclevel = $i + 1;
+ break;
}
}
- else {
- # No change in level, end TOC line
- if( $toclevel<$wgMaxTocLevel ) {
+ if( $i == 0 ) $toclevel = 1;
+ if( $toclevel<$wgMaxTocLevel ) {
+ if($prevtoclevel < $wgMaxTocLevel) {
+ # Unindent only if the previous toc level was shown :p
+ $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
+ $prevtoclevel = $toclevel;
+ } else {
$toc .= $sk->tocLineEnd();
}
}
+ }
+ else {
+ # No change in level, end TOC line
+ if( $toclevel<$wgMaxTocLevel ) {
+ $toc .= $sk->tocLineEnd();
+ }
+ }
- $levelCount[$toclevel] = $level;
+ $levelCount[$toclevel] = $level;
- # count number of headlines for each level
- @$sublevelCount[$toclevel]++;
- $dot = 0;
- for( $i = 1; $i <= $toclevel; $i++ ) {
- if( !empty( $sublevelCount[$i] ) ) {
- if( $dot ) {
- $numbering .= '.';
- }
- $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
- $dot = 1;
+ # count number of headlines for each level
+ @$sublevelCount[$toclevel]++;
+ $dot = 0;
+ for( $i = 1; $i <= $toclevel; $i++ ) {
+ if( !empty( $sublevelCount[$i] ) ) {
+ if( $dot ) {
+ $numbering .= '.';
}
+ $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
+ $dot = 1;
}
}
# For the anchor, strip out HTML-y stuff period
$safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
+ $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
$safeHeadline = trim( $safeHeadline );
# Save headline for section edit hint before it's escaped
$legacyAnchor .= '_' . $refers[$legacyArrayKey];
}
if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
- $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
- $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
+ $toc .= $sk->tocLine($anchor, $tocline,
+ $numbering, $toclevel, ($isTemplate ? false : $sectionIndex));
}
+
+ # Add the section to the section tree
+ # Find the DOM node for this header
+ while ( $node && !$isTemplate ) {
+ if ( $node->getName() === 'h' ) {
+ $bits = $node->splitHeading();
+ if ( $bits['i'] == $sectionIndex )
+ break;
+ }
+ $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
+ $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
+ $node = $node->getNextSibling();
+ }
+ $tocraw[] = array(
+ 'toclevel' => $toclevel,
+ 'level' => $level,
+ 'line' => $tocline,
+ 'number' => $numbering,
+ 'index' => ($isTemplate ? 'T-' : '' ) . $sectionIndex,
+ 'fromtitle' => $titleText,
+ 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
+ 'anchor' => $anchor,
+ );
+
# give headline the correct <h#> tag
if( $showEditLink && $sectionIndex !== false ) {
if( $isTemplate ) {
$headlineCount++;
}
- $this->mOutput->setSections( $tocraw );
+ $this->setOutputType( $oldType );
# Never ever show TOC if no headers
if( $numVisible < 1 ) {
$toc .= $sk->tocUnindent( $prevtoclevel - 1 );
}
$toc = $sk->tocList( $toc );
+ $this->mOutput->setTOCHTML( $toc );
+ }
+
+ if ( $isMain ) {
+ $this->mOutput->setSections( $tocraw );
}
# split up and insert constructed headlines
$blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
$i = 0;
-
+
foreach( $blocks as $block ) {
if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
# This is the [edit] link that appears for the top block of text when
return $full;
}
}
-
+
+ /**
+ * Merge $tree2 into $tree1 by replacing the section with index
+ * $section in $tree1 and its descendants with the sections in $tree2.
+ * Note that in the returned section tree, only the 'index' and
+ * 'byteoffset' fields are guaranteed to be correct.
+ * @param $tree1 array Section tree from ParserOutput::getSectons()
+ * @param $tree2 array Section tree
+ * @param $section int Section index
+ * @param $title Title Title both section trees come from
+ * @param $len2 int Length of the original wikitext for $tree2
+ * @return array Merged section tree
+ */
+ public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
+ global $wgContLang;
+ $newTree = array();
+ $targetLevel = false;
+ $merged = false;
+ $lastLevel = 1;
+ $nextIndex = 1;
+ $numbering = array( 0 );
+ $titletext = $title->getPrefixedDBkey();
+ foreach ( $tree1 as $s ) {
+ if ( $targetLevel !== false ) {
+ if ( $s['level'] <= $targetLevel )
+ // We've skipped enough
+ $targetLevel = false;
+ else
+ continue;
+ }
+ if ( $s['index'] != $section ||
+ $s['fromtitle'] != $titletext ) {
+ self::incrementNumbering( $numbering,
+ $s['toclevel'], $lastLevel );
+
+ // Rewrite index, byteoffset and number
+ if ( $s['fromtitle'] == $titletext ) {
+ $s['index'] = $nextIndex++;
+ if ( $merged )
+ $s['byteoffset'] += $len2;
+ }
+ $s['number'] = implode( '.', array_map(
+ array( $wgContLang, 'formatnum' ),
+ $numbering ) );
+ $lastLevel = $s['toclevel'];
+ $newTree[] = $s;
+ } else {
+ // We're at $section
+ // Insert sections from $tree2 here
+ foreach ( $tree2 as $s2 ) {
+ // Rewrite the fields in $s2
+ // before inserting it
+ $s2['toclevel'] += $s['toclevel'] - 1;
+ $s2['level'] += $s['level'] - 1;
+ $s2['index'] = $nextIndex++;
+ $s2['byteoffset'] += $s['byteoffset'];
+
+ self::incrementNumbering( $numbering,
+ $s2['toclevel'], $lastLevel );
+ $s2['number'] = implode( '.', array_map(
+ array( $wgContLang, 'formatnum' ),
+ $numbering ) );
+ $lastLevel = $s2['toclevel'];
+ $newTree[] = $s2;
+ }
+ // Skip all descendants of $section in $tree1
+ $targetLevel = $s['level'];
+ $merged = true;
+ }
+ }
+ return $newTree;
+ }
+
+ /**
+ * Increment a section number. Helper function for mergeSectionTrees()
+ * @param $number array Array representing a section number
+ * @param $level int Current TOC level (depth)
+ * @param $lastLevel int Level of previous TOC entry
+ */
+ private static function incrementNumbering( &$number, $level, $lastLevel ) {
+ if ( $level > $lastLevel )
+ $number[$level - 1] = 1;
+ else if ( $level < $lastLevel ) {
+ foreach ( $number as $key => $unused )
+ if ( $key >= $level )
+ unset( $number[$key] );
+ $number[$level - 1]++;
+ } else
+ $number[$level - 1]++;
+ }
+
/**
* Transform wiki markup when saving a page by doing \r\n -> \n
* conversion, substitting signatures, {{subst:}} templates, etc.
*
* @param string $text the text to transform
* @param Title &$title the Title object for the current article
- * @param User &$user the User object describing the current user
+ * @param User $user the User object describing the current user
* @param ParserOptions $options parsing options
* @param bool $clearState whether to clear the parser state first
* @return string the altered wiki markup
* @public
*/
- function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
+ function preSaveTransform( $text, Title $title, $user, $options, $clearState = true ) {
$this->mOptions = $options;
$this->setTitle( $title );
$this->setOutputType( self::OT_WIKI );
putenv( 'TZ='.$wgLocaltimezone );
$ts = date( 'YmdHis', $unixts );
$tz = date( 'T', $unixts ); # might vary on DST changeover!
+
+ /* Allow translation of timezones trough wiki. date() can return
+ * whatever crap the system uses, localised or not, so we cannot
+ * ship premade translations.
+ */
+ $key = 'timezone-' . strtolower( trim( $tz ) );
+ $value = wfMsgForContent( $key );
+ if ( !wfEmptyMsg( $key, $value ) ) $tz = $value;
+
putenv( 'TZ='.$oldtz );
}
/**
* Fetch the user's signature text, if any, and normalize to
* validated, ready-to-insert wikitext.
+ * If you have pre-fetched the nickname or the fancySig option, you can
+ * specify them here to save a database query.
*
* @param User $user
* @return string
- * @private
*/
- function getUserSig( &$user ) {
+ function getUserSig( &$user, $nickname = false, $fancySig = null ) {
global $wgMaxSigChars;
$username = $user->getName();
- $nickname = $user->getOption( 'nickname' );
- $nickname = $nickname === '' ? $username : $nickname;
+
+ // If not given, retrieve from the user object.
+ if ( $nickname === false )
+ $nickname = $user->getOption( 'nickname' );
+
+ if ( is_null( $fancySig ) )
+ $fancySig = $user->getBoolOption( 'fancysig' );
+
+ $nickname = $nickname == null ? $username : $nickname;
if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
$nickname = $username;
wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
- } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
+ } elseif( $fancySig !== false ) {
# Sig. might contain markup; validate this
if( $this->validateSig( $nickname ) !== false ) {
# Validated; clean up (if needed) and return it
* @return The old callback function for this name, if any
*/
function setFunctionHook( $id, $callback, $flags = 0 ) {
+ global $wgContLang;
+
$oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
$this->mFunctionHooks[$id] = array( $callback, $flags );
foreach ( $synonyms as $syn ) {
# Case
if ( !$sensitive ) {
- $syn = strtolower( $syn );
+ $syn = $wgContLang->lc( $syn );
}
# Add leading hash
if ( !( $flags & SFH_NO_HASH ) ) {
}
/**
+ * Create a tag function, e.g. <test>some stuff</test>.
+ * Unlike tag hooks, tag functions are parsed at preprocessor level.
+ * Unlike parser functions, their content is not preprocessed.
+ */
+ function setFunctionTagHook( $tag, $callback, $flags ) {
+ $tag = strtolower( $tag );
+ $old = isset( $this->mFunctionTagHooks[$tag] ) ?
+ $this->mFunctionTagHooks[$tag] : null;
+ $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
+
+ if( !in_array( $tag, $this->mStripList ) ) {
+ $this->mStripList[] = $tag;
+ }
+
+ return $old;
+ }
+
+ /**
+ * FIXME: update documentation. makeLinkObj() is deprecated.
* Replace <!--LINK--> link placeholders with actual links, in the buffer
* Placeholders created in Skin::makeLinkObj()
* Returns an array of link CSS classes, indexed by PDBK.
# * none same, but not aligned
# * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
# * center center the image
- # * framed Keep original image size, no magnify-button.
+ # * frame Keep original image size, no magnify-button.
+ # * framed Same as "frame"
# * frameless like 'thumb' but without a frame. Keeps user preferences for width
# * upright reduce width for upright images, rounded to full __0 px
# * border draw a 1px border around the image
# * alt Text for HTML alt attribute (defaults to empty)
+ # * link Set the target of the image link. Can be external, interwiki, or local
# vertical-align values (no % or length right now):
# * baseline
# * sub
# Get the file
$imagename = $title->getDBkey();
- if ( isset( $this->mFileCache[$imagename][$time] ) ) {
- $file = $this->mFileCache[$imagename][$time];
- } else {
- $file = wfFindFile( $title, $time );
- if ( count( $this->mFileCache ) > 1000 ) {
- $this->mFileCache = array();
- }
- $this->mFileCache[$imagename][$time] = $file;
- }
+ $file = wfFindFile( $title, array( 'time' => $time ) );
# Get parameter map
$handler = $file ? $file->getHandler() : false;
$params['frame']['caption'] = $caption;
- $params['frame']['title'] = $this->stripAltText( $caption, $holders );
+ # Will the image be presented in a frame, with the caption below?
+ $imageIsFramed = isset( $params['frame']['frame'] ) ||
+ isset( $params['frame']['framed'] ) ||
+ isset( $params['frame']['thumbnail'] ) ||
+ isset( $params['frame']['manualthumb'] );
# In the old days, [[Image:Foo|text...]] would set alt text. Later it
# came to also set the caption, ordinary text after the image -- which
# named parameter entirely for images without a caption; adding an ex-
# plicit caption= parameter and preserving the old magic unnamed para-
# meter for BC; ...
- if( $caption !== '' && !isset( $params['frame']['alt'] )
- && !isset( $params['frame']['framed'] )
- && !isset( $params['frame']['thumbnail'] )
- && !isset( $params['frame']['manualthumb'] ) ) {
- $params['frame']['alt'] = $params['frame']['title'];
+ if ( $imageIsFramed ) { # Framed image
+ if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
+ # No caption or alt text, add the filename as the alt text so
+ # that screen readers at least get some description of the image
+ $params['frame']['alt'] = $title->getText();
+ }
+ # Do not set $params['frame']['title'] because tooltips don't make sense
+ # for framed images
+ } else { # Inline image
+ if ( !isset( $params['frame']['alt'] ) ) {
+ # No alt text, use the "caption" for the alt text
+ if ( $caption !== '') {
+ $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
+ } else {
+ # No caption, fall back to using the filename for the
+ # alt text
+ $params['frame']['alt'] = $title->getText();
+ }
+ }
+ # Use the "caption" for the tooltip text
+ $params['frame']['title'] = $this->stripAltText( $caption, $holders );
}
wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
// Output the replacement text
// Add two newlines on -- trailing whitespace in $newText is conventionally
// stripped by the editor, so we need both newlines to restore the paragraph gap
- $outText .= $newText . "\n\n";
+ // Only add trailing whitespace if there is newText
+ if($newText != "") {
+ $outText .= $newText . "\n\n";
+ }
+
while ( $node ) {
$outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
$node = $node->getNextSibling();
return $this->mRevisionTimestamp;
}
+ /**
+ * Get the name of the user that edited the last revision
+ */
+ function getRevisionUser() {
+ // if this template is subst: the revision id will be blank,
+ // so just use the current user's name
+ if( $this->mRevisionId ) {
+ $revision = Revision::newFromId( $this->mRevisionId );
+ $revuser = $revision->getUserText();
+ } else {
+ global $wgUser;
+ $revuser = $wgUser->getName();
+ }
+ return $revuser;
+ }
+
/**
* Mutator for $mDefaultSort
*
}
return $out;
}
+
+ function serialiseHalfParsedText( $text ) {
+ $data = array();
+ $data['text'] = $text;
+
+ // First, find all strip markers, and store their
+ // data in an array.
+ $stripState = new StripState;
+ $pos = 0;
+ while( ( $start_pos = strpos( $text, $this->mUniqPrefix, $pos ) ) && ( $end_pos = strpos( $text, self::MARKER_SUFFIX, $pos ) ) ) {
+ $end_pos += strlen( self::MARKER_SUFFIX );
+ $marker = substr( $text, $start_pos, $end_pos-$start_pos );
+
+ if ( !empty( $this->mStripState->general->data[$marker] ) ) {
+ $replaceArray = $stripState->general;
+ $stripText = $this->mStripState->general->data[$marker];
+ } elseif ( !empty( $this->mStripState->nowiki->data[$marker] ) ) {
+ $replaceArray = $stripState->nowiki;
+ $stripText = $this->mStripState->nowiki->data[$marker];
+ } else {
+ throw new MWException( "Hanging strip marker: '$marker'." );
+ }
+
+ $replaceArray->setPair( $marker, $stripText );
+ $pos = $end_pos;
+ }
+ $data['stripstate'] = $stripState;
+
+ // Now, find all of our links, and store THEIR
+ // data in an array! :)
+ $links = array( 'internal' => array(), 'interwiki' => array() );
+ $pos = 0;
+
+ // Internal links
+ while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
+ list( $ns, $trail ) = explode( ':', substr( $text, $start_pos + strlen( '<!--LINK ' ) ), 2 );
+
+ $ns = trim($ns);
+ if (empty( $links['internal'][$ns] )) {
+ $links['internal'][$ns] = array();
+ }
+
+ $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
+ $links['internal'][$ns][] = $this->mLinkHolders->internals[$ns][$key];
+ $pos = $start_pos + strlen( "<!--LINK $ns:$key-->" );
+ }
+
+ $pos = 0;
+
+ // Interwiki links
+ while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
+ $data = substr( $text, $start_pos );
+ $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
+ $links['interwiki'][] = $this->mLinkHolders->interwiki[$key];
+ $pos = $start_pos + strlen( "<!--IWLINK $key-->" );
+ }
+
+ $data['linkholder'] = $links;
+
+ return $data;
+ }
+
+ function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
+ if (!$intPrefix)
+ $intPrefix = $this->getRandomString();
+
+ // First, extract the strip state.
+ $stripState = $data['stripstate'];
+ $this->mStripState->general->merge( $stripState->general );
+ $this->mStripState->nowiki->merge( $stripState->nowiki );
+
+ // Now, extract the text, and renumber links
+ $text = $data['text'];
+ $links = $data['linkholder'];
+
+ // Internal...
+ foreach( $links['internal'] as $ns => $nsLinks ) {
+ foreach( $nsLinks as $key => $entry ) {
+ $newKey = $intPrefix . '-' . $key;
+ $this->mLinkHolders->internals[$ns][$newKey] = $entry;
+
+ $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
+ }
+ }
+
+ // Interwiki...
+ foreach( $links['interwiki'] as $key => $entry ) {
+ $newKey = "$intPrefix-$key";
+ $this->mLinkHolders->interwikis[$newKey] = $entry;
+
+ $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
+ }
+
+ // Should be good to go.
+ return $text;
+ }
}
/**