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 $text = $bits[$i++
];
1089 $trail = $bits[$i++
];
1091 # The characters '<' and '>' (which were escaped by
1092 # removeHTMLtags()) should not be included in
1093 # URLs, per RFC 2396.
1094 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1095 $text = substr($url, $m2[0][1]) . ' ' . $text;
1096 $url = substr($url, 0, $m2[0][1]);
1099 # If the link text is an image URL, replace it with an <img> tag
1100 # This happened by accident in the original parser, but some people used it extensively
1101 $img = $this->maybeMakeExternalImage( $text );
1102 if ( $img !== false ) {
1108 # Set linktype for CSS - if URL==text, link is essentially free
1109 $linktype = ($text == $url) ?
'free' : 'text';
1111 # No link text, e.g. [http://domain.tld/some.link]
1112 if ( $text == '' ) {
1113 # Autonumber if allowed
1114 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1115 $text = '[' . ++
$this->mAutonumber
. ']';
1116 $linktype = 'autonumber';
1118 # Otherwise just use the URL
1119 $text = htmlspecialchars( $url );
1123 # Have link text, e.g. [http://domain.tld/some.link text]s
1125 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1128 $text = $wgContLang->markNoConversion($text);
1130 # Replace & from obsolete syntax with &.
1131 # All HTML entities will be escaped by makeExternalLink()
1132 $url = str_replace( '&', '&', $url );
1133 # Replace unnecessary URL escape codes with the referenced character
1134 # This prevents spammers from hiding links from the filters
1135 $url = Parser
::replaceUnusualEscapes( $url );
1137 # Process the trail (i.e. everything after this link up until start of the next link),
1138 # replacing any non-bracketed links
1139 $trail = $this->replaceFreeExternalLinks( $trail );
1141 # Use the encoded URL
1142 # This means that users can paste URLs directly into the text
1143 # Funny characters like ö aren't valid in URLs anyway
1144 # This was changed in August 2004
1145 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1147 # Register link in the output object
1148 $this->mOutput
->addExternalLink( $url );
1151 wfProfileOut( $fname );
1156 * Replace anything that looks like a URL with a link
1159 function replaceFreeExternalLinks( $text ) {
1161 $fname = 'Parser::replaceFreeExternalLinks';
1162 wfProfileIn( $fname );
1164 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1165 $s = array_shift( $bits );
1168 $sk =& $this->mOptions
->getSkin();
1170 while ( $i < count( $bits ) ){
1171 $protocol = $bits[$i++
];
1172 $remainder = $bits[$i++
];
1174 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1175 # Found some characters after the protocol that look promising
1176 $url = $protocol . $m[1];
1179 # The characters '<' and '>' (which were escaped by
1180 # removeHTMLtags()) should not be included in
1181 # URLs, per RFC 2396.
1182 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1183 $trail = substr($url, $m2[0][1]) . $trail;
1184 $url = substr($url, 0, $m2[0][1]);
1187 # Move trailing punctuation to $trail
1189 # If there is no left bracket, then consider right brackets fair game too
1190 if ( strpos( $url, '(' ) === false ) {
1194 $numSepChars = strspn( strrev( $url ), $sep );
1195 if ( $numSepChars ) {
1196 $trail = substr( $url, -$numSepChars ) . $trail;
1197 $url = substr( $url, 0, -$numSepChars );
1200 # Replace & from obsolete syntax with &.
1201 # All HTML entities will be escaped by makeExternalLink()
1202 # or maybeMakeExternalImage()
1203 $url = str_replace( '&', '&', $url );
1204 # Replace unnecessary URL escape codes with their equivalent characters
1205 $url = Parser
::replaceUnusualEscapes( $url );
1207 # Is this an external image?
1208 $text = $this->maybeMakeExternalImage( $url );
1209 if ( $text === false ) {
1210 # Not an image, make a link
1211 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1212 # Register it in the output object
1213 $this->mOutput
->addExternalLink( $url );
1215 $s .= $text . $trail;
1217 $s .= $protocol . $remainder;
1220 wfProfileOut( $fname );
1225 * Replace unusual URL escape codes with their equivalent characters
1230 function replaceUnusualEscapes( $url ) {
1231 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1232 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1236 * Callback function used in replaceUnusualEscapes().
1237 * Replaces unusual URL escape codes with their equivalent character
1241 function replaceUnusualEscapesCallback( $matches ) {
1242 $char = urldecode( $matches[0] );
1243 $ord = ord( $char );
1244 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1245 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1246 // No, shouldn't be escaped
1249 // Yes, leave it escaped
1255 * make an image if it's allowed, either through the global
1256 * option or through the exception
1259 function maybeMakeExternalImage( $url ) {
1260 $sk =& $this->mOptions
->getSkin();
1261 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1262 $imagesexception = !empty($imagesfrom);
1264 if ( $this->mOptions
->getAllowExternalImages()
1265 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1266 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1268 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1275 * Process [[ ]] wikilinks
1279 function replaceInternalLinks( $s ) {
1281 static $fname = 'Parser::replaceInternalLinks' ;
1283 wfProfileIn( $fname );
1285 wfProfileIn( $fname.'-setup' );
1287 # the % is needed to support urlencoded titles as well
1288 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1290 $sk =& $this->mOptions
->getSkin();
1292 #split the entire text string on occurences of [[
1293 $a = explode( '[[', ' ' . $s );
1294 #get the first element (all text up to first [[), and remove the space we added
1295 $s = array_shift( $a );
1296 $s = substr( $s, 1 );
1298 # Match a link having the form [[namespace:link|alternate]]trail
1300 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1301 # Match cases where there is no "]]", which might still be images
1302 static $e1_img = FALSE;
1303 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1304 # Match the end of a line for a word that's not followed by whitespace,
1305 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1306 $e2 = wfMsgForContent( 'linkprefix' );
1308 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1310 if( is_null( $this->mTitle
) ) {
1311 wfDebugDieBacktrace( 'nooo' );
1313 $nottalk = !$this->mTitle
->isTalkPage();
1315 if ( $useLinkPrefixExtension ) {
1316 if ( preg_match( $e2, $s, $m ) ) {
1317 $first_prefix = $m[2];
1319 $first_prefix = false;
1325 $selflink = $this->mTitle
->getPrefixedText();
1326 wfProfileOut( $fname.'-setup' );
1328 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1329 $useSubpages = $this->areSubpagesAllowed();
1331 # Loop for each link
1332 for ($k = 0; isset( $a[$k] ); $k++
) {
1334 if ( $useLinkPrefixExtension ) {
1335 wfProfileIn( $fname.'-prefixhandling' );
1336 if ( preg_match( $e2, $s, $m ) ) {
1344 $prefix = $first_prefix;
1345 $first_prefix = false;
1347 wfProfileOut( $fname.'-prefixhandling' );
1350 $might_be_img = false;
1352 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1354 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1355 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1356 # the real problem is with the $e1 regex
1359 # Still some problems for cases where the ] is meant to be outside punctuation,
1360 # and no image is in sight. See bug 2095.
1362 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1363 $text .= ']'; # so that replaceExternalLinks($text) works later
1366 # fix up urlencoded title texts
1367 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1369 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1370 $might_be_img = true;
1372 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1374 } else { # Invalid form; output directly
1375 $s .= $prefix . '[[' . $line ;
1379 # Don't allow internal links to pages containing
1380 # PROTO: where PROTO is a valid URL protocol; these
1381 # should be external links.
1382 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1383 $s .= $prefix . '[[' . $line ;
1387 # Make subpage if necessary
1388 if( $useSubpages ) {
1389 $link = $this->maybeDoSubpageLink( $m[1], $text );
1394 $noforce = (substr($m[1], 0, 1) != ':');
1396 # Strip off leading ':'
1397 $link = substr($link, 1);
1400 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1402 $s .= $prefix . '[[' . $line;
1406 #check other language variants of the link
1407 #if the article does not exist
1408 if( $checkVariantLink
1409 && $nt->getArticleID() == 0 ) {
1410 $wgContLang->findVariantLink($link, $nt);
1413 $ns = $nt->getNamespace();
1414 $iw = $nt->getInterWiki();
1416 if ($might_be_img) { # if this is actually an invalid link
1417 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1419 while (isset ($a[$k+
1]) ) {
1420 #look at the next 'line' to see if we can close it there
1421 $spliced = array_splice( $a, $k +
1, 1 );
1422 $next_line = array_shift( $spliced );
1423 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1424 # the first ]] closes the inner link, the second the image
1426 $text .= '[[' . $m[1];
1429 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1430 #if there's exactly one ]] that's fine, we'll keep looking
1431 $text .= '[[' . $m[0];
1433 #if $next_line is invalid too, we need look no further
1434 $text .= '[[' . $next_line;
1439 # we couldn't find the end of this imageLink, so output it raw
1440 #but don't ignore what might be perfectly normal links in the text we've examined
1441 $text = $this->replaceInternalLinks($text);
1442 $s .= $prefix . '[[' . $link . '|' . $text;
1443 # note: no $trail, because without an end, there *is* no trail
1446 } else { #it's not an image, so output it raw
1447 $s .= $prefix . '[[' . $link . '|' . $text;
1448 # note: no $trail, because without an end, there *is* no trail
1453 $wasblank = ( '' == $text );
1454 if( $wasblank ) $text = $link;
1457 # Link not escaped by : , create the various objects
1461 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1462 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1463 $s = rtrim($s . "\n");
1464 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1468 if ( $ns == NS_IMAGE
) {
1469 wfProfileIn( "$fname-image" );
1470 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1471 # recursively parse links inside the image caption
1472 # actually, this will parse them in any other parameters, too,
1473 # but it might be hard to fix that, and it doesn't matter ATM
1474 $text = $this->replaceExternalLinks($text);
1475 $text = $this->replaceInternalLinks($text);
1477 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1478 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1479 $this->mOutput
->addImage( $nt->getDBkey() );
1481 wfProfileOut( "$fname-image" );
1484 wfProfileOut( "$fname-image" );
1488 if ( $ns == NS_CATEGORY
) {
1489 wfProfileIn( "$fname-category" );
1490 $s = rtrim($s . "\n"); # bug 87
1493 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1494 $sortkey = $this->mTitle
->getText();
1496 $sortkey = $this->mTitle
->getPrefixedText();
1501 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1502 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1503 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1506 * Strip the whitespace Category links produce, see bug 87
1507 * @todo We might want to use trim($tmp, "\n") here.
1509 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1511 wfProfileOut( "$fname-category" );
1516 if( ( $nt->getPrefixedText() === $selflink ) &&
1517 ( $nt->getFragment() === '' ) ) {
1518 # Self-links are handled specially; generally de-link and change to bold.
1519 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1523 # Special and Media are pseudo-namespaces; no pages actually exist in them
1524 if( $ns == NS_MEDIA
) {
1525 $link = $sk->makeMediaLinkObj( $nt, $text );
1526 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1527 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1528 $this->mOutput
->addImage( $nt->getDBkey() );
1530 } elseif( $ns == NS_SPECIAL
) {
1531 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1533 } elseif( $ns == NS_IMAGE
) {
1534 $img = Image
::newFromTitle( $nt );
1535 if( $img->exists() ) {
1536 // Force a blue link if the file exists; may be a remote
1537 // upload on the shared repository, and we want to see its
1538 // auto-generated page.
1539 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1543 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1545 wfProfileOut( $fname );
1550 * Make a link placeholder. The text returned can be later resolved to a real link with
1551 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1552 * parsing of interwiki links, and secondly to allow all extistence checks and
1553 * article length checks (for stub links) to be bundled into a single query.
1556 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1557 if ( ! is_object($nt) ) {
1559 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1561 # Separate the link trail from the rest of the link
1562 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1564 if ( $nt->isExternal() ) {
1565 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1566 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1567 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1569 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1570 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1571 $this->mLinkHolders
['queries'][] = $query;
1572 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1573 $this->mLinkHolders
['titles'][] = $nt;
1575 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1582 * Render a forced-blue link inline; protect against double expansion of
1583 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1584 * Since this little disaster has to split off the trail text to avoid
1585 * breaking URLs in the following text without breaking trails on the
1586 * wiki links, it's been made into a horrible function.
1589 * @param string $text
1590 * @param string $query
1591 * @param string $trail
1592 * @param string $prefix
1593 * @return string HTML-wikitext mix oh yuck
1595 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1596 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1597 $sk =& $this->mOptions
->getSkin();
1598 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1599 return $this->armorLinks( $link ) . $trail;
1603 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1604 * going to go through further parsing steps before inline URL expansion.
1606 * In particular this is important when using action=render, which causes
1607 * full URLs to be included.
1609 * Oh man I hate our multi-layer parser!
1611 * @param string more-or-less HTML
1612 * @return string less-or-more HTML with NOPARSE bits
1614 function armorLinks( $text ) {
1615 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1616 "{$this->mUniqPrefix}NOPARSE$1", $text );
1620 * Return true if subpage links should be expanded on this page.
1623 function areSubpagesAllowed() {
1624 # Some namespaces don't allow subpages
1625 global $wgNamespacesWithSubpages;
1626 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1630 * Handle link to subpage if necessary
1631 * @param string $target the source of the link
1632 * @param string &$text the link text, modified as necessary
1633 * @return string the full name of the link
1636 function maybeDoSubpageLink($target, &$text) {
1639 # :Foobar -- override special treatment of prefix (images, language links)
1640 # /Foobar -- convert to CurrentPage/Foobar
1641 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1642 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1643 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1645 $fname = 'Parser::maybeDoSubpageLink';
1646 wfProfileIn( $fname );
1647 $ret = $target; # default return value is no change
1649 # Some namespaces don't allow subpages,
1650 # so only perform processing if subpages are allowed
1651 if( $this->areSubpagesAllowed() ) {
1652 # Look at the first character
1653 if( $target != '' && $target{0} == '/' ) {
1654 # / at end means we don't want the slash to be shown
1655 if( substr( $target, -1, 1 ) == '/' ) {
1656 $target = substr( $target, 1, -1 );
1659 $noslash = substr( $target, 1 );
1662 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1663 if( '' === $text ) {
1665 } # this might be changed for ugliness reasons
1667 # check for .. subpage backlinks
1669 $nodotdot = $target;
1670 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1672 $nodotdot = substr( $nodotdot, 3 );
1674 if($dotdotcount > 0) {
1675 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1676 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1677 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1678 # / at the end means don't show full path
1679 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1680 $nodotdot = substr( $nodotdot, 0, -1 );
1681 if( '' === $text ) {
1685 $nodotdot = trim( $nodotdot );
1686 if( $nodotdot != '' ) {
1687 $ret .= '/' . $nodotdot;
1694 wfProfileOut( $fname );
1699 * Used by doBlockLevels()
1702 /* private */ function closeParagraph() {
1704 if ( '' != $this->mLastSection
) {
1705 $result = '</' . $this->mLastSection
. ">\n";
1707 $this->mInPre
= false;
1708 $this->mLastSection
= '';
1711 # getCommon() returns the length of the longest common substring
1712 # of both arguments, starting at the beginning of both.
1714 /* private */ function getCommon( $st1, $st2 ) {
1715 $fl = strlen( $st1 );
1716 $shorter = strlen( $st2 );
1717 if ( $fl < $shorter ) { $shorter = $fl; }
1719 for ( $i = 0; $i < $shorter; ++
$i ) {
1720 if ( $st1{$i} != $st2{$i} ) { break; }
1724 # These next three functions open, continue, and close the list
1725 # element appropriate to the prefix character passed into them.
1727 /* private */ function openList( $char ) {
1728 $result = $this->closeParagraph();
1730 if ( '*' == $char ) { $result .= '<ul><li>'; }
1731 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1732 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1733 else if ( ';' == $char ) {
1734 $result .= '<dl><dt>';
1735 $this->mDTopen
= true;
1737 else { $result = '<!-- ERR 1 -->'; }
1742 /* private */ function nextItem( $char ) {
1743 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1744 else if ( ':' == $char ||
';' == $char ) {
1746 if ( $this->mDTopen
) { $close = '</dt>'; }
1747 if ( ';' == $char ) {
1748 $this->mDTopen
= true;
1749 return $close . '<dt>';
1751 $this->mDTopen
= false;
1752 return $close . '<dd>';
1755 return '<!-- ERR 2 -->';
1758 /* private */ function closeList( $char ) {
1759 if ( '*' == $char ) { $text = '</li></ul>'; }
1760 else if ( '#' == $char ) { $text = '</li></ol>'; }
1761 else if ( ':' == $char ) {
1762 if ( $this->mDTopen
) {
1763 $this->mDTopen
= false;
1764 $text = '</dt></dl>';
1766 $text = '</dd></dl>';
1769 else { return '<!-- ERR 3 -->'; }
1775 * Make lists from lines starting with ':', '*', '#', etc.
1778 * @return string the lists rendered as HTML
1780 function doBlockLevels( $text, $linestart ) {
1781 $fname = 'Parser::doBlockLevels';
1782 wfProfileIn( $fname );
1784 # Parsing through the text line by line. The main thing
1785 # happening here is handling of block-level elements p, pre,
1786 # and making lists from lines starting with * # : etc.
1788 $textLines = explode( "\n", $text );
1790 $lastPrefix = $output = '';
1791 $this->mDTopen
= $inBlockElem = false;
1793 $paragraphStack = false;
1795 if ( !$linestart ) {
1796 $output .= array_shift( $textLines );
1798 foreach ( $textLines as $oLine ) {
1799 $lastPrefixLength = strlen( $lastPrefix );
1800 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1801 $preOpenMatch = preg_match('/<pre/i', $oLine );
1802 if ( !$this->mInPre
) {
1803 # Multiple prefixes may abut each other for nested lists.
1804 $prefixLength = strspn( $oLine, '*#:;' );
1805 $pref = substr( $oLine, 0, $prefixLength );
1808 $pref2 = str_replace( ';', ':', $pref );
1809 $t = substr( $oLine, $prefixLength );
1810 $this->mInPre
= !empty($preOpenMatch);
1812 # Don't interpret any other prefixes in preformatted text
1814 $pref = $pref2 = '';
1819 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1820 # Same as the last item, so no need to deal with nesting or opening stuff
1821 $output .= $this->nextItem( substr( $pref, -1 ) );
1822 $paragraphStack = false;
1824 if ( substr( $pref, -1 ) == ';') {
1825 # The one nasty exception: definition lists work like this:
1826 # ; title : definition text
1827 # So we check for : in the remainder text to split up the
1828 # title and definition, without b0rking links.
1830 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1832 $output .= $term . $this->nextItem( ':' );
1835 } elseif( $prefixLength ||
$lastPrefixLength ) {
1836 # Either open or close a level...
1837 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1838 $paragraphStack = false;
1840 while( $commonPrefixLength < $lastPrefixLength ) {
1841 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1842 --$lastPrefixLength;
1844 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1845 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1847 while ( $prefixLength > $commonPrefixLength ) {
1848 $char = substr( $pref, $commonPrefixLength, 1 );
1849 $output .= $this->openList( $char );
1851 if ( ';' == $char ) {
1852 # FIXME: This is dupe of code above
1853 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1855 $output .= $term . $this->nextItem( ':' );
1858 ++
$commonPrefixLength;
1860 $lastPrefix = $pref2;
1862 if( 0 == $prefixLength ) {
1863 wfProfileIn( "$fname-paragraph" );
1864 # No prefix (not in list)--go to paragraph mode
1865 // XXX: use a stack for nestable elements like span, table and div
1866 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1867 $closematch = preg_match(
1868 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1869 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1870 if ( $openmatch or $closematch ) {
1871 $paragraphStack = false;
1872 $output .= $this->closeParagraph();
1873 if ( $preOpenMatch and !$preCloseMatch ) {
1874 $this->mInPre
= true;
1876 if ( $closematch ) {
1877 $inBlockElem = false;
1879 $inBlockElem = true;
1881 } else if ( !$inBlockElem && !$this->mInPre
) {
1882 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1884 if ($this->mLastSection
!= 'pre') {
1885 $paragraphStack = false;
1886 $output .= $this->closeParagraph().'<pre>';
1887 $this->mLastSection
= 'pre';
1889 $t = substr( $t, 1 );
1892 if ( '' == trim($t) ) {
1893 if ( $paragraphStack ) {
1894 $output .= $paragraphStack.'<br />';
1895 $paragraphStack = false;
1896 $this->mLastSection
= 'p';
1898 if ($this->mLastSection
!= 'p' ) {
1899 $output .= $this->closeParagraph();
1900 $this->mLastSection
= '';
1901 $paragraphStack = '<p>';
1903 $paragraphStack = '</p><p>';
1907 if ( $paragraphStack ) {
1908 $output .= $paragraphStack;
1909 $paragraphStack = false;
1910 $this->mLastSection
= 'p';
1911 } else if ($this->mLastSection
!= 'p') {
1912 $output .= $this->closeParagraph().'<p>';
1913 $this->mLastSection
= 'p';
1918 wfProfileOut( "$fname-paragraph" );
1920 // somewhere above we forget to get out of pre block (bug 785)
1921 if($preCloseMatch && $this->mInPre
) {
1922 $this->mInPre
= false;
1924 if ($paragraphStack === false) {
1928 while ( $prefixLength ) {
1929 $output .= $this->closeList( $pref2{$prefixLength-1} );
1932 if ( '' != $this->mLastSection
) {
1933 $output .= '</' . $this->mLastSection
. '>';
1934 $this->mLastSection
= '';
1937 wfProfileOut( $fname );
1942 * Split up a string on ':', ignoring any occurences inside
1943 * <a>..</a> or <span>...</span>
1944 * @param string $str the string to split
1945 * @param string &$before set to everything before the ':'
1946 * @param string &$after set to everything after the ':'
1947 * return string the position of the ':', or false if none found
1949 function findColonNoLinks($str, &$before, &$after) {
1950 # I wonder if we should make this count all tags, not just <a>
1951 # and <span>. That would prevent us from matching a ':' that
1952 # comes in the middle of italics other such formatting....
1954 $fname = 'Parser::findColonNoLinks';
1955 wfProfileIn( $fname );
1958 $colon = strpos($str, ':', $pos);
1960 if ($colon !== false) {
1961 $before = substr($str, 0, $colon);
1962 $after = substr($str, $colon +
1);
1964 # Skip any ':' within <a> or <span> pairs
1965 $a = substr_count($before, '<a');
1966 $s = substr_count($before, '<span');
1967 $ca = substr_count($before, '</a>');
1968 $cs = substr_count($before, '</span>');
1970 if ($a <= $ca and $s <= $cs) {
1971 # Tags are balanced before ':'; ok
1976 } while ($colon !== false);
1977 wfProfileOut( $fname );
1982 * Return value of a magic variable (like PAGENAME)
1986 function getVariableValue( $index ) {
1987 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1990 * Some of these require message or data lookups and can be
1991 * expensive to check many times.
1993 static $varCache = array();
1994 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1995 if ( isset( $varCache[$index] ) )
1996 return $varCache[$index];
1999 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2002 case MAG_CURRENTMONTH
:
2003 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2004 case MAG_CURRENTMONTHNAME
:
2005 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2006 case MAG_CURRENTMONTHNAMEGEN
:
2007 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2008 case MAG_CURRENTMONTHABBREV
:
2009 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2010 case MAG_CURRENTDAY
:
2011 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2012 case MAG_CURRENTDAY2
:
2013 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2015 return $this->mTitle
->getText();
2017 return $this->mTitle
->getPartialURL();
2018 case MAG_FULLPAGENAME
:
2019 return $this->mTitle
->getPrefixedText();
2020 case MAG_FULLPAGENAMEE
:
2021 return $this->mTitle
->getPrefixedURL();
2022 case MAG_REVISIONID
:
2023 return $this->mRevisionId
;
2025 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2026 case MAG_NAMESPACEE
:
2027 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2028 case MAG_CURRENTDAYNAME
:
2029 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2030 case MAG_CURRENTYEAR
:
2031 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2032 case MAG_CURRENTTIME
:
2033 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2034 case MAG_CURRENTWEEK
:
2035 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2036 // int to remove the padding
2037 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2038 case MAG_CURRENTDOW
:
2039 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2040 case MAG_NUMBEROFARTICLES
:
2041 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2042 case MAG_NUMBEROFFILES
:
2043 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2048 case MAG_SERVERNAME
:
2049 return $wgServerName;
2050 case MAG_SCRIPTPATH
:
2051 return $wgScriptPath;
2054 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2062 * initialise the magic variables (like CURRENTMONTHNAME)
2066 function initialiseVariables() {
2067 $fname = 'Parser::initialiseVariables';
2068 wfProfileIn( $fname );
2069 global $wgVariableIDs;
2070 $this->mVariables
= array();
2071 foreach ( $wgVariableIDs as $id ) {
2072 $mw =& MagicWord
::get( $id );
2073 $mw->addToArray( $this->mVariables
, $id );
2075 wfProfileOut( $fname );
2079 * parse any parentheses in format ((title|part|part))
2080 * and call callbacks to get a replacement text for any found piece
2082 * @param string $text The text to parse
2083 * @param array $callbacks rules in form:
2084 * '{' => array( # opening parentheses
2085 * 'end' => '}', # closing parentheses
2086 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2087 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2092 function replace_callback ($text, $callbacks) {
2093 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2094 $lastOpeningBrace = -1; # last not closed parentheses
2096 for ($i = 0; $i < strlen($text); $i++
) {
2097 # check for any opening brace
2100 foreach ($callbacks as $key => $value) {
2101 $pos = strpos ($text, $key, $i);
2102 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2108 if ($lastOpeningBrace >= 0) {
2109 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2111 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2116 $pos = strpos ($text, '|', $i);
2118 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2129 # found openning brace, lets add it to parentheses stack
2130 if (null != $rule) {
2131 $piece = array('brace' => $text[$i],
2132 'braceEnd' => $rule['end'],
2137 # count openning brace characters
2138 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2143 $piece['startAt'] = $i+
1;
2144 $piece['partStart'] = $i+
1;
2146 # we need to add to stack only if openning brace count is enough for any given rule
2147 foreach ($rule['cb'] as $cnt => $fn) {
2148 if ($piece['count'] >= $cnt) {
2149 $lastOpeningBrace ++
;
2150 $openingBraceStack[$lastOpeningBrace] = $piece;
2157 else if ($lastOpeningBrace >= 0) {
2158 # first check if it is a closing brace
2159 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2160 # lets check if it is enough characters for closing brace
2162 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2165 # if there are more closing parentheses than opening ones, we parse less
2166 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2167 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2169 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2171 $matchingCallback = null;
2172 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2173 if ($count >= $cnt && $matchingCount < $cnt) {
2174 $matchingCount = $cnt;
2175 $matchingCallback = $fn;
2179 if ($matchingCount == 0) {
2184 # lets set a title or last part (if '|' was found)
2185 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2186 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2188 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2190 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2191 $pieceEnd = $i +
$matchingCount;
2193 if( is_callable( $matchingCallback ) ) {
2195 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2196 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2197 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2198 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2200 # finally we can call a user callback and replace piece of text
2201 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2202 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2203 $i = $pieceStart +
strlen($replaceWith) - 1;
2206 # null value for callback means that parentheses should be parsed, but not replaced
2207 $i +
= $matchingCount - 1;
2210 # reset last openning parentheses, but keep it in case there are unused characters
2211 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2212 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2213 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2216 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2217 $openingBraceStack[$lastOpeningBrace--] = null;
2219 if ($matchingCount < $piece['count']) {
2220 $piece['count'] -= $matchingCount;
2221 $piece['startAt'] -= $matchingCount;
2222 $piece['partStart'] = $piece['startAt'];
2223 # do we still qualify for any callback with remaining count?
2224 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2225 if ($piece['count'] >= $cnt) {
2226 $lastOpeningBrace ++
;
2227 $openingBraceStack[$lastOpeningBrace] = $piece;
2235 # lets set a title if it is a first separator, or next part otherwise
2236 if ($text[$i] == '|') {
2237 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2238 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2239 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2242 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2244 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2253 * Replace magic variables, templates, and template arguments
2254 * with the appropriate text. Templates are substituted recursively,
2255 * taking care to avoid infinite loops.
2257 * Note that the substitution depends on value of $mOutputType:
2258 * OT_WIKI: only {{subst:}} templates
2259 * OT_MSG: only magic variables
2260 * OT_HTML: all templates and magic variables
2262 * @param string $tex The text to transform
2263 * @param array $args Key-value pairs representing template parameters to substitute
2264 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2267 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2268 # Prevent too big inclusions
2269 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2273 $fname = 'Parser::replaceVariables';
2274 wfProfileIn( $fname );
2276 # This function is called recursively. To keep track of arguments we need a stack:
2277 array_push( $this->mArgStack
, $args );
2279 $braceCallbacks = array();
2281 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2283 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2284 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2286 $callbacks = array();
2287 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2288 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2289 $text = $this->replace_callback ($text, $callbacks);
2291 array_pop( $this->mArgStack
);
2293 wfProfileOut( $fname );
2298 * Replace magic variables
2301 function variableSubstitution( $matches ) {
2302 $fname = 'Parser::variableSubstitution';
2303 $varname = $matches[1];
2304 wfProfileIn( $fname );
2305 if ( !$this->mVariables
) {
2306 $this->initialiseVariables();
2309 if ( $this->mOutputType
== OT_WIKI
) {
2310 # Do only magic variables prefixed by SUBST
2311 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2312 if (!$mwSubst->matchStartAndRemove( $varname ))
2314 # Note that if we don't substitute the variable below,
2315 # we don't remove the {{subst:}} magic word, in case
2316 # it is a template rather than a magic variable.
2318 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2319 $id = $this->mVariables
[$varname];
2320 $text = $this->getVariableValue( $id );
2321 $this->mOutput
->mContainsOldMagic
= true;
2323 $text = $matches[0];
2325 wfProfileOut( $fname );
2329 # Split template arguments
2330 function getTemplateArgs( $argsString ) {
2331 if ( $argsString === '' ) {
2335 $args = explode( '|', substr( $argsString, 1 ) );
2337 # If any of the arguments contains a '[[' but no ']]', it needs to be
2338 # merged with the next arg because the '|' character between belongs
2339 # to the link syntax and not the template parameter syntax.
2340 $argc = count($args);
2342 for ( $i = 0; $i < $argc-1; $i++
) {
2343 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2344 $args[$i] .= '|'.$args[$i+
1];
2345 array_splice($args, $i+
1, 1);
2355 * Return the text of a template, after recursively
2356 * replacing any variables or templates within the template.
2358 * @param array $piece The parts of the template
2359 * $piece['text']: matched text
2360 * $piece['title']: the title, i.e. the part before the |
2361 * $piece['parts']: the parameter array
2362 * @return string the text of the template
2365 function braceSubstitution( $piece ) {
2367 $fname = 'Parser::braceSubstitution';
2368 wfProfileIn( $fname );
2371 $found = false; # $text has been filled
2372 $nowiki = false; # wiki markup in $text should be escaped
2373 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2374 $noargs = false; # Don't replace triple-brace arguments in $text
2375 $replaceHeadings = false; # Make the edit section links go to the template not the article
2376 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2377 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2379 # Title object, where $text came from
2384 # $part1 is the bit before the first |, and must contain only title characters
2385 # $args is a list of arguments, starting from index 0, not including $part1
2387 $part1 = $piece['title'];
2388 # If the third subpattern matched anything, it will start with |
2390 if (null == $piece['parts']) {
2391 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2392 if ($replaceWith != $piece['text']) {
2393 $text = $replaceWith;
2400 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2401 $argc = count( $args );
2405 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2406 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2407 # One of two possibilities is true:
2408 # 1) Found SUBST but not in the PST phase
2409 # 2) Didn't find SUBST and in the PST phase
2410 # In either case, return without further processing
2411 $text = $piece['text'];
2418 # MSG, MSGNW, INT and RAW
2421 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2422 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2425 # Remove obsolete MSG:
2426 $mwMsg =& MagicWord
::get( MAG_MSG
);
2427 $mwMsg->matchStartAndRemove( $part1 );
2431 $mwRaw =& MagicWord
::get( MAG_RAW
);
2432 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2433 $forceRawInterwiki = true;
2436 # Check if it is an internal message
2437 $mwInt =& MagicWord
::get( MAG_INT
);
2438 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2439 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2440 $text = $linestart . wfMsgReal( $part1, $args, true );
2448 # Check for NS: (namespace expansion)
2449 $mwNs = MagicWord
::get( MAG_NS
);
2450 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2451 if ( intval( $part1 ) ||
$part1 == "0" ) {
2452 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2455 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2456 if ( !is_null( $index ) ) {
2457 $text = $linestart . $wgContLang->getNsText( $index );
2464 # LCFIRST, UCFIRST, LC and UC
2466 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2467 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2468 $lc =& MagicWord
::get( MAG_LC
);
2469 $uc =& MagicWord
::get( MAG_UC
);
2470 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2471 $text = $linestart . $wgContLang->lcfirst( $part1 );
2473 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2474 $text = $linestart . $wgContLang->ucfirst( $part1 );
2476 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2477 $text = $linestart . $wgContLang->lc( $part1 );
2479 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2480 $text = $linestart . $wgContLang->uc( $part1 );
2485 # LOCALURL and FULLURL
2487 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2488 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2489 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2490 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2493 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2494 $func = 'getLocalURL';
2495 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2496 $func = 'escapeLocalURL';
2497 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2498 $func = 'getFullURL';
2499 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2500 $func = 'escapeFullURL';
2505 if ( $func !== false ) {
2506 $title = Title
::newFromText( $part1 );
2507 if ( !is_null( $title ) ) {
2509 $text = $linestart . $title->$func( $args[0] );
2511 $text = $linestart . $title->$func();
2519 if ( !$found && $argc == 1 ) {
2520 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2521 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2522 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2528 if ( !$found && $argc >= 2 ) {
2529 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2530 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2531 if ($argc==2) {$args[2]=$args[1];}
2532 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2537 # Template table test
2539 # Did we encounter this template already? If yes, it is in the cache
2540 # and we need to check for loops.
2541 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2544 # Infinite loop test
2545 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2549 $text = $linestart .
2550 '{{' . $part1 . '}}' .
2551 '<!-- WARNING: template loop detected -->';
2552 wfDebug( "$fname: template loop broken at '$part1'\n" );
2554 # set $text to cached message.
2555 $text = $linestart . $this->mTemplates
[$piece['title']];
2559 # Load from database
2560 $lastPathLevel = $this->mTemplatePath
;
2563 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2564 if ($subpage !== '') {
2565 $ns = $this->mTitle
->getNamespace();
2567 $title = Title
::newFromText( $part1, $ns );
2569 if ( !is_null( $title ) ) {
2570 if ( !$title->isExternal() ) {
2571 # Check for excessive inclusion
2572 $dbk = $title->getPrefixedDBkey();
2573 if ( $this->incrementIncludeCount( $dbk ) ) {
2574 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2575 # Capture special page output
2576 $text = SpecialPage
::capturePath( $title );
2577 if ( is_string( $text ) ) {
2582 $this->disableCache();
2585 $articleContent = $this->fetchTemplate( $title );
2586 if ( $articleContent !== false ) {
2588 $text = $articleContent;
2589 $replaceHeadings = true;
2594 # If the title is valid but undisplayable, make a link to it
2595 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2596 $text = '[['.$title->getPrefixedText().']]';
2599 } elseif ( $title->isTrans() ) {
2600 // Interwiki transclusion
2601 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2602 $text = $this->interwikiTransclude( $title, 'render' );
2606 $text = $this->interwikiTransclude( $title, 'raw' );
2607 $replaceHeadings = true;
2612 # Template cache array insertion
2613 # Use the original $piece['title'] not the mangled $part1, so that
2614 # modifiers such as RAW: produce separate cache entries
2616 $this->mTemplates
[$piece['title']] = $text;
2617 $text = $linestart . $text;
2622 # Recursive parsing, escaping and link table handling
2623 # Only for HTML output
2624 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2625 $text = wfEscapeWikiText( $text );
2626 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2628 # Clean up argument array
2629 $assocArgs = array();
2631 foreach( $args as $arg ) {
2632 $eqpos = strpos( $arg, '=' );
2633 if ( $eqpos === false ) {
2634 $assocArgs[$index++
] = $arg;
2636 $name = trim( substr( $arg, 0, $eqpos ) );
2637 $value = trim( substr( $arg, $eqpos+
1 ) );
2638 if ( $value === false ) {
2641 if ( $name !== false ) {
2642 $assocArgs[$name] = $value;
2647 # Add a new element to the templace recursion path
2648 $this->mTemplatePath
[$part1] = 1;
2652 # If there are any <onlyinclude> tags, only include them
2653 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2654 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2656 foreach ($m[1] as $piece)
2659 # Remove <noinclude> sections and <includeonly> tags
2660 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2661 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2663 if( $this->mOutputType
== OT_HTML
) {
2664 # Strip <nowiki>, <pre>, etc.
2665 $text = $this->strip( $text, $this->mStripState
);
2666 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2668 $text = $this->replaceVariables( $text, $assocArgs );
2670 # If the template begins with a table or block-level
2671 # element, it should be treated as beginning a new line.
2672 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2673 $text = "\n" . $text;
2675 } elseif ( !$noargs ) {
2676 # $noparse and !$noargs
2677 # Just replace the arguments, not any double-brace items
2678 # This is used for rendered interwiki transclusion
2679 $text = $this->replaceVariables( $text, $assocArgs, true );
2682 # Prune lower levels off the recursion check path
2683 $this->mTemplatePath
= $lastPathLevel;
2686 wfProfileOut( $fname );
2687 return $piece['text'];
2690 # Replace raw HTML by a placeholder
2691 # Add a blank line preceding, to prevent it from mucking up
2692 # immediately preceding headings
2693 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2695 # replace ==section headers==
2696 # XXX this needs to go away once we have a better parser.
2697 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2698 if( !is_null( $title ) )
2699 $encodedname = base64_encode($title->getPrefixedDBkey());
2701 $encodedname = base64_encode("");
2702 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2703 PREG_SPLIT_DELIM_CAPTURE
);
2706 for( $i = 0; $i < count($m); $i +
= 2 ) {
2708 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2710 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2714 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2715 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2716 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2724 # Prune lower levels off the recursion check path
2725 $this->mTemplatePath
= $lastPathLevel;
2728 wfProfileOut( $fname );
2729 return $piece['text'];
2731 wfProfileOut( $fname );
2737 * Fetch the unparsed text of a template and register a reference to it.
2739 function fetchTemplate( $title ) {
2741 // Loop to fetch the article, with up to 1 redirect
2742 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2743 $rev = Revision
::newFromTitle( $title );
2744 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2748 $text = $rev->getText();
2749 if ( $text === false ) {
2753 $title = Title
::newFromRedirect( $text );
2759 * Transclude an interwiki link.
2761 function interwikiTransclude( $title, $action ) {
2762 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2764 if (!$wgEnableScaryTranscluding)
2765 return wfMsg('scarytranscludedisabled');
2767 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2768 // But we'll handle it generally anyway
2769 if ( $title->getNamespace() ) {
2770 // Use the canonical namespace, which should work anywhere
2771 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2773 $articleName = $title->getDBkey();
2776 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2777 $url .= "?action=$action";
2778 if (strlen($url) > 255)
2779 return wfMsg('scarytranscludetoolong');
2780 return $this->fetchScaryTemplateMaybeFromCache($url);
2783 function fetchScaryTemplateMaybeFromCache($url) {
2784 global $wgTranscludeCacheExpiry;
2785 $dbr =& wfGetDB(DB_SLAVE
);
2786 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2787 array('tc_url' => $url));
2789 $time = $obj->tc_time
;
2790 $text = $obj->tc_contents
;
2791 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2796 $text = wfGetHTTP($url);
2798 return wfMsg('scarytranscludefailed', $url);
2800 $dbw =& wfGetDB(DB_MASTER
);
2801 $dbw->replace('transcache', array('tc_url'), array(
2803 'tc_time' => time(),
2804 'tc_contents' => $text));
2810 * Triple brace replacement -- used for template arguments
2813 function argSubstitution( $matches ) {
2814 $arg = trim( $matches['title'] );
2815 $text = $matches['text'];
2816 $inputArgs = end( $this->mArgStack
);
2818 if ( array_key_exists( $arg, $inputArgs ) ) {
2819 $text = $inputArgs[$arg];
2820 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2821 $text = $matches['parts'][0];
2828 * Returns true if the function is allowed to include this entity
2831 function incrementIncludeCount( $dbk ) {
2832 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2833 $this->mIncludeCount
[$dbk] = 0;
2835 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2843 * This function accomplishes several tasks:
2844 * 1) Auto-number headings if that option is enabled
2845 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2846 * 3) Add a Table of contents on the top for users who have enabled the option
2847 * 4) Auto-anchor headings
2849 * It loops through all headlines, collects the necessary data, then splits up the
2850 * string and re-inserts the newly formatted headlines.
2852 * @param string $text
2853 * @param boolean $isMain
2856 function formatHeadings( $text, $isMain=true ) {
2857 global $wgMaxTocLevel, $wgContLang;
2859 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2861 $forceTocHere = false;
2862 if( !$this->mTitle
->userCanEdit() ) {
2865 $showEditLink = $this->mOptions
->getEditSection();
2868 # Inhibit editsection links if requested in the page
2869 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2870 if( $esw->matchAndRemove( $text ) ) {
2873 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2875 $mw =& MagicWord
::get( MAG_NOTOC
);
2876 if( $mw->matchAndRemove( $text ) ) {
2880 # Get all headlines for numbering them and adding funky stuff like [edit]
2881 # links - this is for later, but we need the number of headlines right now
2882 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2884 # if there are fewer than 4 headlines in the article, do not show TOC
2885 if( $numMatches < 4 ) {
2889 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2890 # override above conditions and always show TOC at that place
2892 $mw =& MagicWord
::get( MAG_TOC
);
2893 if($mw->match( $text ) ) {
2895 $forceTocHere = true;
2897 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2898 # override above conditions and always show TOC above first header
2899 $mw =& MagicWord
::get( MAG_FORCETOC
);
2900 if ($mw->matchAndRemove( $text ) ) {
2905 # Never ever show TOC if no headers
2906 if( $numMatches < 1 ) {
2910 # We need this to perform operations on the HTML
2911 $sk =& $this->mOptions
->getSkin();
2915 $sectionCount = 0; # headlineCount excluding template sections
2917 # Ugh .. the TOC should have neat indentation levels which can be
2918 # passed to the skin functions. These are determined here
2922 $sublevelCount = array();
2923 $levelCount = array();
2930 foreach( $matches[3] as $headline ) {
2932 $templatetitle = '';
2933 $templatesection = 0;
2936 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2938 $templatetitle = base64_decode($mat[1]);
2939 $templatesection = 1 +
(int)base64_decode($mat[2]);
2940 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2944 $prevlevel = $level;
2945 $prevtoclevel = $toclevel;
2947 $level = $matches[1][$headlineCount];
2949 if( $doNumberHeadings ||
$doShowToc ) {
2951 if ( $level > $prevlevel ) {
2952 # Increase TOC level
2954 $sublevelCount[$toclevel] = 0;
2955 $toc .= $sk->tocIndent();
2957 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2958 # Decrease TOC level, find level to jump to
2960 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2961 # Can only go down to level 1
2964 for ($i = $toclevel; $i > 0; $i--) {
2965 if ( $levelCount[$i] == $level ) {
2966 # Found last matching level
2970 elseif ( $levelCount[$i] < $level ) {
2971 # Found first matching level below current level
2978 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2981 # No change in level, end TOC line
2982 $toc .= $sk->tocLineEnd();
2985 $levelCount[$toclevel] = $level;
2987 # count number of headlines for each level
2988 @$sublevelCount[$toclevel]++
;
2990 for( $i = 1; $i <= $toclevel; $i++
) {
2991 if( !empty( $sublevelCount[$i] ) ) {
2995 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3001 # The canonized header is a version of the header text safe to use for links
3002 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3003 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3004 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3006 # Remove link placeholders by the link text.
3007 # <!--LINK number-->
3009 # link text with suffix
3010 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3011 "\$this->mLinkHolders['texts'][\$1]",
3012 $canonized_headline );
3013 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3014 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3015 $canonized_headline );
3018 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3019 $tocline = trim( $canonized_headline );
3020 $canonized_headline = Sanitizer
::escapeId( $tocline );
3021 $refers[$headlineCount] = $canonized_headline;
3023 # count how many in assoc. array so we can track dupes in anchors
3024 @$refers[$canonized_headline]++
;
3025 $refcount[$headlineCount]=$refers[$canonized_headline];
3027 # Don't number the heading if it is the only one (looks silly)
3028 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3029 # the two are different if the line contains a link
3030 $headline=$numbering . ' ' . $headline;
3033 # Create the anchor for linking from the TOC to the section
3034 $anchor = $canonized_headline;
3035 if($refcount[$headlineCount] > 1 ) {
3036 $anchor .= '_' . $refcount[$headlineCount];
3038 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3039 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3041 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3042 if ( empty( $head[$headlineCount] ) ) {
3043 $head[$headlineCount] = '';
3046 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3048 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
3051 # give headline the correct <h#> tag
3052 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3060 $toc .= $sk->tocUnindent( $toclevel - 1 );
3061 $toc = $sk->tocList( $toc );
3064 # split up and insert constructed headlines
3066 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3069 foreach( $blocks as $block ) {
3070 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3071 # This is the [edit] link that appears for the top block of text when
3072 # section editing is enabled
3074 # Disabled because it broke block formatting
3075 # For example, a bullet point in the top line
3076 # $full .= $sk->editSectionLink(0);
3079 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3080 # Top anchor now in skin
3084 if( !empty( $head[$i] ) ) {
3090 $mw =& MagicWord
::get( MAG_TOC
);
3091 return $mw->replace( $toc, $full );
3098 * Return an HTML link for the "ISBN 123456" text
3101 function magicISBN( $text ) {
3102 $fname = 'Parser::magicISBN';
3103 wfProfileIn( $fname );
3105 $a = split( 'ISBN ', ' '.$text );
3106 if ( count ( $a ) < 2 ) {
3107 wfProfileOut( $fname );
3110 $text = substr( array_shift( $a ), 1);
3111 $valid = '0123456789-Xx';
3113 foreach ( $a as $x ) {
3114 $isbn = $blank = '' ;
3115 while ( ' ' == $x{0} ) {
3117 $x = substr( $x, 1 );
3119 if ( $x == '' ) { # blank isbn
3120 $text .= "ISBN $blank";
3123 while ( strstr( $valid, $x{0} ) != false ) {
3125 $x = substr( $x, 1 );
3127 $num = str_replace( '-', '', $isbn );
3128 $num = str_replace( ' ', '', $num );
3129 $num = str_replace( 'x', 'X', $num );
3132 $text .= "ISBN $blank$x";
3134 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3135 $text .= '<a href="' .
3136 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3137 "\" class=\"internal\">ISBN $isbn</a>";
3141 wfProfileOut( $fname );
3146 * Return an HTML link for the "RFC 1234" text
3149 * @param string $text Text to be processed
3150 * @param string $keyword Magic keyword to use (default RFC)
3151 * @param string $urlmsg Interface message to use (default rfcurl)
3154 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3156 $valid = '0123456789';
3159 $a = split( $keyword, ' '.$text );
3160 if ( count ( $a ) < 2 ) {
3163 $text = substr( array_shift( $a ), 1);
3165 /* Check if keyword is preceed by [[.
3166 * This test is made here cause of the array_shift above
3167 * that prevent the test to be done in the foreach.
3169 if ( substr( $text, -2 ) == '[[' ) {
3173 foreach ( $a as $x ) {
3174 /* token might be empty if we have RFC RFC 1234 */
3182 /** remove and save whitespaces in $blank */
3183 while ( $x{0} == ' ' ) {
3185 $x = substr( $x, 1 );
3188 /** remove and save the rfc number in $id */
3189 while ( strstr( $valid, $x{0} ) != false ) {
3191 $x = substr( $x, 1 );
3195 /* call back stripped spaces*/
3196 $text .= $keyword.$blank.$x;
3197 } elseif( $internal ) {
3199 $text .= $keyword.$id.$x;
3201 /* build the external link*/
3202 $url = wfMsg( $urlmsg, $id);
3203 $sk =& $this->mOptions
->getSkin();
3204 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3205 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3208 /* Check if the next RFC keyword is preceed by [[ */
3209 $internal = ( substr($x,-2) == '[[' );
3215 * Transform wiki markup when saving a page by doing \r\n -> \n
3216 * conversion, substitting signatures, {{subst:}} templates, etc.
3218 * @param string $text the text to transform
3219 * @param Title &$title the Title object for the current article
3220 * @param User &$user the User object describing the current user
3221 * @param ParserOptions $options parsing options
3222 * @param bool $clearState whether to clear the parser state first
3223 * @return string the altered wiki markup
3226 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3227 $this->mOptions
= $options;
3228 $this->mTitle
=& $title;
3229 $this->mOutputType
= OT_WIKI
;
3231 if ( $clearState ) {
3232 $this->clearState();
3235 $stripState = false;
3239 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3240 $text = $this->strip( $text, $stripState, true );
3241 $text = $this->pstPass2( $text, $user );
3242 $text = $this->unstrip( $text, $stripState );
3243 $text = $this->unstripNoWiki( $text, $stripState );
3248 * Pre-save transform helper function
3251 function pstPass2( $text, &$user ) {
3252 global $wgContLang, $wgLocaltimezone;
3254 /* Note: This is the timestamp saved as hardcoded wikitext to
3255 * the database, we use $wgContLang here in order to give
3256 * everyone the same signiture and use the default one rather
3257 * than the one selected in each users preferences.
3259 if ( isset( $wgLocaltimezone ) ) {
3260 $oldtz = getenv( 'TZ' );
3261 putenv( 'TZ='.$wgLocaltimezone );
3263 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3264 ' (' . date( 'T' ) . ')';
3265 if ( isset( $wgLocaltimezone ) ) {
3266 putenv( 'TZ='.$oldtz );
3269 # Variable replacement
3270 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3271 $text = $this->replaceVariables( $text );
3274 $sigText = $this->getUserSig( $user );
3275 $text = strtr( $text, array(
3277 '~~~~' => "$sigText $d",
3281 # Context links: [[|name]] and [[name (context)|]]
3283 global $wgLegalTitleChars;
3284 $tc = "[$wgLegalTitleChars]";
3285 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3287 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3288 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3290 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3291 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3292 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3293 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3295 $t = $this->mTitle
->getText();
3296 if ( preg_match( $conpat, $t, $m ) ) {
3299 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3300 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3301 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3303 if ( '' == $context ) {
3304 $text = preg_replace( $p2, '[[\\1]]', $text );
3306 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3309 # Trim trailing whitespace
3310 # MAG_END (__END__) tag allows for trailing
3311 # whitespace to be deliberately included
3312 $text = rtrim( $text );
3313 $mw =& MagicWord
::get( MAG_END
);
3314 $mw->matchAndRemove( $text );
3320 * Fetch the user's signature text, if any, and normalize to
3321 * validated, ready-to-insert wikitext.
3327 function getUserSig( &$user ) {
3330 $username = $user->getName();
3331 $nickname = $user->getOption( 'nickname' );
3332 $nickname = $nickname === '' ?
$username : $nickname;
3334 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3335 # Sig. might contain markup; validate this
3336 if( $this->validateSig( $nickname ) !== false ) {
3337 # Validated; clean up (if needed) and return it
3338 return( $this->cleanSig( $nickname ) );
3340 # Failed to validate; fall back to the default
3341 $nickname = $username;
3342 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3346 # If we're still here, make it a link to the user page
3347 $userpage = $user->getUserPage();
3348 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3352 * Check that the user's signature contains no bad XML
3354 * @param string $text
3355 * @return mixed An expanded string, or false if invalid.
3357 function validateSig( $text ) {
3358 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3362 * Clean up signature text
3364 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3365 * 2) Substitute all transclusions
3367 * @param string $text
3368 * @return string Signature text
3370 function cleanSig( $text ) {
3371 $substWord = MagicWord
::get( MAG_SUBST
);
3372 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3373 $substText = '{{' . $substWord->getSynonym( 0 );
3375 $text = preg_replace( $substRegex, $substText, $text );
3376 $text = preg_replace( '/~{3,5}/', '', $text );
3377 $text = $this->replaceVariables( $text );
3383 * Set up some variables which are usually set up in parse()
3384 * so that an external function can call some class members with confidence
3387 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3388 $this->mTitle
=& $title;
3389 $this->mOptions
= $options;
3390 $this->mOutputType
= $outputType;
3391 if ( $clearState ) {
3392 $this->clearState();
3397 * Transform a MediaWiki message by replacing magic variables.
3399 * @param string $text the text to transform
3400 * @param ParserOptions $options options
3401 * @return string the text with variables substituted
3404 function transformMsg( $text, $options ) {
3406 static $executing = false;
3408 $fname = "Parser::transformMsg";
3410 # Guard against infinite recursion
3416 wfProfileIn($fname);
3418 $this->mTitle
= $wgTitle;
3419 $this->mOptions
= $options;
3420 $this->mOutputType
= OT_MSG
;
3421 $this->clearState();
3422 $text = $this->replaceVariables( $text );
3425 wfProfileOut($fname);
3430 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3431 * Callback will be called with the text within
3432 * Transform and return the text within
3436 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3437 * @param mixed $callback The callback function (and object) to use for the tag
3439 * @return The old value of the mTagHooks array associated with the hook
3441 function setHook( $tag, $callback ) {
3442 $oldVal = @$this->mTagHooks
[$tag];
3443 $this->mTagHooks
[$tag] = $callback;
3449 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3450 * Placeholders created in Skin::makeLinkObj()
3451 * Returns an array of links found, indexed by PDBK:
3455 * $options is a bit field, RLH_FOR_UPDATE to select for update
3457 function replaceLinkHolders( &$text, $options = 0 ) {
3459 global $wgOutputReplace;
3461 $fname = 'Parser::replaceLinkHolders';
3462 wfProfileIn( $fname );
3466 $sk =& $this->mOptions
->getSkin();
3467 $linkCache =& LinkCache
::singleton();
3469 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3470 wfProfileIn( $fname.'-check' );
3471 $dbr =& wfGetDB( DB_SLAVE
);
3472 $page = $dbr->tableName( 'page' );
3473 $threshold = $wgUser->getOption('stubthreshold');
3476 asort( $this->mLinkHolders
['namespaces'] );
3480 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3482 $title = $this->mLinkHolders
['titles'][$key];
3484 # Skip invalid entries.
3485 # Result will be ugly, but prevents crash.
3486 if ( is_null( $title ) ) {
3489 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3491 # Check if it's a static known link, e.g. interwiki
3492 if ( $title->isAlwaysKnown() ) {
3493 $colours[$pdbk] = 1;
3494 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3495 $colours[$pdbk] = 1;
3496 $this->mOutput
->addLink( $title, $id );
3497 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3498 $colours[$pdbk] = 0;
3500 # Not in the link cache, add it to the query
3501 if ( !isset( $current ) ) {
3503 $query = "SELECT page_id, page_namespace, page_title";
3504 if ( $threshold > 0 ) {
3505 $query .= ', page_len, page_is_redirect';
3507 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3508 } elseif ( $current != $ns ) {
3510 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3515 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3520 if ( $options & RLH_FOR_UPDATE
) {
3521 $query .= ' FOR UPDATE';
3524 $res = $dbr->query( $query, $fname );
3526 # Fetch data and form into an associative array
3527 # non-existent = broken
3530 while ( $s = $dbr->fetchObject($res) ) {
3531 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3532 $pdbk = $title->getPrefixedDBkey();
3533 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3534 $this->mOutput
->addLink( $title, $s->page_id
);
3536 if ( $threshold > 0 ) {
3537 $size = $s->page_len
;
3538 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3539 $colours[$pdbk] = 1;
3541 $colours[$pdbk] = 2;
3544 $colours[$pdbk] = 1;
3548 wfProfileOut( $fname.'-check' );
3550 # Construct search and replace arrays
3551 wfProfileIn( $fname.'-construct' );
3552 $wgOutputReplace = array();
3553 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3554 $pdbk = $pdbks[$key];
3555 $searchkey = "<!--LINK $key-->";
3556 $title = $this->mLinkHolders
['titles'][$key];
3557 if ( empty( $colours[$pdbk] ) ) {
3558 $linkCache->addBadLinkObj( $title );
3559 $colours[$pdbk] = 0;
3560 $this->mOutput
->addLink( $title, 0 );
3561 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3562 $this->mLinkHolders
['texts'][$key],
3563 $this->mLinkHolders
['queries'][$key] );
3564 } elseif ( $colours[$pdbk] == 1 ) {
3565 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3566 $this->mLinkHolders
['texts'][$key],
3567 $this->mLinkHolders
['queries'][$key] );
3568 } elseif ( $colours[$pdbk] == 2 ) {
3569 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3570 $this->mLinkHolders
['texts'][$key],
3571 $this->mLinkHolders
['queries'][$key] );
3574 wfProfileOut( $fname.'-construct' );
3577 wfProfileIn( $fname.'-replace' );
3579 $text = preg_replace_callback(
3580 '/(<!--LINK .*?-->)/',
3581 "wfOutputReplaceMatches",
3584 wfProfileOut( $fname.'-replace' );
3587 # Now process interwiki link holders
3588 # This is quite a bit simpler than internal links
3589 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3590 wfProfileIn( $fname.'-interwiki' );
3591 # Make interwiki link HTML
3592 $wgOutputReplace = array();
3593 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3594 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3595 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3598 $text = preg_replace_callback(
3599 '/<!--IWLINK (.*?)-->/',
3600 "wfOutputReplaceMatches",
3602 wfProfileOut( $fname.'-interwiki' );
3605 wfProfileOut( $fname );
3610 * Replace <!--LINK--> link placeholders with plain text of links
3611 * (not HTML-formatted).
3612 * @param string $text
3615 function replaceLinkHoldersText( $text ) {
3617 global $wgOutputReplace;
3619 $fname = 'Parser::replaceLinkHoldersText';
3620 wfProfileIn( $fname );
3622 $text = preg_replace_callback(
3623 '/<!--(LINK|IWLINK) (.*?)-->/',
3624 array( &$this, 'replaceLinkHoldersTextCallback' ),
3627 wfProfileOut( $fname );
3632 * @param array $matches
3636 function replaceLinkHoldersTextCallback( $matches ) {
3637 $type = $matches[1];
3639 if( $type == 'LINK' ) {
3640 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3641 return $this->mLinkHolders
['texts'][$key];
3643 } elseif( $type == 'IWLINK' ) {
3644 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3645 return $this->mInterwikiLinkHolders
['texts'][$key];
3652 * Renders an image gallery from a text with one line per image.
3653 * text labels may be given by using |-style alternative text. E.g.
3654 * Image:one.jpg|The number "1"
3655 * Image:tree.jpg|A tree
3656 * given as text will return the HTML of a gallery with two images,
3657 * labeled 'The number "1"' and
3660 function renderImageGallery( $text ) {
3662 $parserOptions = new ParserOptions
;
3663 $localParser = new Parser();
3665 $ig = new ImageGallery();
3666 $ig->setShowBytes( false );
3667 $ig->setShowFilename( false );
3668 $lines = explode( "\n", $text );
3670 foreach ( $lines as $line ) {
3671 # match lines like these:
3672 # Image:someimage.jpg|This is some image
3673 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3675 if ( count( $matches ) == 0 ) {
3678 $nt =& Title
::newFromText( $matches[1] );
3679 if( is_null( $nt ) ) {
3680 # Bogus title. Ignore these so we don't bomb out later.
3683 if ( isset( $matches[3] ) ) {
3684 $label = $matches[3];
3689 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3690 $html = $pout->getText();
3692 $ig->add( new Image( $nt ), $html );
3693 $this->mOutput
->addImage( $nt->getDBkey() );
3695 return $ig->toHTML();
3699 * Parse image options text and use it to make an image
3701 function makeImage( &$nt, $options ) {
3702 global $wgContLang, $wgUseImageResize, $wgUser;
3706 # Check if the options text is of the form "options|alt text"
3708 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3709 # * left no resizing, just left align. label is used for alt= only
3710 # * right same, but right aligned
3711 # * none same, but not aligned
3712 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3713 # * center center the image
3714 # * framed Keep original image size, no magnify-button.
3716 $part = explode( '|', $options);
3718 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3719 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3720 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3721 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3722 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3723 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3724 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3725 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3728 $width = $height = $framed = $thumb = false;
3729 $manual_thumb = '' ;
3731 foreach( $part as $key => $val ) {
3732 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3734 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3735 # use manually specified thumbnail
3737 $manual_thumb = $match;
3738 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3739 # remember to set an alignment, don't render immediately
3741 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3742 # remember to set an alignment, don't render immediately
3744 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3745 # remember to set an alignment, don't render immediately
3747 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3748 # remember to set an alignment, don't render immediately
3750 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3751 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3752 # $match is the image width in pixels
3753 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3754 $width = intval( $m[1] );
3755 $height = intval( $m[2] );
3757 $width = intval($match);
3759 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3765 # Strip bad stuff out of the alt text
3766 $alt = $this->replaceLinkHoldersText( $caption );
3767 $alt = Sanitizer
::stripAllTags( $alt );
3769 # Linker does the rest
3770 $sk =& $this->mOptions
->getSkin();
3771 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3775 * Set a flag in the output object indicating that the content is dynamic and
3776 * shouldn't be cached.
3778 function disableCache() {
3779 $this->mOutput
->mCacheTime
= -1;
3783 * Callback from the Sanitizer for expanding items found in HTML attribute
3784 * values, so they can be safely tested and escaped.
3785 * @param string $text
3786 * @param array $args
3790 function attributeStripCallback( &$text, $args ) {
3791 $text = $this->replaceVariables( $text, $args );
3792 $text = $this->unstripForHTML( $text );
3796 function unstripForHTML( $text ) {
3797 $text = $this->unstrip( $text, $this->mStripState
);
3798 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3806 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3807 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3808 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3814 function getTags() { return array_keys( $this->mTagHooks
); }
3820 * @package MediaWiki
3824 var $mText, # The output text
3825 $mLanguageLinks, # List of the full text of language links, in the order they appear
3826 $mCategories, # Map of category names to sort keys
3827 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3828 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3829 $mVersion, # Compatibility check
3830 $mTitleText, # title text of the chosen language variant
3831 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3832 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3833 $mImages, # DB keys of the images used, in the array key only
3834 $mExternalLinks; # External link URLs, in the key only
3836 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3837 $containsOldMagic = false, $titletext = '' )
3839 $this->mText
= $text;
3840 $this->mLanguageLinks
= $languageLinks;
3841 $this->mCategories
= $categoryLinks;
3842 $this->mContainsOldMagic
= $containsOldMagic;
3843 $this->mCacheTime
= '';
3844 $this->mVersion
= MW_PARSER_VERSION
;
3845 $this->mTitleText
= $titletext;
3846 $this->mLinks
= array();
3847 $this->mTemplates
= array();
3848 $this->mImages
= array();
3849 $this->mExternalLinks
= array();
3852 function getText() { return $this->mText
; }
3853 function getLanguageLinks() { return $this->mLanguageLinks
; }
3854 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3855 function &getCategories() { return $this->mCategories
; }
3856 function getCacheTime() { return $this->mCacheTime
; }
3857 function getTitleText() { return $this->mTitleText
; }
3858 function &getLinks() { return $this->mLinks
; }
3859 function &getTemplates() { return $this->mTemplates
; }
3860 function &getImages() { return $this->mImages
; }
3861 function &getExternalLinks() { return $this->mExternalLinks
; }
3863 function containsOldMagic() { return $this->mContainsOldMagic
; }
3864 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3865 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3866 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3867 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3868 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3869 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3871 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3872 function addImage( $name ) { $this->mImages
[$name] = 1; }
3873 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3874 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3876 function addLink( $title, $id ) {
3877 $ns = $title->getNamespace();
3878 $dbk = $title->getDBkey();
3879 if ( !isset( $this->mLinks
[$ns] ) ) {
3880 $this->mLinks
[$ns] = array();
3882 $this->mLinks
[$ns][$dbk] = $id;
3885 function addTemplate( $title, $id ) {
3886 $ns = $title->getNamespace();
3887 $dbk = $title->getDBkey();
3888 if ( !isset( $this->mTemplates
[$ns] ) ) {
3889 $this->mTemplates
[$ns] = array();
3891 $this->mTemplates
[$ns][$dbk] = $id;
3898 function merge( $other ) {
3899 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3900 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3901 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3905 * Return true if this cached output object predates the global or
3906 * per-article cache invalidation timestamps, or if it comes from
3907 * an incompatible older version.
3909 * @param string $touched the affected article's last touched timestamp
3913 function expired( $touched ) {
3914 global $wgCacheEpoch;
3915 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3916 $this->getCacheTime() < $touched ||
3917 $this->getCacheTime() <= $wgCacheEpoch ||
3918 !isset( $this->mVersion
) ||
3919 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3924 * Set options of the Parser
3926 * @package MediaWiki
3930 # All variables are private
3931 var $mUseTeX; # Use texvc to expand <math> tags
3932 var $mUseDynamicDates; # Use DateFormatter to format dates
3933 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3934 var $mAllowExternalImages; # Allow external images inline
3935 var $mAllowExternalImagesFrom; # If not, any exception?
3936 var $mSkin; # Reference to the preferred skin
3937 var $mDateFormat; # Date format index
3938 var $mEditSection; # Create "edit section" links
3939 var $mNumberHeadings; # Automatically number headings
3940 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3941 var $mTidy; # Ask for tidy cleanup
3943 function getUseTeX() { return $this->mUseTeX
; }
3944 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3945 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3946 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3947 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3948 function &getSkin() { return $this->mSkin
; }
3949 function getDateFormat() { return $this->mDateFormat
; }
3950 function getEditSection() { return $this->mEditSection
; }
3951 function getNumberHeadings() { return $this->mNumberHeadings
; }
3952 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3953 function getTidy() { return $this->mTidy
; }
3955 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3956 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3957 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3958 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3959 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3960 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3961 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3962 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3963 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3964 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3965 function setSkin( &$x ) { $this->mSkin
=& $x; }
3967 function ParserOptions() {
3969 $this->initialiseFromUser( $wgUser );
3973 * Get parser options
3976 function newFromUser( &$user ) {
3977 $popts = new ParserOptions
;
3978 $popts->initialiseFromUser( $user );
3982 /** Get user options */
3983 function initialiseFromUser( &$userInput ) {
3984 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3985 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3986 $fname = 'ParserOptions::initialiseFromUser';
3987 wfProfileIn( $fname );
3988 if ( !$userInput ) {
3990 $user->setLoaded( true );
3992 $user =& $userInput;
3995 $this->mUseTeX
= $wgUseTeX;
3996 $this->mUseDynamicDates
= $wgUseDynamicDates;
3997 $this->mInterwikiMagic
= $wgInterwikiMagic;
3998 $this->mAllowExternalImages
= $wgAllowExternalImages;
3999 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4000 wfProfileIn( $fname.'-skin' );
4001 $this->mSkin
=& $user->getSkin();
4002 wfProfileOut( $fname.'-skin' );
4003 $this->mDateFormat
= $user->getOption( 'date' );
4004 $this->mEditSection
= true;
4005 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4006 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4007 $this->mTidy
= false;
4008 wfProfileOut( $fname );
4013 * Callback function used by Parser::replaceLinkHolders()
4014 * to substitute link placeholders.
4016 function &wfOutputReplaceMatches( $matches ) {
4017 global $wgOutputReplace;
4018 return $wgOutputReplace[$matches[1]];
4022 * Return the total number of articles
4024 function wfNumberOfArticles() {
4025 global $wgNumberOfArticles;
4028 return $wgNumberOfArticles;
4032 * Return the number of files
4034 function wfNumberOfFiles() {
4035 $fname = 'Parser::wfNumberOfFiles';
4037 wfProfileIn( $fname );
4038 $dbr =& wfGetDB( DB_SLAVE
);
4039 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4040 wfProfileOut( $fname );
4046 * Get various statistics from the database
4049 function wfLoadSiteStats() {
4050 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4051 $fname = 'wfLoadSiteStats';
4053 if ( -1 != $wgNumberOfArticles ) return;
4054 $dbr =& wfGetDB( DB_SLAVE
);
4055 $s = $dbr->selectRow( 'site_stats',
4056 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4057 array( 'ss_row_id' => 1 ), $fname
4060 if ( $s === false ) {
4063 $wgTotalViews = $s->ss_total_views
;
4064 $wgTotalEdits = $s->ss_total_edits
;
4065 $wgNumberOfArticles = $s->ss_good_articles
;
4071 * Basically replacing " > and < with HTML entities ( ", >, <)
4073 * @param string $in Text that might contain HTML tags
4074 * @return string Escaped string
4076 function wfEscapeHTMLTagsOnly( $in ) {
4078 array( '"', '>', '<' ),
4079 array( '"', '>', '<' ),