3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
17 * Variable substitution O(N^2) attack
19 * Without countermeasures, it would be possible to attack the parser by saving
20 * a page filled with a large number of inclusions of large pages. The size of
21 * the generated page would be proportional to the square of the input size.
22 * Hence, we limit the number of inclusions of any given page, thus bringing any
23 * attack back to O(N).
26 define( 'MAX_INCLUDE_REPEAT', 100 );
27 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
29 define( 'RLH_FOR_UPDATE', 1 );
31 # Allowed values for $mOutputType
32 define( 'OT_HTML', 1 );
33 define( 'OT_WIKI', 2 );
34 define( 'OT_MSG' , 3 );
36 # Flags for setFunctionHook
37 define( 'SFH_NO_HASH', 1 );
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45 # Constants needed for external link processing
46 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
47 # Everything except bracket, space, or control characters
48 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
49 # Including space, but excluding newlines
50 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
51 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
52 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
53 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
54 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
61 // State constants for the definition list colon extraction
62 define( 'MW_COLON_STATE_TEXT', 0 );
63 define( 'MW_COLON_STATE_TAG', 1 );
64 define( 'MW_COLON_STATE_TAGSTART', 2 );
65 define( 'MW_COLON_STATE_CLOSETAG', 3 );
66 define( 'MW_COLON_STATE_TAGSLASH', 4 );
67 define( 'MW_COLON_STATE_COMMENT', 5 );
68 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
69 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
74 * Processes wiki markup
77 * There are three main entry points into the Parser class:
79 * produces HTML output
81 * produces altered wiki markup.
83 * performs brace substitution on MediaWiki messages
86 * objects: $wgLang, $wgContLang
88 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
91 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
92 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
93 * $wgLocaltimezone, $wgAllowSpecialInclusion*
95 * * only within ParserOptions
106 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
108 # Cleared with clearState():
109 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
110 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
111 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
112 var $mTemplates, // cache of already loaded templates, avoids
113 // multiple SQL queries for the same string
114 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
115 // in this path. Used for loop detection.
118 # These are variables reset at least once per parse regardless of $clearState
119 var $mOptions, // ParserOptions object
120 $mTitle, // Title context, used for self-link rendering and similar things
121 $mOutputType, // Output type, one of the OT_xxx constants
122 $mRevisionId; // ID to display in {{REVISIONID}} tags
132 $this->mTagHooks
= array();
133 $this->mFunctionHooks
= array();
134 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
135 $this->mFirstCall
= true;
139 * Do various kinds of initialisation on the first call of the parser
141 function firstCallInit() {
142 if ( !$this->mFirstCall
) {
146 wfProfileIn( __METHOD__
);
147 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
149 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
151 $this->setFunctionHook( MAG_NS
, array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
152 $this->setFunctionHook( MAG_URLENCODE
, array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
153 $this->setFunctionHook( MAG_LCFIRST
, array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
154 $this->setFunctionHook( MAG_UCFIRST
, array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
155 $this->setFunctionHook( MAG_LC
, array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
156 $this->setFunctionHook( MAG_UC
, array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
157 $this->setFunctionHook( MAG_LOCALURL
, array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
158 $this->setFunctionHook( MAG_LOCALURLE
, array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
159 $this->setFunctionHook( MAG_FULLURL
, array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
160 $this->setFunctionHook( MAG_FULLURLE
, array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
161 $this->setFunctionHook( MAG_FORMATNUM
, array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
162 $this->setFunctionHook( MAG_GRAMMAR
, array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
163 $this->setFunctionHook( MAG_PLURAL
, array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
164 $this->setFunctionHook( MAG_NUMBEROFPAGES
, array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
165 $this->setFunctionHook( MAG_NUMBEROFUSERS
, array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
166 $this->setFunctionHook( MAG_NUMBEROFARTICLES
, array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
167 $this->setFunctionHook( MAG_NUMBEROFFILES
, array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
168 $this->setFunctionHook( MAG_NUMBEROFADMINS
, array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
169 $this->setFunctionHook( MAG_LANGUAGE
, array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
171 if ( $wgAllowDisplayTitle ) {
172 $this->setFunctionHook( MAG_DISPLAYTITLE
, array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
174 if ( $wgAllowSlowParserFunctions ) {
175 $this->setFunctionHook( MAG_PAGESINNAMESPACE
, array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
178 $this->initialiseVariables();
180 $this->mFirstCall
= false;
181 wfProfileOut( __METHOD__
);
189 function clearState() {
190 if ( $this->mFirstCall
) {
191 $this->firstCallInit();
193 $this->mOutput
= new ParserOutput
;
194 $this->mAutonumber
= 0;
195 $this->mLastSection
= '';
196 $this->mDTopen
= false;
197 $this->mIncludeCount
= array();
198 $this->mStripState
= array();
199 $this->mArgStack
= array();
200 $this->mInPre
= false;
201 $this->mInterwikiLinkHolders
= array(
205 $this->mLinkHolders
= array(
206 'namespaces' => array(),
208 'queries' => array(),
212 $this->mRevisionId
= null;
215 * Prefix for temporary replacement strings for the multipass parser.
216 * \x07 should never appear in input as it's disallowed in XML.
217 * Using it at the front also gives us a little extra robustness
218 * since it shouldn't match when butted up against identifier-like
221 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
223 # Clear these on every parse, bug 4549
224 $this->mTemplates
= array();
225 $this->mTemplatePath
= array();
227 $this->mShowToc
= true;
228 $this->mForceTocPosition
= false;
230 wfRunHooks( 'ParserClearState', array( &$this ) );
234 * Accessor for mUniqPrefix.
238 function UniqPrefix() {
239 return $this->mUniqPrefix
;
243 * Convert wikitext to HTML
244 * Do not call this function recursively.
247 * @param string $text Text we want to parse
248 * @param Title &$title A title object
249 * @param array $options
250 * @param boolean $linestart
251 * @param boolean $clearState
252 * @param int $revid number to pass in {{REVISIONID}}
253 * @return ParserOutput a ParserOutput
255 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
257 * First pass--just handle <nowiki> sections, pass the rest off
258 * to internalParse() which does all the real work.
261 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
262 $fname = 'Parser::parse';
263 wfProfileIn( $fname );
269 $this->mOptions
= $options;
270 $this->mTitle
=& $title;
271 $this->mRevisionId
= $revid;
272 $this->mOutputType
= OT_HTML
;
274 //$text = $this->strip( $text, $this->mStripState );
275 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
276 $x =& $this->mStripState
;
278 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
279 $text = $this->strip( $text, $x );
280 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
282 # Hook to suspend the parser in this state
283 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
284 wfProfileOut( $fname );
288 $text = $this->internalParse( $text );
290 $text = $this->unstrip( $text, $this->mStripState
);
292 # Clean up special characters, only run once, next-to-last before doBlockLevels
294 # french spaces, last one Guillemet-left
295 # only if there is something before the space
296 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
297 # french spaces, Guillemet-right
298 '/(\\302\\253) /' => '\\1 ',
300 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
303 $text = $this->doBlockLevels( $text, $linestart );
305 $this->replaceLinkHolders( $text );
307 # the position of the parserConvert() call should not be changed. it
308 # assumes that the links are all replaced and the only thing left
309 # is the <nowiki> mark.
310 # Side-effects: this calls $this->mOutput->setTitleText()
311 $text = $wgContLang->parserConvert( $text, $this );
313 $text = $this->unstripNoWiki( $text, $this->mStripState
);
315 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
317 $text = Sanitizer
::normalizeCharReferences( $text );
319 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
320 $text = Parser
::tidy($text);
322 # attempt to sanitize at least some nesting problems
323 # (bug #2702 and quite a few others)
325 # ''Something [http://www.cool.com cool''] -->
326 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
327 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
328 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
329 # fix up an anchor inside another anchor, only
330 # at least for a single single nested link (bug 3695)
331 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
332 '\\1\\2</a>\\3</a>\\1\\4</a>',
333 # fix div inside inline elements- doBlockLevels won't wrap a line which
334 # contains a div, so fix it up here; replace
335 # div with escaped text
336 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
337 '\\1\\3<div\\5>\\6</div>\\8\\9',
338 # remove empty italic or bold tag pairs, some
339 # introduced by rules above
340 '/<([bi])><\/\\1>/' => ''
343 $text = preg_replace(
344 array_keys( $tidyregs ),
345 array_values( $tidyregs ),
349 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
351 $this->mOutput
->setText( $text );
352 wfProfileOut( $fname );
354 return $this->mOutput
;
358 * Get a random string
363 function getRandomString() {
364 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
367 function &getTitle() { return $this->mTitle
; }
368 function getOptions() { return $this->mOptions
; }
370 function getFunctionLang() {
371 global $wgLang, $wgContLang;
372 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
376 * Replaces all occurrences of HTML-style comments and the given tags
377 * in the text with a random marker and returns teh next text. The output
378 * parameter $matches will be an associative array filled with data in
380 * 'UNIQ-xxxxx' => array(
383 * array( 'param' => 'x' ),
384 * '<element param="x">tag content</element>' ) )
386 * @param $elements list of element names. Comments are always extracted.
387 * @param $text Source text string.
388 * @param $uniq_prefix
393 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
394 $rand = Parser
::getRandomString();
399 $taglist = implode( '|', $elements );
400 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
402 while ( '' != $text ) {
403 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
405 if( count( $p ) < 5 ) {
408 if( count( $p ) > 5 ) {
422 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
) . '-QINU';
423 $stripped .= $marker;
425 if ( $close === '/>' ) {
426 // Empty element tag, <tag />
431 if( $element == '!--' ) {
434 $end = "/(<\\/$element\\s*>)/i";
436 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
438 if( count( $q ) < 3 ) {
439 # No end tag -- let it run out to the end of the text.
448 $matches[$marker] = array( $element,
450 Sanitizer
::decodeTagAttributes( $attributes ),
451 "<$element$attributes$close$content$tail" );
457 * Strips and renders nowiki, pre, math, hiero
458 * If $render is set, performs necessary rendering operations on plugins
459 * Returns the text, and fills an array with data needed in unstrip()
460 * If the $state is already a valid strip state, it adds to the state
462 * @param bool $stripcomments when set, HTML comments <!-- like this -->
463 * will be stripped in addition to other tags. This is important
464 * for section editing, where these comments cause confusion when
465 * counting the sections in the wikisource
467 * @param array dontstrip contains tags which should not be stripped;
468 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
472 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
473 $render = ($this->mOutputType
== OT_HTML
);
475 # Replace any instances of the placeholders
476 $uniq_prefix = $this->mUniqPrefix
;
477 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
478 $commentState = array();
480 $elements = array_merge(
481 array( 'nowiki', 'gallery' ),
482 array_keys( $this->mTagHooks
) );
485 $elements[] = 'html';
487 if( $this->mOptions
->getUseTeX() ) {
488 $elements[] = 'math';
491 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
492 foreach ( $elements AS $k => $v ) {
493 if ( !in_array ( $v , $dontstrip ) ) continue;
494 unset ( $elements[$k] );
498 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
500 foreach( $matches as $marker => $data ) {
501 list( $element, $content, $params, $tag ) = $data;
503 $tagName = strtolower( $element );
507 if( substr( $tag, -3 ) == '-->' ) {
510 // Unclosed comment in input.
511 // Close it so later stripping can remove it
520 // Shouldn't happen otherwise. :)
522 $output = wfEscapeHTMLTagsOnly( $content );
525 $output = MathRenderer
::renderMath( $content );
528 $output = $this->renderImageGallery( $content, $params );
531 if( isset( $this->mTagHooks
[$tagName] ) ) {
532 $output = call_user_func_array( $this->mTagHooks
[$tagName],
533 array( $content, $params, $this ) );
535 throw new MWException( "Invalid call hook $element" );
539 // Just stripping tags; keep the source
542 if( !$stripcomments && $element == '!--' ) {
543 $commentState[$marker] = $output;
545 $state[$element][$marker] = $output;
549 # Unstrip comments unless explicitly told otherwise.
550 # (The comments are always stripped prior to this point, so as to
551 # not invoke any extension tags / parser hooks contained within
553 if ( !$stripcomments ) {
554 // Put them all back and forget them
555 $text = strtr( $text, $commentState );
562 * Restores pre, math, and other extensions removed by strip()
564 * always call unstripNoWiki() after this one
567 function unstrip( $text, &$state ) {
568 if ( !is_array( $state ) ) {
572 $replacements = array();
573 foreach( $state as $tag => $contentDict ) {
574 if( $tag != 'nowiki' && $tag != 'html' ) {
575 foreach( $contentDict as $uniq => $content ) {
576 $replacements[$uniq] = $content;
580 $text = strtr( $text, $replacements );
586 * Always call this after unstrip() to preserve the order
590 function unstripNoWiki( $text, &$state ) {
591 if ( !is_array( $state ) ) {
595 $replacements = array();
596 foreach( $state as $tag => $contentDict ) {
597 if( $tag == 'nowiki' ||
$tag == 'html' ) {
598 foreach( $contentDict as $uniq => $content ) {
599 $replacements[$uniq] = $content;
603 $text = strtr( $text, $replacements );
609 * Add an item to the strip state
610 * Returns the unique tag which must be inserted into the stripped text
611 * The tag will be replaced with the original text in unstrip()
615 function insertStripItem( $text, &$state ) {
616 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
620 $state['item'][$rnd] = $text;
625 * Interface with html tidy, used if $wgUseTidy = true.
626 * If tidy isn't able to correct the markup, the original will be
627 * returned in all its glory with a warning comment appended.
629 * Either the external tidy program or the in-process tidy extension
630 * will be used depending on availability. Override the default
631 * $wgTidyInternal setting to disable the internal if it's not working.
633 * @param string $text Hideous HTML input
634 * @return string Corrected HTML output
638 function tidy( $text ) {
639 global $wgTidyInternal;
640 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
641 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
642 '<head><title>test</title></head><body>'.$text.'</body></html>';
643 if( $wgTidyInternal ) {
644 $correctedtext = Parser
::internalTidy( $wrappedtext );
646 $correctedtext = Parser
::externalTidy( $wrappedtext );
648 if( is_null( $correctedtext ) ) {
649 wfDebug( "Tidy error detected!\n" );
650 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
652 return $correctedtext;
656 * Spawn an external HTML tidy process and get corrected markup back from it.
661 function externalTidy( $text ) {
662 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
663 $fname = 'Parser::externalTidy';
664 wfProfileIn( $fname );
669 $descriptorspec = array(
670 0 => array('pipe', 'r'),
671 1 => array('pipe', 'w'),
672 2 => array('file', '/dev/null', 'a')
675 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
676 if (is_resource($process)) {
677 // Theoretically, this style of communication could cause a deadlock
678 // here. If the stdout buffer fills up, then writes to stdin could
679 // block. This doesn't appear to happen with tidy, because tidy only
680 // writes to stdout after it's finished reading from stdin. Search
681 // for tidyParseStdin and tidySaveStdout in console/tidy.c
682 fwrite($pipes[0], $text);
684 while (!feof($pipes[1])) {
685 $cleansource .= fgets($pipes[1], 1024);
688 proc_close($process);
691 wfProfileOut( $fname );
693 if( $cleansource == '' && $text != '') {
694 // Some kind of error happened, so we couldn't get the corrected text.
695 // Just give up; we'll use the source text and append a warning.
703 * Use the HTML tidy PECL extension to use the tidy library in-process,
704 * saving the overhead of spawning a new process. Currently written to
705 * the PHP 4.3.x version of the extension, may not work on PHP 5.
707 * 'pear install tidy' should be able to compile the extension module.
712 function internalTidy( $text ) {
714 $fname = 'Parser::internalTidy';
715 wfProfileIn( $fname );
717 tidy_load_config( $wgTidyConf );
718 tidy_set_encoding( 'utf8' );
719 tidy_parse_string( $text );
721 if( tidy_get_status() == 2 ) {
722 // 2 is magic number for fatal error
723 // http://www.php.net/manual/en/function.tidy-get-status.php
726 $cleansource = tidy_get_output();
728 wfProfileOut( $fname );
733 * parse the wiki syntax used to render tables
737 function doTableStuff ( $t ) {
738 $fname = 'Parser::doTableStuff';
739 wfProfileIn( $fname );
741 $t = explode ( "\n" , $t ) ;
742 $td = array () ; # Is currently a td tag open?
743 $ltd = array () ; # Was it TD or TH?
744 $tr = array () ; # Is currently a tr tag open?
745 $ltr = array () ; # tr attributes
746 $has_opened_tr = array(); # Did this table open a <tr> element?
747 $indent_level = 0; # indent level of the table
748 foreach ( $t AS $k => $x )
751 $fc = substr ( $x , 0 , 1 ) ;
752 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
753 $indent_level = strlen( $matches[1] );
755 $attributes = $this->unstripForHTML( $matches[2] );
757 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
758 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
759 array_push ( $td , false ) ;
760 array_push ( $ltd , '' ) ;
761 array_push ( $tr , false ) ;
762 array_push ( $ltr , '' ) ;
763 array_push ( $has_opened_tr, false );
765 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
766 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
767 $z = "</table>" . substr ( $x , 2);
768 $l = array_pop ( $ltd ) ;
769 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
770 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
771 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
773 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
775 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
776 $x = substr ( $x , 1 ) ;
777 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
779 $l = array_pop ( $ltd ) ;
780 array_pop ( $has_opened_tr );
781 array_push ( $has_opened_tr , true ) ;
782 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
783 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
786 array_push ( $tr , false ) ;
787 array_push ( $td , false ) ;
788 array_push ( $ltd , '' ) ;
789 $attributes = $this->unstripForHTML( $x );
790 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
792 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
794 if ( '|+' == substr ( $x , 0 , 2 ) ) {
796 $x = substr ( $x , 1 ) ;
798 $after = substr ( $x , 1 ) ;
799 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
801 // Split up multiple cells on the same line.
802 // FIXME: This can result in improper nesting of tags processed
803 // by earlier parser steps, but should avoid splitting up eg
804 // attribute values containing literal "||".
805 $after = wfExplodeMarkup( '||', $after );
809 # Loop through each table cell
810 foreach ( $after AS $theline )
815 $tra = array_pop ( $ltr ) ;
816 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
817 array_push ( $tr , true ) ;
818 array_push ( $ltr , '' ) ;
819 array_pop ( $has_opened_tr );
820 array_push ( $has_opened_tr , true ) ;
823 $l = array_pop ( $ltd ) ;
824 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
825 if ( $fc == '|' ) $l = 'td' ;
826 else if ( $fc == '!' ) $l = 'th' ;
827 else if ( $fc == '+' ) $l = 'caption' ;
829 array_push ( $ltd , $l ) ;
832 $y = explode ( '|' , $theline , 2 ) ;
833 # Note that a '|' inside an invalid link should not
834 # be mistaken as delimiting cell parameters
835 if ( strpos( $y[0], '[[' ) !== false ) {
836 $y = array ($theline);
838 if ( count ( $y ) == 1 )
839 $y = "{$z}<{$l}>{$y[0]}" ;
841 $attributes = $this->unstripForHTML( $y[0] );
842 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
845 array_push ( $td , true ) ;
850 # Closing open td, tr && table
851 while ( count ( $td ) > 0 )
853 $l = array_pop ( $ltd ) ;
854 if ( array_pop ( $td ) ) $t[] = '</td>' ;
855 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
856 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
860 $t = implode ( "\n" , $t ) ;
861 # special case: don't return empty table
862 if($t == "<table>\n<tr><td></td></tr>\n</table>")
864 wfProfileOut( $fname );
869 * Helper function for parse() that transforms wiki markup into
870 * HTML. Only called for $mOutputType == OT_HTML.
874 function internalParse( $text ) {
877 $fname = 'Parser::internalParse';
878 wfProfileIn( $fname );
880 # Remove <noinclude> tags and <includeonly> sections
881 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
882 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
883 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
885 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
887 $text = $this->replaceVariables( $text, $args );
889 // Tables need to come after variable replacement for things to work
890 // properly; putting them before other transformations should keep
891 // exciting things like link expansions from showing up in surprising
893 $text = $this->doTableStuff( $text );
895 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
897 $text = $this->stripToc( $text );
898 $this->stripNoGallery( $text );
899 $text = $this->doHeadings( $text );
900 if($this->mOptions
->getUseDynamicDates()) {
901 $df =& DateFormatter
::getInstance();
902 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
904 $text = $this->doAllQuotes( $text );
905 $text = $this->replaceInternalLinks( $text );
906 $text = $this->replaceExternalLinks( $text );
908 # replaceInternalLinks may sometimes leave behind
909 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
910 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
912 $text = $this->doMagicLinks( $text );
913 $text = $this->formatHeadings( $text, $isMain );
915 wfProfileOut( $fname );
920 * Replace special strings like "ISBN xxx" and "RFC xxx" with
921 * magic external links.
925 function &doMagicLinks( &$text ) {
926 $text = $this->magicISBN( $text );
927 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
928 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
933 * Parse headers and return html
937 function doHeadings( $text ) {
938 $fname = 'Parser::doHeadings';
939 wfProfileIn( $fname );
940 for ( $i = 6; $i >= 1; --$i ) {
941 $h = str_repeat( '=', $i );
942 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
943 "<h{$i}>\\1</h{$i}>\\2", $text );
945 wfProfileOut( $fname );
950 * Replace single quotes with HTML markup
952 * @return string the altered text
954 function doAllQuotes( $text ) {
955 $fname = 'Parser::doAllQuotes';
956 wfProfileIn( $fname );
958 $lines = explode( "\n", $text );
959 foreach ( $lines as $line ) {
960 $outtext .= $this->doQuotes ( $line ) . "\n";
962 $outtext = substr($outtext, 0,-1);
963 wfProfileOut( $fname );
968 * Helper function for doAllQuotes()
971 function doQuotes( $text ) {
972 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
973 if ( count( $arr ) == 1 )
977 # First, do some preliminary work. This may shift some apostrophes from
978 # being mark-up to being text. It also counts the number of occurrences
979 # of bold and italics mark-ups.
983 foreach ( $arr as $r )
985 if ( ( $i %
2 ) == 1 )
987 # If there are ever four apostrophes, assume the first is supposed to
988 # be text, and the remaining three constitute mark-up for bold text.
989 if ( strlen( $arr[$i] ) == 4 )
994 # If there are more than 5 apostrophes in a row, assume they're all
995 # text except for the last 5.
996 else if ( strlen( $arr[$i] ) > 5 )
998 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1001 # Count the number of occurrences of bold and italics mark-ups.
1002 # We are not counting sequences of five apostrophes.
1003 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
1004 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
1005 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1010 # If there is an odd number of both bold and italics, it is likely
1011 # that one of the bold ones was meant to be an apostrophe followed
1012 # by italics. Which one we cannot know for certain, but it is more
1013 # likely to be one that has a single-letter word before it.
1014 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1017 $firstsingleletterword = -1;
1018 $firstmultiletterword = -1;
1020 foreach ( $arr as $r )
1022 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1024 $x1 = substr ($arr[$i-1], -1);
1025 $x2 = substr ($arr[$i-1], -2, 1);
1027 if ($firstspace == -1) $firstspace = $i;
1028 } else if ($x2 == ' ') {
1029 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1031 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1037 # If there is a single-letter word, use it!
1038 if ($firstsingleletterword > -1)
1040 $arr [ $firstsingleletterword ] = "''";
1041 $arr [ $firstsingleletterword-1 ] .= "'";
1043 # If not, but there's a multi-letter word, use that one.
1044 else if ($firstmultiletterword > -1)
1046 $arr [ $firstmultiletterword ] = "''";
1047 $arr [ $firstmultiletterword-1 ] .= "'";
1049 # ... otherwise use the first one that has neither.
1050 # (notice that it is possible for all three to be -1 if, for example,
1051 # there is only one pentuple-apostrophe in the line)
1052 else if ($firstspace > -1)
1054 $arr [ $firstspace ] = "''";
1055 $arr [ $firstspace-1 ] .= "'";
1059 # Now let's actually convert our apostrophic mush to HTML!
1064 foreach ($arr as $r)
1068 if ($state == 'both')
1075 if (strlen ($r) == 2)
1078 { $output .= '</i>'; $state = ''; }
1079 else if ($state == 'bi')
1080 { $output .= '</i>'; $state = 'b'; }
1081 else if ($state == 'ib')
1082 { $output .= '</b></i><b>'; $state = 'b'; }
1083 else if ($state == 'both')
1084 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1085 else # $state can be 'b' or ''
1086 { $output .= '<i>'; $state .= 'i'; }
1088 else if (strlen ($r) == 3)
1091 { $output .= '</b>'; $state = ''; }
1092 else if ($state == 'bi')
1093 { $output .= '</i></b><i>'; $state = 'i'; }
1094 else if ($state == 'ib')
1095 { $output .= '</b>'; $state = 'i'; }
1096 else if ($state == 'both')
1097 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1098 else # $state can be 'i' or ''
1099 { $output .= '<b>'; $state .= 'b'; }
1101 else if (strlen ($r) == 5)
1104 { $output .= '</b><i>'; $state = 'i'; }
1105 else if ($state == 'i')
1106 { $output .= '</i><b>'; $state = 'b'; }
1107 else if ($state == 'bi')
1108 { $output .= '</i></b>'; $state = ''; }
1109 else if ($state == 'ib')
1110 { $output .= '</b></i>'; $state = ''; }
1111 else if ($state == 'both')
1112 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1113 else # ($state == '')
1114 { $buffer = ''; $state = 'both'; }
1119 # Now close all remaining tags. Notice that the order is important.
1120 if ($state == 'b' ||
$state == 'ib')
1122 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1126 if ($state == 'both')
1127 $output .= '<b><i>'.$buffer.'</i></b>';
1133 * Replace external links
1135 * Note: this is all very hackish and the order of execution matters a lot.
1136 * Make sure to run maintenance/parserTests.php if you change this code.
1140 function replaceExternalLinks( $text ) {
1142 $fname = 'Parser::replaceExternalLinks';
1143 wfProfileIn( $fname );
1145 $sk =& $this->mOptions
->getSkin();
1147 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1149 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1152 while ( $i<count( $bits ) ) {
1154 $protocol = $bits[$i++
];
1155 $text = $bits[$i++
];
1156 $trail = $bits[$i++
];
1158 # The characters '<' and '>' (which were escaped by
1159 # removeHTMLtags()) should not be included in
1160 # URLs, per RFC 2396.
1161 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1162 $text = substr($url, $m2[0][1]) . ' ' . $text;
1163 $url = substr($url, 0, $m2[0][1]);
1166 # If the link text is an image URL, replace it with an <img> tag
1167 # This happened by accident in the original parser, but some people used it extensively
1168 $img = $this->maybeMakeExternalImage( $text );
1169 if ( $img !== false ) {
1175 # Set linktype for CSS - if URL==text, link is essentially free
1176 $linktype = ($text == $url) ?
'free' : 'text';
1178 # No link text, e.g. [http://domain.tld/some.link]
1179 if ( $text == '' ) {
1180 # Autonumber if allowed. See bug #5918
1181 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1182 $text = '[' . ++
$this->mAutonumber
. ']';
1183 $linktype = 'autonumber';
1185 # Otherwise just use the URL
1186 $text = htmlspecialchars( $url );
1190 # Have link text, e.g. [http://domain.tld/some.link text]s
1192 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1195 $text = $wgContLang->markNoConversion($text);
1197 # Normalize any HTML entities in input. They will be
1198 # re-escaped by makeExternalLink().
1199 $url = Sanitizer
::decodeCharReferences( $url );
1201 # Escape any control characters introduced by the above step
1202 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1204 # Process the trail (i.e. everything after this link up until start of the next link),
1205 # replacing any non-bracketed links
1206 $trail = $this->replaceFreeExternalLinks( $trail );
1208 # Use the encoded URL
1209 # This means that users can paste URLs directly into the text
1210 # Funny characters like ö aren't valid in URLs anyway
1211 # This was changed in August 2004
1212 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1214 # Register link in the output object.
1215 # Replace unnecessary URL escape codes with the referenced character
1216 # This prevents spammers from hiding links from the filters
1217 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1218 $this->mOutput
->addExternalLink( $pasteurized );
1221 wfProfileOut( $fname );
1226 * Replace anything that looks like a URL with a link
1229 function replaceFreeExternalLinks( $text ) {
1231 $fname = 'Parser::replaceFreeExternalLinks';
1232 wfProfileIn( $fname );
1234 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1235 $s = array_shift( $bits );
1238 $sk =& $this->mOptions
->getSkin();
1240 while ( $i < count( $bits ) ){
1241 $protocol = $bits[$i++
];
1242 $remainder = $bits[$i++
];
1244 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1245 # Found some characters after the protocol that look promising
1246 $url = $protocol . $m[1];
1249 # special case: handle urls as url args:
1250 # http://www.example.com/foo?=http://www.example.com/bar
1251 if(strlen($trail) == 0 &&
1253 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1254 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1257 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1262 # The characters '<' and '>' (which were escaped by
1263 # removeHTMLtags()) should not be included in
1264 # URLs, per RFC 2396.
1265 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1266 $trail = substr($url, $m2[0][1]) . $trail;
1267 $url = substr($url, 0, $m2[0][1]);
1270 # Move trailing punctuation to $trail
1272 # If there is no left bracket, then consider right brackets fair game too
1273 if ( strpos( $url, '(' ) === false ) {
1277 $numSepChars = strspn( strrev( $url ), $sep );
1278 if ( $numSepChars ) {
1279 $trail = substr( $url, -$numSepChars ) . $trail;
1280 $url = substr( $url, 0, -$numSepChars );
1283 # Normalize any HTML entities in input. They will be
1284 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1285 $url = Sanitizer
::decodeCharReferences( $url );
1287 # Escape any control characters introduced by the above step
1288 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1290 # Is this an external image?
1291 $text = $this->maybeMakeExternalImage( $url );
1292 if ( $text === false ) {
1293 # Not an image, make a link
1294 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1295 # Register it in the output object...
1296 # Replace unnecessary URL escape codes with their equivalent characters
1297 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1298 $this->mOutput
->addExternalLink( $pasteurized );
1300 $s .= $text . $trail;
1302 $s .= $protocol . $remainder;
1305 wfProfileOut( $fname );
1310 * Replace unusual URL escape codes with their equivalent characters
1314 * @fixme This can merge genuinely required bits in the path or query string,
1315 * breaking legit URLs. A proper fix would treat the various parts of
1316 * the URL differently; as a workaround, just use the output for
1317 * statistical records, not for actual linking/output.
1319 function replaceUnusualEscapes( $url ) {
1320 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1321 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1325 * Callback function used in replaceUnusualEscapes().
1326 * Replaces unusual URL escape codes with their equivalent character
1330 function replaceUnusualEscapesCallback( $matches ) {
1331 $char = urldecode( $matches[0] );
1332 $ord = ord( $char );
1333 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1334 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1335 // No, shouldn't be escaped
1338 // Yes, leave it escaped
1344 * make an image if it's allowed, either through the global
1345 * option or through the exception
1348 function maybeMakeExternalImage( $url ) {
1349 $sk =& $this->mOptions
->getSkin();
1350 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1351 $imagesexception = !empty($imagesfrom);
1353 if ( $this->mOptions
->getAllowExternalImages()
1354 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1355 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1357 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1364 * Process [[ ]] wikilinks
1368 function replaceInternalLinks( $s ) {
1370 static $fname = 'Parser::replaceInternalLinks' ;
1372 wfProfileIn( $fname );
1374 wfProfileIn( $fname.'-setup' );
1376 # the % is needed to support urlencoded titles as well
1377 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1379 $sk =& $this->mOptions
->getSkin();
1381 #split the entire text string on occurences of [[
1382 $a = explode( '[[', ' ' . $s );
1383 #get the first element (all text up to first [[), and remove the space we added
1384 $s = array_shift( $a );
1385 $s = substr( $s, 1 );
1387 # Match a link having the form [[namespace:link|alternate]]trail
1389 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1390 # Match cases where there is no "]]", which might still be images
1391 static $e1_img = FALSE;
1392 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1393 # Match the end of a line for a word that's not followed by whitespace,
1394 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1395 $e2 = wfMsgForContent( 'linkprefix' );
1397 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1399 if( is_null( $this->mTitle
) ) {
1400 throw new MWException( 'nooo' );
1402 $nottalk = !$this->mTitle
->isTalkPage();
1404 if ( $useLinkPrefixExtension ) {
1405 if ( preg_match( $e2, $s, $m ) ) {
1406 $first_prefix = $m[2];
1408 $first_prefix = false;
1414 $selflink = $this->mTitle
->getPrefixedText();
1415 wfProfileOut( $fname.'-setup' );
1417 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1418 $useSubpages = $this->areSubpagesAllowed();
1420 # Loop for each link
1421 for ($k = 0; isset( $a[$k] ); $k++
) {
1423 if ( $useLinkPrefixExtension ) {
1424 wfProfileIn( $fname.'-prefixhandling' );
1425 if ( preg_match( $e2, $s, $m ) ) {
1433 $prefix = $first_prefix;
1434 $first_prefix = false;
1436 wfProfileOut( $fname.'-prefixhandling' );
1439 $might_be_img = false;
1441 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1443 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1444 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1445 # the real problem is with the $e1 regex
1448 # Still some problems for cases where the ] is meant to be outside punctuation,
1449 # and no image is in sight. See bug 2095.
1452 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1453 strpos($text, '[') !== false
1456 $text .= ']'; # so that replaceExternalLinks($text) works later
1459 # fix up urlencoded title texts
1460 if(preg_match('/%/', $m[1] ))
1461 # Should anchors '#' also be rejected?
1462 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1464 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1465 $might_be_img = true;
1467 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1469 } else { # Invalid form; output directly
1470 $s .= $prefix . '[[' . $line ;
1474 # Don't allow internal links to pages containing
1475 # PROTO: where PROTO is a valid URL protocol; these
1476 # should be external links.
1477 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1478 $s .= $prefix . '[[' . $line ;
1482 # Make subpage if necessary
1483 if( $useSubpages ) {
1484 $link = $this->maybeDoSubpageLink( $m[1], $text );
1489 $noforce = (substr($m[1], 0, 1) != ':');
1491 # Strip off leading ':'
1492 $link = substr($link, 1);
1495 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1497 $s .= $prefix . '[[' . $line;
1501 #check other language variants of the link
1502 #if the article does not exist
1503 if( $checkVariantLink
1504 && $nt->getArticleID() == 0 ) {
1505 $wgContLang->findVariantLink($link, $nt);
1508 $ns = $nt->getNamespace();
1509 $iw = $nt->getInterWiki();
1511 if ($might_be_img) { # if this is actually an invalid link
1512 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1514 while (isset ($a[$k+
1]) ) {
1515 #look at the next 'line' to see if we can close it there
1516 $spliced = array_splice( $a, $k +
1, 1 );
1517 $next_line = array_shift( $spliced );
1518 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1519 # the first ]] closes the inner link, the second the image
1521 $text .= '[[' . $m[1];
1524 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1525 #if there's exactly one ]] that's fine, we'll keep looking
1526 $text .= '[[' . $m[0];
1528 #if $next_line is invalid too, we need look no further
1529 $text .= '[[' . $next_line;
1534 # we couldn't find the end of this imageLink, so output it raw
1535 #but don't ignore what might be perfectly normal links in the text we've examined
1536 $text = $this->replaceInternalLinks($text);
1537 $s .= $prefix . '[[' . $link . '|' . $text;
1538 # note: no $trail, because without an end, there *is* no trail
1541 } else { #it's not an image, so output it raw
1542 $s .= $prefix . '[[' . $link . '|' . $text;
1543 # note: no $trail, because without an end, there *is* no trail
1548 $wasblank = ( '' == $text );
1549 if( $wasblank ) $text = $link;
1552 # Link not escaped by : , create the various objects
1556 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1557 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1558 $s = rtrim($s . "\n");
1559 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1563 if ( $ns == NS_IMAGE
) {
1564 wfProfileIn( "$fname-image" );
1565 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1566 # recursively parse links inside the image caption
1567 # actually, this will parse them in any other parameters, too,
1568 # but it might be hard to fix that, and it doesn't matter ATM
1569 $text = $this->replaceExternalLinks($text);
1570 $text = $this->replaceInternalLinks($text);
1572 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1573 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1574 $this->mOutput
->addImage( $nt->getDBkey() );
1576 wfProfileOut( "$fname-image" );
1579 # We still need to record the image's presence on the page
1580 $this->mOutput
->addImage( $nt->getDBkey() );
1582 wfProfileOut( "$fname-image" );
1586 if ( $ns == NS_CATEGORY
) {
1587 wfProfileIn( "$fname-category" );
1588 $s = rtrim($s . "\n"); # bug 87
1591 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1592 $sortkey = $this->mTitle
->getText();
1594 $sortkey = $this->mTitle
->getPrefixedText();
1599 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1600 $sortkey = str_replace( "\n", '', $sortkey );
1601 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1602 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1605 * Strip the whitespace Category links produce, see bug 87
1606 * @todo We might want to use trim($tmp, "\n") here.
1608 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1610 wfProfileOut( "$fname-category" );
1615 if( ( $nt->getPrefixedText() === $selflink ) &&
1616 ( $nt->getFragment() === '' ) ) {
1617 # Self-links are handled specially; generally de-link and change to bold.
1618 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1622 # Special and Media are pseudo-namespaces; no pages actually exist in them
1623 if( $ns == NS_MEDIA
) {
1624 $link = $sk->makeMediaLinkObj( $nt, $text );
1625 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1626 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1627 $this->mOutput
->addImage( $nt->getDBkey() );
1629 } elseif( $ns == NS_SPECIAL
) {
1630 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1632 } elseif( $ns == NS_IMAGE
) {
1633 $img = Image
::newFromTitle( $nt );
1634 if( $img->exists() ) {
1635 // Force a blue link if the file exists; may be a remote
1636 // upload on the shared repository, and we want to see its
1637 // auto-generated page.
1638 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1642 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1644 wfProfileOut( $fname );
1649 * Make a link placeholder. The text returned can be later resolved to a real link with
1650 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1651 * parsing of interwiki links, and secondly to allow all extistence checks and
1652 * article length checks (for stub links) to be bundled into a single query.
1655 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1656 if ( ! is_object($nt) ) {
1658 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1660 # Separate the link trail from the rest of the link
1661 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1663 if ( $nt->isExternal() ) {
1664 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1665 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1666 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1668 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1669 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1670 $this->mLinkHolders
['queries'][] = $query;
1671 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1672 $this->mLinkHolders
['titles'][] = $nt;
1674 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1681 * Render a forced-blue link inline; protect against double expansion of
1682 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1683 * Since this little disaster has to split off the trail text to avoid
1684 * breaking URLs in the following text without breaking trails on the
1685 * wiki links, it's been made into a horrible function.
1688 * @param string $text
1689 * @param string $query
1690 * @param string $trail
1691 * @param string $prefix
1692 * @return string HTML-wikitext mix oh yuck
1694 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1695 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1696 $sk =& $this->mOptions
->getSkin();
1697 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1698 return $this->armorLinks( $link ) . $trail;
1702 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1703 * going to go through further parsing steps before inline URL expansion.
1705 * In particular this is important when using action=render, which causes
1706 * full URLs to be included.
1708 * Oh man I hate our multi-layer parser!
1710 * @param string more-or-less HTML
1711 * @return string less-or-more HTML with NOPARSE bits
1713 function armorLinks( $text ) {
1714 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1715 "{$this->mUniqPrefix}NOPARSE$1", $text );
1719 * Return true if subpage links should be expanded on this page.
1722 function areSubpagesAllowed() {
1723 # Some namespaces don't allow subpages
1724 global $wgNamespacesWithSubpages;
1725 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1729 * Handle link to subpage if necessary
1730 * @param string $target the source of the link
1731 * @param string &$text the link text, modified as necessary
1732 * @return string the full name of the link
1735 function maybeDoSubpageLink($target, &$text) {
1738 # :Foobar -- override special treatment of prefix (images, language links)
1739 # /Foobar -- convert to CurrentPage/Foobar
1740 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1741 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1742 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1744 $fname = 'Parser::maybeDoSubpageLink';
1745 wfProfileIn( $fname );
1746 $ret = $target; # default return value is no change
1748 # Some namespaces don't allow subpages,
1749 # so only perform processing if subpages are allowed
1750 if( $this->areSubpagesAllowed() ) {
1751 # Look at the first character
1752 if( $target != '' && $target{0} == '/' ) {
1753 # / at end means we don't want the slash to be shown
1754 if( substr( $target, -1, 1 ) == '/' ) {
1755 $target = substr( $target, 1, -1 );
1758 $noslash = substr( $target, 1 );
1761 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1762 if( '' === $text ) {
1764 } # this might be changed for ugliness reasons
1766 # check for .. subpage backlinks
1768 $nodotdot = $target;
1769 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1771 $nodotdot = substr( $nodotdot, 3 );
1773 if($dotdotcount > 0) {
1774 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1775 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1776 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1777 # / at the end means don't show full path
1778 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1779 $nodotdot = substr( $nodotdot, 0, -1 );
1780 if( '' === $text ) {
1784 $nodotdot = trim( $nodotdot );
1785 if( $nodotdot != '' ) {
1786 $ret .= '/' . $nodotdot;
1793 wfProfileOut( $fname );
1798 * Used by doBlockLevels()
1801 /* private */ function closeParagraph() {
1803 if ( '' != $this->mLastSection
) {
1804 $result = '</' . $this->mLastSection
. ">\n";
1806 $this->mInPre
= false;
1807 $this->mLastSection
= '';
1810 # getCommon() returns the length of the longest common substring
1811 # of both arguments, starting at the beginning of both.
1813 /* private */ function getCommon( $st1, $st2 ) {
1814 $fl = strlen( $st1 );
1815 $shorter = strlen( $st2 );
1816 if ( $fl < $shorter ) { $shorter = $fl; }
1818 for ( $i = 0; $i < $shorter; ++
$i ) {
1819 if ( $st1{$i} != $st2{$i} ) { break; }
1823 # These next three functions open, continue, and close the list
1824 # element appropriate to the prefix character passed into them.
1826 /* private */ function openList( $char ) {
1827 $result = $this->closeParagraph();
1829 if ( '*' == $char ) { $result .= '<ul><li>'; }
1830 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1831 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1832 else if ( ';' == $char ) {
1833 $result .= '<dl><dt>';
1834 $this->mDTopen
= true;
1836 else { $result = '<!-- ERR 1 -->'; }
1841 /* private */ function nextItem( $char ) {
1842 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1843 else if ( ':' == $char ||
';' == $char ) {
1845 if ( $this->mDTopen
) { $close = '</dt>'; }
1846 if ( ';' == $char ) {
1847 $this->mDTopen
= true;
1848 return $close . '<dt>';
1850 $this->mDTopen
= false;
1851 return $close . '<dd>';
1854 return '<!-- ERR 2 -->';
1857 /* private */ function closeList( $char ) {
1858 if ( '*' == $char ) { $text = '</li></ul>'; }
1859 else if ( '#' == $char ) { $text = '</li></ol>'; }
1860 else if ( ':' == $char ) {
1861 if ( $this->mDTopen
) {
1862 $this->mDTopen
= false;
1863 $text = '</dt></dl>';
1865 $text = '</dd></dl>';
1868 else { return '<!-- ERR 3 -->'; }
1874 * Make lists from lines starting with ':', '*', '#', etc.
1877 * @return string the lists rendered as HTML
1879 function doBlockLevels( $text, $linestart ) {
1880 $fname = 'Parser::doBlockLevels';
1881 wfProfileIn( $fname );
1883 # Parsing through the text line by line. The main thing
1884 # happening here is handling of block-level elements p, pre,
1885 # and making lists from lines starting with * # : etc.
1887 $textLines = explode( "\n", $text );
1889 $lastPrefix = $output = '';
1890 $this->mDTopen
= $inBlockElem = false;
1892 $paragraphStack = false;
1894 if ( !$linestart ) {
1895 $output .= array_shift( $textLines );
1897 foreach ( $textLines as $oLine ) {
1898 $lastPrefixLength = strlen( $lastPrefix );
1899 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1900 $preOpenMatch = preg_match('/<pre/i', $oLine );
1901 if ( !$this->mInPre
) {
1902 # Multiple prefixes may abut each other for nested lists.
1903 $prefixLength = strspn( $oLine, '*#:;' );
1904 $pref = substr( $oLine, 0, $prefixLength );
1907 $pref2 = str_replace( ';', ':', $pref );
1908 $t = substr( $oLine, $prefixLength );
1909 $this->mInPre
= !empty($preOpenMatch);
1911 # Don't interpret any other prefixes in preformatted text
1913 $pref = $pref2 = '';
1918 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1919 # Same as the last item, so no need to deal with nesting or opening stuff
1920 $output .= $this->nextItem( substr( $pref, -1 ) );
1921 $paragraphStack = false;
1923 if ( substr( $pref, -1 ) == ';') {
1924 # The one nasty exception: definition lists work like this:
1925 # ; title : definition text
1926 # So we check for : in the remainder text to split up the
1927 # title and definition, without b0rking links.
1929 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1931 $output .= $term . $this->nextItem( ':' );
1934 } elseif( $prefixLength ||
$lastPrefixLength ) {
1935 # Either open or close a level...
1936 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1937 $paragraphStack = false;
1939 while( $commonPrefixLength < $lastPrefixLength ) {
1940 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1941 --$lastPrefixLength;
1943 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1944 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1946 while ( $prefixLength > $commonPrefixLength ) {
1947 $char = substr( $pref, $commonPrefixLength, 1 );
1948 $output .= $this->openList( $char );
1950 if ( ';' == $char ) {
1951 # FIXME: This is dupe of code above
1952 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1954 $output .= $term . $this->nextItem( ':' );
1957 ++
$commonPrefixLength;
1959 $lastPrefix = $pref2;
1961 if( 0 == $prefixLength ) {
1962 wfProfileIn( "$fname-paragraph" );
1963 # No prefix (not in list)--go to paragraph mode
1964 // XXX: use a stack for nestable elements like span, table and div
1965 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1966 $closematch = preg_match(
1967 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1968 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1969 if ( $openmatch or $closematch ) {
1970 $paragraphStack = false;
1971 #Â TODO bug 5718: paragraph closed
1972 $output .= $this->closeParagraph();
1973 if ( $preOpenMatch and !$preCloseMatch ) {
1974 $this->mInPre
= true;
1976 if ( $closematch ) {
1977 $inBlockElem = false;
1979 $inBlockElem = true;
1981 } else if ( !$inBlockElem && !$this->mInPre
) {
1982 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1984 if ($this->mLastSection
!= 'pre') {
1985 $paragraphStack = false;
1986 $output .= $this->closeParagraph().'<pre>';
1987 $this->mLastSection
= 'pre';
1989 $t = substr( $t, 1 );
1992 if ( '' == trim($t) ) {
1993 if ( $paragraphStack ) {
1994 $output .= $paragraphStack.'<br />';
1995 $paragraphStack = false;
1996 $this->mLastSection
= 'p';
1998 if ($this->mLastSection
!= 'p' ) {
1999 $output .= $this->closeParagraph();
2000 $this->mLastSection
= '';
2001 $paragraphStack = '<p>';
2003 $paragraphStack = '</p><p>';
2007 if ( $paragraphStack ) {
2008 $output .= $paragraphStack;
2009 $paragraphStack = false;
2010 $this->mLastSection
= 'p';
2011 } else if ($this->mLastSection
!= 'p') {
2012 $output .= $this->closeParagraph().'<p>';
2013 $this->mLastSection
= 'p';
2018 wfProfileOut( "$fname-paragraph" );
2020 // somewhere above we forget to get out of pre block (bug 785)
2021 if($preCloseMatch && $this->mInPre
) {
2022 $this->mInPre
= false;
2024 if ($paragraphStack === false) {
2028 while ( $prefixLength ) {
2029 $output .= $this->closeList( $pref2{$prefixLength-1} );
2032 if ( '' != $this->mLastSection
) {
2033 $output .= '</' . $this->mLastSection
. '>';
2034 $this->mLastSection
= '';
2037 wfProfileOut( $fname );
2042 * Split up a string on ':', ignoring any occurences inside tags
2043 * to prevent illegal overlapping.
2044 * @param string $str the string to split
2045 * @param string &$before set to everything before the ':'
2046 * @param string &$after set to everything after the ':'
2047 * return string the position of the ':', or false if none found
2049 function findColonNoLinks($str, &$before, &$after) {
2050 $fname = 'Parser::findColonNoLinks';
2051 wfProfileIn( $fname );
2053 $pos = strpos( $str, ':' );
2054 if( $pos === false ) {
2056 wfProfileOut( $fname );
2060 $lt = strpos( $str, '<' );
2061 if( $lt === false ||
$lt > $pos ) {
2062 // Easy; no tag nesting to worry about
2063 $before = substr( $str, 0, $pos );
2064 $after = substr( $str, $pos+
1 );
2065 wfProfileOut( $fname );
2069 // Ugly state machine to walk through avoiding tags.
2070 $state = MW_COLON_STATE_TEXT
;
2072 $len = strlen( $str );
2073 for( $i = 0; $i < $len; $i++
) {
2077 // (Using the number is a performance hack for common cases)
2078 case 0: // MW_COLON_STATE_TEXT:
2081 // Could be either a <start> tag or an </end> tag
2082 $state = MW_COLON_STATE_TAGSTART
;
2087 $before = substr( $str, 0, $i );
2088 $after = substr( $str, $i +
1 );
2089 wfProfileOut( $fname );
2092 // Embedded in a tag; don't break it.
2095 // Skip ahead looking for something interesting
2096 $colon = strpos( $str, ':', $i );
2097 if( $colon === false ) {
2098 // Nothing else interesting
2099 wfProfileOut( $fname );
2102 $lt = strpos( $str, '<', $i );
2103 if( $stack === 0 ) {
2104 if( $lt === false ||
$colon < $lt ) {
2106 $before = substr( $str, 0, $colon );
2107 $after = substr( $str, $colon +
1 );
2108 wfProfileOut( $fname );
2112 if( $lt === false ) {
2113 // Nothing else interesting to find; abort!
2114 // We're nested, but there's no close tags left. Abort!
2117 // Skip ahead to next tag start
2119 $state = MW_COLON_STATE_TAGSTART
;
2122 case 1: // MW_COLON_STATE_TAG:
2127 $state = MW_COLON_STATE_TEXT
;
2130 // Slash may be followed by >?
2131 $state = MW_COLON_STATE_TAGSLASH
;
2137 case 2: // MW_COLON_STATE_TAGSTART:
2140 $state = MW_COLON_STATE_CLOSETAG
;
2143 $state = MW_COLON_STATE_COMMENT
;
2146 // Illegal early close? This shouldn't happen D:
2147 $state = MW_COLON_STATE_TEXT
;
2150 $state = MW_COLON_STATE_TAG
;
2153 case 3: // MW_COLON_STATE_CLOSETAG:
2158 wfDebug( "Invalid input in $fname; too many close tags\n" );
2159 wfProfileOut( $fname );
2162 $state = MW_COLON_STATE_TEXT
;
2165 case MW_COLON_STATE_TAGSLASH
:
2167 // Yes, a self-closed tag <blah/>
2168 $state = MW_COLON_STATE_TEXT
;
2170 // Probably we're jumping the gun, and this is an attribute
2171 $state = MW_COLON_STATE_TAG
;
2174 case 5: // MW_COLON_STATE_COMMENT:
2176 $state = MW_COLON_STATE_COMMENTDASH
;
2179 case MW_COLON_STATE_COMMENTDASH
:
2181 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2183 $state = MW_COLON_STATE_COMMENT
;
2186 case MW_COLON_STATE_COMMENTDASHDASH
:
2188 $state = MW_COLON_STATE_TEXT
;
2190 $state = MW_COLON_STATE_COMMENT
;
2194 throw new MWException( "State machine error in $fname" );
2198 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2201 wfProfileOut( $fname );
2206 * Return value of a magic variable (like PAGENAME)
2210 function getVariableValue( $index ) {
2211 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2214 * Some of these require message or data lookups and can be
2215 * expensive to check many times.
2217 static $varCache = array();
2218 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2219 if ( isset( $varCache[$index] ) )
2220 return $varCache[$index];
2223 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2226 case MAG_CURRENTMONTH
:
2227 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2228 case MAG_CURRENTMONTHNAME
:
2229 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2230 case MAG_CURRENTMONTHNAMEGEN
:
2231 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2232 case MAG_CURRENTMONTHABBREV
:
2233 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2234 case MAG_CURRENTDAY
:
2235 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2236 case MAG_CURRENTDAY2
:
2237 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2239 return $this->mTitle
->getText();
2241 return $this->mTitle
->getPartialURL();
2242 case MAG_FULLPAGENAME
:
2243 return $this->mTitle
->getPrefixedText();
2244 case MAG_FULLPAGENAMEE
:
2245 return $this->mTitle
->getPrefixedURL();
2246 case MAG_SUBPAGENAME
:
2247 return $this->mTitle
->getSubpageText();
2248 case MAG_SUBPAGENAMEE
:
2249 return $this->mTitle
->getSubpageUrlForm();
2250 case MAG_BASEPAGENAME
:
2251 return $this->mTitle
->getBaseText();
2252 case MAG_BASEPAGENAMEE
:
2253 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2254 case MAG_TALKPAGENAME
:
2255 if( $this->mTitle
->canTalk() ) {
2256 $talkPage = $this->mTitle
->getTalkPage();
2257 return $talkPage->getPrefixedText();
2261 case MAG_TALKPAGENAMEE
:
2262 if( $this->mTitle
->canTalk() ) {
2263 $talkPage = $this->mTitle
->getTalkPage();
2264 return $talkPage->getPrefixedUrl();
2268 case MAG_SUBJECTPAGENAME
:
2269 $subjPage = $this->mTitle
->getSubjectPage();
2270 return $subjPage->getPrefixedText();
2271 case MAG_SUBJECTPAGENAMEE
:
2272 $subjPage = $this->mTitle
->getSubjectPage();
2273 return $subjPage->getPrefixedUrl();
2274 case MAG_REVISIONID
:
2275 return $this->mRevisionId
;
2277 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2278 case MAG_NAMESPACEE
:
2279 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2281 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2282 case MAG_TALKSPACEE
:
2283 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2284 case MAG_SUBJECTSPACE
:
2285 return $this->mTitle
->getSubjectNsText();
2286 case MAG_SUBJECTSPACEE
:
2287 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2288 case MAG_CURRENTDAYNAME
:
2289 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2290 case MAG_CURRENTYEAR
:
2291 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2292 case MAG_CURRENTTIME
:
2293 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2294 case MAG_CURRENTWEEK
:
2295 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2296 // int to remove the padding
2297 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2298 case MAG_CURRENTDOW
:
2299 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2300 case MAG_NUMBEROFARTICLES
:
2301 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2302 case MAG_NUMBEROFFILES
:
2303 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2304 case MAG_NUMBEROFUSERS
:
2305 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2306 case MAG_NUMBEROFPAGES
:
2307 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2308 case MAG_NUMBEROFADMINS
:
2309 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2310 case MAG_CURRENTTIMESTAMP
:
2311 return $varCache[$index] = wfTimestampNow();
2312 case MAG_CURRENTVERSION
:
2319 case MAG_SERVERNAME
:
2320 return $wgServerName;
2321 case MAG_SCRIPTPATH
:
2322 return $wgScriptPath;
2323 case MAG_DIRECTIONMARK
:
2324 return $wgContLang->getDirMark();
2325 case MAG_CONTENTLANGUAGE
:
2326 global $wgContLanguageCode;
2327 return $wgContLanguageCode;
2330 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2338 * initialise the magic variables (like CURRENTMONTHNAME)
2342 function initialiseVariables() {
2343 $fname = 'Parser::initialiseVariables';
2344 wfProfileIn( $fname );
2345 global $wgVariableIDs;
2347 $this->mVariables
= array();
2348 foreach ( $wgVariableIDs as $id ) {
2349 $mw =& MagicWord
::get( $id );
2350 $mw->addToArray( $this->mVariables
, $id );
2352 wfProfileOut( $fname );
2356 * parse any parentheses in format ((title|part|part))
2357 * and call callbacks to get a replacement text for any found piece
2359 * @param string $text The text to parse
2360 * @param array $callbacks rules in form:
2361 * '{' => array( # opening parentheses
2362 * 'end' => '}', # closing parentheses
2363 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2364 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2369 function replace_callback ($text, $callbacks) {
2370 wfProfileIn( __METHOD__
. '-self' );
2371 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2372 $lastOpeningBrace = -1; # last not closed parentheses
2374 for ($i = 0; $i < strlen($text); $i++
) {
2375 # check for any opening brace
2378 foreach ($callbacks as $key => $value) {
2379 $pos = strpos ($text, $key, $i);
2380 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2386 if ($lastOpeningBrace >= 0) {
2387 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2389 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2394 $pos = strpos ($text, '|', $i);
2396 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2407 # found openning brace, lets add it to parentheses stack
2408 if (null != $rule) {
2409 $piece = array('brace' => $text[$i],
2410 'braceEnd' => $rule['end'],
2415 # count openning brace characters
2416 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2421 $piece['startAt'] = $i+
1;
2422 $piece['partStart'] = $i+
1;
2424 # we need to add to stack only if openning brace count is enough for any given rule
2425 foreach ($rule['cb'] as $cnt => $fn) {
2426 if ($piece['count'] >= $cnt) {
2427 $lastOpeningBrace ++
;
2428 $openingBraceStack[$lastOpeningBrace] = $piece;
2435 else if ($lastOpeningBrace >= 0) {
2436 # first check if it is a closing brace
2437 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2438 # lets check if it is enough characters for closing brace
2440 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2443 # if there are more closing parentheses than opening ones, we parse less
2444 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2445 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2447 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2449 $matchingCallback = null;
2450 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2451 if ($count >= $cnt && $matchingCount < $cnt) {
2452 $matchingCount = $cnt;
2453 $matchingCallback = $fn;
2457 if ($matchingCount == 0) {
2462 # lets set a title or last part (if '|' was found)
2463 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2464 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2466 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2468 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2469 $pieceEnd = $i +
$matchingCount;
2471 if( is_callable( $matchingCallback ) ) {
2473 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2474 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2475 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2476 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2478 # finally we can call a user callback and replace piece of text
2479 wfProfileOut( __METHOD__
. '-self' );
2480 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2481 wfProfileIn( __METHOD__
. '-self' );
2482 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2483 $i = $pieceStart +
strlen($replaceWith) - 1;
2486 # null value for callback means that parentheses should be parsed, but not replaced
2487 $i +
= $matchingCount - 1;
2490 # reset last openning parentheses, but keep it in case there are unused characters
2491 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2492 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2493 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2496 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2497 $openingBraceStack[$lastOpeningBrace--] = null;
2499 if ($matchingCount < $piece['count']) {
2500 $piece['count'] -= $matchingCount;
2501 $piece['startAt'] -= $matchingCount;
2502 $piece['partStart'] = $piece['startAt'];
2503 # do we still qualify for any callback with remaining count?
2504 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2505 if ($piece['count'] >= $cnt) {
2506 $lastOpeningBrace ++
;
2507 $openingBraceStack[$lastOpeningBrace] = $piece;
2515 # lets set a title if it is a first separator, or next part otherwise
2516 if ($text[$i] == '|') {
2517 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2518 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2519 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2522 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2524 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2529 wfProfileOut( __METHOD__
. '-self' );
2534 * Replace magic variables, templates, and template arguments
2535 * with the appropriate text. Templates are substituted recursively,
2536 * taking care to avoid infinite loops.
2538 * Note that the substitution depends on value of $mOutputType:
2539 * OT_WIKI: only {{subst:}} templates
2540 * OT_MSG: only magic variables
2541 * OT_HTML: all templates and magic variables
2543 * @param string $tex The text to transform
2544 * @param array $args Key-value pairs representing template parameters to substitute
2545 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2548 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2549 # Prevent too big inclusions
2550 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2554 $fname = 'Parser::replaceVariables';
2555 wfProfileIn( $fname );
2557 # This function is called recursively. To keep track of arguments we need a stack:
2558 array_push( $this->mArgStack
, $args );
2560 $braceCallbacks = array();
2562 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2564 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2565 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2567 $callbacks = array();
2568 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2569 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2570 $text = $this->replace_callback ($text, $callbacks);
2572 array_pop( $this->mArgStack
);
2574 wfProfileOut( $fname );
2579 * Replace magic variables
2582 function variableSubstitution( $matches ) {
2583 $fname = 'Parser::variableSubstitution';
2584 $varname = $matches[1];
2585 wfProfileIn( $fname );
2587 if ( $this->mOutputType
== OT_WIKI
) {
2588 # Do only magic variables prefixed by SUBST
2589 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2590 if (!$mwSubst->matchStartAndRemove( $varname ))
2592 # Note that if we don't substitute the variable below,
2593 # we don't remove the {{subst:}} magic word, in case
2594 # it is a template rather than a magic variable.
2596 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2597 $id = $this->mVariables
[$varname];
2598 $text = $this->getVariableValue( $id );
2599 $this->mOutput
->mContainsOldMagic
= true;
2601 $text = $matches[0];
2603 wfProfileOut( $fname );
2607 # Split template arguments
2608 function getTemplateArgs( $argsString ) {
2609 if ( $argsString === '' ) {
2613 $args = explode( '|', substr( $argsString, 1 ) );
2615 # If any of the arguments contains a '[[' but no ']]', it needs to be
2616 # merged with the next arg because the '|' character between belongs
2617 # to the link syntax and not the template parameter syntax.
2618 $argc = count($args);
2620 for ( $i = 0; $i < $argc-1; $i++
) {
2621 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2622 $args[$i] .= '|'.$args[$i+
1];
2623 array_splice($args, $i+
1, 1);
2633 * Return the text of a template, after recursively
2634 * replacing any variables or templates within the template.
2636 * @param array $piece The parts of the template
2637 * $piece['text']: matched text
2638 * $piece['title']: the title, i.e. the part before the |
2639 * $piece['parts']: the parameter array
2640 * @return string the text of the template
2643 function braceSubstitution( $piece ) {
2644 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2645 $fname = 'Parser::braceSubstitution';
2646 wfProfileIn( $fname );
2649 $found = false; # $text has been filled
2650 $nowiki = false; # wiki markup in $text should be escaped
2651 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2652 $noargs = false; # Don't replace triple-brace arguments in $text
2653 $replaceHeadings = false; # Make the edit section links go to the template not the article
2654 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2655 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2657 # Title object, where $text came from
2662 # $part1 is the bit before the first |, and must contain only title characters
2663 # $args is a list of arguments, starting from index 0, not including $part1
2665 $part1 = $piece['title'];
2666 # If the third subpattern matched anything, it will start with |
2668 if (null == $piece['parts']) {
2669 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2670 if ($replaceWith != $piece['text']) {
2671 $text = $replaceWith;
2678 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2679 $argc = count( $args );
2683 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2684 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2685 # One of two possibilities is true:
2686 # 1) Found SUBST but not in the PST phase
2687 # 2) Didn't find SUBST and in the PST phase
2688 # In either case, return without further processing
2689 $text = $piece['text'];
2696 # MSG, MSGNW, INT and RAW
2699 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2700 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2703 # Remove obsolete MSG:
2704 $mwMsg =& MagicWord
::get( MAG_MSG
);
2705 $mwMsg->matchStartAndRemove( $part1 );
2709 $mwRaw =& MagicWord
::get( MAG_RAW
);
2710 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2711 $forceRawInterwiki = true;
2714 # Check if it is an internal message
2715 $mwInt =& MagicWord
::get( MAG_INT
);
2716 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2717 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2718 $text = $linestart . wfMsgReal( $part1, $args, true );
2726 wfProfileIn( __METHOD__
. '-pfunc' );
2728 $colonPos = strpos( $part1, ':' );
2729 if ( $colonPos !== false ) {
2730 # Case sensitive functions
2731 $function = substr( $part1, 0, $colonPos );
2732 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2733 $function = $this->mFunctionSynonyms
[1][$function];
2735 # Case insensitive functions
2736 $function = strtolower( $function );
2737 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2738 $function = $this->mFunctionSynonyms
[0][$function];
2744 $funcArgs = array_map( 'trim', $args );
2745 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2746 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2749 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2753 if ( is_array( $result ) ) {
2754 if ( isset( $result[0] ) ) {
2755 $text = $linestart . $result[0];
2756 unset( $result[0] );
2759 // Extract flags into the local scope
2760 // This allows callers to set flags such as nowiki, noparse, found, etc.
2763 $text = $linestart . $result;
2767 wfProfileOut( __METHOD__
. '-pfunc' );
2770 # Template table test
2772 # Did we encounter this template already? If yes, it is in the cache
2773 # and we need to check for loops.
2774 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2777 # Infinite loop test
2778 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2782 $text = $linestart .
2783 '{{' . $part1 . '}}' .
2784 '<!-- WARNING: template loop detected -->';
2785 wfDebug( "$fname: template loop broken at '$part1'\n" );
2787 # set $text to cached message.
2788 $text = $linestart . $this->mTemplates
[$piece['title']];
2792 # Load from database
2793 $lastPathLevel = $this->mTemplatePath
;
2795 wfProfileIn( __METHOD__
. '-loadtpl' );
2797 # declaring $subpage directly in the function call
2798 # does not work correctly with references and breaks
2799 # {{/subpage}}-style inclusions
2801 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2802 if ($subpage !== '') {
2803 $ns = $this->mTitle
->getNamespace();
2805 $title = Title
::newFromText( $part1, $ns );
2808 if ( !is_null( $title ) ) {
2809 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2810 # Check for language variants if the template is not found
2811 if($checkVariantLink && $title->getArticleID() == 0){
2812 $wgContLang->findVariantLink($part1, $title);
2815 if ( !$title->isExternal() ) {
2816 # Check for excessive inclusion
2817 $dbk = $title->getPrefixedDBkey();
2818 if ( $this->incrementIncludeCount( $dbk ) ) {
2819 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2820 $text = SpecialPage
::capturePath( $title );
2821 if ( is_string( $text ) ) {
2826 $this->disableCache();
2829 $articleContent = $this->fetchTemplate( $title );
2830 if ( $articleContent !== false ) {
2832 $text = $articleContent;
2833 $replaceHeadings = true;
2838 # If the title is valid but undisplayable, make a link to it
2839 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2840 $text = '[['.$title->getPrefixedText().']]';
2843 } elseif ( $title->isTrans() ) {
2844 // Interwiki transclusion
2845 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2846 $text = $this->interwikiTransclude( $title, 'render' );
2850 $text = $this->interwikiTransclude( $title, 'raw' );
2851 $replaceHeadings = true;
2856 # Template cache array insertion
2857 # Use the original $piece['title'] not the mangled $part1, so that
2858 # modifiers such as RAW: produce separate cache entries
2861 // A special page; don't store it in the template cache.
2863 $this->mTemplates
[$piece['title']] = $text;
2865 $text = $linestart . $text;
2868 wfProfileOut( __METHOD__
. '-loadtpl' );
2871 # Recursive parsing, escaping and link table handling
2872 # Only for HTML output
2873 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2874 $text = wfEscapeWikiText( $text );
2875 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2877 $assocArgs = array();
2879 # Clean up argument array
2880 $assocArgs = array();
2882 foreach( $args as $arg ) {
2883 $eqpos = strpos( $arg, '=' );
2884 if ( $eqpos === false ) {
2885 $assocArgs[$index++
] = $arg;
2887 $name = trim( substr( $arg, 0, $eqpos ) );
2888 $value = trim( substr( $arg, $eqpos+
1 ) );
2889 if ( $value === false ) {
2892 if ( $name !== false ) {
2893 $assocArgs[$name] = $value;
2898 # Add a new element to the templace recursion path
2899 $this->mTemplatePath
[$part1] = 1;
2903 # If there are any <onlyinclude> tags, only include them
2904 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2905 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2907 foreach ($m[1] as $piece)
2910 # Remove <noinclude> sections and <includeonly> tags
2911 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2912 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2914 if( $this->mOutputType
== OT_HTML
) {
2915 # Strip <nowiki>, <pre>, etc.
2916 $text = $this->strip( $text, $this->mStripState
);
2917 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2919 $text = $this->replaceVariables( $text, $assocArgs );
2921 # If the template begins with a table or block-level
2922 # element, it should be treated as beginning a new line.
2923 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2924 $text = "\n" . $text;
2926 } elseif ( !$noargs ) {
2927 # $noparse and !$noargs
2928 # Just replace the arguments, not any double-brace items
2929 # This is used for rendered interwiki transclusion
2930 $text = $this->replaceVariables( $text, $assocArgs, true );
2933 # Prune lower levels off the recursion check path
2934 $this->mTemplatePath
= $lastPathLevel;
2937 wfProfileOut( $fname );
2938 return $piece['text'];
2940 wfProfileIn( __METHOD__
. '-placeholders' );
2942 # Replace raw HTML by a placeholder
2943 # Add a blank line preceding, to prevent it from mucking up
2944 # immediately preceding headings
2945 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2947 # replace ==section headers==
2948 # XXX this needs to go away once we have a better parser.
2949 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2950 if( !is_null( $title ) )
2951 $encodedname = base64_encode($title->getPrefixedDBkey());
2953 $encodedname = base64_encode("");
2954 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2955 PREG_SPLIT_DELIM_CAPTURE
);
2958 for( $i = 0; $i < count($m); $i +
= 2 ) {
2960 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2962 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2966 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2967 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2968 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2974 wfProfileOut( __METHOD__
. '-placeholders' );
2977 # Prune lower levels off the recursion check path
2978 $this->mTemplatePath
= $lastPathLevel;
2981 wfProfileOut( $fname );
2982 return $piece['text'];
2984 wfProfileOut( $fname );
2990 * Fetch the unparsed text of a template and register a reference to it.
2992 function fetchTemplate( $title ) {
2994 // Loop to fetch the article, with up to 1 redirect
2995 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2996 $rev = Revision
::newFromTitle( $title );
2997 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3001 $text = $rev->getText();
3002 if ( $text === false ) {
3006 $title = Title
::newFromRedirect( $text );
3012 * Transclude an interwiki link.
3014 function interwikiTransclude( $title, $action ) {
3015 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3017 if (!$wgEnableScaryTranscluding)
3018 return wfMsg('scarytranscludedisabled');
3020 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3021 // But we'll handle it generally anyway
3022 if ( $title->getNamespace() ) {
3023 // Use the canonical namespace, which should work anywhere
3024 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3026 $articleName = $title->getDBkey();
3029 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3030 $url .= "?action=$action";
3031 if (strlen($url) > 255)
3032 return wfMsg('scarytranscludetoolong');
3033 return $this->fetchScaryTemplateMaybeFromCache($url);
3036 function fetchScaryTemplateMaybeFromCache($url) {
3037 global $wgTranscludeCacheExpiry;
3038 $dbr =& wfGetDB(DB_SLAVE
);
3039 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3040 array('tc_url' => $url));
3042 $time = $obj->tc_time
;
3043 $text = $obj->tc_contents
;
3044 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3049 $text = Http
::get($url);
3051 return wfMsg('scarytranscludefailed', $url);
3053 $dbw =& wfGetDB(DB_MASTER
);
3054 $dbw->replace('transcache', array('tc_url'), array(
3056 'tc_time' => time(),
3057 'tc_contents' => $text));
3063 * Triple brace replacement -- used for template arguments
3066 function argSubstitution( $matches ) {
3067 $arg = trim( $matches['title'] );
3068 $text = $matches['text'];
3069 $inputArgs = end( $this->mArgStack
);
3071 if ( array_key_exists( $arg, $inputArgs ) ) {
3072 $text = $inputArgs[$arg];
3073 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3074 $text = $matches['parts'][0];
3081 * Returns true if the function is allowed to include this entity
3084 function incrementIncludeCount( $dbk ) {
3085 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3086 $this->mIncludeCount
[$dbk] = 0;
3088 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3096 * Detect __NOGALLERY__ magic word and set a placeholder
3098 function stripNoGallery( &$text ) {
3099 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3101 $mw = MagicWord
::get( MAG_NOGALLERY
);
3102 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3106 * Detect __TOC__ magic word and set a placeholder
3108 function stripToc( $text ) {
3109 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3111 $mw = MagicWord
::get( MAG_NOTOC
);
3112 if( $mw->matchAndRemove( $text ) ) {
3113 $this->mShowToc
= false;
3116 $mw = MagicWord
::get( MAG_TOC
);
3117 if( $mw->match( $text ) ) {
3118 $this->mShowToc
= true;
3119 $this->mForceTocPosition
= true;
3121 // Set a placeholder. At the end we'll fill it in with the TOC.
3122 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3124 // Only keep the first one.
3125 $text = $mw->replace( '', $text );
3131 * This function accomplishes several tasks:
3132 * 1) Auto-number headings if that option is enabled
3133 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3134 * 3) Add a Table of contents on the top for users who have enabled the option
3135 * 4) Auto-anchor headings
3137 * It loops through all headlines, collects the necessary data, then splits up the
3138 * string and re-inserts the newly formatted headlines.
3140 * @param string $text
3141 * @param boolean $isMain
3144 function formatHeadings( $text, $isMain=true ) {
3145 global $wgMaxTocLevel, $wgContLang;
3147 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3148 if( !$this->mTitle
->userCanEdit() ) {
3151 $showEditLink = $this->mOptions
->getEditSection();
3154 # Inhibit editsection links if requested in the page
3155 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3156 if( $esw->matchAndRemove( $text ) ) {
3160 # Get all headlines for numbering them and adding funky stuff like [edit]
3161 # links - this is for later, but we need the number of headlines right now
3162 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3164 # if there are fewer than 4 headlines in the article, do not show TOC
3165 # unless it's been explicitly enabled.
3166 $enoughToc = $this->mShowToc
&&
3167 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3169 # Allow user to stipulate that a page should have a "new section"
3170 # link added via __NEWSECTIONLINK__
3171 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3172 if( $mw->matchAndRemove( $text ) )
3173 $this->mOutput
->setNewSection( true );
3175 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3176 # override above conditions and always show TOC above first header
3177 $mw =& MagicWord
::get( MAG_FORCETOC
);
3178 if ($mw->matchAndRemove( $text ) ) {
3179 $this->mShowToc
= true;
3183 # Never ever show TOC if no headers
3184 if( $numMatches < 1 ) {
3188 # We need this to perform operations on the HTML
3189 $sk =& $this->mOptions
->getSkin();
3193 $sectionCount = 0; # headlineCount excluding template sections
3195 # Ugh .. the TOC should have neat indentation levels which can be
3196 # passed to the skin functions. These are determined here
3200 $sublevelCount = array();
3201 $levelCount = array();
3208 foreach( $matches[3] as $headline ) {
3210 $templatetitle = '';
3211 $templatesection = 0;
3214 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3216 $templatetitle = base64_decode($mat[1]);
3217 $templatesection = 1 +
(int)base64_decode($mat[2]);
3218 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3222 $prevlevel = $level;
3223 $prevtoclevel = $toclevel;
3225 $level = $matches[1][$headlineCount];
3227 if( $doNumberHeadings ||
$enoughToc ) {
3229 if ( $level > $prevlevel ) {
3230 # Increase TOC level
3232 $sublevelCount[$toclevel] = 0;
3233 if( $toclevel<$wgMaxTocLevel ) {
3234 $toc .= $sk->tocIndent();
3237 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3238 # Decrease TOC level, find level to jump to
3240 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3241 # Can only go down to level 1
3244 for ($i = $toclevel; $i > 0; $i--) {
3245 if ( $levelCount[$i] == $level ) {
3246 # Found last matching level
3250 elseif ( $levelCount[$i] < $level ) {
3251 # Found first matching level below current level
3257 if( $toclevel<$wgMaxTocLevel ) {
3258 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3262 # No change in level, end TOC line
3263 if( $toclevel<$wgMaxTocLevel ) {
3264 $toc .= $sk->tocLineEnd();
3268 $levelCount[$toclevel] = $level;
3270 # count number of headlines for each level
3271 @$sublevelCount[$toclevel]++
;
3273 for( $i = 1; $i <= $toclevel; $i++
) {
3274 if( !empty( $sublevelCount[$i] ) ) {
3278 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3284 # The canonized header is a version of the header text safe to use for links
3285 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3286 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3287 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3289 # Remove link placeholders by the link text.
3290 # <!--LINK number-->
3292 # link text with suffix
3293 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3294 "\$this->mLinkHolders['texts'][\$1]",
3295 $canonized_headline );
3296 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3297 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3298 $canonized_headline );
3301 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3302 $tocline = trim( $canonized_headline );
3303 # Save headline for section edit hint before it's escaped
3304 $headline_hint = trim( $canonized_headline );
3305 $canonized_headline = Sanitizer
::escapeId( $tocline );
3306 $refers[$headlineCount] = $canonized_headline;
3308 # count how many in assoc. array so we can track dupes in anchors
3309 @$refers[$canonized_headline]++
;
3310 $refcount[$headlineCount]=$refers[$canonized_headline];
3312 # Don't number the heading if it is the only one (looks silly)
3313 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3314 # the two are different if the line contains a link
3315 $headline=$numbering . ' ' . $headline;
3318 # Create the anchor for linking from the TOC to the section
3319 $anchor = $canonized_headline;
3320 if($refcount[$headlineCount] > 1 ) {
3321 $anchor .= '_' . $refcount[$headlineCount];
3323 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3324 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3326 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3327 if ( empty( $head[$headlineCount] ) ) {
3328 $head[$headlineCount] = '';
3331 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3333 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3336 # give headline the correct <h#> tag
3337 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3345 if( $toclevel<$wgMaxTocLevel ) {
3346 $toc .= $sk->tocUnindent( $toclevel - 1 );
3348 $toc = $sk->tocList( $toc );
3351 # split up and insert constructed headlines
3353 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3356 foreach( $blocks as $block ) {
3357 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3358 # This is the [edit] link that appears for the top block of text when
3359 # section editing is enabled
3361 # Disabled because it broke block formatting
3362 # For example, a bullet point in the top line
3363 # $full .= $sk->editSectionLink(0);
3366 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3367 # Top anchor now in skin
3371 if( !empty( $head[$i] ) ) {
3376 if( $this->mForceTocPosition
) {
3377 return str_replace( '<!--MWTOC-->', $toc, $full );
3384 * Return an HTML link for the "ISBN 123456" text
3387 function magicISBN( $text ) {
3388 $fname = 'Parser::magicISBN';
3389 wfProfileIn( $fname );
3391 $a = split( 'ISBN ', ' '.$text );
3392 if ( count ( $a ) < 2 ) {
3393 wfProfileOut( $fname );
3396 $text = substr( array_shift( $a ), 1);
3397 $valid = '0123456789-Xx';
3399 foreach ( $a as $x ) {
3400 # hack: don't replace inside thumbnail title/alt
3402 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3407 $isbn = $blank = '' ;
3408 while ( ' ' == $x{0} ) {
3410 $x = substr( $x, 1 );
3412 if ( $x == '' ) { # blank isbn
3413 $text .= "ISBN $blank";
3416 while ( strstr( $valid, $x{0} ) != false ) {
3418 $x = substr( $x, 1 );
3420 $num = str_replace( '-', '', $isbn );
3421 $num = str_replace( ' ', '', $num );
3422 $num = str_replace( 'x', 'X', $num );
3425 $text .= "ISBN $blank$x";
3427 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3428 $text .= '<a href="' .
3429 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3430 "\" class=\"internal\">ISBN $isbn</a>";
3434 wfProfileOut( $fname );
3439 * Return an HTML link for the "RFC 1234" text
3442 * @param string $text Text to be processed
3443 * @param string $keyword Magic keyword to use (default RFC)
3444 * @param string $urlmsg Interface message to use (default rfcurl)
3447 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3449 $valid = '0123456789';
3452 $a = split( $keyword, ' '.$text );
3453 if ( count ( $a ) < 2 ) {
3456 $text = substr( array_shift( $a ), 1);
3458 /* Check if keyword is preceed by [[.
3459 * This test is made here cause of the array_shift above
3460 * that prevent the test to be done in the foreach.
3462 if ( substr( $text, -2 ) == '[[' ) {
3466 foreach ( $a as $x ) {
3467 /* token might be empty if we have RFC RFC 1234 */
3473 # hack: don't replace inside thumbnail title/alt
3475 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3476 $text .= $keyword . $x;
3482 /** remove and save whitespaces in $blank */
3483 while ( $x{0} == ' ' ) {
3485 $x = substr( $x, 1 );
3488 /** remove and save the rfc number in $id */
3489 while ( strstr( $valid, $x{0} ) != false ) {
3491 $x = substr( $x, 1 );
3495 /* call back stripped spaces*/
3496 $text .= $keyword.$blank.$x;
3497 } elseif( $internal ) {
3499 $text .= $keyword.$id.$x;
3501 /* build the external link*/
3502 $url = wfMsg( $urlmsg, $id);
3503 $sk =& $this->mOptions
->getSkin();
3504 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3505 $text .= "<a href=\"{$url}\"{$la}>{$keyword}{$id}</a>{$x}";
3508 /* Check if the next RFC keyword is preceed by [[ */
3509 $internal = ( substr($x,-2) == '[[' );
3515 * Transform wiki markup when saving a page by doing \r\n -> \n
3516 * conversion, substitting signatures, {{subst:}} templates, etc.
3518 * @param string $text the text to transform
3519 * @param Title &$title the Title object for the current article
3520 * @param User &$user the User object describing the current user
3521 * @param ParserOptions $options parsing options
3522 * @param bool $clearState whether to clear the parser state first
3523 * @return string the altered wiki markup
3526 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3527 $this->mOptions
= $options;
3528 $this->mTitle
=& $title;
3529 $this->mOutputType
= OT_WIKI
;
3531 if ( $clearState ) {
3532 $this->clearState();
3535 $stripState = false;
3539 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3540 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3541 $text = $this->pstPass2( $text, $stripState, $user );
3542 $text = $this->unstrip( $text, $stripState );
3543 $text = $this->unstripNoWiki( $text, $stripState );
3548 * Pre-save transform helper function
3551 function pstPass2( $text, &$stripState, &$user ) {
3552 global $wgContLang, $wgLocaltimezone;
3554 /* Note: This is the timestamp saved as hardcoded wikitext to
3555 * the database, we use $wgContLang here in order to give
3556 * everyone the same signature and use the default one rather
3557 * than the one selected in each user's preferences.
3559 if ( isset( $wgLocaltimezone ) ) {
3560 $oldtz = getenv( 'TZ' );
3561 putenv( 'TZ='.$wgLocaltimezone );
3563 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3564 ' (' . date( 'T' ) . ')';
3565 if ( isset( $wgLocaltimezone ) ) {
3566 putenv( 'TZ='.$oldtz );
3569 # Variable replacement
3570 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3571 $text = $this->replaceVariables( $text );
3573 # Strip out <nowiki> etc. added via replaceVariables
3574 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3577 $sigText = $this->getUserSig( $user );
3578 $text = strtr( $text, array(
3580 '~~~~' => "$sigText $d",
3584 # Context links: [[|name]] and [[name (context)|]]
3586 global $wgLegalTitleChars;
3587 $tc = "[$wgLegalTitleChars]";
3588 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3590 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3591 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3593 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3594 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3595 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3596 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3598 $t = $this->mTitle
->getText();
3599 if ( preg_match( $conpat, $t, $m ) ) {
3602 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3603 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3604 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3606 if ( '' == $context ) {
3607 $text = preg_replace( $p2, '[[\\1]]', $text );
3609 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3612 # Trim trailing whitespace
3613 # MAG_END (__END__) tag allows for trailing
3614 # whitespace to be deliberately included
3615 $text = rtrim( $text );
3616 $mw =& MagicWord
::get( MAG_END
);
3617 $mw->matchAndRemove( $text );
3623 * Fetch the user's signature text, if any, and normalize to
3624 * validated, ready-to-insert wikitext.
3630 function getUserSig( &$user ) {
3631 $username = $user->getName();
3632 $nickname = $user->getOption( 'nickname' );
3633 $nickname = $nickname === '' ?
$username : $nickname;
3635 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3636 # Sig. might contain markup; validate this
3637 if( $this->validateSig( $nickname ) !== false ) {
3638 # Validated; clean up (if needed) and return it
3639 return $this->cleanSig( $nickname, true );
3641 # Failed to validate; fall back to the default
3642 $nickname = $username;
3643 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3647 // Make sure nickname doesnt get a sig in a sig
3648 $nickname = $this->cleanSigInSig( $nickname );
3650 # If we're still here, make it a link to the user page
3651 $userpage = $user->getUserPage();
3652 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3656 * Check that the user's signature contains no bad XML
3658 * @param string $text
3659 * @return mixed An expanded string, or false if invalid.
3661 function validateSig( $text ) {
3662 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3666 * Clean up signature text
3668 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3669 * 2) Substitute all transclusions
3671 * @param string $text
3672 * @param $parsing Whether we're cleaning (preferences save) or parsing
3673 * @return string Signature text
3675 function cleanSig( $text, $parsing = false ) {
3677 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3679 $substWord = MagicWord
::get( MAG_SUBST
);
3680 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3681 $substText = '{{' . $substWord->getSynonym( 0 );
3683 $text = preg_replace( $substRegex, $substText, $text );
3684 $text = $this->cleanSigInSig( $text );
3685 $text = $this->replaceVariables( $text );
3687 $this->clearState();
3692 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3693 * @param string $text
3694 * @return string Signature text with /~{3,5}/ removed
3696 function cleanSigInSig( $text ) {
3697 $text = preg_replace( '/~{3,5}/', '', $text );
3702 * Set up some variables which are usually set up in parse()
3703 * so that an external function can call some class members with confidence
3706 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3707 $this->mTitle
=& $title;
3708 $this->mOptions
= $options;
3709 $this->mOutputType
= $outputType;
3710 if ( $clearState ) {
3711 $this->clearState();
3716 * Transform a MediaWiki message by replacing magic variables.
3718 * @param string $text the text to transform
3719 * @param ParserOptions $options options
3720 * @return string the text with variables substituted
3723 function transformMsg( $text, $options ) {
3725 static $executing = false;
3727 $fname = "Parser::transformMsg";
3729 # Guard against infinite recursion
3735 wfProfileIn($fname);
3737 $this->mTitle
= $wgTitle;
3738 $this->mOptions
= $options;
3739 $this->mOutputType
= OT_MSG
;
3740 $this->clearState();
3741 $text = $this->replaceVariables( $text );
3744 wfProfileOut($fname);
3749 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3750 * The callback should have the following form:
3751 * function myParserHook( $text, $params, &$parser ) { ... }
3753 * Transform and return $text. Use $parser for any required context, e.g. use
3754 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3758 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3759 * @param mixed $callback The callback function (and object) to use for the tag
3761 * @return The old value of the mTagHooks array associated with the hook
3763 function setHook( $tag, $callback ) {
3764 $tag = strtolower( $tag );
3765 $oldVal = @$this->mTagHooks
[$tag];
3766 $this->mTagHooks
[$tag] = $callback;
3772 * Create a function, e.g. {{sum:1|2|3}}
3773 * The callback function should have the form:
3774 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3776 * The callback may either return the text result of the function, or an array with the text
3777 * in element 0, and a number of flags in the other elements. The names of the flags are
3778 * specified in the keys. Valid flags are:
3779 * found The text returned is valid, stop processing the template. This
3781 * nowiki Wiki markup in the return value should be escaped
3782 * noparse Unsafe HTML tags should not be stripped, etc.
3783 * noargs Don't replace triple-brace arguments in the return value
3784 * isHTML The returned text is HTML, armour it against wikitext transformation
3788 * @param mixed $id The magic word ID, or (deprecated) the function name. Function names are case-insensitive.
3789 * @param mixed $callback The callback function (and object) to use
3790 * @param integer $flags a combination of the following flags:
3791 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3793 * @return The old callback function for this name, if any
3795 function setFunctionHook( $id, $callback, $flags = 0 ) {
3796 if( is_string( $id ) ) {
3797 $id = strtolower( $id );
3799 $oldVal = @$this->mFunctionHooks
[$id];
3800 $this->mFunctionHooks
[$id] = $callback;
3802 # Add to function cache
3803 if ( is_int( $id ) ) {
3804 $mw = MagicWord
::get( $id );
3805 $synonyms = $mw->getSynonyms();
3806 $sensitive = intval( $mw->isCaseSensitive() );
3808 $synonyms = array( $id );
3812 foreach ( $synonyms as $syn ) {
3814 if ( !$sensitive ) {
3815 $syn = strtolower( $syn );
3818 if ( !( $flags & SFH_NO_HASH
) ) {
3821 # Remove trailing colon
3822 if ( substr( $syn, -1, 1 ) == ':' ) {
3823 $syn = substr( $syn, 0, -1 );
3825 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3831 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3832 * Placeholders created in Skin::makeLinkObj()
3833 * Returns an array of links found, indexed by PDBK:
3837 * $options is a bit field, RLH_FOR_UPDATE to select for update
3839 function replaceLinkHolders( &$text, $options = 0 ) {
3841 global $wgOutputReplace;
3843 $fname = 'Parser::replaceLinkHolders';
3844 wfProfileIn( $fname );
3848 $sk =& $this->mOptions
->getSkin();
3849 $linkCache =& LinkCache
::singleton();
3851 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3852 wfProfileIn( $fname.'-check' );
3853 $dbr =& wfGetDB( DB_SLAVE
);
3854 $page = $dbr->tableName( 'page' );
3855 $threshold = $wgUser->getOption('stubthreshold');
3858 asort( $this->mLinkHolders
['namespaces'] );
3862 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3864 $title = $this->mLinkHolders
['titles'][$key];
3866 # Skip invalid entries.
3867 # Result will be ugly, but prevents crash.
3868 if ( is_null( $title ) ) {
3871 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3873 # Check if it's a static known link, e.g. interwiki
3874 if ( $title->isAlwaysKnown() ) {
3875 $colours[$pdbk] = 1;
3876 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3877 $colours[$pdbk] = 1;
3878 $this->mOutput
->addLink( $title, $id );
3879 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3880 $colours[$pdbk] = 0;
3882 # Not in the link cache, add it to the query
3883 if ( !isset( $current ) ) {
3885 $query = "SELECT page_id, page_namespace, page_title";
3886 if ( $threshold > 0 ) {
3887 $query .= ', page_len, page_is_redirect';
3889 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3890 } elseif ( $current != $ns ) {
3892 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3897 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3902 if ( $options & RLH_FOR_UPDATE
) {
3903 $query .= ' FOR UPDATE';
3906 $res = $dbr->query( $query, $fname );
3908 # Fetch data and form into an associative array
3909 # non-existent = broken
3912 while ( $s = $dbr->fetchObject($res) ) {
3913 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3914 $pdbk = $title->getPrefixedDBkey();
3915 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3916 $this->mOutput
->addLink( $title, $s->page_id
);
3918 if ( $threshold > 0 ) {
3919 $size = $s->page_len
;
3920 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3921 $colours[$pdbk] = 1;
3923 $colours[$pdbk] = 2;
3926 $colours[$pdbk] = 1;
3930 wfProfileOut( $fname.'-check' );
3932 # Construct search and replace arrays
3933 wfProfileIn( $fname.'-construct' );
3934 $wgOutputReplace = array();
3935 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3936 $pdbk = $pdbks[$key];
3937 $searchkey = "<!--LINK $key-->";
3938 $title = $this->mLinkHolders
['titles'][$key];
3939 if ( empty( $colours[$pdbk] ) ) {
3940 $linkCache->addBadLinkObj( $title );
3941 $colours[$pdbk] = 0;
3942 $this->mOutput
->addLink( $title, 0 );
3943 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3944 $this->mLinkHolders
['texts'][$key],
3945 $this->mLinkHolders
['queries'][$key] );
3946 } elseif ( $colours[$pdbk] == 1 ) {
3947 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3948 $this->mLinkHolders
['texts'][$key],
3949 $this->mLinkHolders
['queries'][$key] );
3950 } elseif ( $colours[$pdbk] == 2 ) {
3951 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3952 $this->mLinkHolders
['texts'][$key],
3953 $this->mLinkHolders
['queries'][$key] );
3956 wfProfileOut( $fname.'-construct' );
3959 wfProfileIn( $fname.'-replace' );
3961 $text = preg_replace_callback(
3962 '/(<!--LINK .*?-->)/',
3963 "wfOutputReplaceMatches",
3966 wfProfileOut( $fname.'-replace' );
3969 # Now process interwiki link holders
3970 # This is quite a bit simpler than internal links
3971 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3972 wfProfileIn( $fname.'-interwiki' );
3973 # Make interwiki link HTML
3974 $wgOutputReplace = array();
3975 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3976 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3977 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3980 $text = preg_replace_callback(
3981 '/<!--IWLINK (.*?)-->/',
3982 "wfOutputReplaceMatches",
3984 wfProfileOut( $fname.'-interwiki' );
3987 wfProfileOut( $fname );
3992 * Replace <!--LINK--> link placeholders with plain text of links
3993 * (not HTML-formatted).
3994 * @param string $text
3997 function replaceLinkHoldersText( $text ) {
3998 $fname = 'Parser::replaceLinkHoldersText';
3999 wfProfileIn( $fname );
4001 $text = preg_replace_callback(
4002 '/<!--(LINK|IWLINK) (.*?)-->/',
4003 array( &$this, 'replaceLinkHoldersTextCallback' ),
4006 wfProfileOut( $fname );
4011 * @param array $matches
4015 function replaceLinkHoldersTextCallback( $matches ) {
4016 $type = $matches[1];
4018 if( $type == 'LINK' ) {
4019 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4020 return $this->mLinkHolders
['texts'][$key];
4022 } elseif( $type == 'IWLINK' ) {
4023 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4024 return $this->mInterwikiLinkHolders
['texts'][$key];
4031 * Tag hook handler for 'pre'.
4033 function renderPreTag( $text, $attribs, $parser ) {
4034 // Backwards-compatibility hack
4035 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4037 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4038 return wfOpenElement( 'pre', $attribs ) .
4039 wfEscapeHTMLTagsOnly( $content ) .
4044 * Renders an image gallery from a text with one line per image.
4045 * text labels may be given by using |-style alternative text. E.g.
4046 * Image:one.jpg|The number "1"
4047 * Image:tree.jpg|A tree
4048 * given as text will return the HTML of a gallery with two images,
4049 * labeled 'The number "1"' and
4052 function renderImageGallery( $text, $params ) {
4053 $ig = new ImageGallery();
4054 $ig->setShowBytes( false );
4055 $ig->setShowFilename( false );
4057 $ig->useSkin( $this->mOptions
->getSkin() );
4059 if( isset( $params['caption'] ) )
4060 $ig->setCaption( $params['caption'] );
4062 $lines = explode( "\n", $text );
4063 foreach ( $lines as $line ) {
4064 # match lines like these:
4065 # Image:someimage.jpg|This is some image
4066 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4068 if ( count( $matches ) == 0 ) {
4071 $nt =& Title
::newFromText( $matches[1] );
4072 if( is_null( $nt ) ) {
4073 # Bogus title. Ignore these so we don't bomb out later.
4076 if ( isset( $matches[3] ) ) {
4077 $label = $matches[3];
4082 $pout = $this->parse( $label,
4085 false, // Strip whitespace...?
4086 false // Don't clear state!
4088 $html = $pout->getText();
4090 $ig->add( new Image( $nt ), $html );
4092 # Only add real images (bug #5586)
4093 if ( $nt->getNamespace() == NS_IMAGE
) {
4094 $this->mOutput
->addImage( $nt->getDBkey() );
4097 return $ig->toHTML();
4101 * Parse image options text and use it to make an image
4103 function makeImage( &$nt, $options ) {
4104 global $wgUseImageResize;
4108 # Check if the options text is of the form "options|alt text"
4110 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4111 # * left no resizing, just left align. label is used for alt= only
4112 # * right same, but right aligned
4113 # * none same, but not aligned
4114 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4115 # * center center the image
4116 # * framed Keep original image size, no magnify-button.
4118 $part = explode( '|', $options);
4120 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4121 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4122 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4123 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4124 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4125 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4126 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4127 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4130 $width = $height = $framed = $thumb = false;
4131 $manual_thumb = '' ;
4133 foreach( $part as $key => $val ) {
4134 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4136 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4137 # use manually specified thumbnail
4139 $manual_thumb = $match;
4140 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4141 # remember to set an alignment, don't render immediately
4143 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4144 # remember to set an alignment, don't render immediately
4146 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4147 # remember to set an alignment, don't render immediately
4149 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4150 # remember to set an alignment, don't render immediately
4152 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4153 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4154 # $match is the image width in pixels
4155 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4156 $width = intval( $m[1] );
4157 $height = intval( $m[2] );
4159 $width = intval($match);
4161 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4167 # Strip bad stuff out of the alt text
4168 $alt = $this->replaceLinkHoldersText( $caption );
4170 # make sure there are no placeholders in thumbnail attributes
4171 # that are later expanded to html- so expand them now and
4173 $alt = $this->unstrip($alt, $this->mStripState
);
4174 $alt = Sanitizer
::stripAllTags( $alt );
4176 # Linker does the rest
4177 $sk =& $this->mOptions
->getSkin();
4178 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4182 * Set a flag in the output object indicating that the content is dynamic and
4183 * shouldn't be cached.
4185 function disableCache() {
4186 wfDebug( "Parser output marked as uncacheable.\n" );
4187 $this->mOutput
->mCacheTime
= -1;
4191 * Callback from the Sanitizer for expanding items found in HTML attribute
4192 * values, so they can be safely tested and escaped.
4193 * @param string $text
4194 * @param array $args
4198 function attributeStripCallback( &$text, $args ) {
4199 $text = $this->replaceVariables( $text, $args );
4200 $text = $this->unstripForHTML( $text );
4204 function unstripForHTML( $text ) {
4205 $text = $this->unstrip( $text, $this->mStripState
);
4206 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4214 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4215 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4216 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4222 function getTags() { return array_keys( $this->mTagHooks
); }
4227 * Break wikitext input into sections, and either pull or replace
4228 * some particular section's text.
4230 * External callers should use the getSection and replaceSection methods.
4232 * @param $text Page wikitext
4233 * @param $section Numbered section. 0 pulls the text before the first
4234 * heading; other numbers will pull the given section
4235 * along with its lower-level subsections.
4236 * @param $mode One of "get" or "replace"
4237 * @param $newtext Replacement text for section data.
4238 * @return string for "get", the extracted section text.
4239 * for "replace", the whole page with the section replaced.
4241 private function extractSections( $text, $section, $mode, $newtext='' ) {
4242 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4243 # comments to be stripped as well)
4244 $striparray = array();
4246 $oldOutputType = $this->mOutputType
;
4247 $oldOptions = $this->mOptions
;
4248 $this->mOptions
= new ParserOptions();
4249 $this->mOutputType
= OT_WIKI
;
4251 $striptext = $this->strip( $text, $striparray, true );
4253 $this->mOutputType
= $oldOutputType;
4254 $this->mOptions
= $oldOptions;
4256 # now that we can be sure that no pseudo-sections are in the source,
4257 # split it up by section
4258 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4259 $comment = "(?:$uniq-!--.*?QINU)";
4264 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4266 (=+) # Should this be limited to 6?
4267 .+? # Section title...
4268 \\2 # Ending = count must match start
4275 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4282 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4283 (=+) # Should this be limited to 6?
4284 .+? # Section title...
4285 \\2 # Ending = count must match start
4286 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4295 PREG_SPLIT_DELIM_CAPTURE
);
4297 if( $mode == "get" ) {
4298 if( $section == 0 ) {
4299 // "Section 0" returns the content before any other section.
4304 } elseif( $mode == "replace" ) {
4305 if( $section == 0 ) {
4306 $rv = $newtext . "\n\n";
4315 for( $index = 1; $index < count( $secs ); ) {
4316 $headerLine = $secs[$index++
];
4317 if( $secs[$index] ) {
4319 $headerLevel = strlen( $secs[$index++
] );
4323 $headerLevel = intval( $secs[$index++
] );
4325 $content = $secs[$index++
];
4328 if( $mode == "get" ) {
4329 if( $count == $section ) {
4330 $rv = $headerLine . $content;
4331 $sectionLevel = $headerLevel;
4332 } elseif( $count > $section ) {
4333 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4334 $rv .= $headerLine . $content;
4336 // Broke out to a higher-level section
4340 } elseif( $mode == "replace" ) {
4341 if( $count < $section ) {
4342 $rv .= $headerLine . $content;
4343 } elseif( $count == $section ) {
4344 $rv .= $newtext . "\n\n";
4345 $sectionLevel = $headerLevel;
4346 } elseif( $count > $section ) {
4347 if( $headerLevel <= $sectionLevel ) {
4348 // Passed the section's sub-parts.
4352 $rv .= $headerLine . $content;
4357 # reinsert stripped tags
4358 $rv = $this->unstrip( $rv, $striparray );
4359 $rv = $this->unstripNoWiki( $rv, $striparray );
4365 * This function returns the text of a section, specified by a number ($section).
4366 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4367 * the first section before any such heading (section 0).
4369 * If a section contains subsections, these are also returned.
4371 * @param $text String: text to look in
4372 * @param $section Integer: section number
4373 * @return string text of the requested section
4375 function getSection( $text, $section ) {
4376 return $this->extractSections( $text, $section, "get" );
4379 function replaceSection( $oldtext, $section, $text ) {
4380 return $this->extractSections( $oldtext, $section, "replace", $text );
4387 * @package MediaWiki
4391 var $mText, # The output text
4392 $mLanguageLinks, # List of the full text of language links, in the order they appear
4393 $mCategories, # Map of category names to sort keys
4394 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4395 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4396 $mVersion, # Compatibility check
4397 $mTitleText, # title text of the chosen language variant
4398 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4399 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4400 $mImages, # DB keys of the images used, in the array key only
4401 $mExternalLinks, # External link URLs, in the key only
4402 $mHTMLtitle, # Display HTML title
4403 $mSubtitle, # Additional subtitle
4404 $mNewSection, # Show a new section link?
4405 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4407 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4408 $containsOldMagic = false, $titletext = '' )
4410 $this->mText
= $text;
4411 $this->mLanguageLinks
= $languageLinks;
4412 $this->mCategories
= $categoryLinks;
4413 $this->mContainsOldMagic
= $containsOldMagic;
4414 $this->mCacheTime
= '';
4415 $this->mVersion
= MW_PARSER_VERSION
;
4416 $this->mTitleText
= $titletext;
4417 $this->mLinks
= array();
4418 $this->mTemplates
= array();
4419 $this->mImages
= array();
4420 $this->mExternalLinks
= array();
4421 $this->mHTMLtitle
= "" ;
4422 $this->mSubtitle
= "" ;
4423 $this->mNewSection
= false;
4424 $this->mNoGallery
= false;
4427 function getText() { return $this->mText
; }
4428 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4429 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4430 function &getCategories() { return $this->mCategories
; }
4431 function getCacheTime() { return $this->mCacheTime
; }
4432 function getTitleText() { return $this->mTitleText
; }
4433 function &getLinks() { return $this->mLinks
; }
4434 function &getTemplates() { return $this->mTemplates
; }
4435 function &getImages() { return $this->mImages
; }
4436 function &getExternalLinks() { return $this->mExternalLinks
; }
4437 function getNoGallery() { return $this->mNoGallery
; }
4439 function containsOldMagic() { return $this->mContainsOldMagic
; }
4440 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4441 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4442 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4443 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4444 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4445 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4447 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4448 function addImage( $name ) { $this->mImages
[$name] = 1; }
4449 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4450 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4452 function setNewSection( $value ) {
4453 $this->mNewSection
= (bool)$value;
4455 function getNewSection() {
4456 return (bool)$this->mNewSection
;
4459 function addLink( $title, $id ) {
4460 $ns = $title->getNamespace();
4461 $dbk = $title->getDBkey();
4462 if ( !isset( $this->mLinks
[$ns] ) ) {
4463 $this->mLinks
[$ns] = array();
4465 $this->mLinks
[$ns][$dbk] = $id;
4468 function addTemplate( $title, $id ) {
4469 $ns = $title->getNamespace();
4470 $dbk = $title->getDBkey();
4471 if ( !isset( $this->mTemplates
[$ns] ) ) {
4472 $this->mTemplates
[$ns] = array();
4474 $this->mTemplates
[$ns][$dbk] = $id;
4478 * Return true if this cached output object predates the global or
4479 * per-article cache invalidation timestamps, or if it comes from
4480 * an incompatible older version.
4482 * @param string $touched the affected article's last touched timestamp
4486 function expired( $touched ) {
4487 global $wgCacheEpoch;
4488 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4489 $this->getCacheTime() < $touched ||
4490 $this->getCacheTime() <= $wgCacheEpoch ||
4491 !isset( $this->mVersion
) ||
4492 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4497 * Set options of the Parser
4499 * @package MediaWiki
4503 # All variables are private
4504 var $mUseTeX; # Use texvc to expand <math> tags
4505 var $mUseDynamicDates; # Use DateFormatter to format dates
4506 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4507 var $mAllowExternalImages; # Allow external images inline
4508 var $mAllowExternalImagesFrom; # If not, any exception?
4509 var $mSkin; # Reference to the preferred skin
4510 var $mDateFormat; # Date format index
4511 var $mEditSection; # Create "edit section" links
4512 var $mNumberHeadings; # Automatically number headings
4513 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4514 var $mTidy; # Ask for tidy cleanup
4515 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4517 var $mUser; # Stored user object, just used to initialise the skin
4519 function getUseTeX() { return $this->mUseTeX
; }
4520 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4521 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4522 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4523 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4524 function getDateFormat() { return $this->mDateFormat
; }
4525 function getEditSection() { return $this->mEditSection
; }
4526 function getNumberHeadings() { return $this->mNumberHeadings
; }
4527 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4528 function getTidy() { return $this->mTidy
; }
4529 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4531 function &getSkin() {
4532 if ( !isset( $this->mSkin
) ) {
4533 $this->mSkin
= $this->mUser
->getSkin();
4535 return $this->mSkin
;
4538 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4539 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4540 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4541 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4542 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4543 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4544 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4545 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4546 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4547 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4548 function setSkin( &$x ) { $this->mSkin
=& $x; }
4549 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4551 function ParserOptions( $user = null ) {
4552 $this->initialiseFromUser( $user );
4556 * Get parser options
4559 function newFromUser( &$user ) {
4560 return new ParserOptions( $user );
4563 /** Get user options */
4564 function initialiseFromUser( &$userInput ) {
4565 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4566 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4567 $fname = 'ParserOptions::initialiseFromUser';
4568 wfProfileIn( $fname );
4569 if ( !$userInput ) {
4571 if ( isset( $wgUser ) ) {
4575 $user->setLoaded( true );
4578 $user =& $userInput;
4581 $this->mUser
= $user;
4583 $this->mUseTeX
= $wgUseTeX;
4584 $this->mUseDynamicDates
= $wgUseDynamicDates;
4585 $this->mInterwikiMagic
= $wgInterwikiMagic;
4586 $this->mAllowExternalImages
= $wgAllowExternalImages;
4587 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4588 $this->mSkin
= null; # Deferred
4589 $this->mDateFormat
= $user->getOption( 'date' );
4590 $this->mEditSection
= true;
4591 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4592 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4593 $this->mTidy
= false;
4594 $this->mInterfaceMessage
= false;
4595 wfProfileOut( $fname );
4600 * Callback function used by Parser::replaceLinkHolders()
4601 * to substitute link placeholders.
4603 function &wfOutputReplaceMatches( $matches ) {
4604 global $wgOutputReplace;
4605 return $wgOutputReplace[$matches[1]];
4609 * Return the total number of articles
4611 function wfNumberOfArticles() {
4612 global $wgNumberOfArticles;
4615 return $wgNumberOfArticles;
4619 * Return the number of files
4621 function wfNumberOfFiles() {
4622 $fname = 'wfNumberOfFiles';
4624 wfProfileIn( $fname );
4625 $dbr =& wfGetDB( DB_SLAVE
);
4626 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4627 wfProfileOut( $fname );
4633 * Return the number of user accounts
4636 function wfNumberOfUsers() {
4637 wfProfileIn( 'wfNumberOfUsers' );
4638 $dbr =& wfGetDB( DB_SLAVE
);
4639 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4640 wfProfileOut( 'wfNumberOfUsers' );
4645 * Return the total number of pages
4648 function wfNumberOfPages() {
4649 wfProfileIn( 'wfNumberOfPages' );
4650 $dbr =& wfGetDB( DB_SLAVE
);
4651 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4652 wfProfileOut( 'wfNumberOfPages' );
4657 * Return the total number of admins
4661 function wfNumberOfAdmins() {
4662 static $admins = -1;
4663 wfProfileIn( 'wfNumberOfAdmins' );
4664 if( $admins == -1 ) {
4665 $dbr =& wfGetDB( DB_SLAVE
);
4666 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4668 wfProfileOut( 'wfNumberOfAdmins' );
4669 return (int)$admins;
4673 * Count the number of pages in a particular namespace
4675 * @param $ns Namespace
4678 function wfPagesInNs( $ns ) {
4679 static $pageCount = array();
4680 wfProfileIn( 'wfPagesInNs' );
4681 if( !isset( $pageCount[$ns] ) ) {
4682 $dbr =& wfGetDB( DB_SLAVE
);
4683 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4685 wfProfileOut( 'wfPagesInNs' );
4686 return (int)$pageCount[$ns];
4690 * Get various statistics from the database
4693 function wfLoadSiteStats() {
4694 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4695 $fname = 'wfLoadSiteStats';
4697 if ( -1 != $wgNumberOfArticles ) return;
4698 $dbr =& wfGetDB( DB_SLAVE
);
4699 $s = $dbr->selectRow( 'site_stats',
4700 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4701 array( 'ss_row_id' => 1 ), $fname
4704 if ( $s === false ) {
4707 $wgTotalViews = $s->ss_total_views
;
4708 $wgTotalEdits = $s->ss_total_edits
;
4709 $wgNumberOfArticles = $s->ss_good_articles
;
4715 * Basically replacing " > and < with HTML entities ( ", >, <)
4717 * @param $in String: text that might contain HTML tags.
4718 * @return string Escaped string
4720 function wfEscapeHTMLTagsOnly( $in ) {
4722 array( '"', '>', '<' ),
4723 array( '"', '>', '<' ),