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 replaced and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
244 # FIXME: Unexpected data flow
245 # Set the title text in mOutput to a converted version of the global
246 # title. The title is stored in $wgContLang from a previous call to
247 # OutputPage::setPageTitle(). If no call has been made, this will be
248 # blank, a condition which Parser callers are expected to ignore.
249 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
251 $text = $this->unstripNoWiki( $text, $this->mStripState
);
253 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
255 $text = Sanitizer
::normalizeCharReferences( $text );
257 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
258 $text = Parser
::tidy($text);
261 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
263 $this->mOutput
->setText( $text );
264 wfProfileOut( $fname );
266 return $this->mOutput
;
270 * Get a random string
275 function getRandomString() {
276 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
279 function &getTitle() { return $this->mTitle
; }
280 function getOptions() { return $this->mOptions
; }
283 * Replaces all occurrences of <$tag>content</$tag> in the text
284 * with a random marker and returns the new text. the output parameter
285 * $content will be an associative array filled with data on the form
286 * $unique_marker => content.
288 * If $content is already set, the additional entries will be appended
289 * If $tag is set to STRIP_COMMENTS, the function will extract
290 * <!-- HTML comments -->
295 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
296 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
311 if( $tag == STRIP_COMMENTS
) {
312 $start = '/<!--()()/';
315 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
316 $end = "/<\\/$tag\\s*>/i";
319 while ( '' != $text ) {
320 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
322 if( count( $p ) < 4 ) {
329 $marker = $rnd . sprintf('%08X', $n++
);
330 $stripped .= $marker;
332 $tags[$marker] = "<$tag$attributes$empty>";
333 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
335 if ( $empty === '/' ) {
336 // Empty element tag, <tag />
337 $content[$marker] = null;
340 $q = preg_split( $end, $inside, 2 );
341 $content[$marker] = $q[0];
342 if( count( $q ) < 2 ) {
343 # No end tag -- let it run out to the end of the text.
354 * Wrapper function for extractTagsAndParams
355 * for cases where $tags and $params isn't needed
356 * i.e. where tags will never have params, like <nowiki>
361 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
362 $dummy_tags = array();
363 $dummy_params = array();
365 return Parser
::extractTagsAndParams( $tag, $text, $content,
366 $dummy_tags, $dummy_params, $uniq_prefix );
370 * Strips and renders nowiki, pre, math, hiero
371 * If $render is set, performs necessary rendering operations on plugins
372 * Returns the text, and fills an array with data needed in unstrip()
373 * If the $state is already a valid strip state, it adds to the state
375 * @param bool $stripcomments when set, HTML comments <!-- like this -->
376 * will be stripped in addition to other tags. This is important
377 * for section editing, where these comments cause confusion when
378 * counting the sections in the wikisource
382 function strip( $text, &$state, $stripcomments = false ) {
383 $render = ($this->mOutputType
== OT_HTML
);
384 $html_content = array();
385 $nowiki_content = array();
386 $math_content = array();
387 $pre_content = array();
388 $comment_content = array();
389 $ext_content = array();
391 $ext_params = array();
392 $gallery_content = array();
394 # Replace any instances of the placeholders
395 $uniq_prefix = $this->mUniqPrefix
;
396 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
401 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
402 foreach( $html_content as $marker => $content ) {
404 # Raw and unchecked for validity.
405 $html_content[$marker] = $content;
407 $html_content[$marker] = '<html>'.$content.'</html>';
413 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
414 foreach( $nowiki_content as $marker => $content ) {
416 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
418 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
423 if( $this->mOptions
->getUseTeX() ) {
424 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
425 foreach( $math_content as $marker => $content ){
427 $math_content[$marker] = renderMath( $content );
429 $math_content[$marker] = '<math>'.$content.'</math>';
435 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
436 foreach( $pre_content as $marker => $content ){
438 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
440 $pre_content[$marker] = '<pre>'.$content.'</pre>';
445 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
446 foreach( $gallery_content as $marker => $content ) {
447 require_once( 'ImageGallery.php' );
449 $gallery_content[$marker] = $this->renderImageGallery( $content );
451 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
457 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
458 foreach( $comment_content as $marker => $content ){
459 $comment_content[$marker] = '<!--'.$content.'-->';
464 foreach ( $this->mTagHooks
as $tag => $callback ) {
465 $ext_content[$tag] = array();
466 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
467 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
468 foreach( $ext_content[$tag] as $marker => $content ) {
469 $full_tag = $ext_tags[$tag][$marker];
470 $params = $ext_params[$tag][$marker];
472 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
474 if ( is_null( $content ) ) {
476 $ext_content[$tag][$marker] = $full_tag;
478 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
484 # Merge state with the pre-existing state, if there is one
486 $state['html'] = $state['html'] +
$html_content;
487 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
488 $state['math'] = $state['math'] +
$math_content;
489 $state['pre'] = $state['pre'] +
$pre_content;
490 $state['gallery'] = $state['gallery'] +
$gallery_content;
491 $state['comment'] = $state['comment'] +
$comment_content;
493 foreach( $ext_content as $tag => $array ) {
494 if ( array_key_exists( $tag, $state ) ) {
495 $state[$tag] = $state[$tag] +
$array;
500 'html' => $html_content,
501 'nowiki' => $nowiki_content,
502 'math' => $math_content,
503 'pre' => $pre_content,
504 'gallery' => $gallery_content,
505 'comment' => $comment_content,
512 * restores pre, math, and hiero removed by strip()
514 * always call unstripNoWiki() after this one
517 function unstrip( $text, &$state ) {
518 if ( !is_array( $state ) ) {
522 # Must expand in reverse order, otherwise nested tags will be corrupted
523 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
524 if( $tag != 'nowiki' && $tag != 'html' ) {
525 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
526 $text = str_replace( $uniq, $content, $text );
535 * always call this after unstrip() to preserve the order
539 function unstripNoWiki( $text, &$state ) {
540 if ( !is_array( $state ) ) {
544 # Must expand in reverse order, otherwise nested tags will be corrupted
545 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
546 $text = str_replace( key( $state['nowiki'] ), $content, $text );
551 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
552 $text = str_replace( key( $state['html'] ), $content, $text );
560 * Add an item to the strip state
561 * Returns the unique tag which must be inserted into the stripped text
562 * The tag will be replaced with the original text in unstrip()
566 function insertStripItem( $text, &$state ) {
567 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
574 'comment' => array(),
575 'gallery' => array(),
578 $state['item'][$rnd] = $text;
583 * Interface with html tidy, used if $wgUseTidy = true.
584 * If tidy isn't able to correct the markup, the original will be
585 * returned in all its glory with a warning comment appended.
587 * Either the external tidy program or the in-process tidy extension
588 * will be used depending on availability. Override the default
589 * $wgTidyInternal setting to disable the internal if it's not working.
591 * @param string $text Hideous HTML input
592 * @return string Corrected HTML output
596 function tidy( $text ) {
597 global $wgTidyInternal;
598 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
599 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
600 '<head><title>test</title></head><body>'.$text.'</body></html>';
601 if( $wgTidyInternal ) {
602 $correctedtext = Parser
::internalTidy( $wrappedtext );
604 $correctedtext = Parser
::externalTidy( $wrappedtext );
606 if( is_null( $correctedtext ) ) {
607 wfDebug( "Tidy error detected!\n" );
608 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
610 return $correctedtext;
614 * Spawn an external HTML tidy process and get corrected markup back from it.
619 function externalTidy( $text ) {
620 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
621 $fname = 'Parser::externalTidy';
622 wfProfileIn( $fname );
627 $descriptorspec = array(
628 0 => array('pipe', 'r'),
629 1 => array('pipe', 'w'),
630 2 => array('file', '/dev/null', 'a')
633 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
634 if (is_resource($process)) {
635 // Theoretically, this style of communication could cause a deadlock
636 // here. If the stdout buffer fills up, then writes to stdin could
637 // block. This doesn't appear to happen with tidy, because tidy only
638 // writes to stdout after it's finished reading from stdin. Search
639 // for tidyParseStdin and tidySaveStdout in console/tidy.c
640 fwrite($pipes[0], $text);
642 while (!feof($pipes[1])) {
643 $cleansource .= fgets($pipes[1], 1024);
646 proc_close($process);
649 wfProfileOut( $fname );
651 if( $cleansource == '' && $text != '') {
652 // Some kind of error happened, so we couldn't get the corrected text.
653 // Just give up; we'll use the source text and append a warning.
661 * Use the HTML tidy PECL extension to use the tidy library in-process,
662 * saving the overhead of spawning a new process. Currently written to
663 * the PHP 4.3.x version of the extension, may not work on PHP 5.
665 * 'pear install tidy' should be able to compile the extension module.
670 function internalTidy( $text ) {
672 $fname = 'Parser::internalTidy';
673 wfProfileIn( $fname );
675 tidy_load_config( $wgTidyConf );
676 tidy_set_encoding( 'utf8' );
677 tidy_parse_string( $text );
679 if( tidy_get_status() == 2 ) {
680 // 2 is magic number for fatal error
681 // http://www.php.net/manual/en/function.tidy-get-status.php
684 $cleansource = tidy_get_output();
686 wfProfileOut( $fname );
691 * parse the wiki syntax used to render tables
695 function doTableStuff ( $t ) {
696 $fname = 'Parser::doTableStuff';
697 wfProfileIn( $fname );
699 $t = explode ( "\n" , $t ) ;
700 $td = array () ; # Is currently a td tag open?
701 $ltd = array () ; # Was it TD or TH?
702 $tr = array () ; # Is currently a tr tag open?
703 $ltr = array () ; # tr attributes
704 $has_opened_tr = array(); # Did this table open a <tr> element?
705 $indent_level = 0; # indent level of the table
706 foreach ( $t AS $k => $x )
709 $fc = substr ( $x , 0 , 1 ) ;
710 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
711 $indent_level = strlen( $matches[1] );
713 $attributes = $this->unstripForHTML( $matches[2] );
715 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
716 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
717 array_push ( $td , false ) ;
718 array_push ( $ltd , '' ) ;
719 array_push ( $tr , false ) ;
720 array_push ( $ltr , '' ) ;
721 array_push ( $has_opened_tr, false );
723 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
724 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
725 $z = "</table>" . substr ( $x , 2);
726 $l = array_pop ( $ltd ) ;
727 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
728 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
729 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
731 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
733 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
734 $x = substr ( $x , 1 ) ;
735 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
737 $l = array_pop ( $ltd ) ;
738 array_pop ( $has_opened_tr );
739 array_push ( $has_opened_tr , true ) ;
740 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
741 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
744 array_push ( $tr , false ) ;
745 array_push ( $td , false ) ;
746 array_push ( $ltd , '' ) ;
747 $attributes = $this->unstripForHTML( $x );
748 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
750 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
752 if ( '|+' == substr ( $x , 0 , 2 ) ) {
754 $x = substr ( $x , 1 ) ;
756 $after = substr ( $x , 1 ) ;
757 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
758 $after = explode ( '||' , $after ) ;
761 # Loop through each table cell
762 foreach ( $after AS $theline )
767 $tra = array_pop ( $ltr ) ;
768 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
769 array_push ( $tr , true ) ;
770 array_push ( $ltr , '' ) ;
771 array_pop ( $has_opened_tr );
772 array_push ( $has_opened_tr , true ) ;
775 $l = array_pop ( $ltd ) ;
776 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
777 if ( $fc == '|' ) $l = 'td' ;
778 else if ( $fc == '!' ) $l = 'th' ;
779 else if ( $fc == '+' ) $l = 'caption' ;
781 array_push ( $ltd , $l ) ;
784 $y = explode ( '|' , $theline , 2 ) ;
785 # Note that a '|' inside an invalid link should not
786 # be mistaken as delimiting cell parameters
787 if ( strpos( $y[0], '[[' ) !== false ) {
788 $y = array ($theline);
790 if ( count ( $y ) == 1 )
791 $y = "{$z}<{$l}>{$y[0]}" ;
793 $attributes = $this->unstripForHTML( $y[0] );
794 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
797 array_push ( $td , true ) ;
802 # Closing open td, tr && table
803 while ( count ( $td ) > 0 )
805 $l = array_pop ( $ltd ) ;
806 if ( array_pop ( $td ) ) $t[] = '</td>' ;
807 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
808 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
812 $t = implode ( "\n" , $t ) ;
813 wfProfileOut( $fname );
818 * Helper function for parse() that transforms wiki markup into
819 * HTML. Only called for $mOutputType == OT_HTML.
823 function internalParse( $text ) {
827 $fname = 'Parser::internalParse';
828 wfProfileIn( $fname );
830 # Remove <noinclude> tags and <includeonly> sections
831 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
832 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
833 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
835 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
836 $text = $this->replaceVariables( $text, $args );
838 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
840 $text = $this->doHeadings( $text );
841 if($this->mOptions
->getUseDynamicDates()) {
842 $df =& DateFormatter
::getInstance();
843 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
845 $text = $this->doAllQuotes( $text );
846 $text = $this->replaceInternalLinks( $text );
847 $text = $this->replaceExternalLinks( $text );
849 # replaceInternalLinks may sometimes leave behind
850 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
851 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
853 $text = $this->doMagicLinks( $text );
854 $text = $this->doTableStuff( $text );
855 $text = $this->formatHeadings( $text, $isMain );
857 wfProfileOut( $fname );
862 * Replace special strings like "ISBN xxx" and "RFC xxx" with
863 * magic external links.
867 function &doMagicLinks( &$text ) {
868 $text = $this->magicISBN( $text );
869 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
870 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
875 * Parse headers and return html
879 function doHeadings( $text ) {
880 $fname = 'Parser::doHeadings';
881 wfProfileIn( $fname );
882 for ( $i = 6; $i >= 1; --$i ) {
883 $h = str_repeat( '=', $i );
884 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
885 "<h{$i}>\\1</h{$i}>\\2", $text );
887 wfProfileOut( $fname );
892 * Replace single quotes with HTML markup
894 * @return string the altered text
896 function doAllQuotes( $text ) {
897 $fname = 'Parser::doAllQuotes';
898 wfProfileIn( $fname );
900 $lines = explode( "\n", $text );
901 foreach ( $lines as $line ) {
902 $outtext .= $this->doQuotes ( $line ) . "\n";
904 $outtext = substr($outtext, 0,-1);
905 wfProfileOut( $fname );
910 * Helper function for doAllQuotes()
913 function doQuotes( $text ) {
914 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
915 if ( count( $arr ) == 1 )
919 # First, do some preliminary work. This may shift some apostrophes from
920 # being mark-up to being text. It also counts the number of occurrences
921 # of bold and italics mark-ups.
925 foreach ( $arr as $r )
927 if ( ( $i %
2 ) == 1 )
929 # If there are ever four apostrophes, assume the first is supposed to
930 # be text, and the remaining three constitute mark-up for bold text.
931 if ( strlen( $arr[$i] ) == 4 )
936 # If there are more than 5 apostrophes in a row, assume they're all
937 # text except for the last 5.
938 else if ( strlen( $arr[$i] ) > 5 )
940 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
943 # Count the number of occurrences of bold and italics mark-ups.
944 # We are not counting sequences of five apostrophes.
945 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
946 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
947 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
952 # If there is an odd number of both bold and italics, it is likely
953 # that one of the bold ones was meant to be an apostrophe followed
954 # by italics. Which one we cannot know for certain, but it is more
955 # likely to be one that has a single-letter word before it.
956 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
959 $firstsingleletterword = -1;
960 $firstmultiletterword = -1;
962 foreach ( $arr as $r )
964 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
966 $x1 = substr ($arr[$i-1], -1);
967 $x2 = substr ($arr[$i-1], -2, 1);
969 if ($firstspace == -1) $firstspace = $i;
970 } else if ($x2 == ' ') {
971 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
973 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
979 # If there is a single-letter word, use it!
980 if ($firstsingleletterword > -1)
982 $arr [ $firstsingleletterword ] = "''";
983 $arr [ $firstsingleletterword-1 ] .= "'";
985 # If not, but there's a multi-letter word, use that one.
986 else if ($firstmultiletterword > -1)
988 $arr [ $firstmultiletterword ] = "''";
989 $arr [ $firstmultiletterword-1 ] .= "'";
991 # ... otherwise use the first one that has neither.
992 # (notice that it is possible for all three to be -1 if, for example,
993 # there is only one pentuple-apostrophe in the line)
994 else if ($firstspace > -1)
996 $arr [ $firstspace ] = "''";
997 $arr [ $firstspace-1 ] .= "'";
1001 # Now let's actually convert our apostrophic mush to HTML!
1006 foreach ($arr as $r)
1010 if ($state == 'both')
1017 if (strlen ($r) == 2)
1020 { $output .= '</i>'; $state = ''; }
1021 else if ($state == 'bi')
1022 { $output .= '</i>'; $state = 'b'; }
1023 else if ($state == 'ib')
1024 { $output .= '</b></i><b>'; $state = 'b'; }
1025 else if ($state == 'both')
1026 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1027 else # $state can be 'b' or ''
1028 { $output .= '<i>'; $state .= 'i'; }
1030 else if (strlen ($r) == 3)
1033 { $output .= '</b>'; $state = ''; }
1034 else if ($state == 'bi')
1035 { $output .= '</i></b><i>'; $state = 'i'; }
1036 else if ($state == 'ib')
1037 { $output .= '</b>'; $state = 'i'; }
1038 else if ($state == 'both')
1039 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1040 else # $state can be 'i' or ''
1041 { $output .= '<b>'; $state .= 'b'; }
1043 else if (strlen ($r) == 5)
1046 { $output .= '</b><i>'; $state = 'i'; }
1047 else if ($state == 'i')
1048 { $output .= '</i><b>'; $state = 'b'; }
1049 else if ($state == 'bi')
1050 { $output .= '</i></b>'; $state = ''; }
1051 else if ($state == 'ib')
1052 { $output .= '</b></i>'; $state = ''; }
1053 else if ($state == 'both')
1054 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1055 else # ($state == '')
1056 { $buffer = ''; $state = 'both'; }
1061 # Now close all remaining tags. Notice that the order is important.
1062 if ($state == 'b' ||
$state == 'ib')
1064 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1068 if ($state == 'both')
1069 $output .= '<b><i>'.$buffer.'</i></b>';
1075 * Replace external links
1077 * Note: this is all very hackish and the order of execution matters a lot.
1078 * Make sure to run maintenance/parserTests.php if you change this code.
1082 function replaceExternalLinks( $text ) {
1084 $fname = 'Parser::replaceExternalLinks';
1085 wfProfileIn( $fname );
1087 $sk =& $this->mOptions
->getSkin();
1089 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1091 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1094 while ( $i<count( $bits ) ) {
1096 $protocol = $bits[$i++
];
1097 $text = $bits[$i++
];
1098 $trail = $bits[$i++
];
1100 # The characters '<' and '>' (which were escaped by
1101 # removeHTMLtags()) should not be included in
1102 # URLs, per RFC 2396.
1103 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1104 $text = substr($url, $m2[0][1]) . ' ' . $text;
1105 $url = substr($url, 0, $m2[0][1]);
1108 # If the link text is an image URL, replace it with an <img> tag
1109 # This happened by accident in the original parser, but some people used it extensively
1110 $img = $this->maybeMakeExternalImage( $text );
1111 if ( $img !== false ) {
1117 # Set linktype for CSS - if URL==text, link is essentially free
1118 $linktype = ($text == $url) ?
'free' : 'text';
1120 # No link text, e.g. [http://domain.tld/some.link]
1121 if ( $text == '' ) {
1122 # Autonumber if allowed
1123 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1124 $text = '[' . ++
$this->mAutonumber
. ']';
1125 $linktype = 'autonumber';
1127 # Otherwise just use the URL
1128 $text = htmlspecialchars( $url );
1132 # Have link text, e.g. [http://domain.tld/some.link text]s
1134 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1137 $text = $wgContLang->markNoConversion($text);
1139 # Replace & from obsolete syntax with &.
1140 # All HTML entities will be escaped by makeExternalLink()
1141 $url = str_replace( '&', '&', $url );
1142 # Replace unnecessary URL escape codes with the referenced character
1143 # This prevents spammers from hiding links from the filters
1144 $url = Parser
::replaceUnusualEscapes( $url );
1146 # Process the trail (i.e. everything after this link up until start of the next link),
1147 # replacing any non-bracketed links
1148 $trail = $this->replaceFreeExternalLinks( $trail );
1150 # Use the encoded URL
1151 # This means that users can paste URLs directly into the text
1152 # Funny characters like ö aren't valid in URLs anyway
1153 # This was changed in August 2004
1154 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1156 # Register link in the output object
1157 $this->mOutput
->addExternalLink( $url );
1160 wfProfileOut( $fname );
1165 * Replace anything that looks like a URL with a link
1168 function replaceFreeExternalLinks( $text ) {
1170 $fname = 'Parser::replaceFreeExternalLinks';
1171 wfProfileIn( $fname );
1173 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1174 $s = array_shift( $bits );
1177 $sk =& $this->mOptions
->getSkin();
1179 while ( $i < count( $bits ) ){
1180 $protocol = $bits[$i++
];
1181 $remainder = $bits[$i++
];
1183 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1184 # Found some characters after the protocol that look promising
1185 $url = $protocol . $m[1];
1188 # The characters '<' and '>' (which were escaped by
1189 # removeHTMLtags()) should not be included in
1190 # URLs, per RFC 2396.
1191 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1192 $trail = substr($url, $m2[0][1]) . $trail;
1193 $url = substr($url, 0, $m2[0][1]);
1196 # Move trailing punctuation to $trail
1198 # If there is no left bracket, then consider right brackets fair game too
1199 if ( strpos( $url, '(' ) === false ) {
1203 $numSepChars = strspn( strrev( $url ), $sep );
1204 if ( $numSepChars ) {
1205 $trail = substr( $url, -$numSepChars ) . $trail;
1206 $url = substr( $url, 0, -$numSepChars );
1209 # Replace & from obsolete syntax with &.
1210 # All HTML entities will be escaped by makeExternalLink()
1211 # or maybeMakeExternalImage()
1212 $url = str_replace( '&', '&', $url );
1213 # Replace unnecessary URL escape codes with their equivalent characters
1214 $url = Parser
::replaceUnusualEscapes( $url );
1216 # Is this an external image?
1217 $text = $this->maybeMakeExternalImage( $url );
1218 if ( $text === false ) {
1219 # Not an image, make a link
1220 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1221 # Register it in the output object
1222 $this->mOutput
->addExternalLink( $url );
1224 $s .= $text . $trail;
1226 $s .= $protocol . $remainder;
1229 wfProfileOut( $fname );
1234 * Replace unusual URL escape codes with their equivalent characters
1239 function replaceUnusualEscapes( $url ) {
1240 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1241 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1245 * Callback function used in replaceUnusualEscapes().
1246 * Replaces unusual URL escape codes with their equivalent character
1250 function replaceUnusualEscapesCallback( $matches ) {
1251 $char = urldecode( $matches[0] );
1252 $ord = ord( $char );
1253 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1254 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1255 // No, shouldn't be escaped
1258 // Yes, leave it escaped
1264 * make an image if it's allowed, either through the global
1265 * option or through the exception
1268 function maybeMakeExternalImage( $url ) {
1269 $sk =& $this->mOptions
->getSkin();
1270 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1271 $imagesexception = !empty($imagesfrom);
1273 if ( $this->mOptions
->getAllowExternalImages()
1274 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1275 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1277 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1284 * Process [[ ]] wikilinks
1288 function replaceInternalLinks( $s ) {
1290 static $fname = 'Parser::replaceInternalLinks' ;
1292 wfProfileIn( $fname );
1294 wfProfileIn( $fname.'-setup' );
1296 # the % is needed to support urlencoded titles as well
1297 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1299 $sk =& $this->mOptions
->getSkin();
1301 #split the entire text string on occurences of [[
1302 $a = explode( '[[', ' ' . $s );
1303 #get the first element (all text up to first [[), and remove the space we added
1304 $s = array_shift( $a );
1305 $s = substr( $s, 1 );
1307 # Match a link having the form [[namespace:link|alternate]]trail
1309 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1310 # Match cases where there is no "]]", which might still be images
1311 static $e1_img = FALSE;
1312 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1313 # Match the end of a line for a word that's not followed by whitespace,
1314 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1315 $e2 = wfMsgForContent( 'linkprefix' );
1317 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1319 if( is_null( $this->mTitle
) ) {
1320 wfDebugDieBacktrace( 'nooo' );
1322 $nottalk = !$this->mTitle
->isTalkPage();
1324 if ( $useLinkPrefixExtension ) {
1325 if ( preg_match( $e2, $s, $m ) ) {
1326 $first_prefix = $m[2];
1328 $first_prefix = false;
1334 $selflink = $this->mTitle
->getPrefixedText();
1335 wfProfileOut( $fname.'-setup' );
1337 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1338 $useSubpages = $this->areSubpagesAllowed();
1340 # Loop for each link
1341 for ($k = 0; isset( $a[$k] ); $k++
) {
1343 if ( $useLinkPrefixExtension ) {
1344 wfProfileIn( $fname.'-prefixhandling' );
1345 if ( preg_match( $e2, $s, $m ) ) {
1353 $prefix = $first_prefix;
1354 $first_prefix = false;
1356 wfProfileOut( $fname.'-prefixhandling' );
1359 $might_be_img = false;
1361 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1363 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1364 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1365 # the real problem is with the $e1 regex
1368 # Still some problems for cases where the ] is meant to be outside punctuation,
1369 # and no image is in sight. See bug 2095.
1371 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1372 $text .= ']'; # so that replaceExternalLinks($text) works later
1375 # fix up urlencoded title texts
1376 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1378 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1379 $might_be_img = true;
1381 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1383 } else { # Invalid form; output directly
1384 $s .= $prefix . '[[' . $line ;
1388 # Don't allow internal links to pages containing
1389 # PROTO: where PROTO is a valid URL protocol; these
1390 # should be external links.
1391 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1392 $s .= $prefix . '[[' . $line ;
1396 # Make subpage if necessary
1397 if( $useSubpages ) {
1398 $link = $this->maybeDoSubpageLink( $m[1], $text );
1403 $noforce = (substr($m[1], 0, 1) != ':');
1405 # Strip off leading ':'
1406 $link = substr($link, 1);
1409 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1411 $s .= $prefix . '[[' . $line;
1415 #check other language variants of the link
1416 #if the article does not exist
1417 if( $checkVariantLink
1418 && $nt->getArticleID() == 0 ) {
1419 $wgContLang->findVariantLink($link, $nt);
1422 $ns = $nt->getNamespace();
1423 $iw = $nt->getInterWiki();
1425 if ($might_be_img) { # if this is actually an invalid link
1426 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1428 while (isset ($a[$k+
1]) ) {
1429 #look at the next 'line' to see if we can close it there
1430 $spliced = array_splice( $a, $k +
1, 1 );
1431 $next_line = array_shift( $spliced );
1432 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1433 # the first ]] closes the inner link, the second the image
1435 $text .= '[[' . $m[1];
1438 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1439 #if there's exactly one ]] that's fine, we'll keep looking
1440 $text .= '[[' . $m[0];
1442 #if $next_line is invalid too, we need look no further
1443 $text .= '[[' . $next_line;
1448 # we couldn't find the end of this imageLink, so output it raw
1449 #but don't ignore what might be perfectly normal links in the text we've examined
1450 $text = $this->replaceInternalLinks($text);
1451 $s .= $prefix . '[[' . $link . '|' . $text;
1452 # note: no $trail, because without an end, there *is* no trail
1455 } else { #it's not an image, so output it raw
1456 $s .= $prefix . '[[' . $link . '|' . $text;
1457 # note: no $trail, because without an end, there *is* no trail
1462 $wasblank = ( '' == $text );
1463 if( $wasblank ) $text = $link;
1466 # Link not escaped by : , create the various objects
1470 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1471 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1472 $s = rtrim($s . "\n");
1473 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1477 if ( $ns == NS_IMAGE
) {
1478 wfProfileIn( "$fname-image" );
1479 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1480 # recursively parse links inside the image caption
1481 # actually, this will parse them in any other parameters, too,
1482 # but it might be hard to fix that, and it doesn't matter ATM
1483 $text = $this->replaceExternalLinks($text);
1484 $text = $this->replaceInternalLinks($text);
1486 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1487 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1488 $this->mOutput
->addImage( $nt->getDBkey() );
1490 wfProfileOut( "$fname-image" );
1493 wfProfileOut( "$fname-image" );
1497 if ( $ns == NS_CATEGORY
) {
1498 wfProfileIn( "$fname-category" );
1499 $s = rtrim($s . "\n"); # bug 87
1502 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1503 $sortkey = $this->mTitle
->getText();
1505 $sortkey = $this->mTitle
->getPrefixedText();
1510 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1511 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1512 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1515 * Strip the whitespace Category links produce, see bug 87
1516 * @todo We might want to use trim($tmp, "\n") here.
1518 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1520 wfProfileOut( "$fname-category" );
1525 if( ( $nt->getPrefixedText() === $selflink ) &&
1526 ( $nt->getFragment() === '' ) ) {
1527 # Self-links are handled specially; generally de-link and change to bold.
1528 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1532 # Special and Media are pseudo-namespaces; no pages actually exist in them
1533 if( $ns == NS_MEDIA
) {
1534 $link = $sk->makeMediaLinkObj( $nt, $text );
1535 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1536 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1537 $this->mOutput
->addImage( $nt->getDBkey() );
1539 } elseif( $ns == NS_SPECIAL
) {
1540 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1542 } elseif( $ns == NS_IMAGE
) {
1543 $img = Image
::newFromTitle( $nt );
1544 if( $img->exists() ) {
1545 // Force a blue link if the file exists; may be a remote
1546 // upload on the shared repository, and we want to see its
1547 // auto-generated page.
1548 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1552 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1554 wfProfileOut( $fname );
1559 * Make a link placeholder. The text returned can be later resolved to a real link with
1560 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1561 * parsing of interwiki links, and secondly to allow all extistence checks and
1562 * article length checks (for stub links) to be bundled into a single query.
1565 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1566 if ( ! is_object($nt) ) {
1568 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1570 # Separate the link trail from the rest of the link
1571 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1573 if ( $nt->isExternal() ) {
1574 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1575 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1576 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1578 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1579 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1580 $this->mLinkHolders
['queries'][] = $query;
1581 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1582 $this->mLinkHolders
['titles'][] = $nt;
1584 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1591 * Render a forced-blue link inline; protect against double expansion of
1592 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1593 * Since this little disaster has to split off the trail text to avoid
1594 * breaking URLs in the following text without breaking trails on the
1595 * wiki links, it's been made into a horrible function.
1598 * @param string $text
1599 * @param string $query
1600 * @param string $trail
1601 * @param string $prefix
1602 * @return string HTML-wikitext mix oh yuck
1604 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1605 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1606 $sk =& $this->mOptions
->getSkin();
1607 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1608 return $this->armorLinks( $link ) . $trail;
1612 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1613 * going to go through further parsing steps before inline URL expansion.
1615 * In particular this is important when using action=render, which causes
1616 * full URLs to be included.
1618 * Oh man I hate our multi-layer parser!
1620 * @param string more-or-less HTML
1621 * @return string less-or-more HTML with NOPARSE bits
1623 function armorLinks( $text ) {
1624 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1625 "{$this->mUniqPrefix}NOPARSE$1", $text );
1629 * Return true if subpage links should be expanded on this page.
1632 function areSubpagesAllowed() {
1633 # Some namespaces don't allow subpages
1634 global $wgNamespacesWithSubpages;
1635 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1639 * Handle link to subpage if necessary
1640 * @param string $target the source of the link
1641 * @param string &$text the link text, modified as necessary
1642 * @return string the full name of the link
1645 function maybeDoSubpageLink($target, &$text) {
1648 # :Foobar -- override special treatment of prefix (images, language links)
1649 # /Foobar -- convert to CurrentPage/Foobar
1650 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1651 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1652 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1654 $fname = 'Parser::maybeDoSubpageLink';
1655 wfProfileIn( $fname );
1656 $ret = $target; # default return value is no change
1658 # Some namespaces don't allow subpages,
1659 # so only perform processing if subpages are allowed
1660 if( $this->areSubpagesAllowed() ) {
1661 # Look at the first character
1662 if( $target != '' && $target{0} == '/' ) {
1663 # / at end means we don't want the slash to be shown
1664 if( substr( $target, -1, 1 ) == '/' ) {
1665 $target = substr( $target, 1, -1 );
1668 $noslash = substr( $target, 1 );
1671 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1672 if( '' === $text ) {
1674 } # this might be changed for ugliness reasons
1676 # check for .. subpage backlinks
1678 $nodotdot = $target;
1679 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1681 $nodotdot = substr( $nodotdot, 3 );
1683 if($dotdotcount > 0) {
1684 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1685 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1686 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1687 # / at the end means don't show full path
1688 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1689 $nodotdot = substr( $nodotdot, 0, -1 );
1690 if( '' === $text ) {
1694 $nodotdot = trim( $nodotdot );
1695 if( $nodotdot != '' ) {
1696 $ret .= '/' . $nodotdot;
1703 wfProfileOut( $fname );
1708 * Used by doBlockLevels()
1711 /* private */ function closeParagraph() {
1713 if ( '' != $this->mLastSection
) {
1714 $result = '</' . $this->mLastSection
. ">\n";
1716 $this->mInPre
= false;
1717 $this->mLastSection
= '';
1720 # getCommon() returns the length of the longest common substring
1721 # of both arguments, starting at the beginning of both.
1723 /* private */ function getCommon( $st1, $st2 ) {
1724 $fl = strlen( $st1 );
1725 $shorter = strlen( $st2 );
1726 if ( $fl < $shorter ) { $shorter = $fl; }
1728 for ( $i = 0; $i < $shorter; ++
$i ) {
1729 if ( $st1{$i} != $st2{$i} ) { break; }
1733 # These next three functions open, continue, and close the list
1734 # element appropriate to the prefix character passed into them.
1736 /* private */ function openList( $char ) {
1737 $result = $this->closeParagraph();
1739 if ( '*' == $char ) { $result .= '<ul><li>'; }
1740 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1741 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1742 else if ( ';' == $char ) {
1743 $result .= '<dl><dt>';
1744 $this->mDTopen
= true;
1746 else { $result = '<!-- ERR 1 -->'; }
1751 /* private */ function nextItem( $char ) {
1752 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1753 else if ( ':' == $char ||
';' == $char ) {
1755 if ( $this->mDTopen
) { $close = '</dt>'; }
1756 if ( ';' == $char ) {
1757 $this->mDTopen
= true;
1758 return $close . '<dt>';
1760 $this->mDTopen
= false;
1761 return $close . '<dd>';
1764 return '<!-- ERR 2 -->';
1767 /* private */ function closeList( $char ) {
1768 if ( '*' == $char ) { $text = '</li></ul>'; }
1769 else if ( '#' == $char ) { $text = '</li></ol>'; }
1770 else if ( ':' == $char ) {
1771 if ( $this->mDTopen
) {
1772 $this->mDTopen
= false;
1773 $text = '</dt></dl>';
1775 $text = '</dd></dl>';
1778 else { return '<!-- ERR 3 -->'; }
1784 * Make lists from lines starting with ':', '*', '#', etc.
1787 * @return string the lists rendered as HTML
1789 function doBlockLevels( $text, $linestart ) {
1790 $fname = 'Parser::doBlockLevels';
1791 wfProfileIn( $fname );
1793 # Parsing through the text line by line. The main thing
1794 # happening here is handling of block-level elements p, pre,
1795 # and making lists from lines starting with * # : etc.
1797 $textLines = explode( "\n", $text );
1799 $lastPrefix = $output = '';
1800 $this->mDTopen
= $inBlockElem = false;
1802 $paragraphStack = false;
1804 if ( !$linestart ) {
1805 $output .= array_shift( $textLines );
1807 foreach ( $textLines as $oLine ) {
1808 $lastPrefixLength = strlen( $lastPrefix );
1809 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1810 $preOpenMatch = preg_match('/<pre/i', $oLine );
1811 if ( !$this->mInPre
) {
1812 # Multiple prefixes may abut each other for nested lists.
1813 $prefixLength = strspn( $oLine, '*#:;' );
1814 $pref = substr( $oLine, 0, $prefixLength );
1817 $pref2 = str_replace( ';', ':', $pref );
1818 $t = substr( $oLine, $prefixLength );
1819 $this->mInPre
= !empty($preOpenMatch);
1821 # Don't interpret any other prefixes in preformatted text
1823 $pref = $pref2 = '';
1828 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1829 # Same as the last item, so no need to deal with nesting or opening stuff
1830 $output .= $this->nextItem( substr( $pref, -1 ) );
1831 $paragraphStack = false;
1833 if ( substr( $pref, -1 ) == ';') {
1834 # The one nasty exception: definition lists work like this:
1835 # ; title : definition text
1836 # So we check for : in the remainder text to split up the
1837 # title and definition, without b0rking links.
1839 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1841 $output .= $term . $this->nextItem( ':' );
1844 } elseif( $prefixLength ||
$lastPrefixLength ) {
1845 # Either open or close a level...
1846 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1847 $paragraphStack = false;
1849 while( $commonPrefixLength < $lastPrefixLength ) {
1850 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1851 --$lastPrefixLength;
1853 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1854 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1856 while ( $prefixLength > $commonPrefixLength ) {
1857 $char = substr( $pref, $commonPrefixLength, 1 );
1858 $output .= $this->openList( $char );
1860 if ( ';' == $char ) {
1861 # FIXME: This is dupe of code above
1862 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1864 $output .= $term . $this->nextItem( ':' );
1867 ++
$commonPrefixLength;
1869 $lastPrefix = $pref2;
1871 if( 0 == $prefixLength ) {
1872 wfProfileIn( "$fname-paragraph" );
1873 # No prefix (not in list)--go to paragraph mode
1874 // XXX: use a stack for nestable elements like span, table and div
1875 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1876 $closematch = preg_match(
1877 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1878 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1879 if ( $openmatch or $closematch ) {
1880 $paragraphStack = false;
1881 $output .= $this->closeParagraph();
1882 if ( $preOpenMatch and !$preCloseMatch ) {
1883 $this->mInPre
= true;
1885 if ( $closematch ) {
1886 $inBlockElem = false;
1888 $inBlockElem = true;
1890 } else if ( !$inBlockElem && !$this->mInPre
) {
1891 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1893 if ($this->mLastSection
!= 'pre') {
1894 $paragraphStack = false;
1895 $output .= $this->closeParagraph().'<pre>';
1896 $this->mLastSection
= 'pre';
1898 $t = substr( $t, 1 );
1901 if ( '' == trim($t) ) {
1902 if ( $paragraphStack ) {
1903 $output .= $paragraphStack.'<br />';
1904 $paragraphStack = false;
1905 $this->mLastSection
= 'p';
1907 if ($this->mLastSection
!= 'p' ) {
1908 $output .= $this->closeParagraph();
1909 $this->mLastSection
= '';
1910 $paragraphStack = '<p>';
1912 $paragraphStack = '</p><p>';
1916 if ( $paragraphStack ) {
1917 $output .= $paragraphStack;
1918 $paragraphStack = false;
1919 $this->mLastSection
= 'p';
1920 } else if ($this->mLastSection
!= 'p') {
1921 $output .= $this->closeParagraph().'<p>';
1922 $this->mLastSection
= 'p';
1927 wfProfileOut( "$fname-paragraph" );
1929 // somewhere above we forget to get out of pre block (bug 785)
1930 if($preCloseMatch && $this->mInPre
) {
1931 $this->mInPre
= false;
1933 if ($paragraphStack === false) {
1937 while ( $prefixLength ) {
1938 $output .= $this->closeList( $pref2{$prefixLength-1} );
1941 if ( '' != $this->mLastSection
) {
1942 $output .= '</' . $this->mLastSection
. '>';
1943 $this->mLastSection
= '';
1946 wfProfileOut( $fname );
1951 * Split up a string on ':', ignoring any occurences inside
1952 * <a>..</a> or <span>...</span>
1953 * @param string $str the string to split
1954 * @param string &$before set to everything before the ':'
1955 * @param string &$after set to everything after the ':'
1956 * return string the position of the ':', or false if none found
1958 function findColonNoLinks($str, &$before, &$after) {
1959 # I wonder if we should make this count all tags, not just <a>
1960 # and <span>. That would prevent us from matching a ':' that
1961 # comes in the middle of italics other such formatting....
1963 $fname = 'Parser::findColonNoLinks';
1964 wfProfileIn( $fname );
1967 $colon = strpos($str, ':', $pos);
1969 if ($colon !== false) {
1970 $before = substr($str, 0, $colon);
1971 $after = substr($str, $colon +
1);
1973 # Skip any ':' within <a> or <span> pairs
1974 $a = substr_count($before, '<a');
1975 $s = substr_count($before, '<span');
1976 $ca = substr_count($before, '</a>');
1977 $cs = substr_count($before, '</span>');
1979 if ($a <= $ca and $s <= $cs) {
1980 # Tags are balanced before ':'; ok
1985 } while ($colon !== false);
1986 wfProfileOut( $fname );
1991 * Return value of a magic variable (like PAGENAME)
1995 function getVariableValue( $index ) {
1996 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1999 * Some of these require message or data lookups and can be
2000 * expensive to check many times.
2002 static $varCache = array();
2003 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2004 if ( isset( $varCache[$index] ) )
2005 return $varCache[$index];
2008 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2011 case MAG_CURRENTMONTH
:
2012 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2013 case MAG_CURRENTMONTHNAME
:
2014 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2015 case MAG_CURRENTMONTHNAMEGEN
:
2016 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2017 case MAG_CURRENTMONTHABBREV
:
2018 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2019 case MAG_CURRENTDAY
:
2020 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2021 case MAG_CURRENTDAY2
:
2022 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2024 return $this->mTitle
->getText();
2026 return $this->mTitle
->getPartialURL();
2027 case MAG_FULLPAGENAME
:
2028 return $this->mTitle
->getPrefixedText();
2029 case MAG_FULLPAGENAMEE
:
2030 return $this->mTitle
->getPrefixedURL();
2031 case MAG_REVISIONID
:
2032 return $this->mRevisionId
;
2034 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2035 case MAG_NAMESPACEE
:
2036 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2037 case MAG_CURRENTDAYNAME
:
2038 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2039 case MAG_CURRENTYEAR
:
2040 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2041 case MAG_CURRENTTIME
:
2042 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2043 case MAG_CURRENTWEEK
:
2044 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2045 // int to remove the padding
2046 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2047 case MAG_CURRENTDOW
:
2048 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2049 case MAG_NUMBEROFARTICLES
:
2050 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2051 case MAG_NUMBEROFFILES
:
2052 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2057 case MAG_SERVERNAME
:
2058 return $wgServerName;
2059 case MAG_SCRIPTPATH
:
2060 return $wgScriptPath;
2063 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2071 * initialise the magic variables (like CURRENTMONTHNAME)
2075 function initialiseVariables() {
2076 $fname = 'Parser::initialiseVariables';
2077 wfProfileIn( $fname );
2078 global $wgVariableIDs;
2079 $this->mVariables
= array();
2080 foreach ( $wgVariableIDs as $id ) {
2081 $mw =& MagicWord
::get( $id );
2082 $mw->addToArray( $this->mVariables
, $id );
2084 wfProfileOut( $fname );
2088 * parse any parentheses in format ((title|part|part))
2089 * and call callbacks to get a replacement text for any found piece
2091 * @param string $text The text to parse
2092 * @param array $callbacks rules in form:
2093 * '{' => array( # opening parentheses
2094 * 'end' => '}', # closing parentheses
2095 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2096 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2101 function replace_callback ($text, $callbacks) {
2102 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2103 $lastOpeningBrace = -1; # last not closed parentheses
2105 for ($i = 0; $i < strlen($text); $i++
) {
2106 # check for any opening brace
2109 foreach ($callbacks as $key => $value) {
2110 $pos = strpos ($text, $key, $i);
2111 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2117 if ($lastOpeningBrace >= 0) {
2118 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2120 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2125 $pos = strpos ($text, '|', $i);
2127 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2138 # found openning brace, lets add it to parentheses stack
2139 if (null != $rule) {
2140 $piece = array('brace' => $text[$i],
2141 'braceEnd' => $rule['end'],
2146 # count openning brace characters
2147 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2152 $piece['startAt'] = $i+
1;
2153 $piece['partStart'] = $i+
1;
2155 # we need to add to stack only if openning brace count is enough for any given rule
2156 foreach ($rule['cb'] as $cnt => $fn) {
2157 if ($piece['count'] >= $cnt) {
2158 $lastOpeningBrace ++
;
2159 $openingBraceStack[$lastOpeningBrace] = $piece;
2166 else if ($lastOpeningBrace >= 0) {
2167 # first check if it is a closing brace
2168 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2169 # lets check if it is enough characters for closing brace
2171 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2174 # if there are more closing parentheses than opening ones, we parse less
2175 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2176 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2178 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2180 $matchingCallback = null;
2181 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2182 if ($count >= $cnt && $matchingCount < $cnt) {
2183 $matchingCount = $cnt;
2184 $matchingCallback = $fn;
2188 if ($matchingCount == 0) {
2193 # lets set a title or last part (if '|' was found)
2194 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2195 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2197 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2199 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2200 $pieceEnd = $i +
$matchingCount;
2202 if( is_callable( $matchingCallback ) ) {
2204 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2205 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2206 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2207 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2209 # finally we can call a user callback and replace piece of text
2210 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2211 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2212 $i = $pieceStart +
strlen($replaceWith) - 1;
2215 # null value for callback means that parentheses should be parsed, but not replaced
2216 $i +
= $matchingCount - 1;
2219 # reset last openning parentheses, but keep it in case there are unused characters
2220 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2221 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2222 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2225 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2226 $openingBraceStack[$lastOpeningBrace--] = null;
2228 if ($matchingCount < $piece['count']) {
2229 $piece['count'] -= $matchingCount;
2230 $piece['startAt'] -= $matchingCount;
2231 $piece['partStart'] = $piece['startAt'];
2232 # do we still qualify for any callback with remaining count?
2233 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2234 if ($piece['count'] >= $cnt) {
2235 $lastOpeningBrace ++
;
2236 $openingBraceStack[$lastOpeningBrace] = $piece;
2244 # lets set a title if it is a first separator, or next part otherwise
2245 if ($text[$i] == '|') {
2246 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2247 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2248 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2251 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2253 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2262 * Replace magic variables, templates, and template arguments
2263 * with the appropriate text. Templates are substituted recursively,
2264 * taking care to avoid infinite loops.
2266 * Note that the substitution depends on value of $mOutputType:
2267 * OT_WIKI: only {{subst:}} templates
2268 * OT_MSG: only magic variables
2269 * OT_HTML: all templates and magic variables
2271 * @param string $tex The text to transform
2272 * @param array $args Key-value pairs representing template parameters to substitute
2273 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2276 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2277 # Prevent too big inclusions
2278 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2282 $fname = 'Parser::replaceVariables';
2283 wfProfileIn( $fname );
2285 # This function is called recursively. To keep track of arguments we need a stack:
2286 array_push( $this->mArgStack
, $args );
2288 $braceCallbacks = array();
2290 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2292 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2293 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2295 $callbacks = array();
2296 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2297 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2298 $text = $this->replace_callback ($text, $callbacks);
2300 array_pop( $this->mArgStack
);
2302 wfProfileOut( $fname );
2307 * Replace magic variables
2310 function variableSubstitution( $matches ) {
2311 $fname = 'Parser::variableSubstitution';
2312 $varname = $matches[1];
2313 wfProfileIn( $fname );
2314 if ( !$this->mVariables
) {
2315 $this->initialiseVariables();
2318 if ( $this->mOutputType
== OT_WIKI
) {
2319 # Do only magic variables prefixed by SUBST
2320 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2321 if (!$mwSubst->matchStartAndRemove( $varname ))
2323 # Note that if we don't substitute the variable below,
2324 # we don't remove the {{subst:}} magic word, in case
2325 # it is a template rather than a magic variable.
2327 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2328 $id = $this->mVariables
[$varname];
2329 $text = $this->getVariableValue( $id );
2330 $this->mOutput
->mContainsOldMagic
= true;
2332 $text = $matches[0];
2334 wfProfileOut( $fname );
2338 # Split template arguments
2339 function getTemplateArgs( $argsString ) {
2340 if ( $argsString === '' ) {
2344 $args = explode( '|', substr( $argsString, 1 ) );
2346 # If any of the arguments contains a '[[' but no ']]', it needs to be
2347 # merged with the next arg because the '|' character between belongs
2348 # to the link syntax and not the template parameter syntax.
2349 $argc = count($args);
2351 for ( $i = 0; $i < $argc-1; $i++
) {
2352 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2353 $args[$i] .= '|'.$args[$i+
1];
2354 array_splice($args, $i+
1, 1);
2364 * Return the text of a template, after recursively
2365 * replacing any variables or templates within the template.
2367 * @param array $piece The parts of the template
2368 * $piece['text']: matched text
2369 * $piece['title']: the title, i.e. the part before the |
2370 * $piece['parts']: the parameter array
2371 * @return string the text of the template
2374 function braceSubstitution( $piece ) {
2376 $fname = 'Parser::braceSubstitution';
2377 wfProfileIn( $fname );
2380 $found = false; # $text has been filled
2381 $nowiki = false; # wiki markup in $text should be escaped
2382 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2383 $noargs = false; # Don't replace triple-brace arguments in $text
2384 $replaceHeadings = false; # Make the edit section links go to the template not the article
2385 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2386 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2388 # Title object, where $text came from
2393 # $part1 is the bit before the first |, and must contain only title characters
2394 # $args is a list of arguments, starting from index 0, not including $part1
2396 $part1 = $piece['title'];
2397 # If the third subpattern matched anything, it will start with |
2399 if (null == $piece['parts']) {
2400 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2401 if ($replaceWith != $piece['text']) {
2402 $text = $replaceWith;
2409 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2410 $argc = count( $args );
2414 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2415 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2416 # One of two possibilities is true:
2417 # 1) Found SUBST but not in the PST phase
2418 # 2) Didn't find SUBST and in the PST phase
2419 # In either case, return without further processing
2420 $text = $piece['text'];
2427 # MSG, MSGNW, INT and RAW
2430 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2431 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2434 # Remove obsolete MSG:
2435 $mwMsg =& MagicWord
::get( MAG_MSG
);
2436 $mwMsg->matchStartAndRemove( $part1 );
2440 $mwRaw =& MagicWord
::get( MAG_RAW
);
2441 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2442 $forceRawInterwiki = true;
2445 # Check if it is an internal message
2446 $mwInt =& MagicWord
::get( MAG_INT
);
2447 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2448 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2449 $text = $linestart . wfMsgReal( $part1, $args, true );
2457 # Check for NS: (namespace expansion)
2458 $mwNs = MagicWord
::get( MAG_NS
);
2459 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2460 if ( intval( $part1 ) ||
$part1 == "0" ) {
2461 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2464 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2465 if ( !is_null( $index ) ) {
2466 $text = $linestart . $wgContLang->getNsText( $index );
2473 # LCFIRST, UCFIRST, LC and UC
2475 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2476 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2477 $lc =& MagicWord
::get( MAG_LC
);
2478 $uc =& MagicWord
::get( MAG_UC
);
2479 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2480 $text = $linestart . $wgContLang->lcfirst( $part1 );
2482 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2483 $text = $linestart . $wgContLang->ucfirst( $part1 );
2485 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2486 $text = $linestart . $wgContLang->lc( $part1 );
2488 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2489 $text = $linestart . $wgContLang->uc( $part1 );
2494 # LOCALURL and FULLURL
2496 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2497 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2498 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2499 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2502 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2503 $func = 'getLocalURL';
2504 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2505 $func = 'escapeLocalURL';
2506 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2507 $func = 'getFullURL';
2508 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2509 $func = 'escapeFullURL';
2514 if ( $func !== false ) {
2515 $title = Title
::newFromText( $part1 );
2516 if ( !is_null( $title ) ) {
2518 $text = $linestart . $title->$func( $args[0] );
2520 $text = $linestart . $title->$func();
2528 if ( !$found && $argc == 1 ) {
2529 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2530 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2531 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2537 if ( !$found && $argc >= 2 ) {
2538 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2539 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2540 if ($argc==2) {$args[2]=$args[1];}
2541 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2546 # Template table test
2548 # Did we encounter this template already? If yes, it is in the cache
2549 # and we need to check for loops.
2550 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2553 # Infinite loop test
2554 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2558 $text = $linestart .
2559 '{{' . $part1 . '}}' .
2560 '<!-- WARNING: template loop detected -->';
2561 wfDebug( "$fname: template loop broken at '$part1'\n" );
2563 # set $text to cached message.
2564 $text = $linestart . $this->mTemplates
[$piece['title']];
2568 # Load from database
2569 $lastPathLevel = $this->mTemplatePath
;
2572 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2573 if ($subpage !== '') {
2574 $ns = $this->mTitle
->getNamespace();
2576 $title = Title
::newFromText( $part1, $ns );
2578 if ( !is_null( $title ) ) {
2579 if ( !$title->isExternal() ) {
2580 # Check for excessive inclusion
2581 $dbk = $title->getPrefixedDBkey();
2582 if ( $this->incrementIncludeCount( $dbk ) ) {
2583 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2584 # Capture special page output
2585 $text = SpecialPage
::capturePath( $title );
2586 if ( is_string( $text ) ) {
2591 $this->disableCache();
2594 $articleContent = $this->fetchTemplate( $title );
2595 if ( $articleContent !== false ) {
2597 $text = $articleContent;
2598 $replaceHeadings = true;
2603 # If the title is valid but undisplayable, make a link to it
2604 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2605 $text = '[['.$title->getPrefixedText().']]';
2608 } elseif ( $title->isTrans() ) {
2609 // Interwiki transclusion
2610 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2611 $text = $this->interwikiTransclude( $title, 'render' );
2615 $text = $this->interwikiTransclude( $title, 'raw' );
2616 $replaceHeadings = true;
2621 # Template cache array insertion
2622 # Use the original $piece['title'] not the mangled $part1, so that
2623 # modifiers such as RAW: produce separate cache entries
2625 $this->mTemplates
[$piece['title']] = $text;
2626 $text = $linestart . $text;
2631 # Recursive parsing, escaping and link table handling
2632 # Only for HTML output
2633 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2634 $text = wfEscapeWikiText( $text );
2635 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2637 # Clean up argument array
2638 $assocArgs = array();
2640 foreach( $args as $arg ) {
2641 $eqpos = strpos( $arg, '=' );
2642 if ( $eqpos === false ) {
2643 $assocArgs[$index++
] = $arg;
2645 $name = trim( substr( $arg, 0, $eqpos ) );
2646 $value = trim( substr( $arg, $eqpos+
1 ) );
2647 if ( $value === false ) {
2650 if ( $name !== false ) {
2651 $assocArgs[$name] = $value;
2656 # Add a new element to the templace recursion path
2657 $this->mTemplatePath
[$part1] = 1;
2661 # If there are any <onlyinclude> tags, only include them
2662 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2663 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2665 foreach ($m[1] as $piece)
2668 # Remove <noinclude> sections and <includeonly> tags
2669 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2670 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2672 if( $this->mOutputType
== OT_HTML
) {
2673 # Strip <nowiki>, <pre>, etc.
2674 $text = $this->strip( $text, $this->mStripState
);
2675 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2677 $text = $this->replaceVariables( $text, $assocArgs );
2679 # If the template begins with a table or block-level
2680 # element, it should be treated as beginning a new line.
2681 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2682 $text = "\n" . $text;
2684 } elseif ( !$noargs ) {
2685 # $noparse and !$noargs
2686 # Just replace the arguments, not any double-brace items
2687 # This is used for rendered interwiki transclusion
2688 $text = $this->replaceVariables( $text, $assocArgs, true );
2691 # Prune lower levels off the recursion check path
2692 $this->mTemplatePath
= $lastPathLevel;
2695 wfProfileOut( $fname );
2696 return $piece['text'];
2699 # Replace raw HTML by a placeholder
2700 # Add a blank line preceding, to prevent it from mucking up
2701 # immediately preceding headings
2702 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2704 # replace ==section headers==
2705 # XXX this needs to go away once we have a better parser.
2706 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2707 if( !is_null( $title ) )
2708 $encodedname = base64_encode($title->getPrefixedDBkey());
2710 $encodedname = base64_encode("");
2711 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2712 PREG_SPLIT_DELIM_CAPTURE
);
2715 for( $i = 0; $i < count($m); $i +
= 2 ) {
2717 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2719 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2723 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2724 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2725 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2733 # Prune lower levels off the recursion check path
2734 $this->mTemplatePath
= $lastPathLevel;
2737 wfProfileOut( $fname );
2738 return $piece['text'];
2740 wfProfileOut( $fname );
2746 * Fetch the unparsed text of a template and register a reference to it.
2748 function fetchTemplate( $title ) {
2750 // Loop to fetch the article, with up to 1 redirect
2751 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2752 $rev = Revision
::newFromTitle( $title );
2753 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2757 $text = $rev->getText();
2758 if ( $text === false ) {
2762 $title = Title
::newFromRedirect( $text );
2768 * Transclude an interwiki link.
2770 function interwikiTransclude( $title, $action ) {
2771 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2773 if (!$wgEnableScaryTranscluding)
2774 return wfMsg('scarytranscludedisabled');
2776 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2777 // But we'll handle it generally anyway
2778 if ( $title->getNamespace() ) {
2779 // Use the canonical namespace, which should work anywhere
2780 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2782 $articleName = $title->getDBkey();
2785 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2786 $url .= "?action=$action";
2787 if (strlen($url) > 255)
2788 return wfMsg('scarytranscludetoolong');
2789 return $this->fetchScaryTemplateMaybeFromCache($url);
2792 function fetchScaryTemplateMaybeFromCache($url) {
2793 global $wgTranscludeCacheExpiry;
2794 $dbr =& wfGetDB(DB_SLAVE
);
2795 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2796 array('tc_url' => $url));
2798 $time = $obj->tc_time
;
2799 $text = $obj->tc_contents
;
2800 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2805 $text = wfGetHTTP($url);
2807 return wfMsg('scarytranscludefailed', $url);
2809 $dbw =& wfGetDB(DB_MASTER
);
2810 $dbw->replace('transcache', array('tc_url'), array(
2812 'tc_time' => time(),
2813 'tc_contents' => $text));
2819 * Triple brace replacement -- used for template arguments
2822 function argSubstitution( $matches ) {
2823 $arg = trim( $matches['title'] );
2824 $text = $matches['text'];
2825 $inputArgs = end( $this->mArgStack
);
2827 if ( array_key_exists( $arg, $inputArgs ) ) {
2828 $text = $inputArgs[$arg];
2829 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2830 $text = $matches['parts'][0];
2837 * Returns true if the function is allowed to include this entity
2840 function incrementIncludeCount( $dbk ) {
2841 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2842 $this->mIncludeCount
[$dbk] = 0;
2844 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2852 * This function accomplishes several tasks:
2853 * 1) Auto-number headings if that option is enabled
2854 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2855 * 3) Add a Table of contents on the top for users who have enabled the option
2856 * 4) Auto-anchor headings
2858 * It loops through all headlines, collects the necessary data, then splits up the
2859 * string and re-inserts the newly formatted headlines.
2861 * @param string $text
2862 * @param boolean $isMain
2865 function formatHeadings( $text, $isMain=true ) {
2866 global $wgMaxTocLevel, $wgContLang;
2868 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2870 $forceTocHere = false;
2871 if( !$this->mTitle
->userCanEdit() ) {
2874 $showEditLink = $this->mOptions
->getEditSection();
2877 # Inhibit editsection links if requested in the page
2878 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2879 if( $esw->matchAndRemove( $text ) ) {
2882 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2884 $mw =& MagicWord
::get( MAG_NOTOC
);
2885 if( $mw->matchAndRemove( $text ) ) {
2889 # Get all headlines for numbering them and adding funky stuff like [edit]
2890 # links - this is for later, but we need the number of headlines right now
2891 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2893 # if there are fewer than 4 headlines in the article, do not show TOC
2894 if( $numMatches < 4 ) {
2898 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2899 # override above conditions and always show TOC at that place
2901 $mw =& MagicWord
::get( MAG_TOC
);
2902 if($mw->match( $text ) ) {
2904 $forceTocHere = true;
2906 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2907 # override above conditions and always show TOC above first header
2908 $mw =& MagicWord
::get( MAG_FORCETOC
);
2909 if ($mw->matchAndRemove( $text ) ) {
2914 # Never ever show TOC if no headers
2915 if( $numMatches < 1 ) {
2919 # We need this to perform operations on the HTML
2920 $sk =& $this->mOptions
->getSkin();
2924 $sectionCount = 0; # headlineCount excluding template sections
2926 # Ugh .. the TOC should have neat indentation levels which can be
2927 # passed to the skin functions. These are determined here
2931 $sublevelCount = array();
2932 $levelCount = array();
2939 foreach( $matches[3] as $headline ) {
2941 $templatetitle = '';
2942 $templatesection = 0;
2945 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2947 $templatetitle = base64_decode($mat[1]);
2948 $templatesection = 1 +
(int)base64_decode($mat[2]);
2949 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2953 $prevlevel = $level;
2954 $prevtoclevel = $toclevel;
2956 $level = $matches[1][$headlineCount];
2958 if( $doNumberHeadings ||
$doShowToc ) {
2960 if ( $level > $prevlevel ) {
2961 # Increase TOC level
2963 $sublevelCount[$toclevel] = 0;
2964 $toc .= $sk->tocIndent();
2966 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2967 # Decrease TOC level, find level to jump to
2969 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2970 # Can only go down to level 1
2973 for ($i = $toclevel; $i > 0; $i--) {
2974 if ( $levelCount[$i] == $level ) {
2975 # Found last matching level
2979 elseif ( $levelCount[$i] < $level ) {
2980 # Found first matching level below current level
2987 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2990 # No change in level, end TOC line
2991 $toc .= $sk->tocLineEnd();
2994 $levelCount[$toclevel] = $level;
2996 # count number of headlines for each level
2997 @$sublevelCount[$toclevel]++
;
2999 for( $i = 1; $i <= $toclevel; $i++
) {
3000 if( !empty( $sublevelCount[$i] ) ) {
3004 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3010 # The canonized header is a version of the header text safe to use for links
3011 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3012 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3013 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3015 # Remove link placeholders by the link text.
3016 # <!--LINK number-->
3018 # link text with suffix
3019 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3020 "\$this->mLinkHolders['texts'][\$1]",
3021 $canonized_headline );
3022 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3023 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3024 $canonized_headline );
3027 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3028 $tocline = trim( $canonized_headline );
3029 $canonized_headline = Sanitizer
::escapeId( $tocline );
3030 $refers[$headlineCount] = $canonized_headline;
3032 # count how many in assoc. array so we can track dupes in anchors
3033 @$refers[$canonized_headline]++
;
3034 $refcount[$headlineCount]=$refers[$canonized_headline];
3036 # Don't number the heading if it is the only one (looks silly)
3037 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3038 # the two are different if the line contains a link
3039 $headline=$numbering . ' ' . $headline;
3042 # Create the anchor for linking from the TOC to the section
3043 $anchor = $canonized_headline;
3044 if($refcount[$headlineCount] > 1 ) {
3045 $anchor .= '_' . $refcount[$headlineCount];
3047 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3048 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3050 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3051 if ( empty( $head[$headlineCount] ) ) {
3052 $head[$headlineCount] = '';
3055 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3057 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
3060 # give headline the correct <h#> tag
3061 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3069 $toc .= $sk->tocUnindent( $toclevel - 1 );
3070 $toc = $sk->tocList( $toc );
3073 # split up and insert constructed headlines
3075 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3078 foreach( $blocks as $block ) {
3079 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3080 # This is the [edit] link that appears for the top block of text when
3081 # section editing is enabled
3083 # Disabled because it broke block formatting
3084 # For example, a bullet point in the top line
3085 # $full .= $sk->editSectionLink(0);
3088 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3089 # Top anchor now in skin
3093 if( !empty( $head[$i] ) ) {
3099 $mw =& MagicWord
::get( MAG_TOC
);
3100 return $mw->replace( $toc, $full );
3107 * Return an HTML link for the "ISBN 123456" text
3110 function magicISBN( $text ) {
3111 $fname = 'Parser::magicISBN';
3112 wfProfileIn( $fname );
3114 $a = split( 'ISBN ', ' '.$text );
3115 if ( count ( $a ) < 2 ) {
3116 wfProfileOut( $fname );
3119 $text = substr( array_shift( $a ), 1);
3120 $valid = '0123456789-Xx';
3122 foreach ( $a as $x ) {
3123 $isbn = $blank = '' ;
3124 while ( ' ' == $x{0} ) {
3126 $x = substr( $x, 1 );
3128 if ( $x == '' ) { # blank isbn
3129 $text .= "ISBN $blank";
3132 while ( strstr( $valid, $x{0} ) != false ) {
3134 $x = substr( $x, 1 );
3136 $num = str_replace( '-', '', $isbn );
3137 $num = str_replace( ' ', '', $num );
3138 $num = str_replace( 'x', 'X', $num );
3141 $text .= "ISBN $blank$x";
3143 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3144 $text .= '<a href="' .
3145 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3146 "\" class=\"internal\">ISBN $isbn</a>";
3150 wfProfileOut( $fname );
3155 * Return an HTML link for the "RFC 1234" text
3158 * @param string $text Text to be processed
3159 * @param string $keyword Magic keyword to use (default RFC)
3160 * @param string $urlmsg Interface message to use (default rfcurl)
3163 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3165 $valid = '0123456789';
3168 $a = split( $keyword, ' '.$text );
3169 if ( count ( $a ) < 2 ) {
3172 $text = substr( array_shift( $a ), 1);
3174 /* Check if keyword is preceed by [[.
3175 * This test is made here cause of the array_shift above
3176 * that prevent the test to be done in the foreach.
3178 if ( substr( $text, -2 ) == '[[' ) {
3182 foreach ( $a as $x ) {
3183 /* token might be empty if we have RFC RFC 1234 */
3191 /** remove and save whitespaces in $blank */
3192 while ( $x{0} == ' ' ) {
3194 $x = substr( $x, 1 );
3197 /** remove and save the rfc number in $id */
3198 while ( strstr( $valid, $x{0} ) != false ) {
3200 $x = substr( $x, 1 );
3204 /* call back stripped spaces*/
3205 $text .= $keyword.$blank.$x;
3206 } elseif( $internal ) {
3208 $text .= $keyword.$id.$x;
3210 /* build the external link*/
3211 $url = wfMsg( $urlmsg, $id);
3212 $sk =& $this->mOptions
->getSkin();
3213 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3214 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3217 /* Check if the next RFC keyword is preceed by [[ */
3218 $internal = ( substr($x,-2) == '[[' );
3224 * Transform wiki markup when saving a page by doing \r\n -> \n
3225 * conversion, substitting signatures, {{subst:}} templates, etc.
3227 * @param string $text the text to transform
3228 * @param Title &$title the Title object for the current article
3229 * @param User &$user the User object describing the current user
3230 * @param ParserOptions $options parsing options
3231 * @param bool $clearState whether to clear the parser state first
3232 * @return string the altered wiki markup
3235 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3236 $this->mOptions
= $options;
3237 $this->mTitle
=& $title;
3238 $this->mOutputType
= OT_WIKI
;
3240 if ( $clearState ) {
3241 $this->clearState();
3244 $stripState = false;
3248 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3249 $text = $this->strip( $text, $stripState, true );
3250 $text = $this->pstPass2( $text, $user );
3251 $text = $this->unstrip( $text, $stripState );
3252 $text = $this->unstripNoWiki( $text, $stripState );
3257 * Pre-save transform helper function
3260 function pstPass2( $text, &$user ) {
3261 global $wgContLang, $wgLocaltimezone;
3263 /* Note: This is the timestamp saved as hardcoded wikitext to
3264 * the database, we use $wgContLang here in order to give
3265 * everyone the same signiture and use the default one rather
3266 * than the one selected in each users preferences.
3268 if ( isset( $wgLocaltimezone ) ) {
3269 $oldtz = getenv( 'TZ' );
3270 putenv( 'TZ='.$wgLocaltimezone );
3272 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3273 ' (' . date( 'T' ) . ')';
3274 if ( isset( $wgLocaltimezone ) ) {
3275 putenv( 'TZ='.$oldtz );
3278 # Variable replacement
3279 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3280 $text = $this->replaceVariables( $text );
3283 $sigText = $this->getUserSig( $user );
3284 $text = strtr( $text, array(
3286 '~~~~' => "$sigText $d",
3290 # Context links: [[|name]] and [[name (context)|]]
3292 global $wgLegalTitleChars;
3293 $tc = "[$wgLegalTitleChars]";
3294 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3296 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3297 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3299 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3300 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3301 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3302 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3304 $t = $this->mTitle
->getText();
3305 if ( preg_match( $conpat, $t, $m ) ) {
3308 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3309 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3310 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3312 if ( '' == $context ) {
3313 $text = preg_replace( $p2, '[[\\1]]', $text );
3315 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3318 # Trim trailing whitespace
3319 # MAG_END (__END__) tag allows for trailing
3320 # whitespace to be deliberately included
3321 $text = rtrim( $text );
3322 $mw =& MagicWord
::get( MAG_END
);
3323 $mw->matchAndRemove( $text );
3329 * Fetch the user's signature text, if any, and normalize to
3330 * validated, ready-to-insert wikitext.
3336 function getUserSig( &$user ) {
3339 $username = $user->getName();
3340 $nickname = $user->getOption( 'nickname' );
3341 $nickname = $nickname === '' ?
$username : $nickname;
3343 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3344 # Sig. might contain markup; validate this
3345 if( $this->validateSig( $nickname ) !== false ) {
3346 # Validated; clean up (if needed) and return it
3347 return( $this->cleanSig( $nickname ) );
3349 # Failed to validate; fall back to the default
3350 $nickname = $username;
3351 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3355 # If we're still here, make it a link to the user page
3356 $userpage = $user->getUserPage();
3357 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3361 * Check that the user's signature contains no bad XML
3363 * @param string $text
3364 * @return mixed An expanded string, or false if invalid.
3366 function validateSig( $text ) {
3367 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3371 * Clean up signature text
3373 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3374 * 2) Substitute all transclusions
3376 * @param string $text
3377 * @return string Signature text
3379 function cleanSig( $text ) {
3380 $substWord = MagicWord
::get( MAG_SUBST
);
3381 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3382 $substText = '{{' . $substWord->getSynonym( 0 );
3384 $text = preg_replace( $substRegex, $substText, $text );
3385 $text = preg_replace( '/~{3,5}/', '', $text );
3386 $text = $this->replaceVariables( $text );
3392 * Set up some variables which are usually set up in parse()
3393 * so that an external function can call some class members with confidence
3396 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3397 $this->mTitle
=& $title;
3398 $this->mOptions
= $options;
3399 $this->mOutputType
= $outputType;
3400 if ( $clearState ) {
3401 $this->clearState();
3406 * Transform a MediaWiki message by replacing magic variables.
3408 * @param string $text the text to transform
3409 * @param ParserOptions $options options
3410 * @return string the text with variables substituted
3413 function transformMsg( $text, $options ) {
3415 static $executing = false;
3417 $fname = "Parser::transformMsg";
3419 # Guard against infinite recursion
3425 wfProfileIn($fname);
3427 $this->mTitle
= $wgTitle;
3428 $this->mOptions
= $options;
3429 $this->mOutputType
= OT_MSG
;
3430 $this->clearState();
3431 $text = $this->replaceVariables( $text );
3434 wfProfileOut($fname);
3439 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3440 * The callback should have the following form:
3441 * function myParserHook( $text, $params, &$parser ) { ... }
3443 * Transform and return $text. Use $parser for any required context, e.g. use
3444 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3448 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3449 * @param mixed $callback The callback function (and object) to use for the tag
3451 * @return The old value of the mTagHooks array associated with the hook
3453 function setHook( $tag, $callback ) {
3454 $oldVal = @$this->mTagHooks
[$tag];
3455 $this->mTagHooks
[$tag] = $callback;
3461 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3462 * Placeholders created in Skin::makeLinkObj()
3463 * Returns an array of links found, indexed by PDBK:
3467 * $options is a bit field, RLH_FOR_UPDATE to select for update
3469 function replaceLinkHolders( &$text, $options = 0 ) {
3471 global $wgOutputReplace;
3473 $fname = 'Parser::replaceLinkHolders';
3474 wfProfileIn( $fname );
3478 $sk =& $this->mOptions
->getSkin();
3479 $linkCache =& LinkCache
::singleton();
3481 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3482 wfProfileIn( $fname.'-check' );
3483 $dbr =& wfGetDB( DB_SLAVE
);
3484 $page = $dbr->tableName( 'page' );
3485 $threshold = $wgUser->getOption('stubthreshold');
3488 asort( $this->mLinkHolders
['namespaces'] );
3492 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3494 $title = $this->mLinkHolders
['titles'][$key];
3496 # Skip invalid entries.
3497 # Result will be ugly, but prevents crash.
3498 if ( is_null( $title ) ) {
3501 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3503 # Check if it's a static known link, e.g. interwiki
3504 if ( $title->isAlwaysKnown() ) {
3505 $colours[$pdbk] = 1;
3506 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3507 $colours[$pdbk] = 1;
3508 $this->mOutput
->addLink( $title, $id );
3509 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3510 $colours[$pdbk] = 0;
3512 # Not in the link cache, add it to the query
3513 if ( !isset( $current ) ) {
3515 $query = "SELECT page_id, page_namespace, page_title";
3516 if ( $threshold > 0 ) {
3517 $query .= ', page_len, page_is_redirect';
3519 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3520 } elseif ( $current != $ns ) {
3522 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3527 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3532 if ( $options & RLH_FOR_UPDATE
) {
3533 $query .= ' FOR UPDATE';
3536 $res = $dbr->query( $query, $fname );
3538 # Fetch data and form into an associative array
3539 # non-existent = broken
3542 while ( $s = $dbr->fetchObject($res) ) {
3543 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3544 $pdbk = $title->getPrefixedDBkey();
3545 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3546 $this->mOutput
->addLink( $title, $s->page_id
);
3548 if ( $threshold > 0 ) {
3549 $size = $s->page_len
;
3550 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3551 $colours[$pdbk] = 1;
3553 $colours[$pdbk] = 2;
3556 $colours[$pdbk] = 1;
3560 wfProfileOut( $fname.'-check' );
3562 # Construct search and replace arrays
3563 wfProfileIn( $fname.'-construct' );
3564 $wgOutputReplace = array();
3565 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3566 $pdbk = $pdbks[$key];
3567 $searchkey = "<!--LINK $key-->";
3568 $title = $this->mLinkHolders
['titles'][$key];
3569 if ( empty( $colours[$pdbk] ) ) {
3570 $linkCache->addBadLinkObj( $title );
3571 $colours[$pdbk] = 0;
3572 $this->mOutput
->addLink( $title, 0 );
3573 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3574 $this->mLinkHolders
['texts'][$key],
3575 $this->mLinkHolders
['queries'][$key] );
3576 } elseif ( $colours[$pdbk] == 1 ) {
3577 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3578 $this->mLinkHolders
['texts'][$key],
3579 $this->mLinkHolders
['queries'][$key] );
3580 } elseif ( $colours[$pdbk] == 2 ) {
3581 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3582 $this->mLinkHolders
['texts'][$key],
3583 $this->mLinkHolders
['queries'][$key] );
3586 wfProfileOut( $fname.'-construct' );
3589 wfProfileIn( $fname.'-replace' );
3591 $text = preg_replace_callback(
3592 '/(<!--LINK .*?-->)/',
3593 "wfOutputReplaceMatches",
3596 wfProfileOut( $fname.'-replace' );
3599 # Now process interwiki link holders
3600 # This is quite a bit simpler than internal links
3601 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3602 wfProfileIn( $fname.'-interwiki' );
3603 # Make interwiki link HTML
3604 $wgOutputReplace = array();
3605 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3606 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3607 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3610 $text = preg_replace_callback(
3611 '/<!--IWLINK (.*?)-->/',
3612 "wfOutputReplaceMatches",
3614 wfProfileOut( $fname.'-interwiki' );
3617 wfProfileOut( $fname );
3622 * Replace <!--LINK--> link placeholders with plain text of links
3623 * (not HTML-formatted).
3624 * @param string $text
3627 function replaceLinkHoldersText( $text ) {
3629 global $wgOutputReplace;
3631 $fname = 'Parser::replaceLinkHoldersText';
3632 wfProfileIn( $fname );
3634 $text = preg_replace_callback(
3635 '/<!--(LINK|IWLINK) (.*?)-->/',
3636 array( &$this, 'replaceLinkHoldersTextCallback' ),
3639 wfProfileOut( $fname );
3644 * @param array $matches
3648 function replaceLinkHoldersTextCallback( $matches ) {
3649 $type = $matches[1];
3651 if( $type == 'LINK' ) {
3652 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3653 return $this->mLinkHolders
['texts'][$key];
3655 } elseif( $type == 'IWLINK' ) {
3656 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3657 return $this->mInterwikiLinkHolders
['texts'][$key];
3664 * Renders an image gallery from a text with one line per image.
3665 * text labels may be given by using |-style alternative text. E.g.
3666 * Image:one.jpg|The number "1"
3667 * Image:tree.jpg|A tree
3668 * given as text will return the HTML of a gallery with two images,
3669 * labeled 'The number "1"' and
3672 function renderImageGallery( $text ) {
3674 $parserOptions = new ParserOptions
;
3675 $localParser = new Parser();
3677 $ig = new ImageGallery();
3678 $ig->setShowBytes( false );
3679 $ig->setShowFilename( false );
3680 $lines = explode( "\n", $text );
3682 foreach ( $lines as $line ) {
3683 # match lines like these:
3684 # Image:someimage.jpg|This is some image
3685 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3687 if ( count( $matches ) == 0 ) {
3690 $nt =& Title
::newFromText( $matches[1] );
3691 if( is_null( $nt ) ) {
3692 # Bogus title. Ignore these so we don't bomb out later.
3695 if ( isset( $matches[3] ) ) {
3696 $label = $matches[3];
3701 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3702 $html = $pout->getText();
3704 $ig->add( new Image( $nt ), $html );
3705 $this->mOutput
->addImage( $nt->getDBkey() );
3707 return $ig->toHTML();
3711 * Parse image options text and use it to make an image
3713 function makeImage( &$nt, $options ) {
3714 global $wgContLang, $wgUseImageResize, $wgUser;
3718 # Check if the options text is of the form "options|alt text"
3720 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3721 # * left no resizing, just left align. label is used for alt= only
3722 # * right same, but right aligned
3723 # * none same, but not aligned
3724 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3725 # * center center the image
3726 # * framed Keep original image size, no magnify-button.
3728 $part = explode( '|', $options);
3730 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3731 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3732 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3733 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3734 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3735 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3736 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3737 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3740 $width = $height = $framed = $thumb = false;
3741 $manual_thumb = '' ;
3743 foreach( $part as $key => $val ) {
3744 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3746 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3747 # use manually specified thumbnail
3749 $manual_thumb = $match;
3750 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3751 # remember to set an alignment, don't render immediately
3753 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3754 # remember to set an alignment, don't render immediately
3756 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3757 # remember to set an alignment, don't render immediately
3759 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3760 # remember to set an alignment, don't render immediately
3762 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3763 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3764 # $match is the image width in pixels
3765 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3766 $width = intval( $m[1] );
3767 $height = intval( $m[2] );
3769 $width = intval($match);
3771 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3777 # Strip bad stuff out of the alt text
3778 $alt = $this->replaceLinkHoldersText( $caption );
3779 $alt = Sanitizer
::stripAllTags( $alt );
3781 # Linker does the rest
3782 $sk =& $this->mOptions
->getSkin();
3783 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3787 * Set a flag in the output object indicating that the content is dynamic and
3788 * shouldn't be cached.
3790 function disableCache() {
3791 $this->mOutput
->mCacheTime
= -1;
3795 * Callback from the Sanitizer for expanding items found in HTML attribute
3796 * values, so they can be safely tested and escaped.
3797 * @param string $text
3798 * @param array $args
3802 function attributeStripCallback( &$text, $args ) {
3803 $text = $this->replaceVariables( $text, $args );
3804 $text = $this->unstripForHTML( $text );
3808 function unstripForHTML( $text ) {
3809 $text = $this->unstrip( $text, $this->mStripState
);
3810 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3818 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3819 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3820 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3826 function getTags() { return array_keys( $this->mTagHooks
); }
3832 * @package MediaWiki
3836 var $mText, # The output text
3837 $mLanguageLinks, # List of the full text of language links, in the order they appear
3838 $mCategories, # Map of category names to sort keys
3839 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3840 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3841 $mVersion, # Compatibility check
3842 $mTitleText, # title text of the chosen language variant
3843 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3844 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3845 $mImages, # DB keys of the images used, in the array key only
3846 $mExternalLinks; # External link URLs, in the key only
3848 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3849 $containsOldMagic = false, $titletext = '' )
3851 $this->mText
= $text;
3852 $this->mLanguageLinks
= $languageLinks;
3853 $this->mCategories
= $categoryLinks;
3854 $this->mContainsOldMagic
= $containsOldMagic;
3855 $this->mCacheTime
= '';
3856 $this->mVersion
= MW_PARSER_VERSION
;
3857 $this->mTitleText
= $titletext;
3858 $this->mLinks
= array();
3859 $this->mTemplates
= array();
3860 $this->mImages
= array();
3861 $this->mExternalLinks
= array();
3864 function getText() { return $this->mText
; }
3865 function getLanguageLinks() { return $this->mLanguageLinks
; }
3866 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3867 function &getCategories() { return $this->mCategories
; }
3868 function getCacheTime() { return $this->mCacheTime
; }
3869 function getTitleText() { return $this->mTitleText
; }
3870 function &getLinks() { return $this->mLinks
; }
3871 function &getTemplates() { return $this->mTemplates
; }
3872 function &getImages() { return $this->mImages
; }
3873 function &getExternalLinks() { return $this->mExternalLinks
; }
3875 function containsOldMagic() { return $this->mContainsOldMagic
; }
3876 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3877 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3878 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3879 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3880 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3881 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3883 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3884 function addImage( $name ) { $this->mImages
[$name] = 1; }
3885 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3886 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3888 function addLink( $title, $id ) {
3889 $ns = $title->getNamespace();
3890 $dbk = $title->getDBkey();
3891 if ( !isset( $this->mLinks
[$ns] ) ) {
3892 $this->mLinks
[$ns] = array();
3894 $this->mLinks
[$ns][$dbk] = $id;
3897 function addTemplate( $title, $id ) {
3898 $ns = $title->getNamespace();
3899 $dbk = $title->getDBkey();
3900 if ( !isset( $this->mTemplates
[$ns] ) ) {
3901 $this->mTemplates
[$ns] = array();
3903 $this->mTemplates
[$ns][$dbk] = $id;
3910 function merge( $other ) {
3911 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3912 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3913 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3917 * Return true if this cached output object predates the global or
3918 * per-article cache invalidation timestamps, or if it comes from
3919 * an incompatible older version.
3921 * @param string $touched the affected article's last touched timestamp
3925 function expired( $touched ) {
3926 global $wgCacheEpoch;
3927 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3928 $this->getCacheTime() < $touched ||
3929 $this->getCacheTime() <= $wgCacheEpoch ||
3930 !isset( $this->mVersion
) ||
3931 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3936 * Set options of the Parser
3938 * @package MediaWiki
3942 # All variables are private
3943 var $mUseTeX; # Use texvc to expand <math> tags
3944 var $mUseDynamicDates; # Use DateFormatter to format dates
3945 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3946 var $mAllowExternalImages; # Allow external images inline
3947 var $mAllowExternalImagesFrom; # If not, any exception?
3948 var $mSkin; # Reference to the preferred skin
3949 var $mDateFormat; # Date format index
3950 var $mEditSection; # Create "edit section" links
3951 var $mNumberHeadings; # Automatically number headings
3952 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3953 var $mTidy; # Ask for tidy cleanup
3955 function getUseTeX() { return $this->mUseTeX
; }
3956 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3957 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3958 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3959 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3960 function &getSkin() { return $this->mSkin
; }
3961 function getDateFormat() { return $this->mDateFormat
; }
3962 function getEditSection() { return $this->mEditSection
; }
3963 function getNumberHeadings() { return $this->mNumberHeadings
; }
3964 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3965 function getTidy() { return $this->mTidy
; }
3967 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3968 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3969 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3970 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3971 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3972 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3973 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3974 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3975 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3976 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3977 function setSkin( &$x ) { $this->mSkin
=& $x; }
3979 function ParserOptions() {
3981 $this->initialiseFromUser( $wgUser );
3985 * Get parser options
3988 function newFromUser( &$user ) {
3989 $popts = new ParserOptions
;
3990 $popts->initialiseFromUser( $user );
3994 /** Get user options */
3995 function initialiseFromUser( &$userInput ) {
3996 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3997 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3998 $fname = 'ParserOptions::initialiseFromUser';
3999 wfProfileIn( $fname );
4000 if ( !$userInput ) {
4002 $user->setLoaded( true );
4004 $user =& $userInput;
4007 $this->mUseTeX
= $wgUseTeX;
4008 $this->mUseDynamicDates
= $wgUseDynamicDates;
4009 $this->mInterwikiMagic
= $wgInterwikiMagic;
4010 $this->mAllowExternalImages
= $wgAllowExternalImages;
4011 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4012 wfProfileIn( $fname.'-skin' );
4013 $this->mSkin
=& $user->getSkin();
4014 wfProfileOut( $fname.'-skin' );
4015 $this->mDateFormat
= $user->getOption( 'date' );
4016 $this->mEditSection
= true;
4017 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4018 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4019 $this->mTidy
= false;
4020 wfProfileOut( $fname );
4025 * Callback function used by Parser::replaceLinkHolders()
4026 * to substitute link placeholders.
4028 function &wfOutputReplaceMatches( $matches ) {
4029 global $wgOutputReplace;
4030 return $wgOutputReplace[$matches[1]];
4034 * Return the total number of articles
4036 function wfNumberOfArticles() {
4037 global $wgNumberOfArticles;
4040 return $wgNumberOfArticles;
4044 * Return the number of files
4046 function wfNumberOfFiles() {
4047 $fname = 'Parser::wfNumberOfFiles';
4049 wfProfileIn( $fname );
4050 $dbr =& wfGetDB( DB_SLAVE
);
4051 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4052 wfProfileOut( $fname );
4058 * Get various statistics from the database
4061 function wfLoadSiteStats() {
4062 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4063 $fname = 'wfLoadSiteStats';
4065 if ( -1 != $wgNumberOfArticles ) return;
4066 $dbr =& wfGetDB( DB_SLAVE
);
4067 $s = $dbr->selectRow( 'site_stats',
4068 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4069 array( 'ss_row_id' => 1 ), $fname
4072 if ( $s === false ) {
4075 $wgTotalViews = $s->ss_total_views
;
4076 $wgTotalEdits = $s->ss_total_edits
;
4077 $wgNumberOfArticles = $s->ss_good_articles
;
4083 * Basically replacing " > and < with HTML entities ( ", >, <)
4085 * @param string $in Text that might contain HTML tags
4086 * @return string Escaped string
4088 function wfEscapeHTMLTagsOnly( $in ) {
4090 array( '"', '>', '<' ),
4091 array( '"', '>', '<' ),