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.5.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 # prefix for escaping, used in two functions at least
47 define( 'UNIQ_PREFIX', 'NaodW29');
49 # Constants needed for external link processing
50 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.$wgUrlProtocols.')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone, $wgAllowSpecialInclusion*
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array(), $mCurrentParams = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
113 var $mIWTransData = array();
123 $this->mTemplates
= array();
124 $this->mTemplatePath
= array();
125 $this->mTagHooks
= array();
134 function clearState() {
135 $this->mOutput
= new ParserOutput
;
136 $this->mAutonumber
= 0;
137 $this->mLastSection
= '';
138 $this->mDTopen
= false;
139 $this->mVariables
= false;
140 $this->mIncludeCount
= array();
141 $this->mStripState
= array();
142 $this->mArgStack
= array();
143 $this->mInPre
= false;
144 $this->mCurrentParams
= array();
145 $this->mInterwikiLinkHolders
= array(
149 $this->mLinkHolders
= array(
150 'namespaces' => array(),
152 'queries' => array(),
159 * First pass--just handle <nowiki> sections, pass the rest off
160 * to internalParse() which does all the real work.
163 * @param string $text Text we want to parse
164 * @param Title &$title A title object
165 * @param array $options
166 * @param boolean $linestart
167 * @param boolean $clearState
168 * @return ParserOutput a ParserOutput
170 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
171 global $wgUseTidy, $wgContLang;
172 $fname = 'Parser::parse';
173 wfProfileIn( $fname );
179 $this->mOptions
= $options;
180 $this->mTitle
=& $title;
181 $this->mOutputType
= OT_HTML
;
183 $this->mStripState
= NULL;
185 //$text = $this->strip( $text, $this->mStripState );
186 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
187 $x =& $this->mStripState
;
189 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
190 $text = $this->strip( $text, $x );
191 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
193 $text = $this->internalParse( $text );
195 $text = $this->unstrip( $text, $this->mStripState
);
197 # Clean up special characters, only run once, next-to-last before doBlockLevels
199 # french spaces, last one Guillemet-left
200 # only if there is something before the space
201 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
202 # french spaces, Guillemet-right
203 '/(\\302\\253) /' => '\\1 ',
204 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
206 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
209 $text = $this->doBlockLevels( $text, $linestart );
211 $this->replaceLinkHolders( $text );
213 # the position of the convert() call should not be changed. it
214 # assumes that the links are all replaces and the only thing left
215 # is the <nowiki> mark.
216 $text = $wgContLang->convert($text);
217 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
219 $text = $this->unstripNoWiki( $text, $this->mStripState
);
221 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
223 $text = Sanitizer
::normalizeCharReferences( $text );
226 $text = Parser
::tidy($text);
229 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
231 $this->mOutput
->setText( $text );
232 wfProfileOut( $fname );
233 return $this->mOutput
;
237 * Get a random string
242 function getRandomString() {
243 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
247 * Replaces all occurrences of <$tag>content</$tag> in the text
248 * with a random marker and returns the new text. the output parameter
249 * $content will be an associative array filled with data on the form
250 * $unique_marker => content.
252 * If $content is already set, the additional entries will be appended
253 * If $tag is set to STRIP_COMMENTS, the function will extract
254 * <!-- HTML comments -->
259 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
260 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
275 if( $tag == STRIP_COMMENTS
) {
279 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
280 $end = "/<\\/$tag\\s*>/i";
283 while ( '' != $text ) {
284 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
286 if( count( $p ) < 3 ) {
292 $marker = $rnd . sprintf('%08X', $n++
);
293 $stripped .= $marker;
295 $tags[$marker] = "<$tag$attributes>";
296 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
298 $q = preg_split( $end, $inside, 2 );
299 $content[$marker] = $q[0];
300 if( count( $q ) < 2 ) {
301 # No end tag -- let it run out to the end of the text.
311 * Wrapper function for extractTagsAndParams
312 * for cases where $tags and $params isn't needed
313 * i.e. where tags will never have params, like <nowiki>
318 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
319 $dummy_tags = array();
320 $dummy_params = array();
322 return Parser
::extractTagsAndParams( $tag, $text, $content,
323 $dummy_tags, $dummy_params, $uniq_prefix );
327 * Strips and renders nowiki, pre, math, hiero
328 * If $render is set, performs necessary rendering operations on plugins
329 * Returns the text, and fills an array with data needed in unstrip()
330 * If the $state is already a valid strip state, it adds to the state
332 * @param bool $stripcomments when set, HTML comments <!-- like this -->
333 * will be stripped in addition to other tags. This is important
334 * for section editing, where these comments cause confusion when
335 * counting the sections in the wikisource
339 function strip( $text, &$state, $stripcomments = false ) {
340 $render = ($this->mOutputType
== OT_HTML
);
341 $html_content = array();
342 $nowiki_content = array();
343 $math_content = array();
344 $pre_content = array();
345 $comment_content = array();
346 $ext_content = array();
348 $ext_params = array();
349 $gallery_content = array();
351 # Replace any instances of the placeholders
352 $uniq_prefix = UNIQ_PREFIX
;
353 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
358 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
359 foreach( $html_content as $marker => $content ) {
361 # Raw and unchecked for validity.
362 $html_content[$marker] = $content;
364 $html_content[$marker] = '<html>'.$content.'</html>';
370 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
371 foreach( $nowiki_content as $marker => $content ) {
373 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
375 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
380 if( $this->mOptions
->getUseTeX() ) {
381 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
382 foreach( $math_content as $marker => $content ){
384 $math_content[$marker] = renderMath( $content );
386 $math_content[$marker] = '<math>'.$content.'</math>';
392 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
393 foreach( $pre_content as $marker => $content ){
395 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
397 $pre_content[$marker] = '<pre>'.$content.'</pre>';
402 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
403 foreach( $gallery_content as $marker => $content ) {
404 require_once( 'ImageGallery.php' );
406 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
408 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
414 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
415 foreach( $comment_content as $marker => $content ){
416 $comment_content[$marker] = '<!--'.$content.'-->';
421 foreach ( $this->mTagHooks
as $tag => $callback ) {
422 $ext_content[$tag] = array();
423 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
424 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
425 foreach( $ext_content[$tag] as $marker => $content ) {
426 $content = $this->replaceVariables( $content, $this->mCurrentParams
);
427 $full_tag = $ext_tags[$tag][$marker];
428 $params = $ext_params[$tag][$marker];
430 $ext_content[$tag][$marker] = $callback( $content, $params, $this );
432 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
437 # Merge state with the pre-existing state, if there is one
439 $state['html'] = $state['html'] +
$html_content;
440 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
441 $state['math'] = $state['math'] +
$math_content;
442 $state['pre'] = $state['pre'] +
$pre_content;
443 $state['comment'] = $state['comment'] +
$comment_content;
444 $state['gallery'] = $state['gallery'] +
$gallery_content;
446 foreach( $ext_content as $tag => $array ) {
447 if ( array_key_exists( $tag, $state ) ) {
448 $state[$tag] = $state[$tag] +
$array;
453 'html' => $html_content,
454 'nowiki' => $nowiki_content,
455 'math' => $math_content,
456 'pre' => $pre_content,
457 'comment' => $comment_content,
458 'gallery' => $gallery_content,
465 * restores pre, math, and hiero removed by strip()
467 * always call unstripNoWiki() after this one
470 function unstrip( $text, &$state ) {
471 if ( !is_array( $state ) ) {
475 # Must expand in reverse order, otherwise nested tags will be corrupted
476 $contentDict = end( $state );
477 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
478 if( key($state) != 'nowiki' && key($state) != 'html') {
479 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
480 $text = str_replace( key( $contentDict ), $content, $text );
489 * always call this after unstrip() to preserve the order
493 function unstripNoWiki( $text, &$state ) {
494 if ( !is_array( $state ) ) {
498 # Must expand in reverse order, otherwise nested tags will be corrupted
499 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
500 $text = str_replace( key( $state['nowiki'] ), $content, $text );
505 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
506 $text = str_replace( key( $state['html'] ), $content, $text );
514 * Add an item to the strip state
515 * Returns the unique tag which must be inserted into the stripped text
516 * The tag will be replaced with the original text in unstrip()
520 function insertStripItem( $text, &$state ) {
521 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
528 'comment' => array(),
529 'gallery' => array(),
532 $state['item'][$rnd] = $text;
537 * Interface with html tidy, used if $wgUseTidy = true.
538 * If tidy isn't able to correct the markup, the original will be
539 * returned in all its glory with a warning comment appended.
541 * Either the external tidy program or the in-process tidy extension
542 * will be used depending on availability. Override the default
543 * $wgTidyInternal setting to disable the internal if it's not working.
545 * @param string $text Hideous HTML input
546 * @return string Corrected HTML output
550 function tidy( $text ) {
551 global $wgTidyInternal;
552 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
553 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
554 '<head><title>test</title></head><body>'.$text.'</body></html>';
555 if( $wgTidyInternal ) {
556 $correctedtext = Parser
::internalTidy( $wrappedtext );
558 $correctedtext = Parser
::externalTidy( $wrappedtext );
560 if( is_null( $correctedtext ) ) {
561 wfDebug( "Tidy error detected!\n" );
562 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
564 return $correctedtext;
568 * Spawn an external HTML tidy process and get corrected markup back from it.
573 function externalTidy( $text ) {
574 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
575 $fname = 'Parser::externalTidy';
576 wfProfileIn( $fname );
581 $descriptorspec = array(
582 0 => array('pipe', 'r'),
583 1 => array('pipe', 'w'),
584 2 => array('file', '/dev/null', 'a')
587 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
588 if (is_resource($process)) {
589 fwrite($pipes[0], $text);
591 while (!feof($pipes[1])) {
592 $cleansource .= fgets($pipes[1], 1024);
595 proc_close($process);
598 wfProfileOut( $fname );
600 if( $cleansource == '' && $text != '') {
601 // Some kind of error happened, so we couldn't get the corrected text.
602 // Just give up; we'll use the source text and append a warning.
610 * Use the HTML tidy PECL extension to use the tidy library in-process,
611 * saving the overhead of spawning a new process. Currently written to
612 * the PHP 4.3.x version of the extension, may not work on PHP 5.
614 * 'pear install tidy' should be able to compile the extension module.
619 function internalTidy( $text ) {
621 $fname = 'Parser::internalTidy';
622 wfProfileIn( $fname );
624 tidy_load_config( $wgTidyConf );
625 tidy_set_encoding( 'utf8' );
626 tidy_parse_string( $text );
628 if( tidy_get_status() == 2 ) {
629 // 2 is magic number for fatal error
630 // http://www.php.net/manual/en/function.tidy-get-status.php
633 $cleansource = tidy_get_output();
635 wfProfileOut( $fname );
640 * parse the wiki syntax used to render tables
644 function doTableStuff ( $t ) {
645 $fname = 'Parser::doTableStuff';
646 wfProfileIn( $fname );
648 $t = explode ( "\n" , $t ) ;
649 $td = array () ; # Is currently a td tag open?
650 $ltd = array () ; # Was it TD or TH?
651 $tr = array () ; # Is currently a tr tag open?
652 $ltr = array () ; # tr attributes
653 $indent_level = 0; # indent level of the table
654 foreach ( $t AS $k => $x )
657 $fc = substr ( $x , 0 , 1 ) ;
658 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
659 $indent_level = strlen( $matches[1] );
661 $attributes = $this->unstripForHTML( $matches[2] );
663 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
664 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
665 array_push ( $td , false ) ;
666 array_push ( $ltd , '' ) ;
667 array_push ( $tr , false ) ;
668 array_push ( $ltr , '' ) ;
670 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
671 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
672 $z = "</table>" . substr ( $x , 2);
673 $l = array_pop ( $ltd ) ;
674 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
675 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
677 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
679 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
680 $x = substr ( $x , 1 ) ;
681 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
683 $l = array_pop ( $ltd ) ;
684 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
685 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
688 array_push ( $tr , false ) ;
689 array_push ( $td , false ) ;
690 array_push ( $ltd , '' ) ;
691 $attributes = $this->unstripForHTML( $x );
692 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
694 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
696 if ( '|+' == substr ( $x , 0 , 2 ) ) {
698 $x = substr ( $x , 1 ) ;
700 $after = substr ( $x , 1 ) ;
701 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
702 $after = explode ( '||' , $after ) ;
705 # Loop through each table cell
706 foreach ( $after AS $theline )
711 $tra = array_pop ( $ltr ) ;
712 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
713 array_push ( $tr , true ) ;
714 array_push ( $ltr , '' ) ;
717 $l = array_pop ( $ltd ) ;
718 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
719 if ( $fc == '|' ) $l = 'td' ;
720 else if ( $fc == '!' ) $l = 'th' ;
721 else if ( $fc == '+' ) $l = 'caption' ;
723 array_push ( $ltd , $l ) ;
726 $y = explode ( '|' , $theline , 2 ) ;
727 # Note that a '|' inside an invalid link should not
728 # be mistaken as delimiting cell parameters
729 if ( strpos( $y[0], '[[' ) !== false ) {
730 $y = array ($theline);
732 if ( count ( $y ) == 1 )
733 $y = "{$z}<{$l}>{$y[0]}" ;
735 $attributes = $this->unstripForHTML( $y[0] );
736 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
739 array_push ( $td , true ) ;
744 # Closing open td, tr && table
745 while ( count ( $td ) > 0 )
747 if ( array_pop ( $td ) ) $t[] = '</td>' ;
748 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
752 $t = implode ( "\n" , $t ) ;
753 wfProfileOut( $fname );
758 * Helper function for parse() that transforms wiki markup into
759 * HTML. Only called for $mOutputType == OT_HTML.
763 function internalParse( $text ) {
767 $fname = 'Parser::internalParse';
768 wfProfileIn( $fname );
770 # Remove <noinclude> tags and <includeonly> sections
771 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
772 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
774 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
775 $text = $this->replaceVariables( $text, $args );
777 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
779 $text = $this->doHeadings( $text );
780 if($this->mOptions
->getUseDynamicDates()) {
781 $df =& DateFormatter
::getInstance();
782 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
784 $text = $this->doAllQuotes( $text );
785 $text = $this->replaceInternalLinks( $text );
786 $text = $this->replaceExternalLinks( $text );
788 # replaceInternalLinks may sometimes leave behind
789 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
790 $text = str_replace(UNIQ_PREFIX
."NOPARSE", "", $text);
792 $text = $this->doMagicLinks( $text );
793 $text = $this->doTableStuff( $text );
794 $text = $this->formatHeadings( $text, $isMain );
796 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
797 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
799 wfProfileOut( $fname );
803 function scarySubstitution($matches) {
804 # return "[[".$matches[0]."]]";
805 return $this->mIWTransData
[(int)$matches[0]];
809 * Replace special strings like "ISBN xxx" and "RFC xxx" with
810 * magic external links.
814 function &doMagicLinks( &$text ) {
815 $text = $this->magicISBN( $text );
816 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
817 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
822 * Parse ^^ tokens and return html
826 function doExponent( $text ) {
827 $fname = 'Parser::doExponent';
828 wfProfileIn( $fname );
829 $text = preg_replace('/\^\^(.*?)\^\^/','<small><sup>\\1</sup></small>', $text);
830 wfProfileOut( $fname );
835 * Parse headers and return html
839 function doHeadings( $text ) {
840 $fname = 'Parser::doHeadings';
841 wfProfileIn( $fname );
842 for ( $i = 6; $i >= 1; --$i ) {
843 $h = substr( '======', 0, $i );
844 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
845 "<h{$i}>\\1</h{$i}>\\2", $text );
847 wfProfileOut( $fname );
852 * Replace single quotes with HTML markup
854 * @return string the altered text
856 function doAllQuotes( $text ) {
857 $fname = 'Parser::doAllQuotes';
858 wfProfileIn( $fname );
860 $lines = explode( "\n", $text );
861 foreach ( $lines as $line ) {
862 $outtext .= $this->doQuotes ( $line ) . "\n";
864 $outtext = substr($outtext, 0,-1);
865 wfProfileOut( $fname );
870 * Helper function for doAllQuotes()
873 function doQuotes( $text ) {
874 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
875 if ( count( $arr ) == 1 )
879 # First, do some preliminary work. This may shift some apostrophes from
880 # being mark-up to being text. It also counts the number of occurrences
881 # of bold and italics mark-ups.
885 foreach ( $arr as $r )
887 if ( ( $i %
2 ) == 1 )
889 # If there are ever four apostrophes, assume the first is supposed to
890 # be text, and the remaining three constitute mark-up for bold text.
891 if ( strlen( $arr[$i] ) == 4 )
896 # If there are more than 5 apostrophes in a row, assume they're all
897 # text except for the last 5.
898 else if ( strlen( $arr[$i] ) > 5 )
900 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
903 # Count the number of occurrences of bold and italics mark-ups.
904 # We are not counting sequences of five apostrophes.
905 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
906 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
907 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
912 # If there is an odd number of both bold and italics, it is likely
913 # that one of the bold ones was meant to be an apostrophe followed
914 # by italics. Which one we cannot know for certain, but it is more
915 # likely to be one that has a single-letter word before it.
916 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
919 $firstsingleletterword = -1;
920 $firstmultiletterword = -1;
922 foreach ( $arr as $r )
924 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
926 $x1 = substr ($arr[$i-1], -1);
927 $x2 = substr ($arr[$i-1], -2, 1);
929 if ($firstspace == -1) $firstspace = $i;
930 } else if ($x2 == ' ') {
931 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
933 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
939 # If there is a single-letter word, use it!
940 if ($firstsingleletterword > -1)
942 $arr [ $firstsingleletterword ] = "''";
943 $arr [ $firstsingleletterword-1 ] .= "'";
945 # If not, but there's a multi-letter word, use that one.
946 else if ($firstmultiletterword > -1)
948 $arr [ $firstmultiletterword ] = "''";
949 $arr [ $firstmultiletterword-1 ] .= "'";
951 # ... otherwise use the first one that has neither.
952 # (notice that it is possible for all three to be -1 if, for example,
953 # there is only one pentuple-apostrophe in the line)
954 else if ($firstspace > -1)
956 $arr [ $firstspace ] = "''";
957 $arr [ $firstspace-1 ] .= "'";
961 # Now let's actually convert our apostrophic mush to HTML!
970 if ($state == 'both')
977 if (strlen ($r) == 2)
980 { $output .= '</i>'; $state = ''; }
981 else if ($state == 'bi')
982 { $output .= '</i>'; $state = 'b'; }
983 else if ($state == 'ib')
984 { $output .= '</b></i><b>'; $state = 'b'; }
985 else if ($state == 'both')
986 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
987 else # $state can be 'b' or ''
988 { $output .= '<i>'; $state .= 'i'; }
990 else if (strlen ($r) == 3)
993 { $output .= '</b>'; $state = ''; }
994 else if ($state == 'bi')
995 { $output .= '</i></b><i>'; $state = 'i'; }
996 else if ($state == 'ib')
997 { $output .= '</b>'; $state = 'i'; }
998 else if ($state == 'both')
999 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1000 else # $state can be 'i' or ''
1001 { $output .= '<b>'; $state .= 'b'; }
1003 else if (strlen ($r) == 5)
1006 { $output .= '</b><i>'; $state = 'i'; }
1007 else if ($state == 'i')
1008 { $output .= '</i><b>'; $state = 'b'; }
1009 else if ($state == 'bi')
1010 { $output .= '</i></b>'; $state = ''; }
1011 else if ($state == 'ib')
1012 { $output .= '</b></i>'; $state = ''; }
1013 else if ($state == 'both')
1014 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1015 else # ($state == '')
1016 { $buffer = ''; $state = 'both'; }
1021 # Now close all remaining tags. Notice that the order is important.
1022 if ($state == 'b' ||
$state == 'ib')
1024 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1028 if ($state == 'both')
1029 $output .= '<b><i>'.$buffer.'</i></b>';
1035 * Replace external links
1037 * Note: this is all very hackish and the order of execution matters a lot.
1038 * Make sure to run maintenance/parserTests.php if you change this code.
1042 function replaceExternalLinks( $text ) {
1044 $fname = 'Parser::replaceExternalLinks';
1045 wfProfileIn( $fname );
1047 $sk =& $this->mOptions
->getSkin();
1049 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1051 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1054 while ( $i<count( $bits ) ) {
1056 $protocol = $bits[$i++
];
1057 $text = $bits[$i++
];
1058 $trail = $bits[$i++
];
1060 # The characters '<' and '>' (which were escaped by
1061 # removeHTMLtags()) should not be included in
1062 # URLs, per RFC 2396.
1063 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1064 $text = substr($url, $m2[0][1]) . ' ' . $text;
1065 $url = substr($url, 0, $m2[0][1]);
1068 # If the link text is an image URL, replace it with an <img> tag
1069 # This happened by accident in the original parser, but some people used it extensively
1070 $img = $this->maybeMakeExternalImage( $text );
1071 if ( $img !== false ) {
1077 # Set linktype for CSS - if URL==text, link is essentially free
1078 $linktype = ($text == $url) ?
'free' : 'text';
1080 # No link text, e.g. [http://domain.tld/some.link]
1081 if ( $text == '' ) {
1082 # Autonumber if allowed
1083 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1084 $text = '[' . ++
$this->mAutonumber
. ']';
1085 $linktype = 'autonumber';
1087 # Otherwise just use the URL
1088 $text = htmlspecialchars( $url );
1092 # Have link text, e.g. [http://domain.tld/some.link text]s
1094 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1097 $text = $wgContLang->markNoConversion($text);
1099 # Replace & from obsolete syntax with &.
1100 # All HTML entities will be escaped by makeExternalLink()
1101 # or maybeMakeExternalImage()
1102 $url = str_replace( '&', '&', $url );
1104 # Process the trail (i.e. everything after this link up until start of the next link),
1105 # replacing any non-bracketed links
1106 $trail = $this->replaceFreeExternalLinks( $trail );
1109 # Use the encoded URL
1110 # This means that users can paste URLs directly into the text
1111 # Funny characters like ö aren't valid in URLs anyway
1112 # This was changed in August 2004
1113 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1116 wfProfileOut( $fname );
1121 * Replace anything that looks like a URL with a link
1124 function replaceFreeExternalLinks( $text ) {
1125 global $wgUrlProtocols;
1127 $fname = 'Parser::replaceFreeExternalLinks';
1128 wfProfileIn( $fname );
1130 $bits = preg_split( '/(\b(?:'.$wgUrlProtocols.'))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1131 $s = array_shift( $bits );
1134 $sk =& $this->mOptions
->getSkin();
1136 while ( $i < count( $bits ) ){
1137 $protocol = $bits[$i++
];
1138 $remainder = $bits[$i++
];
1140 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1141 # Found some characters after the protocol that look promising
1142 $url = $protocol . $m[1];
1145 # The characters '<' and '>' (which were escaped by
1146 # removeHTMLtags()) should not be included in
1147 # URLs, per RFC 2396.
1148 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1149 $trail = substr($url, $m2[0][1]) . $trail;
1150 $url = substr($url, 0, $m2[0][1]);
1153 # Move trailing punctuation to $trail
1155 # If there is no left bracket, then consider right brackets fair game too
1156 if ( strpos( $url, '(' ) === false ) {
1160 $numSepChars = strspn( strrev( $url ), $sep );
1161 if ( $numSepChars ) {
1162 $trail = substr( $url, -$numSepChars ) . $trail;
1163 $url = substr( $url, 0, -$numSepChars );
1166 # Replace & from obsolete syntax with &.
1167 # All HTML entities will be escaped by makeExternalLink()
1168 # or maybeMakeExternalImage()
1169 $url = str_replace( '&', '&', $url );
1171 # Is this an external image?
1172 $text = $this->maybeMakeExternalImage( $url );
1173 if ( $text === false ) {
1174 # Not an image, make a link
1175 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1177 $s .= $text . $trail;
1179 $s .= $protocol . $remainder;
1182 wfProfileOut( $fname );
1187 * make an image if it's allowed
1190 function maybeMakeExternalImage( $url ) {
1191 $sk =& $this->mOptions
->getSkin();
1193 if ( $this->mOptions
->getAllowExternalImages() ) {
1194 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1196 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1203 * Process [[ ]] wikilinks
1207 function replaceInternalLinks( $s ) {
1208 global $wgContLang, $wgLinkCache, $wgUrlProtocols;
1209 static $fname = 'Parser::replaceInternalLinks' ;
1211 wfProfileIn( $fname );
1213 wfProfileIn( $fname.'-setup' );
1215 # the % is needed to support urlencoded titles as well
1216 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1218 $sk =& $this->mOptions
->getSkin();
1220 #split the entire text string on occurences of [[
1221 $a = explode( '[[', ' ' . $s );
1222 #get the first element (all text up to first [[), and remove the space we added
1223 $s = array_shift( $a );
1224 $s = substr( $s, 1 );
1226 # Match a link having the form [[namespace:link|alternate]]trail
1228 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1229 # Match cases where there is no "]]", which might still be images
1230 static $e1_img = FALSE;
1231 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1232 # Match the end of a line for a word that's not followed by whitespace,
1233 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1234 $e2 = wfMsgForContent( 'linkprefix' );
1236 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1238 if( is_null( $this->mTitle
) ) {
1239 wfDebugDieBacktrace( 'nooo' );
1241 $nottalk = !$this->mTitle
->isTalkPage();
1243 if ( $useLinkPrefixExtension ) {
1244 if ( preg_match( $e2, $s, $m ) ) {
1245 $first_prefix = $m[2];
1247 $first_prefix = false;
1253 $selflink = $this->mTitle
->getPrefixedText();
1254 wfProfileOut( $fname.'-setup' );
1256 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1257 $useSubpages = $this->areSubpagesAllowed();
1259 # Loop for each link
1260 for ($k = 0; isset( $a[$k] ); $k++
) {
1262 if ( $useLinkPrefixExtension ) {
1263 wfProfileIn( $fname.'-prefixhandling' );
1264 if ( preg_match( $e2, $s, $m ) ) {
1272 $prefix = $first_prefix;
1273 $first_prefix = false;
1275 wfProfileOut( $fname.'-prefixhandling' );
1278 $might_be_img = false;
1280 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1282 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1283 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1284 # the real problem is with the $e1 regex
1287 # Still some problems for cases where the ] is meant to be outside punctuation,
1288 # and no image is in sight. See bug 2095.
1290 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1291 $text .= ']'; # so that replaceExternalLinks($text) works later
1294 # fix up urlencoded title texts
1295 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1297 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1298 $might_be_img = true;
1300 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1302 } else { # Invalid form; output directly
1303 $s .= $prefix . '[[' . $line ;
1307 # Don't allow internal links to pages containing
1308 # PROTO: where PROTO is a valid URL protocol; these
1309 # should be external links.
1310 if (preg_match('/^(\b(?:'.$wgUrlProtocols.'))/', $m[1])) {
1311 $s .= $prefix . '[[' . $line ;
1315 # Make subpage if necessary
1316 if( $useSubpages ) {
1317 $link = $this->maybeDoSubpageLink( $m[1], $text );
1322 $noforce = (substr($m[1], 0, 1) != ':');
1324 # Strip off leading ':'
1325 $link = substr($link, 1);
1328 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1330 $s .= $prefix . '[[' . $line;
1334 #check other language variants of the link
1335 #if the article does not exist
1336 if( $checkVariantLink
1337 && $nt->getArticleID() == 0 ) {
1338 $wgContLang->findVariantLink($link, $nt);
1341 $ns = $nt->getNamespace();
1342 $iw = $nt->getInterWiki();
1344 if ($might_be_img) { # if this is actually an invalid link
1345 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1347 while (isset ($a[$k+
1]) ) {
1348 #look at the next 'line' to see if we can close it there
1349 $spliced = array_splice( $a, $k +
1, 1 );
1350 $next_line = array_shift( $spliced );
1351 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1352 # the first ]] closes the inner link, the second the image
1354 $text .= '[[' . $m[1];
1357 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1358 #if there's exactly one ]] that's fine, we'll keep looking
1359 $text .= '[[' . $m[0];
1361 #if $next_line is invalid too, we need look no further
1362 $text .= '[[' . $next_line;
1367 # we couldn't find the end of this imageLink, so output it raw
1368 #but don't ignore what might be perfectly normal links in the text we've examined
1369 $text = $this->replaceInternalLinks($text);
1370 $s .= $prefix . '[[' . $link . '|' . $text;
1371 # note: no $trail, because without an end, there *is* no trail
1374 } else { #it's not an image, so output it raw
1375 $s .= $prefix . '[[' . $link . '|' . $text;
1376 # note: no $trail, because without an end, there *is* no trail
1381 $wasblank = ( '' == $text );
1382 if( $wasblank ) $text = $link;
1385 # Link not escaped by : , create the various objects
1389 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1390 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1391 $s = rtrim($s . "\n");
1392 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1396 if ( $ns == NS_IMAGE
) {
1397 wfProfileIn( "$fname-image" );
1398 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1399 # recursively parse links inside the image caption
1400 # actually, this will parse them in any other parameters, too,
1401 # but it might be hard to fix that, and it doesn't matter ATM
1402 $text = $this->replaceExternalLinks($text);
1403 $text = $this->replaceInternalLinks($text);
1405 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1406 $s .= $prefix . preg_replace("/\b($wgUrlProtocols)/", UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1407 $wgLinkCache->addImageLinkObj( $nt );
1409 wfProfileOut( "$fname-image" );
1412 wfProfileOut( "$fname-image" );
1416 if ( $ns == NS_CATEGORY
) {
1417 wfProfileIn( "$fname-category" );
1418 $t = $wgContLang->convertHtml( $nt->getText() );
1419 $s = rtrim($s . "\n"); # bug 87
1421 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1422 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1423 $wgLinkCache->resume();
1426 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1427 $sortkey = $this->mTitle
->getText();
1429 $sortkey = $this->mTitle
->getPrefixedText();
1434 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1435 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1436 $this->mOutput
->addCategoryLink( $t );
1439 * Strip the whitespace Category links produce, see bug 87
1440 * @todo We might want to use trim($tmp, "\n") here.
1442 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1444 wfProfileOut( "$fname-category" );
1449 if( ( $nt->getPrefixedText() === $selflink ) &&
1450 ( $nt->getFragment() === '' ) ) {
1451 # Self-links are handled specially; generally de-link and change to bold.
1452 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1456 # Special and Media are pseudo-namespaces; no pages actually exist in them
1457 if( $ns == NS_MEDIA
) {
1458 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1459 $wgLinkCache->addImageLinkObj( $nt );
1461 } elseif( $ns == NS_SPECIAL
) {
1462 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1465 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1467 wfProfileOut( $fname );
1472 * Make a link placeholder. The text returned can be later resolved to a real link with
1473 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1474 * parsing of interwiki links, and secondly to allow all extistence checks and
1475 * article length checks (for stub links) to be bundled into a single query.
1478 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1479 if ( ! is_object($nt) ) {
1481 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1483 # Separate the link trail from the rest of the link
1484 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1486 if ( $nt->isExternal() ) {
1487 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1488 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1489 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1491 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1492 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1493 $this->mLinkHolders
['queries'][] = $query;
1494 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1495 $this->mLinkHolders
['titles'][] = $nt;
1497 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1504 * Return true if subpage links should be expanded on this page.
1507 function areSubpagesAllowed() {
1508 # Some namespaces don't allow subpages
1509 global $wgNamespacesWithSubpages;
1510 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1514 * Handle link to subpage if necessary
1515 * @param string $target the source of the link
1516 * @param string &$text the link text, modified as necessary
1517 * @return string the full name of the link
1520 function maybeDoSubpageLink($target, &$text) {
1523 # :Foobar -- override special treatment of prefix (images, language links)
1524 # /Foobar -- convert to CurrentPage/Foobar
1525 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1526 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1527 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1529 $fname = 'Parser::maybeDoSubpageLink';
1530 wfProfileIn( $fname );
1531 $ret = $target; # default return value is no change
1533 # Some namespaces don't allow subpages,
1534 # so only perform processing if subpages are allowed
1535 if( $this->areSubpagesAllowed() ) {
1536 # Look at the first character
1537 if( $target != '' && $target{0} == '/' ) {
1538 # / at end means we don't want the slash to be shown
1539 if( substr( $target, -1, 1 ) == '/' ) {
1540 $target = substr( $target, 1, -1 );
1543 $noslash = substr( $target, 1 );
1546 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1547 if( '' === $text ) {
1549 } # this might be changed for ugliness reasons
1551 # check for .. subpage backlinks
1553 $nodotdot = $target;
1554 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1556 $nodotdot = substr( $nodotdot, 3 );
1558 if($dotdotcount > 0) {
1559 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1560 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1561 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1562 # / at the end means don't show full path
1563 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1564 $nodotdot = substr( $nodotdot, 0, -1 );
1565 if( '' === $text ) {
1569 $nodotdot = trim( $nodotdot );
1570 if( $nodotdot != '' ) {
1571 $ret .= '/' . $nodotdot;
1578 wfProfileOut( $fname );
1583 * Used by doBlockLevels()
1586 /* private */ function closeParagraph() {
1588 if ( '' != $this->mLastSection
) {
1589 $result = '</' . $this->mLastSection
. ">\n";
1591 $this->mInPre
= false;
1592 $this->mLastSection
= '';
1595 # getCommon() returns the length of the longest common substring
1596 # of both arguments, starting at the beginning of both.
1598 /* private */ function getCommon( $st1, $st2 ) {
1599 $fl = strlen( $st1 );
1600 $shorter = strlen( $st2 );
1601 if ( $fl < $shorter ) { $shorter = $fl; }
1603 for ( $i = 0; $i < $shorter; ++
$i ) {
1604 if ( $st1{$i} != $st2{$i} ) { break; }
1608 # These next three functions open, continue, and close the list
1609 # element appropriate to the prefix character passed into them.
1611 /* private */ function openList( $char ) {
1612 $result = $this->closeParagraph();
1614 if ( '*' == $char ) { $result .= '<ul><li>'; }
1615 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1616 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1617 else if ( ';' == $char ) {
1618 $result .= '<dl><dt>';
1619 $this->mDTopen
= true;
1621 else { $result = '<!-- ERR 1 -->'; }
1626 /* private */ function nextItem( $char ) {
1627 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1628 else if ( ':' == $char ||
';' == $char ) {
1630 if ( $this->mDTopen
) { $close = '</dt>'; }
1631 if ( ';' == $char ) {
1632 $this->mDTopen
= true;
1633 return $close . '<dt>';
1635 $this->mDTopen
= false;
1636 return $close . '<dd>';
1639 return '<!-- ERR 2 -->';
1642 /* private */ function closeList( $char ) {
1643 if ( '*' == $char ) { $text = '</li></ul>'; }
1644 else if ( '#' == $char ) { $text = '</li></ol>'; }
1645 else if ( ':' == $char ) {
1646 if ( $this->mDTopen
) {
1647 $this->mDTopen
= false;
1648 $text = '</dt></dl>';
1650 $text = '</dd></dl>';
1653 else { return '<!-- ERR 3 -->'; }
1659 * Make lists from lines starting with ':', '*', '#', etc.
1662 * @return string the lists rendered as HTML
1664 function doBlockLevels( $text, $linestart ) {
1665 $fname = 'Parser::doBlockLevels';
1666 wfProfileIn( $fname );
1668 # Parsing through the text line by line. The main thing
1669 # happening here is handling of block-level elements p, pre,
1670 # and making lists from lines starting with * # : etc.
1672 $textLines = explode( "\n", $text );
1674 $lastPrefix = $output = '';
1675 $this->mDTopen
= $inBlockElem = false;
1677 $paragraphStack = false;
1679 if ( !$linestart ) {
1680 $output .= array_shift( $textLines );
1682 foreach ( $textLines as $oLine ) {
1683 $lastPrefixLength = strlen( $lastPrefix );
1684 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1685 $preOpenMatch = preg_match('/<pre/i', $oLine );
1686 if ( !$this->mInPre
) {
1687 # Multiple prefixes may abut each other for nested lists.
1688 $prefixLength = strspn( $oLine, '*#:;' );
1689 $pref = substr( $oLine, 0, $prefixLength );
1692 $pref2 = str_replace( ';', ':', $pref );
1693 $t = substr( $oLine, $prefixLength );
1694 $this->mInPre
= !empty($preOpenMatch);
1696 # Don't interpret any other prefixes in preformatted text
1698 $pref = $pref2 = '';
1703 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1704 # Same as the last item, so no need to deal with nesting or opening stuff
1705 $output .= $this->nextItem( substr( $pref, -1 ) );
1706 $paragraphStack = false;
1708 if ( substr( $pref, -1 ) == ';') {
1709 # The one nasty exception: definition lists work like this:
1710 # ; title : definition text
1711 # So we check for : in the remainder text to split up the
1712 # title and definition, without b0rking links.
1714 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1716 $output .= $term . $this->nextItem( ':' );
1719 } elseif( $prefixLength ||
$lastPrefixLength ) {
1720 # Either open or close a level...
1721 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1722 $paragraphStack = false;
1724 while( $commonPrefixLength < $lastPrefixLength ) {
1725 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1726 --$lastPrefixLength;
1728 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1729 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1731 while ( $prefixLength > $commonPrefixLength ) {
1732 $char = substr( $pref, $commonPrefixLength, 1 );
1733 $output .= $this->openList( $char );
1735 if ( ';' == $char ) {
1736 # FIXME: This is dupe of code above
1737 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1739 $output .= $term . $this->nextItem( ':' );
1742 ++
$commonPrefixLength;
1744 $lastPrefix = $pref2;
1746 if( 0 == $prefixLength ) {
1747 wfProfileIn( "$fname-paragraph" );
1748 # No prefix (not in list)--go to paragraph mode
1749 $uniq_prefix = UNIQ_PREFIX
;
1750 // XXX: use a stack for nestable elements like span, table and div
1751 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1752 $closematch = preg_match(
1753 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1754 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1755 if ( $openmatch or $closematch ) {
1756 $paragraphStack = false;
1757 $output .= $this->closeParagraph();
1758 if ( $preOpenMatch and !$preCloseMatch ) {
1759 $this->mInPre
= true;
1761 if ( $closematch ) {
1762 $inBlockElem = false;
1764 $inBlockElem = true;
1766 } else if ( !$inBlockElem && !$this->mInPre
) {
1767 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1769 if ($this->mLastSection
!= 'pre') {
1770 $paragraphStack = false;
1771 $output .= $this->closeParagraph().'<pre>';
1772 $this->mLastSection
= 'pre';
1774 $t = substr( $t, 1 );
1777 if ( '' == trim($t) ) {
1778 if ( $paragraphStack ) {
1779 $output .= $paragraphStack.'<br />';
1780 $paragraphStack = false;
1781 $this->mLastSection
= 'p';
1783 if ($this->mLastSection
!= 'p' ) {
1784 $output .= $this->closeParagraph();
1785 $this->mLastSection
= '';
1786 $paragraphStack = '<p>';
1788 $paragraphStack = '</p><p>';
1792 if ( $paragraphStack ) {
1793 $output .= $paragraphStack;
1794 $paragraphStack = false;
1795 $this->mLastSection
= 'p';
1796 } else if ($this->mLastSection
!= 'p') {
1797 $output .= $this->closeParagraph().'<p>';
1798 $this->mLastSection
= 'p';
1803 wfProfileOut( "$fname-paragraph" );
1805 // somewhere above we forget to get out of pre block (bug 785)
1806 if($preCloseMatch && $this->mInPre
) {
1807 $this->mInPre
= false;
1809 if ($paragraphStack === false) {
1813 while ( $prefixLength ) {
1814 $output .= $this->closeList( $pref2{$prefixLength-1} );
1817 if ( '' != $this->mLastSection
) {
1818 $output .= '</' . $this->mLastSection
. '>';
1819 $this->mLastSection
= '';
1822 wfProfileOut( $fname );
1827 * Split up a string on ':', ignoring any occurences inside
1828 * <a>..</a> or <span>...</span>
1829 * @param string $str the string to split
1830 * @param string &$before set to everything before the ':'
1831 * @param string &$after set to everything after the ':'
1832 * return string the position of the ':', or false if none found
1834 function findColonNoLinks($str, &$before, &$after) {
1835 # I wonder if we should make this count all tags, not just <a>
1836 # and <span>. That would prevent us from matching a ':' that
1837 # comes in the middle of italics other such formatting....
1839 $fname = 'Parser::findColonNoLinks';
1840 wfProfileIn( $fname );
1843 $colon = strpos($str, ':', $pos);
1845 if ($colon !== false) {
1846 $before = substr($str, 0, $colon);
1847 $after = substr($str, $colon +
1);
1849 # Skip any ':' within <a> or <span> pairs
1850 $a = substr_count($before, '<a');
1851 $s = substr_count($before, '<span');
1852 $ca = substr_count($before, '</a>');
1853 $cs = substr_count($before, '</span>');
1855 if ($a <= $ca and $s <= $cs) {
1856 # Tags are balanced before ':'; ok
1861 } while ($colon !== false);
1862 wfProfileOut( $fname );
1867 * Return value of a magic variable (like PAGENAME)
1871 function getVariableValue( $index ) {
1872 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1875 * Some of these require message or data lookups and can be
1876 * expensive to check many times.
1878 static $varCache = array();
1879 if( isset( $varCache[$index] ) ) return $varCache[$index];
1882 case MAG_CURRENTMONTH
:
1883 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1884 case MAG_CURRENTMONTHNAME
:
1885 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1886 case MAG_CURRENTMONTHNAMEGEN
:
1887 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1888 case MAG_CURRENTMONTHABBREV
:
1889 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1890 case MAG_CURRENTDAY
:
1891 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1893 return $this->mTitle
->getText();
1895 return $this->mTitle
->getPartialURL();
1896 case MAG_REVISIONID
:
1897 return $wgArticle->getRevIdFetched();
1899 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1900 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1901 case MAG_CURRENTDAYNAME
:
1902 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1903 case MAG_CURRENTYEAR
:
1904 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1905 case MAG_CURRENTTIME
:
1906 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1907 case MAG_CURRENTWEEK
:
1908 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1909 case MAG_CURRENTDOW
:
1910 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1911 case MAG_NUMBEROFARTICLES
:
1912 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1913 case MAG_NUMBEROFFILES
:
1914 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1919 case MAG_SERVERNAME
:
1920 return $wgServerName;
1921 case MAG_SCRIPTPATH
:
1922 return $wgScriptPath;
1929 * initialise the magic variables (like CURRENTMONTHNAME)
1933 function initialiseVariables() {
1934 $fname = 'Parser::initialiseVariables';
1935 wfProfileIn( $fname );
1936 global $wgVariableIDs;
1937 $this->mVariables
= array();
1938 foreach ( $wgVariableIDs as $id ) {
1939 $mw =& MagicWord
::get( $id );
1940 $mw->addToArray( $this->mVariables
, $id );
1942 wfProfileOut( $fname );
1946 * Replace magic variables, templates, and template arguments
1947 * with the appropriate text. Templates are substituted recursively,
1948 * taking care to avoid infinite loops.
1950 * Note that the substitution depends on value of $mOutputType:
1951 * OT_WIKI: only {{subst:}} templates
1952 * OT_MSG: only magic variables
1953 * OT_HTML: all templates and magic variables
1955 * @param string $tex The text to transform
1956 * @param array $args Key-value pairs representing template parameters to substitute
1959 function replaceVariables( $text, $args = array() ) {
1961 # Prevent too big inclusions
1962 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1966 $fname = 'Parser::replaceVariables';
1967 wfProfileIn( $fname );
1969 $titleChars = Title
::legalChars();
1971 # This function is called recursively. To keep track of arguments we need a stack:
1972 array_push( $this->mArgStack
, $args );
1974 # Variable substitution
1975 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1977 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1978 # Argument substitution
1979 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1981 # Template substitution
1982 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1983 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1985 array_pop( $this->mArgStack
);
1987 wfProfileOut( $fname );
1992 * Replace magic variables
1995 function variableSubstitution( $matches ) {
1996 $fname = 'parser::variableSubstitution';
1997 $varname = $matches[1];
1998 wfProfileIn( $fname );
1999 if ( !$this->mVariables
) {
2000 $this->initialiseVariables();
2003 if ( $this->mOutputType
== OT_WIKI
) {
2004 # Do only magic variables prefixed by SUBST
2005 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2006 if (!$mwSubst->matchStartAndRemove( $varname ))
2008 # Note that if we don't substitute the variable below,
2009 # we don't remove the {{subst:}} magic word, in case
2010 # it is a template rather than a magic variable.
2012 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2013 $id = $this->mVariables
[$varname];
2014 $text = $this->getVariableValue( $id );
2015 $this->mOutput
->mContainsOldMagic
= true;
2017 $text = $matches[0];
2019 wfProfileOut( $fname );
2023 # Split template arguments
2024 function getTemplateArgs( $argsString ) {
2025 if ( $argsString === '' ) {
2029 $args = explode( '|', substr( $argsString, 1 ) );
2031 # If any of the arguments contains a '[[' but no ']]', it needs to be
2032 # merged with the next arg because the '|' character between belongs
2033 # to the link syntax and not the template parameter syntax.
2034 $argc = count($args);
2036 for ( $i = 0; $i < $argc-1; $i++
) {
2037 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2038 $args[$i] .= '|'.$args[$i+
1];
2039 array_splice($args, $i+
1, 1);
2049 * Return the text of a template, after recursively
2050 * replacing any variables or templates within the template.
2052 * @param array $matches The parts of the template
2053 * $matches[1]: the title, i.e. the part before the |
2054 * $matches[2]: the parameters (including a leading |), if any
2055 * @return string the text of the template
2058 function braceSubstitution( $matches ) {
2059 global $wgLinkCache, $wgContLang;
2060 $fname = 'Parser::braceSubstitution';
2061 wfProfileIn( $fname );
2069 # Need to know if the template comes at the start of a line,
2070 # to treat the beginning of the template like the beginning
2071 # of a line for tables and block-level elements.
2072 $linestart = $matches[1];
2074 # $part1 is the bit before the first |, and must contain only title characters
2075 # $args is a list of arguments, starting from index 0, not including $part1
2077 $part1 = $matches[2];
2078 # If the third subpattern matched anything, it will start with |
2080 $args = $this->getTemplateArgs($matches[3]);
2081 $argc = count( $args );
2083 # Don't parse {{{}}} because that's only for template arguments
2084 if ( $linestart === '{' ) {
2085 $text = $matches[0];
2092 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2093 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2094 # One of two possibilities is true:
2095 # 1) Found SUBST but not in the PST phase
2096 # 2) Didn't find SUBST and in the PST phase
2097 # In either case, return without further processing
2098 $text = $matches[0];
2104 # MSG, MSGNW and INT
2107 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2108 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2111 # Remove obsolete MSG:
2112 $mwMsg =& MagicWord
::get( MAG_MSG
);
2113 $mwMsg->matchStartAndRemove( $part1 );
2116 # Check if it is an internal message
2117 $mwInt =& MagicWord
::get( MAG_INT
);
2118 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2119 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2120 $text = $linestart . wfMsgReal( $part1, $args, true );
2128 # Check for NS: (namespace expansion)
2129 $mwNs = MagicWord
::get( MAG_NS
);
2130 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2131 if ( intval( $part1 ) ) {
2132 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2135 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2136 if ( !is_null( $index ) ) {
2137 $text = $linestart . $wgContLang->getNsText( $index );
2144 # LOCALURL and FULLURL
2146 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2147 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2148 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2149 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2152 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2153 $func = 'getLocalURL';
2154 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2155 $func = 'escapeLocalURL';
2156 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2157 $func = 'getFullURL';
2158 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2159 $func = 'escapeFullURL';
2164 if ( $func !== false ) {
2165 $title = Title
::newFromText( $part1 );
2166 if ( !is_null( $title ) ) {
2168 $text = $linestart . $title->$func( $args[0] );
2170 $text = $linestart . $title->$func();
2178 if ( !$found && $argc == 1 ) {
2179 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2180 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2181 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2187 if ( !$found && $argc >= 2 ) {
2188 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2189 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2190 if ($argc==2) {$args[2]=$args[1];}
2191 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2196 # Template table test
2198 # Did we encounter this template already? If yes, it is in the cache
2199 # and we need to check for loops.
2200 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2203 # Infinite loop test
2204 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2207 $text = $linestart .
2209 '<!-- WARNING: template loop detected -->';
2210 wfDebug( "$fname: template loop broken at '$part1'\n" );
2212 # set $text to cached message.
2213 $text = $linestart . $this->mTemplates
[$part1];
2217 # Load from database
2218 $replaceHeadings = false;
2220 $lastPathLevel = $this->mTemplatePath
;
2223 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2224 if ($subpage !== '') {
2225 $ns = $this->mTitle
->getNamespace();
2227 $title = Title
::newFromText( $part1, $ns );
2230 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2231 if ($interwiki != '' && $title->isTrans()) {
2232 return $this->scarytransclude($title, $interwiki);
2236 if ( !is_null( $title ) && !$title->isExternal() ) {
2237 # Check for excessive inclusion
2238 $dbk = $title->getPrefixedDBkey();
2239 if ( $this->incrementIncludeCount( $dbk ) ) {
2240 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2241 # Capture special page output
2242 $text = SpecialPage
::capturePath( $title );
2243 if ( is_string( $text ) ) {
2247 $this->disableCache();
2250 $article = new Article( $title );
2251 $articleContent = $article->fetchContent(0, false);
2252 if ( $articleContent !== false ) {
2254 $text = $articleContent;
2255 $replaceHeadings = true;
2260 # If the title is valid but undisplayable, make a link to it
2261 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2262 $text = '[['.$title->getPrefixedText().']]';
2266 # Template cache array insertion
2268 $this->mTemplates
[$part1] = $text;
2269 $text = $linestart . $text;
2274 # Recursive parsing, escaping and link table handling
2275 # Only for HTML output
2276 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2277 $text = wfEscapeWikiText( $text );
2278 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2279 # Clean up argument array
2280 $assocArgs = array();
2282 foreach( $args as $arg ) {
2283 $eqpos = strpos( $arg, '=' );
2284 if ( $eqpos === false ) {
2285 $assocArgs[$index++
] = $arg;
2287 $name = trim( substr( $arg, 0, $eqpos ) );
2288 $value = trim( substr( $arg, $eqpos+
1 ) );
2289 if ( $value === false ) {
2292 if ( $name !== false ) {
2293 $assocArgs[$name] = $value;
2298 # Add a new element to the templace recursion path
2299 $this->mTemplatePath
[$part1] = 1;
2301 if( $this->mOutputType
== OT_HTML
) {
2302 # Remove <noinclude> sections and <includeonly> tags
2303 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2304 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2305 # Strip <nowiki>, <pre>, etc.
2306 $this->mCurrentParams
= $assocArgs;
2307 $text = $this->strip( $text, $this->mStripState
);
2308 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2310 $text = $this->replaceVariables( $text, $assocArgs );
2312 # Resume the link cache and register the inclusion as a link
2313 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2314 $wgLinkCache->addLinkObj( $title );
2317 # If the template begins with a table or block-level
2318 # element, it should be treated as beginning a new line.
2319 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2320 $text = "\n" . $text;
2323 # Prune lower levels off the recursion check path
2324 $this->mTemplatePath
= $lastPathLevel;
2327 wfProfileOut( $fname );
2331 # Replace raw HTML by a placeholder
2332 # Add a blank line preceding, to prevent it from mucking up
2333 # immediately preceding headings
2334 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2336 # replace ==section headers==
2337 # XXX this needs to go away once we have a better parser.
2338 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2339 if( !is_null( $title ) )
2340 $encodedname = base64_encode($title->getPrefixedDBkey());
2342 $encodedname = base64_encode("");
2343 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2344 PREG_SPLIT_DELIM_CAPTURE
);
2347 for( $i = 0; $i < count($m); $i +
= 2 ) {
2349 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2351 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2355 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2356 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2357 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2365 # Prune lower levels off the recursion check path
2366 $this->mTemplatePath
= $lastPathLevel;
2369 wfProfileOut( $fname );
2372 wfProfileOut( $fname );
2378 * Translude an interwiki link.
2380 function scarytransclude($title, $interwiki) {
2381 global $wgEnableScaryTranscluding;
2383 if (!$wgEnableScaryTranscluding)
2384 return wfMsg('scarytranscludedisabled');
2386 $articlename = "Template:" . $title->getDBkey();
2387 $url = str_replace('$1', urlencode($articlename), $interwiki);
2388 if (strlen($url) > 255)
2389 return wfMsg('scarytranscludetoolong');
2390 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2391 $this->mIWTransData
[] = $text;
2392 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2395 function fetchScaryTemplateMaybeFromCache($url) {
2396 $dbr =& wfGetDB(DB_SLAVE
);
2397 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2398 array('tc_url' => $url));
2400 $time = $obj->tc_time
;
2401 $text = $obj->tc_contents
;
2402 if ($time && $time < (time() +
(60*60))) {
2407 $text = wfGetHTTP($url . '?action=render');
2409 return wfMsg('scarytranscludefailed', $url);
2411 $dbw =& wfGetDB(DB_MASTER
);
2412 $dbw->replace('transcache', array(), array(
2414 'tc_time' => time(),
2415 'tc_contents' => $text));
2421 * Triple brace replacement -- used for template arguments
2424 function argSubstitution( $matches ) {
2425 $arg = trim( $matches[1] );
2426 $text = $matches[0];
2427 $inputArgs = end( $this->mArgStack
);
2429 if ( array_key_exists( $arg, $inputArgs ) ) {
2430 $text = $inputArgs[$arg];
2437 * Returns true if the function is allowed to include this entity
2440 function incrementIncludeCount( $dbk ) {
2441 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2442 $this->mIncludeCount
[$dbk] = 0;
2444 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2452 * This function accomplishes several tasks:
2453 * 1) Auto-number headings if that option is enabled
2454 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2455 * 3) Add a Table of contents on the top for users who have enabled the option
2456 * 4) Auto-anchor headings
2458 * It loops through all headlines, collects the necessary data, then splits up the
2459 * string and re-inserts the newly formatted headlines.
2461 * @param string $text
2462 * @param boolean $isMain
2465 function formatHeadings( $text, $isMain=true ) {
2466 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2468 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2470 $forceTocHere = false;
2471 if( !$this->mTitle
->userCanEdit() ) {
2474 $showEditLink = $this->mOptions
->getEditSection();
2477 # Inhibit editsection links if requested in the page
2478 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2479 if( $esw->matchAndRemove( $text ) ) {
2482 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2484 $mw =& MagicWord
::get( MAG_NOTOC
);
2485 if( $mw->matchAndRemove( $text ) ) {
2489 # Get all headlines for numbering them and adding funky stuff like [edit]
2490 # links - this is for later, but we need the number of headlines right now
2491 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2493 # if there are fewer than 4 headlines in the article, do not show TOC
2494 if( $numMatches < 4 ) {
2498 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2499 # override above conditions and always show TOC at that place
2501 $mw =& MagicWord
::get( MAG_TOC
);
2502 if($mw->match( $text ) ) {
2504 $forceTocHere = true;
2506 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2507 # override above conditions and always show TOC above first header
2508 $mw =& MagicWord
::get( MAG_FORCETOC
);
2509 if ($mw->matchAndRemove( $text ) ) {
2514 # Never ever show TOC if no headers
2515 if( $numMatches < 1 ) {
2519 # We need this to perform operations on the HTML
2520 $sk =& $this->mOptions
->getSkin();
2524 $sectionCount = 0; # headlineCount excluding template sections
2526 # Ugh .. the TOC should have neat indentation levels which can be
2527 # passed to the skin functions. These are determined here
2531 $sublevelCount = array();
2532 $levelCount = array();
2539 foreach( $matches[3] as $headline ) {
2541 $templatetitle = '';
2542 $templatesection = 0;
2545 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2547 $templatetitle = base64_decode($mat[1]);
2548 $templatesection = 1 +
(int)base64_decode($mat[2]);
2549 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2553 $prevlevel = $level;
2554 $prevtoclevel = $toclevel;
2556 $level = $matches[1][$headlineCount];
2558 if( $doNumberHeadings ||
$doShowToc ) {
2560 if ( $level > $prevlevel ) {
2561 # Increase TOC level
2563 $sublevelCount[$toclevel] = 0;
2564 $toc .= $sk->tocIndent();
2566 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2567 # Decrease TOC level, find level to jump to
2569 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2570 # Can only go down to level 1
2573 for ($i = $toclevel; $i > 0; $i--) {
2574 if ( $levelCount[$i] == $level ) {
2575 # Found last matching level
2579 elseif ( $levelCount[$i] < $level ) {
2580 # Found first matching level below current level
2587 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2590 # No change in level, end TOC line
2591 $toc .= $sk->tocLineEnd();
2594 $levelCount[$toclevel] = $level;
2596 # count number of headlines for each level
2597 @$sublevelCount[$toclevel]++
;
2599 for( $i = 1; $i <= $toclevel; $i++
) {
2600 if( !empty( $sublevelCount[$i] ) ) {
2604 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2610 # The canonized header is a version of the header text safe to use for links
2611 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2612 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2613 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2615 # Remove link placeholders by the link text.
2616 # <!--LINK number-->
2618 # link text with suffix
2619 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2620 "\$this->mLinkHolders['texts'][\$1]",
2621 $canonized_headline );
2622 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2623 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2624 $canonized_headline );
2627 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2628 $tocline = trim( $canonized_headline );
2629 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2630 $replacearray = array(
2634 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2635 $refers[$headlineCount] = $canonized_headline;
2637 # count how many in assoc. array so we can track dupes in anchors
2638 @$refers[$canonized_headline]++
;
2639 $refcount[$headlineCount]=$refers[$canonized_headline];
2641 # Don't number the heading if it is the only one (looks silly)
2642 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2643 # the two are different if the line contains a link
2644 $headline=$numbering . ' ' . $headline;
2647 # Create the anchor for linking from the TOC to the section
2648 $anchor = $canonized_headline;
2649 if($refcount[$headlineCount] > 1 ) {
2650 $anchor .= '_' . $refcount[$headlineCount];
2652 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2653 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2655 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2656 if ( empty( $head[$headlineCount] ) ) {
2657 $head[$headlineCount] = '';
2660 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2662 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2665 # give headline the correct <h#> tag
2666 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2674 $toc .= $sk->tocUnindent( $toclevel - 1 );
2675 $toc = $sk->tocList( $toc );
2678 # split up and insert constructed headlines
2680 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2683 foreach( $blocks as $block ) {
2684 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2685 # This is the [edit] link that appears for the top block of text when
2686 # section editing is enabled
2688 # Disabled because it broke block formatting
2689 # For example, a bullet point in the top line
2690 # $full .= $sk->editSectionLink(0);
2693 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2694 # Top anchor now in skin
2698 if( !empty( $head[$i] ) ) {
2704 $mw =& MagicWord
::get( MAG_TOC
);
2705 return $mw->replace( $toc, $full );
2712 * Return an HTML link for the "ISBN 123456" text
2715 function magicISBN( $text ) {
2716 $fname = 'Parser::magicISBN';
2717 wfProfileIn( $fname );
2719 $a = split( 'ISBN ', ' '.$text );
2720 if ( count ( $a ) < 2 ) {
2721 wfProfileOut( $fname );
2724 $text = substr( array_shift( $a ), 1);
2725 $valid = '0123456789-Xx';
2727 foreach ( $a as $x ) {
2728 $isbn = $blank = '' ;
2729 while ( ' ' == $x{0} ) {
2731 $x = substr( $x, 1 );
2733 if ( $x == '' ) { # blank isbn
2734 $text .= "ISBN $blank";
2737 while ( strstr( $valid, $x{0} ) != false ) {
2739 $x = substr( $x, 1 );
2741 $num = str_replace( '-', '', $isbn );
2742 $num = str_replace( ' ', '', $num );
2743 $num = str_replace( 'x', 'X', $num );
2746 $text .= "ISBN $blank$x";
2748 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2749 $text .= '<a href="' .
2750 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2751 "\" class=\"internal\">ISBN $isbn</a>";
2755 wfProfileOut( $fname );
2760 * Return an HTML link for the "RFC 1234" text
2763 * @param string $text Text to be processed
2764 * @param string $keyword Magic keyword to use (default RFC)
2765 * @param string $urlmsg Interface message to use (default rfcurl)
2768 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2770 $valid = '0123456789';
2773 $a = split( $keyword, ' '.$text );
2774 if ( count ( $a ) < 2 ) {
2777 $text = substr( array_shift( $a ), 1);
2779 /* Check if keyword is preceed by [[.
2780 * This test is made here cause of the array_shift above
2781 * that prevent the test to be done in the foreach.
2783 if ( substr( $text, -2 ) == '[[' ) {
2787 foreach ( $a as $x ) {
2788 /* token might be empty if we have RFC RFC 1234 */
2796 /** remove and save whitespaces in $blank */
2797 while ( $x{0} == ' ' ) {
2799 $x = substr( $x, 1 );
2802 /** remove and save the rfc number in $id */
2803 while ( strstr( $valid, $x{0} ) != false ) {
2805 $x = substr( $x, 1 );
2809 /* call back stripped spaces*/
2810 $text .= $keyword.$blank.$x;
2811 } elseif( $internal ) {
2813 $text .= $keyword.$id.$x;
2815 /* build the external link*/
2816 $url = wfMsg( $urlmsg, $id);
2817 $sk =& $this->mOptions
->getSkin();
2818 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2819 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2822 /* Check if the next RFC keyword is preceed by [[ */
2823 $internal = ( substr($x,-2) == '[[' );
2829 * Transform wiki markup when saving a page by doing \r\n -> \n
2830 * conversion, substitting signatures, {{subst:}} templates, etc.
2832 * @param string $text the text to transform
2833 * @param Title &$title the Title object for the current article
2834 * @param User &$user the User object describing the current user
2835 * @param ParserOptions $options parsing options
2836 * @param bool $clearState whether to clear the parser state first
2837 * @return string the altered wiki markup
2840 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2841 $this->mOptions
= $options;
2842 $this->mTitle
=& $title;
2843 $this->mOutputType
= OT_WIKI
;
2845 if ( $clearState ) {
2846 $this->clearState();
2849 $stripState = false;
2853 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2854 $text = $this->strip( $text, $stripState, false );
2855 $text = $this->pstPass2( $text, $user );
2856 $text = $this->unstrip( $text, $stripState );
2857 $text = $this->unstripNoWiki( $text, $stripState );
2862 * Pre-save transform helper function
2865 function pstPass2( $text, &$user ) {
2866 global $wgContLang, $wgLocaltimezone;
2868 # Variable replacement
2869 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2870 $text = $this->replaceVariables( $text );
2874 $n = $user->getName();
2875 $k = $user->getOption( 'nickname' );
2876 if ( '' == $k ) { $k = $n; }
2877 if ( isset( $wgLocaltimezone ) ) {
2878 $oldtz = getenv( 'TZ' );
2879 putenv( 'TZ='.$wgLocaltimezone );
2882 /* Note: This is the timestamp saved as hardcoded wikitext to
2883 * the database, we use $wgContLang here in order to give
2884 * everyone the same signiture and use the default one rather
2885 * than the one selected in each users preferences.
2887 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
2888 ' (' . date( 'T' ) . ')';
2889 if ( isset( $wgLocaltimezone ) ) {
2890 putenv( 'TZ='.$oldtz );
2893 if( $user->getOption( 'fancysig' ) ) {
2896 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2898 $text = preg_replace( '/~~~~~/', $d, $text );
2899 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2900 $text = preg_replace( '/~~~/', $sigText, $text );
2902 # Context links: [[|name]] and [[name (context)|]]
2904 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2905 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2906 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2907 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2909 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2910 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2911 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2912 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2914 $t = $this->mTitle
->getText();
2915 if ( preg_match( $conpat, $t, $m ) ) {
2918 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2919 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2920 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2922 if ( '' == $context ) {
2923 $text = preg_replace( $p2, '[[\\1]]', $text );
2925 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2928 # Trim trailing whitespace
2929 # MAG_END (__END__) tag allows for trailing
2930 # whitespace to be deliberately included
2931 $text = rtrim( $text );
2932 $mw =& MagicWord
::get( MAG_END
);
2933 $mw->matchAndRemove( $text );
2939 * Set up some variables which are usually set up in parse()
2940 * so that an external function can call some class members with confidence
2943 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2944 $this->mTitle
=& $title;
2945 $this->mOptions
= $options;
2946 $this->mOutputType
= $outputType;
2947 if ( $clearState ) {
2948 $this->clearState();
2953 * Transform a MediaWiki message by replacing magic variables.
2955 * @param string $text the text to transform
2956 * @param ParserOptions $options options
2957 * @return string the text with variables substituted
2960 function transformMsg( $text, $options ) {
2962 static $executing = false;
2964 # Guard against infinite recursion
2970 $this->mTitle
= $wgTitle;
2971 $this->mOptions
= $options;
2972 $this->mOutputType
= OT_MSG
;
2973 $this->clearState();
2974 $text = $this->replaceVariables( $text );
2981 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2982 * Callback will be called with the text within
2983 * Transform and return the text within
2986 function setHook( $tag, $callback ) {
2987 $oldVal = @$this->mTagHooks
[$tag];
2988 $this->mTagHooks
[$tag] = $callback;
2993 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2994 * Placeholders created in Skin::makeLinkObj()
2995 * Returns an array of links found, indexed by PDBK:
2999 * $options is a bit field, RLH_FOR_UPDATE to select for update
3001 function replaceLinkHolders( &$text, $options = 0 ) {
3002 global $wgUser, $wgLinkCache;
3003 global $wgOutputReplace;
3005 $fname = 'Parser::replaceLinkHolders';
3006 wfProfileIn( $fname );
3010 $sk = $this->mOptions
->getSkin();
3012 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3013 wfProfileIn( $fname.'-check' );
3014 $dbr =& wfGetDB( DB_SLAVE
);
3015 $page = $dbr->tableName( 'page' );
3016 $threshold = $wgUser->getOption('stubthreshold');
3019 asort( $this->mLinkHolders
['namespaces'] );
3023 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3025 $title = $this->mLinkHolders
['titles'][$key];
3027 # Skip invalid entries.
3028 # Result will be ugly, but prevents crash.
3029 if ( is_null( $title ) ) {
3032 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3034 # Check if it's in the link cache already
3035 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3036 $colours[$pdbk] = 1;
3037 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3038 $colours[$pdbk] = 0;
3040 # Not in the link cache, add it to the query
3041 if ( !isset( $current ) ) {
3043 $query = "SELECT page_id, page_namespace, page_title";
3044 if ( $threshold > 0 ) {
3045 $query .= ', page_len, page_is_redirect';
3047 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3048 } elseif ( $current != $val ) {
3050 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3055 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3060 if ( $options & RLH_FOR_UPDATE
) {
3061 $query .= ' FOR UPDATE';
3064 $res = $dbr->query( $query, $fname );
3066 # Fetch data and form into an associative array
3067 # non-existent = broken
3070 while ( $s = $dbr->fetchObject($res) ) {
3071 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3072 $pdbk = $title->getPrefixedDBkey();
3073 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3075 if ( $threshold > 0 ) {
3076 $size = $s->page_len
;
3077 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3078 $colours[$pdbk] = 1;
3080 $colours[$pdbk] = 2;
3083 $colours[$pdbk] = 1;
3087 wfProfileOut( $fname.'-check' );
3089 # Construct search and replace arrays
3090 wfProfileIn( $fname.'-construct' );
3091 $wgOutputReplace = array();
3092 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3093 $pdbk = $pdbks[$key];
3094 $searchkey = "<!--LINK $key-->";
3095 $title = $this->mLinkHolders
['titles'][$key];
3096 if ( empty( $colours[$pdbk] ) ) {
3097 $wgLinkCache->addBadLinkObj( $title );
3098 $colours[$pdbk] = 0;
3099 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3100 $this->mLinkHolders
['texts'][$key],
3101 $this->mLinkHolders
['queries'][$key] );
3102 } elseif ( $colours[$pdbk] == 1 ) {
3103 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3104 $this->mLinkHolders
['texts'][$key],
3105 $this->mLinkHolders
['queries'][$key] );
3106 } elseif ( $colours[$pdbk] == 2 ) {
3107 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3108 $this->mLinkHolders
['texts'][$key],
3109 $this->mLinkHolders
['queries'][$key] );
3112 wfProfileOut( $fname.'-construct' );
3115 wfProfileIn( $fname.'-replace' );
3117 $text = preg_replace_callback(
3118 '/(<!--LINK .*?-->)/',
3119 "wfOutputReplaceMatches",
3122 wfProfileOut( $fname.'-replace' );
3125 # Now process interwiki link holders
3126 # This is quite a bit simpler than internal links
3127 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3128 wfProfileIn( $fname.'-interwiki' );
3129 # Make interwiki link HTML
3130 $wgOutputReplace = array();
3131 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3132 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3133 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3136 $text = preg_replace_callback(
3137 '/<!--IWLINK (.*?)-->/',
3138 "wfOutputReplaceMatches",
3140 wfProfileOut( $fname.'-interwiki' );
3143 wfProfileOut( $fname );
3148 * Replace <!--LINK--> link placeholders with plain text of links
3149 * (not HTML-formatted).
3150 * @param string $text
3153 function replaceLinkHoldersText( $text ) {
3154 global $wgUser, $wgLinkCache;
3155 global $wgOutputReplace;
3157 $fname = 'Parser::replaceLinkHoldersText';
3158 wfProfileIn( $fname );
3160 $text = preg_replace_callback(
3161 '/<!--(LINK|IWLINK) (.*?)-->/',
3162 array( &$this, 'replaceLinkHoldersTextCallback' ),
3165 wfProfileOut( $fname );
3170 * @param array $matches
3174 function replaceLinkHoldersTextCallback( $matches ) {
3175 $type = $matches[1];
3177 if( $type == 'LINK' ) {
3178 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3179 return $this->mLinkHolders
['texts'][$key];
3181 } elseif( $type == 'IWLINK' ) {
3182 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3183 return $this->mInterwikiLinkHolders
['texts'][$key];
3190 * Renders an image gallery from a text with one line per image.
3191 * text labels may be given by using |-style alternative text. E.g.
3192 * Image:one.jpg|The number "1"
3193 * Image:tree.jpg|A tree
3194 * given as text will return the HTML of a gallery with two images,
3195 * labeled 'The number "1"' and
3200 function renderImageGallery( $text ) {
3202 global $wgUser, $wgTitle;
3203 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3204 $localParser = new Parser();
3206 global $wgLinkCache;
3207 $ig = new ImageGallery();
3208 $ig->setShowBytes( false );
3209 $ig->setShowFilename( false );
3210 $lines = explode( "\n", $text );
3212 foreach ( $lines as $line ) {
3213 # match lines like these:
3214 # Image:someimage.jpg|This is some image
3215 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3217 if ( count( $matches ) == 0 ) {
3220 $nt = Title
::newFromURL( $matches[1] );
3221 if( is_null( $nt ) ) {
3222 # Bogus title. Ignore these so we don't bomb out later.
3225 if ( isset( $matches[3] ) ) {
3226 $label = $matches[3];
3231 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3232 $html = $html->mText
;
3234 $ig->add( new Image( $nt ), $html );
3235 $wgLinkCache->addImageLinkObj( $nt );
3237 return $ig->toHTML();
3241 * Parse image options text and use it to make an image
3243 function makeImage( &$nt, $options ) {
3244 global $wgContLang, $wgUseImageResize;
3245 global $wgUser, $wgThumbLimits;
3249 # Check if the options text is of the form "options|alt text"
3251 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3252 # * left no resizing, just left align. label is used for alt= only
3253 # * right same, but right aligned
3254 # * none same, but not aligned
3255 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3256 # * center center the image
3257 # * framed Keep original image size, no magnify-button.
3259 $part = explode( '|', $options);
3261 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3262 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3263 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3264 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3265 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3266 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3267 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3268 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3271 $width = $height = $framed = $thumb = false;
3272 $manual_thumb = '' ;
3274 foreach( $part as $key => $val ) {
3275 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3277 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3278 # use manually specified thumbnail
3280 $manual_thumb = $match;
3281 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3282 # remember to set an alignment, don't render immediately
3284 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3285 # remember to set an alignment, don't render immediately
3287 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3288 # remember to set an alignment, don't render immediately
3290 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3291 # remember to set an alignment, don't render immediately
3293 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3294 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3295 # $match is the image width in pixels
3296 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3297 $width = intval( $m[1] );
3298 $height = intval( $m[2] );
3300 $width = intval($match);
3302 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3308 # Strip bad stuff out of the alt text
3309 $alt = $this->replaceLinkHoldersText( $caption );
3310 $alt = Sanitizer
::stripAllTags( $alt );
3312 # Linker does the rest
3313 $sk =& $this->mOptions
->getSkin();
3314 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3318 * Set a flag in the output object indicating that the content is dynamic and
3319 * shouldn't be cached.
3321 function disableCache() {
3322 $this->mOutput
->mCacheTime
= -1;
3326 * Callback from the Sanitizer for expanding items found in HTML attribute
3327 * values, so they can be safely tested and escaped.
3328 * @param string $text
3329 * @param array $args
3333 function attributeStripCallback( &$text, $args ) {
3334 $text = $this->replaceVariables( $text, $args );
3335 $text = $this->unstripForHTML( $text );
3339 function unstripForHTML( $text ) {
3340 $text = $this->unstrip( $text, $this->mStripState
);
3341 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3348 * @package MediaWiki
3352 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3353 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3354 var $mVersion; # Compatibility check
3355 var $mTitleText; # title text of the chosen language variant
3357 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3358 $containsOldMagic = false, $titletext = '' )
3360 $this->mText
= $text;
3361 $this->mLanguageLinks
= $languageLinks;
3362 $this->mCategoryLinks
= $categoryLinks;
3363 $this->mContainsOldMagic
= $containsOldMagic;
3364 $this->mCacheTime
= '';
3365 $this->mVersion
= MW_PARSER_VERSION
;
3366 $this->mTitleText
= $titletext;
3369 function getText() { return $this->mText
; }
3370 function getLanguageLinks() { return $this->mLanguageLinks
; }
3371 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3372 function getCacheTime() { return $this->mCacheTime
; }
3373 function getTitleText() { return $this->mTitleText
; }
3374 function containsOldMagic() { return $this->mContainsOldMagic
; }
3375 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3376 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3377 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3378 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3379 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3380 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3382 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3384 function merge( $other ) {
3385 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3386 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3387 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3391 * Return true if this cached output object predates the global or
3392 * per-article cache invalidation timestamps, or if it comes from
3393 * an incompatible older version.
3395 * @param string $touched the affected article's last touched timestamp
3399 function expired( $touched ) {
3400 global $wgCacheEpoch;
3401 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3402 $this->getCacheTime() <= $touched ||
3403 $this->getCacheTime() <= $wgCacheEpoch ||
3404 !isset( $this->mVersion
) ||
3405 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3410 * Set options of the Parser
3412 * @package MediaWiki
3416 # All variables are private
3417 var $mUseTeX; # Use texvc to expand <math> tags
3418 var $mUseDynamicDates; # Use DateFormatter to format dates
3419 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3420 var $mAllowExternalImages; # Allow external images inline
3421 var $mSkin; # Reference to the preferred skin
3422 var $mDateFormat; # Date format index
3423 var $mEditSection; # Create "edit section" links
3424 var $mNumberHeadings; # Automatically number headings
3425 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3427 function getUseTeX() { return $this->mUseTeX
; }
3428 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3429 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3430 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3431 function &getSkin() { return $this->mSkin
; }
3432 function getDateFormat() { return $this->mDateFormat
; }
3433 function getEditSection() { return $this->mEditSection
; }
3434 function getNumberHeadings() { return $this->mNumberHeadings
; }
3435 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3438 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3439 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3440 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3441 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3442 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3443 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3444 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3445 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3447 function setSkin( &$x ) { $this->mSkin
=& $x; }
3449 function ParserOptions() {
3451 $this->initialiseFromUser( $wgUser );
3455 * Get parser options
3458 function newFromUser( &$user ) {
3459 $popts = new ParserOptions
;
3460 $popts->initialiseFromUser( $user );
3464 /** Get user options */
3465 function initialiseFromUser( &$userInput ) {
3466 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3467 $wgAllowSpecialInclusion;
3468 $fname = 'ParserOptions::initialiseFromUser';
3469 wfProfileIn( $fname );
3470 if ( !$userInput ) {
3472 $user->setLoaded( true );
3474 $user =& $userInput;
3477 $this->mUseTeX
= $wgUseTeX;
3478 $this->mUseDynamicDates
= $wgUseDynamicDates;
3479 $this->mInterwikiMagic
= $wgInterwikiMagic;
3480 $this->mAllowExternalImages
= $wgAllowExternalImages;
3481 wfProfileIn( $fname.'-skin' );
3482 $this->mSkin
=& $user->getSkin();
3483 wfProfileOut( $fname.'-skin' );
3484 $this->mDateFormat
= $user->getOption( 'date' );
3485 $this->mEditSection
= true;
3486 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3487 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3488 wfProfileOut( $fname );
3493 * Callback function used by Parser::replaceLinkHolders()
3494 * to substitute link placeholders.
3496 function &wfOutputReplaceMatches( $matches ) {
3497 global $wgOutputReplace;
3498 return $wgOutputReplace[$matches[1]];
3502 * Return the total number of articles
3504 function wfNumberOfArticles() {
3505 global $wgNumberOfArticles;
3508 return $wgNumberOfArticles;
3512 * Return the number of files
3514 function wfNumberOfFiles() {
3515 $fname = 'Parser::wfNumberOfFiles';
3517 wfProfileIn( $fname );
3518 $dbr =& wfGetDB( DB_SLAVE
);
3519 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3520 wfProfileOut( $fname );
3526 * Get various statistics from the database
3529 function wfLoadSiteStats() {
3530 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3531 $fname = 'wfLoadSiteStats';
3533 if ( -1 != $wgNumberOfArticles ) return;
3534 $dbr =& wfGetDB( DB_SLAVE
);
3535 $s = $dbr->selectRow( 'site_stats',
3536 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3537 array( 'ss_row_id' => 1 ), $fname
3540 if ( $s === false ) {
3543 $wgTotalViews = $s->ss_total_views
;
3544 $wgTotalEdits = $s->ss_total_edits
;
3545 $wgNumberOfArticles = $s->ss_good_articles
;
3551 * Basicly replacing " > and < with HTML entities ( ", >, <)
3553 * @param string $in Text that might contain HTML tags
3554 * @return string Escaped string
3556 function wfEscapeHTMLTagsOnly( $in ) {
3558 array( '"', '>', '<' ),
3559 array( '"', '>', '<' ),