c4fed1d1b774231c8d3c2fea8b30eda70bee26b8
3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.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
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 # Clear these on every parse, bug 4549
156 $this->mTemplates
= array();
157 $this->mTemplatePath
= array();
159 wfRunHooks( 'ParserClearState', array( &$this ) );
163 * Accessor for mUniqPrefix.
167 function UniqPrefix() {
168 return $this->mUniqPrefix
;
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
198 $this->mOptions
= $options;
199 $this->mTitle
=& $title;
200 $this->mRevisionId
= $revid;
201 $this->mOutputType
= OT_HTML
;
203 $this->mStripState
= NULL;
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState
;
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
219 $text = $this->internalParse( $text );
221 $text = $this->unstrip( $text, $this->mStripState
);
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1 ',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
235 $text = $this->doBlockLevels( $text, $linestart );
237 $this->replaceLinkHolders( $text );
239 # the position of the convert() call should not be changed. it
240 # assumes that the links are all replaces and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
243 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
245 $text = $this->unstripNoWiki( $text, $this->mStripState
);
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
249 $text = Sanitizer
::normalizeCharReferences( $text );
251 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
252 $text = Parser
::tidy($text);
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
257 $this->mOutput
->setText( $text );
258 wfProfileOut( $fname );
260 return $this->mOutput
;
264 * Get a random string
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
274 * Replaces all occurrences of <$tag>content</$tag> in the text
275 * with a random marker and returns the new text. the output parameter
276 * $content will be an associative array filled with data on the form
277 * $unique_marker => content.
279 * If $content is already set, the additional entries will be appended
280 * If $tag is set to STRIP_COMMENTS, the function will extract
281 * <!-- HTML comments -->
286 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
287 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
302 if( $tag == STRIP_COMMENTS
) {
303 $start = '/<!--()()/';
306 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
307 $end = "/<\\/$tag\\s*>/i";
310 while ( '' != $text ) {
311 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
313 if( count( $p ) < 4 ) {
320 $marker = $rnd . sprintf('%08X', $n++
);
321 $stripped .= $marker;
323 $tags[$marker] = "<$tag$attributes$empty>";
324 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
326 if ( $empty === '/' ) {
327 // Empty element tag, <tag />
328 $content[$marker] = null;
331 $q = preg_split( $end, $inside, 2 );
332 $content[$marker] = $q[0];
333 if( count( $q ) < 2 ) {
334 # No end tag -- let it run out to the end of the text.
345 * Wrapper function for extractTagsAndParams
346 * for cases where $tags and $params isn't needed
347 * i.e. where tags will never have params, like <nowiki>
352 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
353 $dummy_tags = array();
354 $dummy_params = array();
356 return Parser
::extractTagsAndParams( $tag, $text, $content,
357 $dummy_tags, $dummy_params, $uniq_prefix );
361 * Strips and renders nowiki, pre, math, hiero
362 * If $render is set, performs necessary rendering operations on plugins
363 * Returns the text, and fills an array with data needed in unstrip()
364 * If the $state is already a valid strip state, it adds to the state
366 * @param bool $stripcomments when set, HTML comments <!-- like this -->
367 * will be stripped in addition to other tags. This is important
368 * for section editing, where these comments cause confusion when
369 * counting the sections in the wikisource
373 function strip( $text, &$state, $stripcomments = false ) {
374 $render = ($this->mOutputType
== OT_HTML
);
375 $html_content = array();
376 $nowiki_content = array();
377 $math_content = array();
378 $pre_content = array();
379 $comment_content = array();
380 $ext_content = array();
382 $ext_params = array();
383 $gallery_content = array();
385 # Replace any instances of the placeholders
386 $uniq_prefix = $this->mUniqPrefix
;
387 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
392 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
393 foreach( $html_content as $marker => $content ) {
395 # Raw and unchecked for validity.
396 $html_content[$marker] = $content;
398 $html_content[$marker] = '<html>'.$content.'</html>';
404 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
405 foreach( $nowiki_content as $marker => $content ) {
407 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
409 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
414 if( $this->mOptions
->getUseTeX() ) {
415 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
416 foreach( $math_content as $marker => $content ){
418 $math_content[$marker] = renderMath( $content );
420 $math_content[$marker] = '<math>'.$content.'</math>';
426 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
427 foreach( $pre_content as $marker => $content ){
429 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
431 $pre_content[$marker] = '<pre>'.$content.'</pre>';
436 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
437 foreach( $gallery_content as $marker => $content ) {
438 require_once( 'ImageGallery.php' );
440 $gallery_content[$marker] = $this->renderImageGallery( $content );
442 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
448 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
449 foreach( $comment_content as $marker => $content ){
450 $comment_content[$marker] = '<!--'.$content.'-->';
455 foreach ( $this->mTagHooks
as $tag => $callback ) {
456 $ext_content[$tag] = array();
457 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
458 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
459 foreach( $ext_content[$tag] as $marker => $content ) {
460 $full_tag = $ext_tags[$tag][$marker];
461 $params = $ext_params[$tag][$marker];
463 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
465 if ( is_null( $content ) ) {
467 $ext_content[$tag][$marker] = $full_tag;
469 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
475 # Merge state with the pre-existing state, if there is one
477 $state['html'] = $state['html'] +
$html_content;
478 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
479 $state['math'] = $state['math'] +
$math_content;
480 $state['pre'] = $state['pre'] +
$pre_content;
481 $state['gallery'] = $state['gallery'] +
$gallery_content;
482 $state['comment'] = $state['comment'] +
$comment_content;
484 foreach( $ext_content as $tag => $array ) {
485 if ( array_key_exists( $tag, $state ) ) {
486 $state[$tag] = $state[$tag] +
$array;
491 'html' => $html_content,
492 'nowiki' => $nowiki_content,
493 'math' => $math_content,
494 'pre' => $pre_content,
495 'gallery' => $gallery_content,
496 'comment' => $comment_content,
503 * restores pre, math, and hiero removed by strip()
505 * always call unstripNoWiki() after this one
508 function unstrip( $text, &$state ) {
509 if ( !is_array( $state ) ) {
513 # Must expand in reverse order, otherwise nested tags will be corrupted
514 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
515 if( $tag != 'nowiki' && $tag != 'html' ) {
516 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
517 $text = str_replace( $uniq, $content, $text );
526 * always call this after unstrip() to preserve the order
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
535 # Must expand in reverse order, otherwise nested tags will be corrupted
536 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
537 $text = str_replace( key( $state['nowiki'] ), $content, $text );
542 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
543 $text = str_replace( key( $state['html'] ), $content, $text );
551 * Add an item to the strip state
552 * Returns the unique tag which must be inserted into the stripped text
553 * The tag will be replaced with the original text in unstrip()
557 function insertStripItem( $text, &$state ) {
558 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
565 'comment' => array(),
566 'gallery' => array(),
569 $state['item'][$rnd] = $text;
574 * Interface with html tidy, used if $wgUseTidy = true.
575 * If tidy isn't able to correct the markup, the original will be
576 * returned in all its glory with a warning comment appended.
578 * Either the external tidy program or the in-process tidy extension
579 * will be used depending on availability. Override the default
580 * $wgTidyInternal setting to disable the internal if it's not working.
582 * @param string $text Hideous HTML input
583 * @return string Corrected HTML output
587 function tidy( $text ) {
588 global $wgTidyInternal;
589 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
590 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
591 '<head><title>test</title></head><body>'.$text.'</body></html>';
592 if( $wgTidyInternal ) {
593 $correctedtext = Parser
::internalTidy( $wrappedtext );
595 $correctedtext = Parser
::externalTidy( $wrappedtext );
597 if( is_null( $correctedtext ) ) {
598 wfDebug( "Tidy error detected!\n" );
599 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
601 return $correctedtext;
605 * Spawn an external HTML tidy process and get corrected markup back from it.
610 function externalTidy( $text ) {
611 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
612 $fname = 'Parser::externalTidy';
613 wfProfileIn( $fname );
618 $descriptorspec = array(
619 0 => array('pipe', 'r'),
620 1 => array('pipe', 'w'),
621 2 => array('file', '/dev/null', 'a')
624 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
625 if (is_resource($process)) {
626 // Theoretically, this style of communication could cause a deadlock
627 // here. If the stdout buffer fills up, then writes to stdin could
628 // block. This doesn't appear to happen with tidy, because tidy only
629 // writes to stdout after it's finished reading from stdin. Search
630 // for tidyParseStdin and tidySaveStdout in console/tidy.c
631 fwrite($pipes[0], $text);
633 while (!feof($pipes[1])) {
634 $cleansource .= fgets($pipes[1], 1024);
637 proc_close($process);
640 wfProfileOut( $fname );
642 if( $cleansource == '' && $text != '') {
643 // Some kind of error happened, so we couldn't get the corrected text.
644 // Just give up; we'll use the source text and append a warning.
652 * Use the HTML tidy PECL extension to use the tidy library in-process,
653 * saving the overhead of spawning a new process. Currently written to
654 * the PHP 4.3.x version of the extension, may not work on PHP 5.
656 * 'pear install tidy' should be able to compile the extension module.
661 function internalTidy( $text ) {
663 $fname = 'Parser::internalTidy';
664 wfProfileIn( $fname );
666 tidy_load_config( $wgTidyConf );
667 tidy_set_encoding( 'utf8' );
668 tidy_parse_string( $text );
670 if( tidy_get_status() == 2 ) {
671 // 2 is magic number for fatal error
672 // http://www.php.net/manual/en/function.tidy-get-status.php
675 $cleansource = tidy_get_output();
677 wfProfileOut( $fname );
682 * parse the wiki syntax used to render tables
686 function doTableStuff ( $t ) {
687 $fname = 'Parser::doTableStuff';
688 wfProfileIn( $fname );
690 $t = explode ( "\n" , $t ) ;
691 $td = array () ; # Is currently a td tag open?
692 $ltd = array () ; # Was it TD or TH?
693 $tr = array () ; # Is currently a tr tag open?
694 $ltr = array () ; # tr attributes
695 $has_opened_tr = array(); # Did this table open a <tr> element?
696 $indent_level = 0; # indent level of the table
697 foreach ( $t AS $k => $x )
700 $fc = substr ( $x , 0 , 1 ) ;
701 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
702 $indent_level = strlen( $matches[1] );
704 $attributes = $this->unstripForHTML( $matches[2] );
706 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
707 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
708 array_push ( $td , false ) ;
709 array_push ( $ltd , '' ) ;
710 array_push ( $tr , false ) ;
711 array_push ( $ltr , '' ) ;
712 array_push ( $has_opened_tr, false );
714 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
715 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
716 $z = "</table>" . substr ( $x , 2);
717 $l = array_pop ( $ltd ) ;
718 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
719 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
720 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
722 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
724 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
725 $x = substr ( $x , 1 ) ;
726 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
728 $l = array_pop ( $ltd ) ;
729 array_pop ( $has_opened_tr );
730 array_push ( $has_opened_tr , true ) ;
731 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
732 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
735 array_push ( $tr , false ) ;
736 array_push ( $td , false ) ;
737 array_push ( $ltd , '' ) ;
738 $attributes = $this->unstripForHTML( $x );
739 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
741 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
743 if ( '|+' == substr ( $x , 0 , 2 ) ) {
745 $x = substr ( $x , 1 ) ;
747 $after = substr ( $x , 1 ) ;
748 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
749 $after = explode ( '||' , $after ) ;
752 # Loop through each table cell
753 foreach ( $after AS $theline )
758 $tra = array_pop ( $ltr ) ;
759 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
760 array_push ( $tr , true ) ;
761 array_push ( $ltr , '' ) ;
762 array_pop ( $has_opened_tr );
763 array_push ( $has_opened_tr , true ) ;
766 $l = array_pop ( $ltd ) ;
767 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
768 if ( $fc == '|' ) $l = 'td' ;
769 else if ( $fc == '!' ) $l = 'th' ;
770 else if ( $fc == '+' ) $l = 'caption' ;
772 array_push ( $ltd , $l ) ;
775 $y = explode ( '|' , $theline , 2 ) ;
776 # Note that a '|' inside an invalid link should not
777 # be mistaken as delimiting cell parameters
778 if ( strpos( $y[0], '[[' ) !== false ) {
779 $y = array ($theline);
781 if ( count ( $y ) == 1 )
782 $y = "{$z}<{$l}>{$y[0]}" ;
784 $attributes = $this->unstripForHTML( $y[0] );
785 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
788 array_push ( $td , true ) ;
793 # Closing open td, tr && table
794 while ( count ( $td ) > 0 )
796 $l = array_pop ( $ltd ) ;
797 if ( array_pop ( $td ) ) $t[] = '</td>' ;
798 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
799 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
803 $t = implode ( "\n" , $t ) ;
804 wfProfileOut( $fname );
809 * Helper function for parse() that transforms wiki markup into
810 * HTML. Only called for $mOutputType == OT_HTML.
814 function internalParse( $text ) {
818 $fname = 'Parser::internalParse';
819 wfProfileIn( $fname );
821 # Remove <noinclude> tags and <includeonly> sections
822 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
823 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
824 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
826 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
827 $text = $this->replaceVariables( $text, $args );
829 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
831 $text = $this->doHeadings( $text );
832 if($this->mOptions
->getUseDynamicDates()) {
833 $df =& DateFormatter
::getInstance();
834 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
836 $text = $this->doAllQuotes( $text );
837 $text = $this->replaceInternalLinks( $text );
838 $text = $this->replaceExternalLinks( $text );
840 # replaceInternalLinks may sometimes leave behind
841 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
842 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
844 $text = $this->doMagicLinks( $text );
845 $text = $this->doTableStuff( $text );
846 $text = $this->formatHeadings( $text, $isMain );
848 wfProfileOut( $fname );
853 * Replace special strings like "ISBN xxx" and "RFC xxx" with
854 * magic external links.
858 function &doMagicLinks( &$text ) {
859 $text = $this->magicISBN( $text );
860 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
861 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
866 * Parse headers and return html
870 function doHeadings( $text ) {
871 $fname = 'Parser::doHeadings';
872 wfProfileIn( $fname );
873 for ( $i = 6; $i >= 1; --$i ) {
874 $h = str_repeat( '=', $i );
875 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
876 "<h{$i}>\\1</h{$i}>\\2", $text );
878 wfProfileOut( $fname );
883 * Replace single quotes with HTML markup
885 * @return string the altered text
887 function doAllQuotes( $text ) {
888 $fname = 'Parser::doAllQuotes';
889 wfProfileIn( $fname );
891 $lines = explode( "\n", $text );
892 foreach ( $lines as $line ) {
893 $outtext .= $this->doQuotes ( $line ) . "\n";
895 $outtext = substr($outtext, 0,-1);
896 wfProfileOut( $fname );
901 * Helper function for doAllQuotes()
904 function doQuotes( $text ) {
905 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
906 if ( count( $arr ) == 1 )
910 # First, do some preliminary work. This may shift some apostrophes from
911 # being mark-up to being text. It also counts the number of occurrences
912 # of bold and italics mark-ups.
916 foreach ( $arr as $r )
918 if ( ( $i %
2 ) == 1 )
920 # If there are ever four apostrophes, assume the first is supposed to
921 # be text, and the remaining three constitute mark-up for bold text.
922 if ( strlen( $arr[$i] ) == 4 )
927 # If there are more than 5 apostrophes in a row, assume they're all
928 # text except for the last 5.
929 else if ( strlen( $arr[$i] ) > 5 )
931 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
934 # Count the number of occurrences of bold and italics mark-ups.
935 # We are not counting sequences of five apostrophes.
936 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
937 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
938 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
943 # If there is an odd number of both bold and italics, it is likely
944 # that one of the bold ones was meant to be an apostrophe followed
945 # by italics. Which one we cannot know for certain, but it is more
946 # likely to be one that has a single-letter word before it.
947 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
950 $firstsingleletterword = -1;
951 $firstmultiletterword = -1;
953 foreach ( $arr as $r )
955 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
957 $x1 = substr ($arr[$i-1], -1);
958 $x2 = substr ($arr[$i-1], -2, 1);
960 if ($firstspace == -1) $firstspace = $i;
961 } else if ($x2 == ' ') {
962 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
964 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
970 # If there is a single-letter word, use it!
971 if ($firstsingleletterword > -1)
973 $arr [ $firstsingleletterword ] = "''";
974 $arr [ $firstsingleletterword-1 ] .= "'";
976 # If not, but there's a multi-letter word, use that one.
977 else if ($firstmultiletterword > -1)
979 $arr [ $firstmultiletterword ] = "''";
980 $arr [ $firstmultiletterword-1 ] .= "'";
982 # ... otherwise use the first one that has neither.
983 # (notice that it is possible for all three to be -1 if, for example,
984 # there is only one pentuple-apostrophe in the line)
985 else if ($firstspace > -1)
987 $arr [ $firstspace ] = "''";
988 $arr [ $firstspace-1 ] .= "'";
992 # Now let's actually convert our apostrophic mush to HTML!
1001 if ($state == 'both')
1008 if (strlen ($r) == 2)
1011 { $output .= '</i>'; $state = ''; }
1012 else if ($state == 'bi')
1013 { $output .= '</i>'; $state = 'b'; }
1014 else if ($state == 'ib')
1015 { $output .= '</b></i><b>'; $state = 'b'; }
1016 else if ($state == 'both')
1017 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1018 else # $state can be 'b' or ''
1019 { $output .= '<i>'; $state .= 'i'; }
1021 else if (strlen ($r) == 3)
1024 { $output .= '</b>'; $state = ''; }
1025 else if ($state == 'bi')
1026 { $output .= '</i></b><i>'; $state = 'i'; }
1027 else if ($state == 'ib')
1028 { $output .= '</b>'; $state = 'i'; }
1029 else if ($state == 'both')
1030 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1031 else # $state can be 'i' or ''
1032 { $output .= '<b>'; $state .= 'b'; }
1034 else if (strlen ($r) == 5)
1037 { $output .= '</b><i>'; $state = 'i'; }
1038 else if ($state == 'i')
1039 { $output .= '</i><b>'; $state = 'b'; }
1040 else if ($state == 'bi')
1041 { $output .= '</i></b>'; $state = ''; }
1042 else if ($state == 'ib')
1043 { $output .= '</b></i>'; $state = ''; }
1044 else if ($state == 'both')
1045 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1046 else # ($state == '')
1047 { $buffer = ''; $state = 'both'; }
1052 # Now close all remaining tags. Notice that the order is important.
1053 if ($state == 'b' ||
$state == 'ib')
1055 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1059 if ($state == 'both')
1060 $output .= '<b><i>'.$buffer.'</i></b>';
1066 * Replace external links
1068 * Note: this is all very hackish and the order of execution matters a lot.
1069 * Make sure to run maintenance/parserTests.php if you change this code.
1073 function replaceExternalLinks( $text ) {
1075 $fname = 'Parser::replaceExternalLinks';
1076 wfProfileIn( $fname );
1078 $sk =& $this->mOptions
->getSkin();
1080 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1082 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1085 while ( $i<count( $bits ) ) {
1087 $protocol = $bits[$i++
];
1088 $spaces = $bits[$i++
];
1089 $text = $bits[$i++
];
1090 $trail = $bits[$i++
];
1092 # The characters '<' and '>' (which were escaped by
1093 # removeHTMLtags()) should not be included in
1094 # URLs, per RFC 2396.
1095 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1096 $text = substr($url, $m2[0][1]) . ' ' . $text;
1097 $url = substr($url, 0, $m2[0][1]);
1100 # If the link text is an image URL, replace it with an <img> tag
1101 # This happened by accident in the original parser, but some people used it extensively
1102 $img = $this->maybeMakeExternalImage( $text );
1103 if ( $img !== false ) {
1109 # Set linktype for CSS - if URL==text, link is essentially free
1110 $linktype = ($text == $url) ?
'free' : 'text';
1112 # No link text, e.g. [http://domain.tld/some.link]
1113 if ( $text == '' ) {
1114 # Autonumber if allowed
1115 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1116 $text = '[' . ++
$this->mAutonumber
. ']';
1117 $linktype = 'autonumber';
1119 # Otherwise just use the URL
1120 $text = htmlspecialchars( $url );
1124 # Have link text, e.g. [http://domain.tld/some.link text]s
1126 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1129 $text = $wgContLang->markNoConversion($text);
1131 # Replace & from obsolete syntax with &.
1132 # All HTML entities will be escaped by makeExternalLink()
1133 $url = str_replace( '&', '&', $url );
1134 # Replace unnecessary URL escape codes with the referenced character
1135 # This prevents spammers from hiding links from the filters
1136 $url = Parser
::replaceUnusualEscapes( $url );
1138 # Process the trail (i.e. everything after this link up until start of the next link),
1139 # replacing any non-bracketed links
1140 $trail = $this->replaceFreeExternalLinks( $trail );
1142 # Use the encoded URL
1143 # This means that users can paste URLs directly into the text
1144 # Funny characters like ö aren't valid in URLs anyway
1145 # This was changed in August 2004
1146 if ( strlen ( $spaces ) < 2 ) {
1148 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1150 # Fix for [url text] (notice the two blanks)
1151 $s .= '[' . $sk->makeExternalLink( $url, $url, false, "free" ) . $spaces . $text . ']' . $dtrail . $trail;
1154 # Register link in the output object
1155 $this->mOutput
->addExternalLink( $url );
1158 wfProfileOut( $fname );
1163 * Replace anything that looks like a URL with a link
1166 function replaceFreeExternalLinks( $text ) {
1168 $fname = 'Parser::replaceFreeExternalLinks';
1169 wfProfileIn( $fname );
1171 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1172 $s = array_shift( $bits );
1175 $sk =& $this->mOptions
->getSkin();
1177 while ( $i < count( $bits ) ){
1178 $protocol = $bits[$i++
];
1179 $remainder = $bits[$i++
];
1181 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1182 # Found some characters after the protocol that look promising
1183 $url = $protocol . $m[1];
1186 # The characters '<' and '>' (which were escaped by
1187 # removeHTMLtags()) should not be included in
1188 # URLs, per RFC 2396.
1189 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1190 $trail = substr($url, $m2[0][1]) . $trail;
1191 $url = substr($url, 0, $m2[0][1]);
1194 # Move trailing punctuation to $trail
1196 # If there is no left bracket, then consider right brackets fair game too
1197 if ( strpos( $url, '(' ) === false ) {
1201 $numSepChars = strspn( strrev( $url ), $sep );
1202 if ( $numSepChars ) {
1203 $trail = substr( $url, -$numSepChars ) . $trail;
1204 $url = substr( $url, 0, -$numSepChars );
1207 # Replace & from obsolete syntax with &.
1208 # All HTML entities will be escaped by makeExternalLink()
1209 # or maybeMakeExternalImage()
1210 $url = str_replace( '&', '&', $url );
1211 # Replace unnecessary URL escape codes with their equivalent characters
1212 $url = Parser
::replaceUnusualEscapes( $url );
1214 # Is this an external image?
1215 $text = $this->maybeMakeExternalImage( $url );
1216 if ( $text === false ) {
1217 # Not an image, make a link
1218 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1219 # Register it in the output object
1220 $this->mOutput
->addExternalLink( $url );
1222 $s .= $text . $trail;
1224 $s .= $protocol . $remainder;
1227 wfProfileOut( $fname );
1232 * Replace unusual URL escape codes with their equivalent characters
1237 function replaceUnusualEscapes( $url ) {
1238 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1239 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1243 * Callback function used in replaceUnusualEscapes().
1244 * Replaces unusual URL escape codes with their equivalent character
1248 function replaceUnusualEscapesCallback( $matches ) {
1249 $char = urldecode( $matches[0] );
1250 $ord = ord( $char );
1251 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1252 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1253 // No, shouldn't be escaped
1256 // Yes, leave it escaped
1262 * make an image if it's allowed, either through the global
1263 * option or through the exception
1266 function maybeMakeExternalImage( $url ) {
1267 $sk =& $this->mOptions
->getSkin();
1268 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1269 $imagesexception = !empty($imagesfrom);
1271 if ( $this->mOptions
->getAllowExternalImages()
1272 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1273 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1275 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1282 * Process [[ ]] wikilinks
1286 function replaceInternalLinks( $s ) {
1288 static $fname = 'Parser::replaceInternalLinks' ;
1290 wfProfileIn( $fname );
1292 wfProfileIn( $fname.'-setup' );
1294 # the % is needed to support urlencoded titles as well
1295 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1297 $sk =& $this->mOptions
->getSkin();
1299 #split the entire text string on occurences of [[
1300 $a = explode( '[[', ' ' . $s );
1301 #get the first element (all text up to first [[), and remove the space we added
1302 $s = array_shift( $a );
1303 $s = substr( $s, 1 );
1305 # Match a link having the form [[namespace:link|alternate]]trail
1307 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1308 # Match cases where there is no "]]", which might still be images
1309 static $e1_img = FALSE;
1310 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1311 # Match the end of a line for a word that's not followed by whitespace,
1312 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1313 $e2 = wfMsgForContent( 'linkprefix' );
1315 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1317 if( is_null( $this->mTitle
) ) {
1318 wfDebugDieBacktrace( 'nooo' );
1320 $nottalk = !$this->mTitle
->isTalkPage();
1322 if ( $useLinkPrefixExtension ) {
1323 if ( preg_match( $e2, $s, $m ) ) {
1324 $first_prefix = $m[2];
1326 $first_prefix = false;
1332 $selflink = $this->mTitle
->getPrefixedText();
1333 wfProfileOut( $fname.'-setup' );
1335 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1336 $useSubpages = $this->areSubpagesAllowed();
1338 # Loop for each link
1339 for ($k = 0; isset( $a[$k] ); $k++
) {
1341 if ( $useLinkPrefixExtension ) {
1342 wfProfileIn( $fname.'-prefixhandling' );
1343 if ( preg_match( $e2, $s, $m ) ) {
1351 $prefix = $first_prefix;
1352 $first_prefix = false;
1354 wfProfileOut( $fname.'-prefixhandling' );
1357 $might_be_img = false;
1359 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1361 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1362 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1363 # the real problem is with the $e1 regex
1366 # Still some problems for cases where the ] is meant to be outside punctuation,
1367 # and no image is in sight. See bug 2095.
1369 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1370 $text .= ']'; # so that replaceExternalLinks($text) works later
1373 # fix up urlencoded title texts
1374 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1376 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1377 $might_be_img = true;
1379 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1381 } else { # Invalid form; output directly
1382 $s .= $prefix . '[[' . $line ;
1386 # Don't allow internal links to pages containing
1387 # PROTO: where PROTO is a valid URL protocol; these
1388 # should be external links.
1389 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1390 $s .= $prefix . '[[' . $line ;
1394 # Make subpage if necessary
1395 if( $useSubpages ) {
1396 $link = $this->maybeDoSubpageLink( $m[1], $text );
1401 $noforce = (substr($m[1], 0, 1) != ':');
1403 # Strip off leading ':'
1404 $link = substr($link, 1);
1407 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1409 $s .= $prefix . '[[' . $line;
1413 #check other language variants of the link
1414 #if the article does not exist
1415 if( $checkVariantLink
1416 && $nt->getArticleID() == 0 ) {
1417 $wgContLang->findVariantLink($link, $nt);
1420 $ns = $nt->getNamespace();
1421 $iw = $nt->getInterWiki();
1423 if ($might_be_img) { # if this is actually an invalid link
1424 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1426 while (isset ($a[$k+
1]) ) {
1427 #look at the next 'line' to see if we can close it there
1428 $spliced = array_splice( $a, $k +
1, 1 );
1429 $next_line = array_shift( $spliced );
1430 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1431 # the first ]] closes the inner link, the second the image
1433 $text .= '[[' . $m[1];
1436 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1437 #if there's exactly one ]] that's fine, we'll keep looking
1438 $text .= '[[' . $m[0];
1440 #if $next_line is invalid too, we need look no further
1441 $text .= '[[' . $next_line;
1446 # we couldn't find the end of this imageLink, so output it raw
1447 #but don't ignore what might be perfectly normal links in the text we've examined
1448 $text = $this->replaceInternalLinks($text);
1449 $s .= $prefix . '[[' . $link . '|' . $text;
1450 # note: no $trail, because without an end, there *is* no trail
1453 } else { #it's not an image, so output it raw
1454 $s .= $prefix . '[[' . $link . '|' . $text;
1455 # note: no $trail, because without an end, there *is* no trail
1460 $wasblank = ( '' == $text );
1461 if( $wasblank ) $text = $link;
1464 # Link not escaped by : , create the various objects
1468 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1469 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1470 $s = rtrim($s . "\n");
1471 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1475 if ( $ns == NS_IMAGE
) {
1476 wfProfileIn( "$fname-image" );
1477 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1478 # recursively parse links inside the image caption
1479 # actually, this will parse them in any other parameters, too,
1480 # but it might be hard to fix that, and it doesn't matter ATM
1481 $text = $this->replaceExternalLinks($text);
1482 $text = $this->replaceInternalLinks($text);
1484 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1485 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1486 $this->mOutput
->addImage( $nt->getDBkey() );
1488 wfProfileOut( "$fname-image" );
1491 wfProfileOut( "$fname-image" );
1495 if ( $ns == NS_CATEGORY
) {
1496 wfProfileIn( "$fname-category" );
1497 $s = rtrim($s . "\n"); # bug 87
1500 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1501 $sortkey = $this->mTitle
->getText();
1503 $sortkey = $this->mTitle
->getPrefixedText();
1508 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1509 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1510 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1513 * Strip the whitespace Category links produce, see bug 87
1514 * @todo We might want to use trim($tmp, "\n") here.
1516 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1518 wfProfileOut( "$fname-category" );
1523 if( ( $nt->getPrefixedText() === $selflink ) &&
1524 ( $nt->getFragment() === '' ) ) {
1525 # Self-links are handled specially; generally de-link and change to bold.
1526 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1530 # Special and Media are pseudo-namespaces; no pages actually exist in them
1531 if( $ns == NS_MEDIA
) {
1532 $link = $sk->makeMediaLinkObj( $nt, $text );
1533 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1534 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1535 $this->mOutput
->addImage( $nt->getDBkey() );
1537 } elseif( $ns == NS_SPECIAL
) {
1538 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1540 } elseif( $ns == NS_IMAGE
) {
1541 $img = Image
::newFromTitle( $nt );
1542 if( $img->exists() ) {
1543 // Force a blue link if the file exists; may be a remote
1544 // upload on the shared repository, and we want to see its
1545 // auto-generated page.
1546 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1550 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1552 wfProfileOut( $fname );
1557 * Make a link placeholder. The text returned can be later resolved to a real link with
1558 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1559 * parsing of interwiki links, and secondly to allow all extistence checks and
1560 * article length checks (for stub links) to be bundled into a single query.
1563 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1564 if ( ! is_object($nt) ) {
1566 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1568 # Separate the link trail from the rest of the link
1569 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1571 if ( $nt->isExternal() ) {
1572 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1573 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1574 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1576 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1577 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1578 $this->mLinkHolders
['queries'][] = $query;
1579 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1580 $this->mLinkHolders
['titles'][] = $nt;
1582 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1589 * Render a forced-blue link inline; protect against double expansion of
1590 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1591 * Since this little disaster has to split off the trail text to avoid
1592 * breaking URLs in the following text without breaking trails on the
1593 * wiki links, it's been made into a horrible function.
1596 * @param string $text
1597 * @param string $query
1598 * @param string $trail
1599 * @param string $prefix
1600 * @return string HTML-wikitext mix oh yuck
1602 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1603 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1604 $sk =& $this->mOptions
->getSkin();
1605 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1606 return $this->armorLinks( $link ) . $trail;
1610 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1611 * going to go through further parsing steps before inline URL expansion.
1613 * In particular this is important when using action=render, which causes
1614 * full URLs to be included.
1616 * Oh man I hate our multi-layer parser!
1618 * @param string more-or-less HTML
1619 * @return string less-or-more HTML with NOPARSE bits
1621 function armorLinks( $text ) {
1622 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1623 "{$this->mUniqPrefix}NOPARSE$1", $text );
1627 * Return true if subpage links should be expanded on this page.
1630 function areSubpagesAllowed() {
1631 # Some namespaces don't allow subpages
1632 global $wgNamespacesWithSubpages;
1633 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1637 * Handle link to subpage if necessary
1638 * @param string $target the source of the link
1639 * @param string &$text the link text, modified as necessary
1640 * @return string the full name of the link
1643 function maybeDoSubpageLink($target, &$text) {
1646 # :Foobar -- override special treatment of prefix (images, language links)
1647 # /Foobar -- convert to CurrentPage/Foobar
1648 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1649 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1650 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1652 $fname = 'Parser::maybeDoSubpageLink';
1653 wfProfileIn( $fname );
1654 $ret = $target; # default return value is no change
1656 # Some namespaces don't allow subpages,
1657 # so only perform processing if subpages are allowed
1658 if( $this->areSubpagesAllowed() ) {
1659 # Look at the first character
1660 if( $target != '' && $target{0} == '/' ) {
1661 # / at end means we don't want the slash to be shown
1662 if( substr( $target, -1, 1 ) == '/' ) {
1663 $target = substr( $target, 1, -1 );
1666 $noslash = substr( $target, 1 );
1669 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1670 if( '' === $text ) {
1672 } # this might be changed for ugliness reasons
1674 # check for .. subpage backlinks
1676 $nodotdot = $target;
1677 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1679 $nodotdot = substr( $nodotdot, 3 );
1681 if($dotdotcount > 0) {
1682 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1683 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1684 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1685 # / at the end means don't show full path
1686 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1687 $nodotdot = substr( $nodotdot, 0, -1 );
1688 if( '' === $text ) {
1692 $nodotdot = trim( $nodotdot );
1693 if( $nodotdot != '' ) {
1694 $ret .= '/' . $nodotdot;
1701 wfProfileOut( $fname );
1706 * Used by doBlockLevels()
1709 /* private */ function closeParagraph() {
1711 if ( '' != $this->mLastSection
) {
1712 $result = '</' . $this->mLastSection
. ">\n";
1714 $this->mInPre
= false;
1715 $this->mLastSection
= '';
1718 # getCommon() returns the length of the longest common substring
1719 # of both arguments, starting at the beginning of both.
1721 /* private */ function getCommon( $st1, $st2 ) {
1722 $fl = strlen( $st1 );
1723 $shorter = strlen( $st2 );
1724 if ( $fl < $shorter ) { $shorter = $fl; }
1726 for ( $i = 0; $i < $shorter; ++
$i ) {
1727 if ( $st1{$i} != $st2{$i} ) { break; }
1731 # These next three functions open, continue, and close the list
1732 # element appropriate to the prefix character passed into them.
1734 /* private */ function openList( $char ) {
1735 $result = $this->closeParagraph();
1737 if ( '*' == $char ) { $result .= '<ul><li>'; }
1738 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1739 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1740 else if ( ';' == $char ) {
1741 $result .= '<dl><dt>';
1742 $this->mDTopen
= true;
1744 else { $result = '<!-- ERR 1 -->'; }
1749 /* private */ function nextItem( $char ) {
1750 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1751 else if ( ':' == $char ||
';' == $char ) {
1753 if ( $this->mDTopen
) { $close = '</dt>'; }
1754 if ( ';' == $char ) {
1755 $this->mDTopen
= true;
1756 return $close . '<dt>';
1758 $this->mDTopen
= false;
1759 return $close . '<dd>';
1762 return '<!-- ERR 2 -->';
1765 /* private */ function closeList( $char ) {
1766 if ( '*' == $char ) { $text = '</li></ul>'; }
1767 else if ( '#' == $char ) { $text = '</li></ol>'; }
1768 else if ( ':' == $char ) {
1769 if ( $this->mDTopen
) {
1770 $this->mDTopen
= false;
1771 $text = '</dt></dl>';
1773 $text = '</dd></dl>';
1776 else { return '<!-- ERR 3 -->'; }
1782 * Make lists from lines starting with ':', '*', '#', etc.
1785 * @return string the lists rendered as HTML
1787 function doBlockLevels( $text, $linestart ) {
1788 $fname = 'Parser::doBlockLevels';
1789 wfProfileIn( $fname );
1791 # Parsing through the text line by line. The main thing
1792 # happening here is handling of block-level elements p, pre,
1793 # and making lists from lines starting with * # : etc.
1795 $textLines = explode( "\n", $text );
1797 $lastPrefix = $output = '';
1798 $this->mDTopen
= $inBlockElem = false;
1800 $paragraphStack = false;
1802 if ( !$linestart ) {
1803 $output .= array_shift( $textLines );
1805 foreach ( $textLines as $oLine ) {
1806 $lastPrefixLength = strlen( $lastPrefix );
1807 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1808 $preOpenMatch = preg_match('/<pre/i', $oLine );
1809 if ( !$this->mInPre
) {
1810 # Multiple prefixes may abut each other for nested lists.
1811 $prefixLength = strspn( $oLine, '*#:;' );
1812 $pref = substr( $oLine, 0, $prefixLength );
1815 $pref2 = str_replace( ';', ':', $pref );
1816 $t = substr( $oLine, $prefixLength );
1817 $this->mInPre
= !empty($preOpenMatch);
1819 # Don't interpret any other prefixes in preformatted text
1821 $pref = $pref2 = '';
1826 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1827 # Same as the last item, so no need to deal with nesting or opening stuff
1828 $output .= $this->nextItem( substr( $pref, -1 ) );
1829 $paragraphStack = false;
1831 if ( substr( $pref, -1 ) == ';') {
1832 # The one nasty exception: definition lists work like this:
1833 # ; title : definition text
1834 # So we check for : in the remainder text to split up the
1835 # title and definition, without b0rking links.
1837 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1839 $output .= $term . $this->nextItem( ':' );
1842 } elseif( $prefixLength ||
$lastPrefixLength ) {
1843 # Either open or close a level...
1844 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1845 $paragraphStack = false;
1847 while( $commonPrefixLength < $lastPrefixLength ) {
1848 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1849 --$lastPrefixLength;
1851 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1852 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1854 while ( $prefixLength > $commonPrefixLength ) {
1855 $char = substr( $pref, $commonPrefixLength, 1 );
1856 $output .= $this->openList( $char );
1858 if ( ';' == $char ) {
1859 # FIXME: This is dupe of code above
1860 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1862 $output .= $term . $this->nextItem( ':' );
1865 ++
$commonPrefixLength;
1867 $lastPrefix = $pref2;
1869 if( 0 == $prefixLength ) {
1870 wfProfileIn( "$fname-paragraph" );
1871 # No prefix (not in list)--go to paragraph mode
1872 // XXX: use a stack for nestable elements like span, table and div
1873 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1874 $closematch = preg_match(
1875 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1876 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1877 if ( $openmatch or $closematch ) {
1878 $paragraphStack = false;
1879 $output .= $this->closeParagraph();
1880 if ( $preOpenMatch and !$preCloseMatch ) {
1881 $this->mInPre
= true;
1883 if ( $closematch ) {
1884 $inBlockElem = false;
1886 $inBlockElem = true;
1888 } else if ( !$inBlockElem && !$this->mInPre
) {
1889 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1891 if ($this->mLastSection
!= 'pre') {
1892 $paragraphStack = false;
1893 $output .= $this->closeParagraph().'<pre>';
1894 $this->mLastSection
= 'pre';
1896 $t = substr( $t, 1 );
1899 if ( '' == trim($t) ) {
1900 if ( $paragraphStack ) {
1901 $output .= $paragraphStack.'<br />';
1902 $paragraphStack = false;
1903 $this->mLastSection
= 'p';
1905 if ($this->mLastSection
!= 'p' ) {
1906 $output .= $this->closeParagraph();
1907 $this->mLastSection
= '';
1908 $paragraphStack = '<p>';
1910 $paragraphStack = '</p><p>';
1914 if ( $paragraphStack ) {
1915 $output .= $paragraphStack;
1916 $paragraphStack = false;
1917 $this->mLastSection
= 'p';
1918 } else if ($this->mLastSection
!= 'p') {
1919 $output .= $this->closeParagraph().'<p>';
1920 $this->mLastSection
= 'p';
1925 wfProfileOut( "$fname-paragraph" );
1927 // somewhere above we forget to get out of pre block (bug 785)
1928 if($preCloseMatch && $this->mInPre
) {
1929 $this->mInPre
= false;
1931 if ($paragraphStack === false) {
1935 while ( $prefixLength ) {
1936 $output .= $this->closeList( $pref2{$prefixLength-1} );
1939 if ( '' != $this->mLastSection
) {
1940 $output .= '</' . $this->mLastSection
. '>';
1941 $this->mLastSection
= '';
1944 wfProfileOut( $fname );
1949 * Split up a string on ':', ignoring any occurences inside
1950 * <a>..</a> or <span>...</span>
1951 * @param string $str the string to split
1952 * @param string &$before set to everything before the ':'
1953 * @param string &$after set to everything after the ':'
1954 * return string the position of the ':', or false if none found
1956 function findColonNoLinks($str, &$before, &$after) {
1957 # I wonder if we should make this count all tags, not just <a>
1958 # and <span>. That would prevent us from matching a ':' that
1959 # comes in the middle of italics other such formatting....
1961 $fname = 'Parser::findColonNoLinks';
1962 wfProfileIn( $fname );
1965 $colon = strpos($str, ':', $pos);
1967 if ($colon !== false) {
1968 $before = substr($str, 0, $colon);
1969 $after = substr($str, $colon +
1);
1971 # Skip any ':' within <a> or <span> pairs
1972 $a = substr_count($before, '<a');
1973 $s = substr_count($before, '<span');
1974 $ca = substr_count($before, '</a>');
1975 $cs = substr_count($before, '</span>');
1977 if ($a <= $ca and $s <= $cs) {
1978 # Tags are balanced before ':'; ok
1983 } while ($colon !== false);
1984 wfProfileOut( $fname );
1989 * Return value of a magic variable (like PAGENAME)
1993 function getVariableValue( $index ) {
1994 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1997 * Some of these require message or data lookups and can be
1998 * expensive to check many times.
2000 static $varCache = array();
2001 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2002 if ( isset( $varCache[$index] ) )
2003 return $varCache[$index];
2006 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2009 case MAG_CURRENTMONTH
:
2010 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2011 case MAG_CURRENTMONTHNAME
:
2012 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2013 case MAG_CURRENTMONTHNAMEGEN
:
2014 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2015 case MAG_CURRENTMONTHABBREV
:
2016 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2017 case MAG_CURRENTDAY
:
2018 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2019 case MAG_CURRENTDAY2
:
2020 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2022 return $this->mTitle
->getText();
2024 return $this->mTitle
->getPartialURL();
2025 case MAG_FULLPAGENAME
:
2026 return $this->mTitle
->getPrefixedText();
2027 case MAG_FULLPAGENAMEE
:
2028 return $this->mTitle
->getPrefixedURL();
2029 case MAG_REVISIONID
:
2030 return $this->mRevisionId
;
2032 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2033 case MAG_NAMESPACEE
:
2034 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2035 case MAG_CURRENTDAYNAME
:
2036 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2037 case MAG_CURRENTYEAR
:
2038 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2039 case MAG_CURRENTTIME
:
2040 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2041 case MAG_CURRENTWEEK
:
2042 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2043 // int to remove the padding
2044 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2045 case MAG_CURRENTDOW
:
2046 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2047 case MAG_NUMBEROFARTICLES
:
2048 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2049 case MAG_NUMBEROFFILES
:
2050 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2055 case MAG_SERVERNAME
:
2056 return $wgServerName;
2057 case MAG_SCRIPTPATH
:
2058 return $wgScriptPath;
2061 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2069 * initialise the magic variables (like CURRENTMONTHNAME)
2073 function initialiseVariables() {
2074 $fname = 'Parser::initialiseVariables';
2075 wfProfileIn( $fname );
2076 global $wgVariableIDs;
2077 $this->mVariables
= array();
2078 foreach ( $wgVariableIDs as $id ) {
2079 $mw =& MagicWord
::get( $id );
2080 $mw->addToArray( $this->mVariables
, $id );
2082 wfProfileOut( $fname );
2086 * parse any parentheses in format ((title|part|part))
2087 * and call callbacks to get a replacement text for any found piece
2089 * @param string $text The text to parse
2090 * @param array $callbacks rules in form:
2091 * '{' => array( # opening parentheses
2092 * 'end' => '}', # closing parentheses
2093 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2094 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2099 function replace_callback ($text, $callbacks) {
2100 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2101 $lastOpeningBrace = -1; # last not closed parentheses
2103 for ($i = 0; $i < strlen($text); $i++
) {
2104 # check for any opening brace
2107 foreach ($callbacks as $key => $value) {
2108 $pos = strpos ($text, $key, $i);
2109 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2115 if ($lastOpeningBrace >= 0) {
2116 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2118 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2123 $pos = strpos ($text, '|', $i);
2125 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2136 # found openning brace, lets add it to parentheses stack
2137 if (null != $rule) {
2138 $piece = array('brace' => $text[$i],
2139 'braceEnd' => $rule['end'],
2144 # count openning brace characters
2145 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2150 $piece['startAt'] = $i+
1;
2151 $piece['partStart'] = $i+
1;
2153 # we need to add to stack only if openning brace count is enough for any given rule
2154 foreach ($rule['cb'] as $cnt => $fn) {
2155 if ($piece['count'] >= $cnt) {
2156 $lastOpeningBrace ++
;
2157 $openingBraceStack[$lastOpeningBrace] = $piece;
2164 else if ($lastOpeningBrace >= 0) {
2165 # first check if it is a closing brace
2166 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2167 # lets check if it is enough characters for closing brace
2169 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2172 # if there are more closing parentheses than opening ones, we parse less
2173 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2174 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2176 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2178 $matchingCallback = null;
2179 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2180 if ($count >= $cnt && $matchingCount < $cnt) {
2181 $matchingCount = $cnt;
2182 $matchingCallback = $fn;
2186 if ($matchingCount == 0) {
2191 # lets set a title or last part (if '|' was found)
2192 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2193 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2195 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2197 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2198 $pieceEnd = $i +
$matchingCount;
2200 if( is_callable( $matchingCallback ) ) {
2202 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2203 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2204 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2205 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2207 # finally we can call a user callback and replace piece of text
2208 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2209 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2210 $i = $pieceStart +
strlen($replaceWith) - 1;
2213 # null value for callback means that parentheses should be parsed, but not replaced
2214 $i +
= $matchingCount - 1;
2217 # reset last openning parentheses, but keep it in case there are unused characters
2218 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2219 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2220 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2223 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2224 $openingBraceStack[$lastOpeningBrace--] = null;
2226 if ($matchingCount < $piece['count']) {
2227 $piece['count'] -= $matchingCount;
2228 $piece['startAt'] -= $matchingCount;
2229 $piece['partStart'] = $piece['startAt'];
2230 # do we still qualify for any callback with remaining count?
2231 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2232 if ($piece['count'] >= $cnt) {
2233 $lastOpeningBrace ++
;
2234 $openingBraceStack[$lastOpeningBrace] = $piece;
2242 # lets set a title if it is a first separator, or next part otherwise
2243 if ($text[$i] == '|') {
2244 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2245 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2246 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2249 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2251 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2260 * Replace magic variables, templates, and template arguments
2261 * with the appropriate text. Templates are substituted recursively,
2262 * taking care to avoid infinite loops.
2264 * Note that the substitution depends on value of $mOutputType:
2265 * OT_WIKI: only {{subst:}} templates
2266 * OT_MSG: only magic variables
2267 * OT_HTML: all templates and magic variables
2269 * @param string $tex The text to transform
2270 * @param array $args Key-value pairs representing template parameters to substitute
2271 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2274 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2275 # Prevent too big inclusions
2276 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2280 $fname = 'Parser::replaceVariables';
2281 wfProfileIn( $fname );
2283 # This function is called recursively. To keep track of arguments we need a stack:
2284 array_push( $this->mArgStack
, $args );
2286 $braceCallbacks = array();
2288 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2290 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2291 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2293 $callbacks = array();
2294 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2295 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2296 $text = $this->replace_callback ($text, $callbacks);
2298 array_pop( $this->mArgStack
);
2300 wfProfileOut( $fname );
2305 * Replace magic variables
2308 function variableSubstitution( $matches ) {
2309 $fname = 'Parser::variableSubstitution';
2310 $varname = $matches[1];
2311 wfProfileIn( $fname );
2312 if ( !$this->mVariables
) {
2313 $this->initialiseVariables();
2316 if ( $this->mOutputType
== OT_WIKI
) {
2317 # Do only magic variables prefixed by SUBST
2318 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2319 if (!$mwSubst->matchStartAndRemove( $varname ))
2321 # Note that if we don't substitute the variable below,
2322 # we don't remove the {{subst:}} magic word, in case
2323 # it is a template rather than a magic variable.
2325 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2326 $id = $this->mVariables
[$varname];
2327 $text = $this->getVariableValue( $id );
2328 $this->mOutput
->mContainsOldMagic
= true;
2330 $text = $matches[0];
2332 wfProfileOut( $fname );
2336 # Split template arguments
2337 function getTemplateArgs( $argsString ) {
2338 if ( $argsString === '' ) {
2342 $args = explode( '|', substr( $argsString, 1 ) );
2344 # If any of the arguments contains a '[[' but no ']]', it needs to be
2345 # merged with the next arg because the '|' character between belongs
2346 # to the link syntax and not the template parameter syntax.
2347 $argc = count($args);
2349 for ( $i = 0; $i < $argc-1; $i++
) {
2350 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2351 $args[$i] .= '|'.$args[$i+
1];
2352 array_splice($args, $i+
1, 1);
2362 * Return the text of a template, after recursively
2363 * replacing any variables or templates within the template.
2365 * @param array $piece The parts of the template
2366 * $piece['text']: matched text
2367 * $piece['title']: the title, i.e. the part before the |
2368 * $piece['parts']: the parameter array
2369 * @return string the text of the template
2372 function braceSubstitution( $piece ) {
2374 $fname = 'Parser::braceSubstitution';
2375 wfProfileIn( $fname );
2378 $found = false; # $text has been filled
2379 $nowiki = false; # wiki markup in $text should be escaped
2380 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2381 $noargs = false; # Don't replace triple-brace arguments in $text
2382 $replaceHeadings = false; # Make the edit section links go to the template not the article
2383 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2384 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2386 # Title object, where $text came from
2391 # $part1 is the bit before the first |, and must contain only title characters
2392 # $args is a list of arguments, starting from index 0, not including $part1
2394 $part1 = $piece['title'];
2395 # If the third subpattern matched anything, it will start with |
2397 if (null == $piece['parts']) {
2398 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2399 if ($replaceWith != $piece['text']) {
2400 $text = $replaceWith;
2407 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2408 $argc = count( $args );
2412 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2413 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2414 # One of two possibilities is true:
2415 # 1) Found SUBST but not in the PST phase
2416 # 2) Didn't find SUBST and in the PST phase
2417 # In either case, return without further processing
2418 $text = $piece['text'];
2425 # MSG, MSGNW, INT and RAW
2428 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2429 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2432 # Remove obsolete MSG:
2433 $mwMsg =& MagicWord
::get( MAG_MSG
);
2434 $mwMsg->matchStartAndRemove( $part1 );
2438 $mwRaw =& MagicWord
::get( MAG_RAW
);
2439 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2440 $forceRawInterwiki = true;
2443 # Check if it is an internal message
2444 $mwInt =& MagicWord
::get( MAG_INT
);
2445 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2446 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2447 $text = $linestart . wfMsgReal( $part1, $args, true );
2455 # Check for NS: (namespace expansion)
2456 $mwNs = MagicWord
::get( MAG_NS
);
2457 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2458 if ( intval( $part1 ) ||
$part1 == "0" ) {
2459 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2462 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2463 if ( !is_null( $index ) ) {
2464 $text = $linestart . $wgContLang->getNsText( $index );
2471 # LCFIRST, UCFIRST, LC and UC
2473 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2474 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2475 $lc =& MagicWord
::get( MAG_LC
);
2476 $uc =& MagicWord
::get( MAG_UC
);
2477 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2478 $text = $linestart . $wgContLang->lcfirst( $part1 );
2480 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2481 $text = $linestart . $wgContLang->ucfirst( $part1 );
2483 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2484 $text = $linestart . $wgContLang->lc( $part1 );
2486 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2487 $text = $linestart . $wgContLang->uc( $part1 );
2492 # LOCALURL and FULLURL
2494 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2495 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2496 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2497 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2500 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2501 $func = 'getLocalURL';
2502 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2503 $func = 'escapeLocalURL';
2504 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2505 $func = 'getFullURL';
2506 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2507 $func = 'escapeFullURL';
2512 if ( $func !== false ) {
2513 $title = Title
::newFromText( $part1 );
2514 if ( !is_null( $title ) ) {
2516 $text = $linestart . $title->$func( $args[0] );
2518 $text = $linestart . $title->$func();
2526 if ( !$found && $argc == 1 ) {
2527 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2528 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2529 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2535 if ( !$found && $argc >= 2 ) {
2536 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2537 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2538 if ($argc==2) {$args[2]=$args[1];}
2539 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2544 # Template table test
2546 # Did we encounter this template already? If yes, it is in the cache
2547 # and we need to check for loops.
2548 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2551 # Infinite loop test
2552 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2556 $text = $linestart .
2557 '{{' . $part1 . '}}' .
2558 '<!-- WARNING: template loop detected -->';
2559 wfDebug( "$fname: template loop broken at '$part1'\n" );
2561 # set $text to cached message.
2562 $text = $linestart . $this->mTemplates
[$piece['title']];
2566 # Load from database
2567 $lastPathLevel = $this->mTemplatePath
;
2570 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2571 if ($subpage !== '') {
2572 $ns = $this->mTitle
->getNamespace();
2574 $title = Title
::newFromText( $part1, $ns );
2576 if ( !is_null( $title ) ) {
2577 if ( !$title->isExternal() ) {
2578 # Check for excessive inclusion
2579 $dbk = $title->getPrefixedDBkey();
2580 if ( $this->incrementIncludeCount( $dbk ) ) {
2581 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2582 # Capture special page output
2583 $text = SpecialPage
::capturePath( $title );
2584 if ( is_string( $text ) ) {
2589 $this->disableCache();
2592 $articleContent = $this->fetchTemplate( $title );
2593 if ( $articleContent !== false ) {
2595 $text = $articleContent;
2596 $replaceHeadings = true;
2601 # If the title is valid but undisplayable, make a link to it
2602 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2603 $text = '[['.$title->getPrefixedText().']]';
2606 } elseif ( $title->isTrans() ) {
2607 // Interwiki transclusion
2608 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2609 $text = $this->interwikiTransclude( $title, 'render' );
2613 $text = $this->interwikiTransclude( $title, 'raw' );
2614 $replaceHeadings = true;
2619 # Template cache array insertion
2620 # Use the original $piece['title'] not the mangled $part1, so that
2621 # modifiers such as RAW: produce separate cache entries
2623 $this->mTemplates
[$piece['title']] = $text;
2624 $text = $linestart . $text;
2629 # Recursive parsing, escaping and link table handling
2630 # Only for HTML output
2631 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2632 $text = wfEscapeWikiText( $text );
2633 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2635 # Clean up argument array
2636 $assocArgs = array();
2638 foreach( $args as $arg ) {
2639 $eqpos = strpos( $arg, '=' );
2640 if ( $eqpos === false ) {
2641 $assocArgs[$index++
] = $arg;
2643 $name = trim( substr( $arg, 0, $eqpos ) );
2644 $value = trim( substr( $arg, $eqpos+
1 ) );
2645 if ( $value === false ) {
2648 if ( $name !== false ) {
2649 $assocArgs[$name] = $value;
2654 # Add a new element to the templace recursion path
2655 $this->mTemplatePath
[$part1] = 1;
2659 # If there are any <onlyinclude> tags, only include them
2660 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2661 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2663 foreach ($m[1] as $piece)
2666 # Remove <noinclude> sections and <includeonly> tags
2667 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2668 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2670 if( $this->mOutputType
== OT_HTML
) {
2671 # Strip <nowiki>, <pre>, etc.
2672 $text = $this->strip( $text, $this->mStripState
);
2673 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2675 $text = $this->replaceVariables( $text, $assocArgs );
2677 # If the template begins with a table or block-level
2678 # element, it should be treated as beginning a new line.
2679 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2680 $text = "\n" . $text;
2682 } elseif ( !$noargs ) {
2683 # $noparse and !$noargs
2684 # Just replace the arguments, not any double-brace items
2685 # This is used for rendered interwiki transclusion
2686 $text = $this->replaceVariables( $text, $assocArgs, true );
2689 # Prune lower levels off the recursion check path
2690 $this->mTemplatePath
= $lastPathLevel;
2693 wfProfileOut( $fname );
2694 return $piece['text'];
2697 # Replace raw HTML by a placeholder
2698 # Add a blank line preceding, to prevent it from mucking up
2699 # immediately preceding headings
2700 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2702 # replace ==section headers==
2703 # XXX this needs to go away once we have a better parser.
2704 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2705 if( !is_null( $title ) )
2706 $encodedname = base64_encode($title->getPrefixedDBkey());
2708 $encodedname = base64_encode("");
2709 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2710 PREG_SPLIT_DELIM_CAPTURE
);
2713 for( $i = 0; $i < count($m); $i +
= 2 ) {
2715 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2717 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2721 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2722 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2723 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2731 # Prune lower levels off the recursion check path
2732 $this->mTemplatePath
= $lastPathLevel;
2735 wfProfileOut( $fname );
2736 return $piece['text'];
2738 wfProfileOut( $fname );
2744 * Fetch the unparsed text of a template and register a reference to it.
2746 function fetchTemplate( $title ) {
2748 // Loop to fetch the article, with up to 1 redirect
2749 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2750 $rev = Revision
::newFromTitle( $title );
2751 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2755 $text = $rev->getText();
2756 if ( $text === false ) {
2760 $title = Title
::newFromRedirect( $text );
2766 * Transclude an interwiki link.
2768 function interwikiTransclude( $title, $action ) {
2769 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2771 if (!$wgEnableScaryTranscluding)
2772 return wfMsg('scarytranscludedisabled');
2774 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2775 // But we'll handle it generally anyway
2776 if ( $title->getNamespace() ) {
2777 // Use the canonical namespace, which should work anywhere
2778 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2780 $articleName = $title->getDBkey();
2783 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2784 $url .= "?action=$action";
2785 if (strlen($url) > 255)
2786 return wfMsg('scarytranscludetoolong');
2787 return $this->fetchScaryTemplateMaybeFromCache($url);
2790 function fetchScaryTemplateMaybeFromCache($url) {
2791 global $wgTranscludeCacheExpiry;
2792 $dbr =& wfGetDB(DB_SLAVE
);
2793 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2794 array('tc_url' => $url));
2796 $time = $obj->tc_time
;
2797 $text = $obj->tc_contents
;
2798 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2803 $text = wfGetHTTP($url);
2805 return wfMsg('scarytranscludefailed', $url);
2807 $dbw =& wfGetDB(DB_MASTER
);
2808 $dbw->replace('transcache', array('tc_url'), array(
2810 'tc_time' => time(),
2811 'tc_contents' => $text));
2817 * Triple brace replacement -- used for template arguments
2820 function argSubstitution( $matches ) {
2821 $arg = trim( $matches['title'] );
2822 $text = $matches['text'];
2823 $inputArgs = end( $this->mArgStack
);
2825 if ( array_key_exists( $arg, $inputArgs ) ) {
2826 $text = $inputArgs[$arg];
2827 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2828 $text = $matches['parts'][0];
2835 * Returns true if the function is allowed to include this entity
2838 function incrementIncludeCount( $dbk ) {
2839 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2840 $this->mIncludeCount
[$dbk] = 0;
2842 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2850 * This function accomplishes several tasks:
2851 * 1) Auto-number headings if that option is enabled
2852 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2853 * 3) Add a Table of contents on the top for users who have enabled the option
2854 * 4) Auto-anchor headings
2856 * It loops through all headlines, collects the necessary data, then splits up the
2857 * string and re-inserts the newly formatted headlines.
2859 * @param string $text
2860 * @param boolean $isMain
2863 function formatHeadings( $text, $isMain=true ) {
2864 global $wgMaxTocLevel, $wgContLang;
2866 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2868 $forceTocHere = false;
2869 if( !$this->mTitle
->userCanEdit() ) {
2872 $showEditLink = $this->mOptions
->getEditSection();
2875 # Inhibit editsection links if requested in the page
2876 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2877 if( $esw->matchAndRemove( $text ) ) {
2880 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2882 $mw =& MagicWord
::get( MAG_NOTOC
);
2883 if( $mw->matchAndRemove( $text ) ) {
2887 # Get all headlines for numbering them and adding funky stuff like [edit]
2888 # links - this is for later, but we need the number of headlines right now
2889 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2891 # if there are fewer than 4 headlines in the article, do not show TOC
2892 if( $numMatches < 4 ) {
2896 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2897 # override above conditions and always show TOC at that place
2899 $mw =& MagicWord
::get( MAG_TOC
);
2900 if($mw->match( $text ) ) {
2902 $forceTocHere = true;
2904 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2905 # override above conditions and always show TOC above first header
2906 $mw =& MagicWord
::get( MAG_FORCETOC
);
2907 if ($mw->matchAndRemove( $text ) ) {
2912 # Never ever show TOC if no headers
2913 if( $numMatches < 1 ) {
2917 # We need this to perform operations on the HTML
2918 $sk =& $this->mOptions
->getSkin();
2922 $sectionCount = 0; # headlineCount excluding template sections
2924 # Ugh .. the TOC should have neat indentation levels which can be
2925 # passed to the skin functions. These are determined here
2929 $sublevelCount = array();
2930 $levelCount = array();
2937 foreach( $matches[3] as $headline ) {
2939 $templatetitle = '';
2940 $templatesection = 0;
2943 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2945 $templatetitle = base64_decode($mat[1]);
2946 $templatesection = 1 +
(int)base64_decode($mat[2]);
2947 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2951 $prevlevel = $level;
2952 $prevtoclevel = $toclevel;
2954 $level = $matches[1][$headlineCount];
2956 if( $doNumberHeadings ||
$doShowToc ) {
2958 if ( $level > $prevlevel ) {
2959 # Increase TOC level
2961 $sublevelCount[$toclevel] = 0;
2962 $toc .= $sk->tocIndent();
2964 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2965 # Decrease TOC level, find level to jump to
2967 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2968 # Can only go down to level 1
2971 for ($i = $toclevel; $i > 0; $i--) {
2972 if ( $levelCount[$i] == $level ) {
2973 # Found last matching level
2977 elseif ( $levelCount[$i] < $level ) {
2978 # Found first matching level below current level
2985 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2988 # No change in level, end TOC line
2989 $toc .= $sk->tocLineEnd();
2992 $levelCount[$toclevel] = $level;
2994 # count number of headlines for each level
2995 @$sublevelCount[$toclevel]++
;
2997 for( $i = 1; $i <= $toclevel; $i++
) {
2998 if( !empty( $sublevelCount[$i] ) ) {
3002 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3008 # The canonized header is a version of the header text safe to use for links
3009 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3010 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3011 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3013 # Remove link placeholders by the link text.
3014 # <!--LINK number-->
3016 # link text with suffix
3017 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3018 "\$this->mLinkHolders['texts'][\$1]",
3019 $canonized_headline );
3020 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3021 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3022 $canonized_headline );
3025 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3026 $tocline = trim( $canonized_headline );
3027 $canonized_headline = Sanitizer
::escapeId( $tocline );
3028 $refers[$headlineCount] = $canonized_headline;
3030 # count how many in assoc. array so we can track dupes in anchors
3031 @$refers[$canonized_headline]++
;
3032 $refcount[$headlineCount]=$refers[$canonized_headline];
3034 # Don't number the heading if it is the only one (looks silly)
3035 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3036 # the two are different if the line contains a link
3037 $headline=$numbering . ' ' . $headline;
3040 # Create the anchor for linking from the TOC to the section
3041 $anchor = $canonized_headline;
3042 if($refcount[$headlineCount] > 1 ) {
3043 $anchor .= '_' . $refcount[$headlineCount];
3045 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3046 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3048 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3049 if ( empty( $head[$headlineCount] ) ) {
3050 $head[$headlineCount] = '';
3053 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3055 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
3058 # give headline the correct <h#> tag
3059 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3067 $toc .= $sk->tocUnindent( $toclevel - 1 );
3068 $toc = $sk->tocList( $toc );
3071 # split up and insert constructed headlines
3073 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3076 foreach( $blocks as $block ) {
3077 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3078 # This is the [edit] link that appears for the top block of text when
3079 # section editing is enabled
3081 # Disabled because it broke block formatting
3082 # For example, a bullet point in the top line
3083 # $full .= $sk->editSectionLink(0);
3086 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3087 # Top anchor now in skin
3091 if( !empty( $head[$i] ) ) {
3097 $mw =& MagicWord
::get( MAG_TOC
);
3098 return $mw->replace( $toc, $full );
3105 * Return an HTML link for the "ISBN 123456" text
3108 function magicISBN( $text ) {
3109 $fname = 'Parser::magicISBN';
3110 wfProfileIn( $fname );
3112 $a = split( 'ISBN ', ' '.$text );
3113 if ( count ( $a ) < 2 ) {
3114 wfProfileOut( $fname );
3117 $text = substr( array_shift( $a ), 1);
3118 $valid = '0123456789-Xx';
3120 foreach ( $a as $x ) {
3121 $isbn = $blank = '' ;
3122 while ( ' ' == $x{0} ) {
3124 $x = substr( $x, 1 );
3126 if ( $x == '' ) { # blank isbn
3127 $text .= "ISBN $blank";
3130 while ( strstr( $valid, $x{0} ) != false ) {
3132 $x = substr( $x, 1 );
3134 $num = str_replace( '-', '', $isbn );
3135 $num = str_replace( ' ', '', $num );
3136 $num = str_replace( 'x', 'X', $num );
3139 $text .= "ISBN $blank$x";
3141 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3142 $text .= '<a href="' .
3143 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3144 "\" class=\"internal\">ISBN $isbn</a>";
3148 wfProfileOut( $fname );
3153 * Return an HTML link for the "RFC 1234" text
3156 * @param string $text Text to be processed
3157 * @param string $keyword Magic keyword to use (default RFC)
3158 * @param string $urlmsg Interface message to use (default rfcurl)
3161 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3163 $valid = '0123456789';
3166 $a = split( $keyword, ' '.$text );
3167 if ( count ( $a ) < 2 ) {
3170 $text = substr( array_shift( $a ), 1);
3172 /* Check if keyword is preceed by [[.
3173 * This test is made here cause of the array_shift above
3174 * that prevent the test to be done in the foreach.
3176 if ( substr( $text, -2 ) == '[[' ) {
3180 foreach ( $a as $x ) {
3181 /* token might be empty if we have RFC RFC 1234 */
3189 /** remove and save whitespaces in $blank */
3190 while ( $x{0} == ' ' ) {
3192 $x = substr( $x, 1 );
3195 /** remove and save the rfc number in $id */
3196 while ( strstr( $valid, $x{0} ) != false ) {
3198 $x = substr( $x, 1 );
3202 /* call back stripped spaces*/
3203 $text .= $keyword.$blank.$x;
3204 } elseif( $internal ) {
3206 $text .= $keyword.$id.$x;
3208 /* build the external link*/
3209 $url = wfMsg( $urlmsg, $id);
3210 $sk =& $this->mOptions
->getSkin();
3211 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3212 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3215 /* Check if the next RFC keyword is preceed by [[ */
3216 $internal = ( substr($x,-2) == '[[' );
3222 * Transform wiki markup when saving a page by doing \r\n -> \n
3223 * conversion, substitting signatures, {{subst:}} templates, etc.
3225 * @param string $text the text to transform
3226 * @param Title &$title the Title object for the current article
3227 * @param User &$user the User object describing the current user
3228 * @param ParserOptions $options parsing options
3229 * @param bool $clearState whether to clear the parser state first
3230 * @return string the altered wiki markup
3233 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3234 $this->mOptions
= $options;
3235 $this->mTitle
=& $title;
3236 $this->mOutputType
= OT_WIKI
;
3238 if ( $clearState ) {
3239 $this->clearState();
3242 $stripState = false;
3246 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3247 $text = $this->strip( $text, $stripState, true );
3248 $text = $this->pstPass2( $text, $user );
3249 $text = $this->unstrip( $text, $stripState );
3250 $text = $this->unstripNoWiki( $text, $stripState );
3255 * Pre-save transform helper function
3258 function pstPass2( $text, &$user ) {
3259 global $wgContLang, $wgLocaltimezone;
3261 /* Note: This is the timestamp saved as hardcoded wikitext to
3262 * the database, we use $wgContLang here in order to give
3263 * everyone the same signiture and use the default one rather
3264 * than the one selected in each users preferences.
3266 if ( isset( $wgLocaltimezone ) ) {
3267 $oldtz = getenv( 'TZ' );
3268 putenv( 'TZ='.$wgLocaltimezone );
3270 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3271 ' (' . date( 'T' ) . ')';
3272 if ( isset( $wgLocaltimezone ) ) {
3273 putenv( 'TZ='.$oldtz );
3276 # Variable replacement
3277 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3278 $text = $this->replaceVariables( $text );
3281 $sigText = $this->getUserSig( $user );
3282 $text = strtr( $text, array(
3284 '~~~~' => "$sigText $d",
3288 # Context links: [[|name]] and [[name (context)|]]
3290 global $wgLegalTitleChars;
3291 $tc = "[$wgLegalTitleChars]";
3292 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3294 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3295 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3297 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3298 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3299 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3300 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3302 $t = $this->mTitle
->getText();
3303 if ( preg_match( $conpat, $t, $m ) ) {
3306 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3307 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3308 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3310 if ( '' == $context ) {
3311 $text = preg_replace( $p2, '[[\\1]]', $text );
3313 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3316 # Trim trailing whitespace
3317 # MAG_END (__END__) tag allows for trailing
3318 # whitespace to be deliberately included
3319 $text = rtrim( $text );
3320 $mw =& MagicWord
::get( MAG_END
);
3321 $mw->matchAndRemove( $text );
3327 * Fetch the user's signature text, if any, and normalize to
3328 * validated, ready-to-insert wikitext.
3334 function getUserSig( &$user ) {
3337 $username = $user->getName();
3338 $nickname = $user->getOption( 'nickname' );
3339 $nickname = $nickname === '' ?
$username : $nickname;
3341 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3342 # Sig. might contain markup; validate this
3343 if( $this->validateSig( $nickname ) !== false ) {
3344 # Validated; clean up (if needed) and return it
3345 return( $this->cleanSig( $nickname ) );
3347 # Failed to validate; fall back to the default
3348 $nickname = $username;
3349 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3353 # If we're still here, make it a link to the user page
3354 $userpage = $user->getUserPage();
3355 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3359 * Check that the user's signature contains no bad XML
3361 * @param string $text
3362 * @return mixed An expanded string, or false if invalid.
3364 function validateSig( $text ) {
3365 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3369 * Clean up signature text
3371 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3372 * 2) Substitute all transclusions
3374 * @param string $text
3375 * @return string Signature text
3377 function cleanSig( $text ) {
3378 $substWord = MagicWord
::get( MAG_SUBST
);
3379 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3380 $substText = '{{' . $substWord->getSynonym( 0 );
3382 $text = preg_replace( $substRegex, $substText, $text );
3383 $text = preg_replace( '/~{3,5}/', '', $text );
3384 $text = $this->replaceVariables( $text );
3390 * Set up some variables which are usually set up in parse()
3391 * so that an external function can call some class members with confidence
3394 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3395 $this->mTitle
=& $title;
3396 $this->mOptions
= $options;
3397 $this->mOutputType
= $outputType;
3398 if ( $clearState ) {
3399 $this->clearState();
3404 * Transform a MediaWiki message by replacing magic variables.
3406 * @param string $text the text to transform
3407 * @param ParserOptions $options options
3408 * @return string the text with variables substituted
3411 function transformMsg( $text, $options ) {
3413 static $executing = false;
3415 $fname = "Parser::transformMsg";
3417 # Guard against infinite recursion
3423 wfProfileIn($fname);
3425 $this->mTitle
= $wgTitle;
3426 $this->mOptions
= $options;
3427 $this->mOutputType
= OT_MSG
;
3428 $this->clearState();
3429 $text = $this->replaceVariables( $text );
3432 wfProfileOut($fname);
3437 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3438 * Callback will be called with the text within
3439 * Transform and return the text within
3443 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3444 * @param mixed $callback The callback function (and object) to use for the tag
3446 * @return The old value of the mTagHooks array associated with the hook
3448 function setHook( $tag, $callback ) {
3449 $oldVal = @$this->mTagHooks
[$tag];
3450 $this->mTagHooks
[$tag] = $callback;
3456 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3457 * Placeholders created in Skin::makeLinkObj()
3458 * Returns an array of links found, indexed by PDBK:
3462 * $options is a bit field, RLH_FOR_UPDATE to select for update
3464 function replaceLinkHolders( &$text, $options = 0 ) {
3466 global $wgOutputReplace;
3468 $fname = 'Parser::replaceLinkHolders';
3469 wfProfileIn( $fname );
3473 $sk =& $this->mOptions
->getSkin();
3474 $linkCache =& LinkCache
::singleton();
3476 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3477 wfProfileIn( $fname.'-check' );
3478 $dbr =& wfGetDB( DB_SLAVE
);
3479 $page = $dbr->tableName( 'page' );
3480 $threshold = $wgUser->getOption('stubthreshold');
3483 asort( $this->mLinkHolders
['namespaces'] );
3487 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3489 $title = $this->mLinkHolders
['titles'][$key];
3491 # Skip invalid entries.
3492 # Result will be ugly, but prevents crash.
3493 if ( is_null( $title ) ) {
3496 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3498 # Check if it's a static known link, e.g. interwiki
3499 if ( $title->isAlwaysKnown() ) {
3500 $colours[$pdbk] = 1;
3501 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3502 $colours[$pdbk] = 1;
3503 $this->mOutput
->addLink( $title, $id );
3504 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3505 $colours[$pdbk] = 0;
3507 # Not in the link cache, add it to the query
3508 if ( !isset( $current ) ) {
3510 $query = "SELECT page_id, page_namespace, page_title";
3511 if ( $threshold > 0 ) {
3512 $query .= ', page_len, page_is_redirect';
3514 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3515 } elseif ( $current != $ns ) {
3517 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3522 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3527 if ( $options & RLH_FOR_UPDATE
) {
3528 $query .= ' FOR UPDATE';
3531 $res = $dbr->query( $query, $fname );
3533 # Fetch data and form into an associative array
3534 # non-existent = broken
3537 while ( $s = $dbr->fetchObject($res) ) {
3538 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3539 $pdbk = $title->getPrefixedDBkey();
3540 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3541 $this->mOutput
->addLink( $title, $s->page_id
);
3543 if ( $threshold > 0 ) {
3544 $size = $s->page_len
;
3545 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3546 $colours[$pdbk] = 1;
3548 $colours[$pdbk] = 2;
3551 $colours[$pdbk] = 1;
3555 wfProfileOut( $fname.'-check' );
3557 # Construct search and replace arrays
3558 wfProfileIn( $fname.'-construct' );
3559 $wgOutputReplace = array();
3560 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3561 $pdbk = $pdbks[$key];
3562 $searchkey = "<!--LINK $key-->";
3563 $title = $this->mLinkHolders
['titles'][$key];
3564 if ( empty( $colours[$pdbk] ) ) {
3565 $linkCache->addBadLinkObj( $title );
3566 $colours[$pdbk] = 0;
3567 $this->mOutput
->addLink( $title, 0 );
3568 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3569 $this->mLinkHolders
['texts'][$key],
3570 $this->mLinkHolders
['queries'][$key] );
3571 } elseif ( $colours[$pdbk] == 1 ) {
3572 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3573 $this->mLinkHolders
['texts'][$key],
3574 $this->mLinkHolders
['queries'][$key] );
3575 } elseif ( $colours[$pdbk] == 2 ) {
3576 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3577 $this->mLinkHolders
['texts'][$key],
3578 $this->mLinkHolders
['queries'][$key] );
3581 wfProfileOut( $fname.'-construct' );
3584 wfProfileIn( $fname.'-replace' );
3586 $text = preg_replace_callback(
3587 '/(<!--LINK .*?-->)/',
3588 "wfOutputReplaceMatches",
3591 wfProfileOut( $fname.'-replace' );
3594 # Now process interwiki link holders
3595 # This is quite a bit simpler than internal links
3596 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3597 wfProfileIn( $fname.'-interwiki' );
3598 # Make interwiki link HTML
3599 $wgOutputReplace = array();
3600 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3601 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3602 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3605 $text = preg_replace_callback(
3606 '/<!--IWLINK (.*?)-->/',
3607 "wfOutputReplaceMatches",
3609 wfProfileOut( $fname.'-interwiki' );
3612 wfProfileOut( $fname );
3617 * Replace <!--LINK--> link placeholders with plain text of links
3618 * (not HTML-formatted).
3619 * @param string $text
3622 function replaceLinkHoldersText( $text ) {
3624 global $wgOutputReplace;
3626 $fname = 'Parser::replaceLinkHoldersText';
3627 wfProfileIn( $fname );
3629 $text = preg_replace_callback(
3630 '/<!--(LINK|IWLINK) (.*?)-->/',
3631 array( &$this, 'replaceLinkHoldersTextCallback' ),
3634 wfProfileOut( $fname );
3639 * @param array $matches
3643 function replaceLinkHoldersTextCallback( $matches ) {
3644 $type = $matches[1];
3646 if( $type == 'LINK' ) {
3647 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3648 return $this->mLinkHolders
['texts'][$key];
3650 } elseif( $type == 'IWLINK' ) {
3651 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3652 return $this->mInterwikiLinkHolders
['texts'][$key];
3659 * Renders an image gallery from a text with one line per image.
3660 * text labels may be given by using |-style alternative text. E.g.
3661 * Image:one.jpg|The number "1"
3662 * Image:tree.jpg|A tree
3663 * given as text will return the HTML of a gallery with two images,
3664 * labeled 'The number "1"' and
3667 function renderImageGallery( $text ) {
3669 $parserOptions = new ParserOptions
;
3670 $localParser = new Parser();
3672 $ig = new ImageGallery();
3673 $ig->setShowBytes( false );
3674 $ig->setShowFilename( false );
3675 $lines = explode( "\n", $text );
3677 foreach ( $lines as $line ) {
3678 # match lines like these:
3679 # Image:someimage.jpg|This is some image
3680 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3682 if ( count( $matches ) == 0 ) {
3685 $nt =& Title
::newFromText( $matches[1] );
3686 if( is_null( $nt ) ) {
3687 # Bogus title. Ignore these so we don't bomb out later.
3690 if ( isset( $matches[3] ) ) {
3691 $label = $matches[3];
3696 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3697 $html = $pout->getText();
3699 $ig->add( new Image( $nt ), $html );
3700 $this->mOutput
->addImage( $nt->getDBkey() );
3702 return $ig->toHTML();
3706 * Parse image options text and use it to make an image
3708 function makeImage( &$nt, $options ) {
3709 global $wgContLang, $wgUseImageResize, $wgUser;
3713 # Check if the options text is of the form "options|alt text"
3715 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3716 # * left no resizing, just left align. label is used for alt= only
3717 # * right same, but right aligned
3718 # * none same, but not aligned
3719 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3720 # * center center the image
3721 # * framed Keep original image size, no magnify-button.
3723 $part = explode( '|', $options);
3725 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3726 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3727 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3728 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3729 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3730 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3731 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3732 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3735 $width = $height = $framed = $thumb = false;
3736 $manual_thumb = '' ;
3738 foreach( $part as $key => $val ) {
3739 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3741 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3742 # use manually specified thumbnail
3744 $manual_thumb = $match;
3745 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3746 # remember to set an alignment, don't render immediately
3748 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3749 # remember to set an alignment, don't render immediately
3751 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3752 # remember to set an alignment, don't render immediately
3754 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3755 # remember to set an alignment, don't render immediately
3757 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3758 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3759 # $match is the image width in pixels
3760 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3761 $width = intval( $m[1] );
3762 $height = intval( $m[2] );
3764 $width = intval($match);
3766 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3772 # Strip bad stuff out of the alt text
3773 $alt = $this->replaceLinkHoldersText( $caption );
3774 $alt = Sanitizer
::stripAllTags( $alt );
3776 # Linker does the rest
3777 $sk =& $this->mOptions
->getSkin();
3778 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3782 * Set a flag in the output object indicating that the content is dynamic and
3783 * shouldn't be cached.
3785 function disableCache() {
3786 $this->mOutput
->mCacheTime
= -1;
3790 * Callback from the Sanitizer for expanding items found in HTML attribute
3791 * values, so they can be safely tested and escaped.
3792 * @param string $text
3793 * @param array $args
3797 function attributeStripCallback( &$text, $args ) {
3798 $text = $this->replaceVariables( $text, $args );
3799 $text = $this->unstripForHTML( $text );
3803 function unstripForHTML( $text ) {
3804 $text = $this->unstrip( $text, $this->mStripState
);
3805 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3813 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3814 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3815 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3821 function getTags() { return array_keys( $this->mTagHooks
); }
3827 * @package MediaWiki
3831 var $mText, # The output text
3832 $mLanguageLinks, # List of the full text of language links, in the order they appear
3833 $mCategories, # Map of category names to sort keys
3834 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3835 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3836 $mVersion, # Compatibility check
3837 $mTitleText, # title text of the chosen language variant
3838 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3839 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3840 $mImages, # DB keys of the images used, in the array key only
3841 $mExternalLinks; # External link URLs, in the key only
3843 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3844 $containsOldMagic = false, $titletext = '' )
3846 $this->mText
= $text;
3847 $this->mLanguageLinks
= $languageLinks;
3848 $this->mCategories
= $categoryLinks;
3849 $this->mContainsOldMagic
= $containsOldMagic;
3850 $this->mCacheTime
= '';
3851 $this->mVersion
= MW_PARSER_VERSION
;
3852 $this->mTitleText
= $titletext;
3853 $this->mLinks
= array();
3854 $this->mTemplates
= array();
3855 $this->mImages
= array();
3856 $this->mExternalLinks
= array();
3859 function getText() { return $this->mText
; }
3860 function getLanguageLinks() { return $this->mLanguageLinks
; }
3861 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3862 function &getCategories() { return $this->mCategories
; }
3863 function getCacheTime() { return $this->mCacheTime
; }
3864 function getTitleText() { return $this->mTitleText
; }
3865 function &getLinks() { return $this->mLinks
; }
3866 function &getTemplates() { return $this->mTemplates
; }
3867 function &getImages() { return $this->mImages
; }
3868 function &getExternalLinks() { return $this->mExternalLinks
; }
3870 function containsOldMagic() { return $this->mContainsOldMagic
; }
3871 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3872 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3873 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3874 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3875 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3876 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3878 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3879 function addImage( $name ) { $this->mImages
[$name] = 1; }
3880 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3881 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3883 function addLink( $title, $id ) {
3884 $ns = $title->getNamespace();
3885 $dbk = $title->getDBkey();
3886 if ( !isset( $this->mLinks
[$ns] ) ) {
3887 $this->mLinks
[$ns] = array();
3889 $this->mLinks
[$ns][$dbk] = $id;
3892 function addTemplate( $title, $id ) {
3893 $ns = $title->getNamespace();
3894 $dbk = $title->getDBkey();
3895 if ( !isset( $this->mTemplates
[$ns] ) ) {
3896 $this->mTemplates
[$ns] = array();
3898 $this->mTemplates
[$ns][$dbk] = $id;
3905 function merge( $other ) {
3906 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3907 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3908 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3912 * Return true if this cached output object predates the global or
3913 * per-article cache invalidation timestamps, or if it comes from
3914 * an incompatible older version.
3916 * @param string $touched the affected article's last touched timestamp
3920 function expired( $touched ) {
3921 global $wgCacheEpoch;
3922 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3923 $this->getCacheTime() < $touched ||
3924 $this->getCacheTime() <= $wgCacheEpoch ||
3925 !isset( $this->mVersion
) ||
3926 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3931 * Set options of the Parser
3933 * @package MediaWiki
3937 # All variables are private
3938 var $mUseTeX; # Use texvc to expand <math> tags
3939 var $mUseDynamicDates; # Use DateFormatter to format dates
3940 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3941 var $mAllowExternalImages; # Allow external images inline
3942 var $mAllowExternalImagesFrom; # If not, any exception?
3943 var $mSkin; # Reference to the preferred skin
3944 var $mDateFormat; # Date format index
3945 var $mEditSection; # Create "edit section" links
3946 var $mNumberHeadings; # Automatically number headings
3947 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3948 var $mTidy; # Ask for tidy cleanup
3950 function getUseTeX() { return $this->mUseTeX
; }
3951 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3952 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3953 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3954 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3955 function &getSkin() { return $this->mSkin
; }
3956 function getDateFormat() { return $this->mDateFormat
; }
3957 function getEditSection() { return $this->mEditSection
; }
3958 function getNumberHeadings() { return $this->mNumberHeadings
; }
3959 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3960 function getTidy() { return $this->mTidy
; }
3962 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3963 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3964 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3965 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3966 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3967 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3968 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3969 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3970 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3971 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3972 function setSkin( &$x ) { $this->mSkin
=& $x; }
3974 function ParserOptions() {
3976 $this->initialiseFromUser( $wgUser );
3980 * Get parser options
3983 function newFromUser( &$user ) {
3984 $popts = new ParserOptions
;
3985 $popts->initialiseFromUser( $user );
3989 /** Get user options */
3990 function initialiseFromUser( &$userInput ) {
3991 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3992 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3993 $fname = 'ParserOptions::initialiseFromUser';
3994 wfProfileIn( $fname );
3995 if ( !$userInput ) {
3997 $user->setLoaded( true );
3999 $user =& $userInput;
4002 $this->mUseTeX
= $wgUseTeX;
4003 $this->mUseDynamicDates
= $wgUseDynamicDates;
4004 $this->mInterwikiMagic
= $wgInterwikiMagic;
4005 $this->mAllowExternalImages
= $wgAllowExternalImages;
4006 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4007 wfProfileIn( $fname.'-skin' );
4008 $this->mSkin
=& $user->getSkin();
4009 wfProfileOut( $fname.'-skin' );
4010 $this->mDateFormat
= $user->getOption( 'date' );
4011 $this->mEditSection
= true;
4012 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4013 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4014 $this->mTidy
= false;
4015 wfProfileOut( $fname );
4020 * Callback function used by Parser::replaceLinkHolders()
4021 * to substitute link placeholders.
4023 function &wfOutputReplaceMatches( $matches ) {
4024 global $wgOutputReplace;
4025 return $wgOutputReplace[$matches[1]];
4029 * Return the total number of articles
4031 function wfNumberOfArticles() {
4032 global $wgNumberOfArticles;
4035 return $wgNumberOfArticles;
4039 * Return the number of files
4041 function wfNumberOfFiles() {
4042 $fname = 'Parser::wfNumberOfFiles';
4044 wfProfileIn( $fname );
4045 $dbr =& wfGetDB( DB_SLAVE
);
4046 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4047 wfProfileOut( $fname );
4053 * Get various statistics from the database
4056 function wfLoadSiteStats() {
4057 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4058 $fname = 'wfLoadSiteStats';
4060 if ( -1 != $wgNumberOfArticles ) return;
4061 $dbr =& wfGetDB( DB_SLAVE
);
4062 $s = $dbr->selectRow( 'site_stats',
4063 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4064 array( 'ss_row_id' => 1 ), $fname
4067 if ( $s === false ) {
4070 $wgTotalViews = $s->ss_total_views
;
4071 $wgTotalEdits = $s->ss_total_edits
;
4072 $wgNumberOfArticles = $s->ss_good_articles
;
4078 * Basically replacing " > and < with HTML entities ( ", >, <)
4080 * @param string $in Text that might contain HTML tags
4081 * @return string Escaped string
4083 function wfEscapeHTMLTagsOnly( $in ) {
4085 array( '"', '>', '<' ),
4086 array( '"', '>', '<' ),