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(' . wfUrlProtocols() . ')'.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();
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->mInterwikiLinkHolders
= array(
148 $this->mLinkHolders
= array(
149 'namespaces' => array(),
151 'queries' => array(),
158 * First pass--just handle <nowiki> sections, pass the rest off
159 * to internalParse() which does all the real work.
162 * @param string $text Text we want to parse
163 * @param Title &$title A title object
164 * @param array $options
165 * @param boolean $linestart
166 * @param boolean $clearState
167 * @return ParserOutput a ParserOutput
169 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
170 global $wgUseTidy, $wgContLang;
171 $fname = 'Parser::parse';
172 wfProfileIn( $fname );
178 $this->mOptions
= $options;
179 $this->mTitle
=& $title;
180 $this->mOutputType
= OT_HTML
;
182 $this->mStripState
= NULL;
184 //$text = $this->strip( $text, $this->mStripState );
185 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
186 $x =& $this->mStripState
;
188 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
189 $text = $this->strip( $text, $x );
190 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
192 $text = $this->internalParse( $text );
194 $text = $this->unstrip( $text, $this->mStripState
);
196 # Clean up special characters, only run once, next-to-last before doBlockLevels
198 # french spaces, last one Guillemet-left
199 # only if there is something before the space
200 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
201 # french spaces, Guillemet-right
202 '/(\\302\\253) /' => '\\1 ',
203 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
205 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
208 $text = $this->doBlockLevels( $text, $linestart );
210 $this->replaceLinkHolders( $text );
212 # the position of the convert() call should not be changed. it
213 # assumes that the links are all replaces and the only thing left
214 # is the <nowiki> mark.
215 $text = $wgContLang->convert($text);
216 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
218 $text = $this->unstripNoWiki( $text, $this->mStripState
);
220 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
222 $text = Sanitizer
::normalizeCharReferences( $text );
225 $text = Parser
::tidy($text);
228 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
230 $this->mOutput
->setText( $text );
231 wfProfileOut( $fname );
232 return $this->mOutput
;
236 * Get a random string
241 function getRandomString() {
242 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
246 * Replaces all occurrences of <$tag>content</$tag> in the text
247 * with a random marker and returns the new text. the output parameter
248 * $content will be an associative array filled with data on the form
249 * $unique_marker => content.
251 * If $content is already set, the additional entries will be appended
252 * If $tag is set to STRIP_COMMENTS, the function will extract
253 * <!-- HTML comments -->
258 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
259 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
274 if( $tag == STRIP_COMMENTS
) {
278 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
279 $end = "/<\\/$tag\\s*>/i";
282 while ( '' != $text ) {
283 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
285 if( count( $p ) < 3 ) {
291 $marker = $rnd . sprintf('%08X', $n++
);
292 $stripped .= $marker;
294 $tags[$marker] = "<$tag$attributes>";
295 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
297 $q = preg_split( $end, $inside, 2 );
298 $content[$marker] = $q[0];
299 if( count( $q ) < 2 ) {
300 # No end tag -- let it run out to the end of the text.
310 * Wrapper function for extractTagsAndParams
311 * for cases where $tags and $params isn't needed
312 * i.e. where tags will never have params, like <nowiki>
317 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
318 $dummy_tags = array();
319 $dummy_params = array();
321 return Parser
::extractTagsAndParams( $tag, $text, $content,
322 $dummy_tags, $dummy_params, $uniq_prefix );
326 * Strips and renders nowiki, pre, math, hiero
327 * If $render is set, performs necessary rendering operations on plugins
328 * Returns the text, and fills an array with data needed in unstrip()
329 * If the $state is already a valid strip state, it adds to the state
331 * @param bool $stripcomments when set, HTML comments <!-- like this -->
332 * will be stripped in addition to other tags. This is important
333 * for section editing, where these comments cause confusion when
334 * counting the sections in the wikisource
338 function strip( $text, &$state, $stripcomments = false ) {
339 $render = ($this->mOutputType
== OT_HTML
);
340 $html_content = array();
341 $nowiki_content = array();
342 $math_content = array();
343 $pre_content = array();
344 $comment_content = array();
345 $ext_content = array();
347 $ext_params = array();
348 $gallery_content = array();
350 # Replace any instances of the placeholders
351 $uniq_prefix = UNIQ_PREFIX
;
352 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
357 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
358 foreach( $html_content as $marker => $content ) {
360 # Raw and unchecked for validity.
361 $html_content[$marker] = $content;
363 $html_content[$marker] = '<html>'.$content.'</html>';
369 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
370 foreach( $nowiki_content as $marker => $content ) {
372 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
374 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
379 if( $this->mOptions
->getUseTeX() ) {
380 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
381 foreach( $math_content as $marker => $content ){
383 $math_content[$marker] = renderMath( $content );
385 $math_content[$marker] = '<math>'.$content.'</math>';
391 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
392 foreach( $pre_content as $marker => $content ){
394 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
396 $pre_content[$marker] = '<pre>'.$content.'</pre>';
401 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
402 foreach( $gallery_content as $marker => $content ) {
403 require_once( 'ImageGallery.php' );
405 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
407 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
413 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
414 foreach( $comment_content as $marker => $content ){
415 $comment_content[$marker] = '<!--'.$content.'-->';
420 foreach ( $this->mTagHooks
as $tag => $callback ) {
421 $ext_content[$tag] = array();
422 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
423 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
424 foreach( $ext_content[$tag] as $marker => $content ) {
425 $full_tag = $ext_tags[$tag][$marker];
426 $params = $ext_params[$tag][$marker];
428 $ext_content[$tag][$marker] = $callback( $content, $params, $this );
430 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
435 # Merge state with the pre-existing state, if there is one
437 $state['html'] = $state['html'] +
$html_content;
438 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
439 $state['math'] = $state['math'] +
$math_content;
440 $state['pre'] = $state['pre'] +
$pre_content;
441 $state['comment'] = $state['comment'] +
$comment_content;
442 $state['gallery'] = $state['gallery'] +
$gallery_content;
444 foreach( $ext_content as $tag => $array ) {
445 if ( array_key_exists( $tag, $state ) ) {
446 $state[$tag] = $state[$tag] +
$array;
451 'html' => $html_content,
452 'nowiki' => $nowiki_content,
453 'math' => $math_content,
454 'pre' => $pre_content,
455 'comment' => $comment_content,
456 'gallery' => $gallery_content,
463 * restores pre, math, and hiero removed by strip()
465 * always call unstripNoWiki() after this one
468 function unstrip( $text, &$state ) {
469 if ( !is_array( $state ) ) {
473 # Must expand in reverse order, otherwise nested tags will be corrupted
474 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
475 if( $tag != 'nowiki' && $tag != 'html' ) {
476 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
477 $text = str_replace( $uniq, $content, $text );
486 * always call this after unstrip() to preserve the order
490 function unstripNoWiki( $text, &$state ) {
491 if ( !is_array( $state ) ) {
495 # Must expand in reverse order, otherwise nested tags will be corrupted
496 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
497 $text = str_replace( key( $state['nowiki'] ), $content, $text );
502 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
503 $text = str_replace( key( $state['html'] ), $content, $text );
511 * Add an item to the strip state
512 * Returns the unique tag which must be inserted into the stripped text
513 * The tag will be replaced with the original text in unstrip()
517 function insertStripItem( $text, &$state ) {
518 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
525 'comment' => array(),
526 'gallery' => array(),
529 $state['item'][$rnd] = $text;
534 * Interface with html tidy, used if $wgUseTidy = true.
535 * If tidy isn't able to correct the markup, the original will be
536 * returned in all its glory with a warning comment appended.
538 * Either the external tidy program or the in-process tidy extension
539 * will be used depending on availability. Override the default
540 * $wgTidyInternal setting to disable the internal if it's not working.
542 * @param string $text Hideous HTML input
543 * @return string Corrected HTML output
547 function tidy( $text ) {
548 global $wgTidyInternal;
549 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
550 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
551 '<head><title>test</title></head><body>'.$text.'</body></html>';
552 if( $wgTidyInternal ) {
553 $correctedtext = Parser
::internalTidy( $wrappedtext );
555 $correctedtext = Parser
::externalTidy( $wrappedtext );
557 if( is_null( $correctedtext ) ) {
558 wfDebug( "Tidy error detected!\n" );
559 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
561 return $correctedtext;
565 * Spawn an external HTML tidy process and get corrected markup back from it.
570 function externalTidy( $text ) {
571 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
572 $fname = 'Parser::externalTidy';
573 wfProfileIn( $fname );
578 $descriptorspec = array(
579 0 => array('pipe', 'r'),
580 1 => array('pipe', 'w'),
581 2 => array('file', '/dev/null', 'a')
584 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
585 if (is_resource($process)) {
586 fwrite($pipes[0], $text);
588 while (!feof($pipes[1])) {
589 $cleansource .= fgets($pipes[1], 1024);
592 proc_close($process);
595 wfProfileOut( $fname );
597 if( $cleansource == '' && $text != '') {
598 // Some kind of error happened, so we couldn't get the corrected text.
599 // Just give up; we'll use the source text and append a warning.
607 * Use the HTML tidy PECL extension to use the tidy library in-process,
608 * saving the overhead of spawning a new process. Currently written to
609 * the PHP 4.3.x version of the extension, may not work on PHP 5.
611 * 'pear install tidy' should be able to compile the extension module.
616 function internalTidy( $text ) {
618 $fname = 'Parser::internalTidy';
619 wfProfileIn( $fname );
621 tidy_load_config( $wgTidyConf );
622 tidy_set_encoding( 'utf8' );
623 tidy_parse_string( $text );
625 if( tidy_get_status() == 2 ) {
626 // 2 is magic number for fatal error
627 // http://www.php.net/manual/en/function.tidy-get-status.php
630 $cleansource = tidy_get_output();
632 wfProfileOut( $fname );
637 * parse the wiki syntax used to render tables
641 function doTableStuff ( $t ) {
642 $fname = 'Parser::doTableStuff';
643 wfProfileIn( $fname );
645 $t = explode ( "\n" , $t ) ;
646 $td = array () ; # Is currently a td tag open?
647 $ltd = array () ; # Was it TD or TH?
648 $tr = array () ; # Is currently a tr tag open?
649 $ltr = array () ; # tr attributes
650 $indent_level = 0; # indent level of the table
651 foreach ( $t AS $k => $x )
654 $fc = substr ( $x , 0 , 1 ) ;
655 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
656 $indent_level = strlen( $matches[1] );
658 $attributes = $this->unstripForHTML( $matches[2] );
660 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
661 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
662 array_push ( $td , false ) ;
663 array_push ( $ltd , '' ) ;
664 array_push ( $tr , false ) ;
665 array_push ( $ltr , '' ) ;
667 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
668 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
669 $z = "</table>" . substr ( $x , 2);
670 $l = array_pop ( $ltd ) ;
671 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
672 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
674 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
676 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
677 $x = substr ( $x , 1 ) ;
678 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
680 $l = array_pop ( $ltd ) ;
681 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
682 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
685 array_push ( $tr , false ) ;
686 array_push ( $td , false ) ;
687 array_push ( $ltd , '' ) ;
688 $attributes = $this->unstripForHTML( $x );
689 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
691 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
693 if ( '|+' == substr ( $x , 0 , 2 ) ) {
695 $x = substr ( $x , 1 ) ;
697 $after = substr ( $x , 1 ) ;
698 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
699 $after = explode ( '||' , $after ) ;
702 # Loop through each table cell
703 foreach ( $after AS $theline )
708 $tra = array_pop ( $ltr ) ;
709 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
710 array_push ( $tr , true ) ;
711 array_push ( $ltr , '' ) ;
714 $l = array_pop ( $ltd ) ;
715 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
716 if ( $fc == '|' ) $l = 'td' ;
717 else if ( $fc == '!' ) $l = 'th' ;
718 else if ( $fc == '+' ) $l = 'caption' ;
720 array_push ( $ltd , $l ) ;
723 $y = explode ( '|' , $theline , 2 ) ;
724 # Note that a '|' inside an invalid link should not
725 # be mistaken as delimiting cell parameters
726 if ( strpos( $y[0], '[[' ) !== false ) {
727 $y = array ($theline);
729 if ( count ( $y ) == 1 )
730 $y = "{$z}<{$l}>{$y[0]}" ;
732 $attributes = $this->unstripForHTML( $y[0] );
733 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
736 array_push ( $td , true ) ;
741 # Closing open td, tr && table
742 while ( count ( $td ) > 0 )
744 if ( array_pop ( $td ) ) $t[] = '</td>' ;
745 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
749 $t = implode ( "\n" , $t ) ;
750 wfProfileOut( $fname );
755 * Helper function for parse() that transforms wiki markup into
756 * HTML. Only called for $mOutputType == OT_HTML.
760 function internalParse( $text ) {
764 $fname = 'Parser::internalParse';
765 wfProfileIn( $fname );
767 # Remove <noinclude> tags and <includeonly> sections
768 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
769 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
770 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
772 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
773 $text = $this->replaceVariables( $text, $args );
775 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
777 $text = $this->doHeadings( $text );
778 if($this->mOptions
->getUseDynamicDates()) {
779 $df =& DateFormatter
::getInstance();
780 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
782 $text = $this->doAllQuotes( $text );
783 $text = $this->replaceInternalLinks( $text );
784 $text = $this->replaceExternalLinks( $text );
786 # replaceInternalLinks may sometimes leave behind
787 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
788 $text = str_replace(UNIQ_PREFIX
."NOPARSE", "", $text);
790 $text = $this->doMagicLinks( $text );
791 $text = $this->doTableStuff( $text );
792 $text = $this->formatHeadings( $text, $isMain );
794 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
795 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
797 wfProfileOut( $fname );
801 function scarySubstitution($matches) {
802 # return "[[".$matches[0]."]]";
803 return $this->mIWTransData
[(int)$matches[0]];
807 * Replace special strings like "ISBN xxx" and "RFC xxx" with
808 * magic external links.
812 function &doMagicLinks( &$text ) {
813 $text = $this->magicISBN( $text );
814 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
815 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
820 * Parse ^^ tokens and return html
824 function doExponent( $text ) {
825 $fname = 'Parser::doExponent';
826 wfProfileIn( $fname );
827 $text = preg_replace('/\^\^(.*?)\^\^/','<small><sup>\\1</sup></small>', $text);
828 wfProfileOut( $fname );
833 * Parse headers and return html
837 function doHeadings( $text ) {
838 $fname = 'Parser::doHeadings';
839 wfProfileIn( $fname );
840 for ( $i = 6; $i >= 1; --$i ) {
841 $h = substr( '======', 0, $i );
842 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
843 "<h{$i}>\\1</h{$i}>\\2", $text );
845 wfProfileOut( $fname );
850 * Replace single quotes with HTML markup
852 * @return string the altered text
854 function doAllQuotes( $text ) {
855 $fname = 'Parser::doAllQuotes';
856 wfProfileIn( $fname );
858 $lines = explode( "\n", $text );
859 foreach ( $lines as $line ) {
860 $outtext .= $this->doQuotes ( $line ) . "\n";
862 $outtext = substr($outtext, 0,-1);
863 wfProfileOut( $fname );
868 * Helper function for doAllQuotes()
871 function doQuotes( $text ) {
872 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
873 if ( count( $arr ) == 1 )
877 # First, do some preliminary work. This may shift some apostrophes from
878 # being mark-up to being text. It also counts the number of occurrences
879 # of bold and italics mark-ups.
883 foreach ( $arr as $r )
885 if ( ( $i %
2 ) == 1 )
887 # If there are ever four apostrophes, assume the first is supposed to
888 # be text, and the remaining three constitute mark-up for bold text.
889 if ( strlen( $arr[$i] ) == 4 )
894 # If there are more than 5 apostrophes in a row, assume they're all
895 # text except for the last 5.
896 else if ( strlen( $arr[$i] ) > 5 )
898 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
901 # Count the number of occurrences of bold and italics mark-ups.
902 # We are not counting sequences of five apostrophes.
903 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
904 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
905 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
910 # If there is an odd number of both bold and italics, it is likely
911 # that one of the bold ones was meant to be an apostrophe followed
912 # by italics. Which one we cannot know for certain, but it is more
913 # likely to be one that has a single-letter word before it.
914 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
917 $firstsingleletterword = -1;
918 $firstmultiletterword = -1;
920 foreach ( $arr as $r )
922 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
924 $x1 = substr ($arr[$i-1], -1);
925 $x2 = substr ($arr[$i-1], -2, 1);
927 if ($firstspace == -1) $firstspace = $i;
928 } else if ($x2 == ' ') {
929 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
931 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
937 # If there is a single-letter word, use it!
938 if ($firstsingleletterword > -1)
940 $arr [ $firstsingleletterword ] = "''";
941 $arr [ $firstsingleletterword-1 ] .= "'";
943 # If not, but there's a multi-letter word, use that one.
944 else if ($firstmultiletterword > -1)
946 $arr [ $firstmultiletterword ] = "''";
947 $arr [ $firstmultiletterword-1 ] .= "'";
949 # ... otherwise use the first one that has neither.
950 # (notice that it is possible for all three to be -1 if, for example,
951 # there is only one pentuple-apostrophe in the line)
952 else if ($firstspace > -1)
954 $arr [ $firstspace ] = "''";
955 $arr [ $firstspace-1 ] .= "'";
959 # Now let's actually convert our apostrophic mush to HTML!
968 if ($state == 'both')
975 if (strlen ($r) == 2)
978 { $output .= '</i>'; $state = ''; }
979 else if ($state == 'bi')
980 { $output .= '</i>'; $state = 'b'; }
981 else if ($state == 'ib')
982 { $output .= '</b></i><b>'; $state = 'b'; }
983 else if ($state == 'both')
984 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
985 else # $state can be 'b' or ''
986 { $output .= '<i>'; $state .= 'i'; }
988 else if (strlen ($r) == 3)
991 { $output .= '</b>'; $state = ''; }
992 else if ($state == 'bi')
993 { $output .= '</i></b><i>'; $state = 'i'; }
994 else if ($state == 'ib')
995 { $output .= '</b>'; $state = 'i'; }
996 else if ($state == 'both')
997 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
998 else # $state can be 'i' or ''
999 { $output .= '<b>'; $state .= 'b'; }
1001 else if (strlen ($r) == 5)
1004 { $output .= '</b><i>'; $state = 'i'; }
1005 else if ($state == 'i')
1006 { $output .= '</i><b>'; $state = 'b'; }
1007 else if ($state == 'bi')
1008 { $output .= '</i></b>'; $state = ''; }
1009 else if ($state == 'ib')
1010 { $output .= '</b></i>'; $state = ''; }
1011 else if ($state == 'both')
1012 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1013 else # ($state == '')
1014 { $buffer = ''; $state = 'both'; }
1019 # Now close all remaining tags. Notice that the order is important.
1020 if ($state == 'b' ||
$state == 'ib')
1022 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1026 if ($state == 'both')
1027 $output .= '<b><i>'.$buffer.'</i></b>';
1033 * Replace external links
1035 * Note: this is all very hackish and the order of execution matters a lot.
1036 * Make sure to run maintenance/parserTests.php if you change this code.
1040 function replaceExternalLinks( $text ) {
1042 $fname = 'Parser::replaceExternalLinks';
1043 wfProfileIn( $fname );
1045 $sk =& $this->mOptions
->getSkin();
1047 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1049 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1052 while ( $i<count( $bits ) ) {
1054 $protocol = $bits[$i++
];
1055 $text = $bits[$i++
];
1056 $trail = $bits[$i++
];
1058 # The characters '<' and '>' (which were escaped by
1059 # removeHTMLtags()) should not be included in
1060 # URLs, per RFC 2396.
1061 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1062 $text = substr($url, $m2[0][1]) . ' ' . $text;
1063 $url = substr($url, 0, $m2[0][1]);
1066 # If the link text is an image URL, replace it with an <img> tag
1067 # This happened by accident in the original parser, but some people used it extensively
1068 $img = $this->maybeMakeExternalImage( $text );
1069 if ( $img !== false ) {
1075 # Set linktype for CSS - if URL==text, link is essentially free
1076 $linktype = ($text == $url) ?
'free' : 'text';
1078 # No link text, e.g. [http://domain.tld/some.link]
1079 if ( $text == '' ) {
1080 # Autonumber if allowed
1081 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1082 $text = '[' . ++
$this->mAutonumber
. ']';
1083 $linktype = 'autonumber';
1085 # Otherwise just use the URL
1086 $text = htmlspecialchars( $url );
1090 # Have link text, e.g. [http://domain.tld/some.link text]s
1092 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1095 $text = $wgContLang->markNoConversion($text);
1097 # Replace & from obsolete syntax with &.
1098 # All HTML entities will be escaped by makeExternalLink()
1099 # or maybeMakeExternalImage()
1100 $url = str_replace( '&', '&', $url );
1102 # Process the trail (i.e. everything after this link up until start of the next link),
1103 # replacing any non-bracketed links
1104 $trail = $this->replaceFreeExternalLinks( $trail );
1107 # Use the encoded URL
1108 # This means that users can paste URLs directly into the text
1109 # Funny characters like ö aren't valid in URLs anyway
1110 # This was changed in August 2004
1111 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1114 wfProfileOut( $fname );
1119 * Replace anything that looks like a URL with a link
1122 function replaceFreeExternalLinks( $text ) {
1124 $fname = 'Parser::replaceFreeExternalLinks';
1125 wfProfileIn( $fname );
1127 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1128 $s = array_shift( $bits );
1131 $sk =& $this->mOptions
->getSkin();
1133 while ( $i < count( $bits ) ){
1134 $protocol = $bits[$i++
];
1135 $remainder = $bits[$i++
];
1137 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1138 # Found some characters after the protocol that look promising
1139 $url = $protocol . $m[1];
1142 # The characters '<' and '>' (which were escaped by
1143 # removeHTMLtags()) should not be included in
1144 # URLs, per RFC 2396.
1145 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1146 $trail = substr($url, $m2[0][1]) . $trail;
1147 $url = substr($url, 0, $m2[0][1]);
1150 # Move trailing punctuation to $trail
1152 # If there is no left bracket, then consider right brackets fair game too
1153 if ( strpos( $url, '(' ) === false ) {
1157 $numSepChars = strspn( strrev( $url ), $sep );
1158 if ( $numSepChars ) {
1159 $trail = substr( $url, -$numSepChars ) . $trail;
1160 $url = substr( $url, 0, -$numSepChars );
1163 # Replace & from obsolete syntax with &.
1164 # All HTML entities will be escaped by makeExternalLink()
1165 # or maybeMakeExternalImage()
1166 $url = str_replace( '&', '&', $url );
1168 # Is this an external image?
1169 $text = $this->maybeMakeExternalImage( $url );
1170 if ( $text === false ) {
1171 # Not an image, make a link
1172 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1174 $s .= $text . $trail;
1176 $s .= $protocol . $remainder;
1179 wfProfileOut( $fname );
1184 * make an image if it's allowed, either through the global
1185 * option or through the exception
1188 function maybeMakeExternalImage( $url ) {
1189 $sk =& $this->mOptions
->getSkin();
1190 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1191 $imagesexception = !empty($imagesfrom);
1193 if ( $this->mOptions
->getAllowExternalImages()
1194 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1195 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1197 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1204 * Process [[ ]] wikilinks
1208 function replaceInternalLinks( $s ) {
1209 global $wgContLang, $wgLinkCache;
1210 static $fname = 'Parser::replaceInternalLinks' ;
1212 wfProfileIn( $fname );
1214 wfProfileIn( $fname.'-setup' );
1216 # the % is needed to support urlencoded titles as well
1217 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1219 $sk =& $this->mOptions
->getSkin();
1221 #split the entire text string on occurences of [[
1222 $a = explode( '[[', ' ' . $s );
1223 #get the first element (all text up to first [[), and remove the space we added
1224 $s = array_shift( $a );
1225 $s = substr( $s, 1 );
1227 # Match a link having the form [[namespace:link|alternate]]trail
1229 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1230 # Match cases where there is no "]]", which might still be images
1231 static $e1_img = FALSE;
1232 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1233 # Match the end of a line for a word that's not followed by whitespace,
1234 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1235 $e2 = wfMsgForContent( 'linkprefix' );
1237 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1239 if( is_null( $this->mTitle
) ) {
1240 wfDebugDieBacktrace( 'nooo' );
1242 $nottalk = !$this->mTitle
->isTalkPage();
1244 if ( $useLinkPrefixExtension ) {
1245 if ( preg_match( $e2, $s, $m ) ) {
1246 $first_prefix = $m[2];
1248 $first_prefix = false;
1254 $selflink = $this->mTitle
->getPrefixedText();
1255 wfProfileOut( $fname.'-setup' );
1257 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1258 $useSubpages = $this->areSubpagesAllowed();
1260 # Loop for each link
1261 for ($k = 0; isset( $a[$k] ); $k++
) {
1263 if ( $useLinkPrefixExtension ) {
1264 wfProfileIn( $fname.'-prefixhandling' );
1265 if ( preg_match( $e2, $s, $m ) ) {
1273 $prefix = $first_prefix;
1274 $first_prefix = false;
1276 wfProfileOut( $fname.'-prefixhandling' );
1279 $might_be_img = false;
1281 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1283 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1284 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1285 # the real problem is with the $e1 regex
1288 # Still some problems for cases where the ] is meant to be outside punctuation,
1289 # and no image is in sight. See bug 2095.
1291 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1292 $text .= ']'; # so that replaceExternalLinks($text) works later
1295 # fix up urlencoded title texts
1296 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1298 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1299 $might_be_img = true;
1301 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1303 } else { # Invalid form; output directly
1304 $s .= $prefix . '[[' . $line ;
1308 # Don't allow internal links to pages containing
1309 # PROTO: where PROTO is a valid URL protocol; these
1310 # should be external links.
1311 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1312 $s .= $prefix . '[[' . $line ;
1316 # Make subpage if necessary
1317 if( $useSubpages ) {
1318 $link = $this->maybeDoSubpageLink( $m[1], $text );
1323 $noforce = (substr($m[1], 0, 1) != ':');
1325 # Strip off leading ':'
1326 $link = substr($link, 1);
1329 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1331 $s .= $prefix . '[[' . $line;
1335 #check other language variants of the link
1336 #if the article does not exist
1337 if( $checkVariantLink
1338 && $nt->getArticleID() == 0 ) {
1339 $wgContLang->findVariantLink($link, $nt);
1342 $ns = $nt->getNamespace();
1343 $iw = $nt->getInterWiki();
1345 if ($might_be_img) { # if this is actually an invalid link
1346 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1348 while (isset ($a[$k+
1]) ) {
1349 #look at the next 'line' to see if we can close it there
1350 $spliced = array_splice( $a, $k +
1, 1 );
1351 $next_line = array_shift( $spliced );
1352 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1353 # the first ]] closes the inner link, the second the image
1355 $text .= '[[' . $m[1];
1358 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1359 #if there's exactly one ]] that's fine, we'll keep looking
1360 $text .= '[[' . $m[0];
1362 #if $next_line is invalid too, we need look no further
1363 $text .= '[[' . $next_line;
1368 # we couldn't find the end of this imageLink, so output it raw
1369 #but don't ignore what might be perfectly normal links in the text we've examined
1370 $text = $this->replaceInternalLinks($text);
1371 $s .= $prefix . '[[' . $link . '|' . $text;
1372 # note: no $trail, because without an end, there *is* no trail
1375 } else { #it's not an image, so output it raw
1376 $s .= $prefix . '[[' . $link . '|' . $text;
1377 # note: no $trail, because without an end, there *is* no trail
1382 $wasblank = ( '' == $text );
1383 if( $wasblank ) $text = $link;
1386 # Link not escaped by : , create the various objects
1390 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1391 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1392 $s = rtrim($s . "\n");
1393 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1397 if ( $ns == NS_IMAGE
) {
1398 wfProfileIn( "$fname-image" );
1399 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1400 # recursively parse links inside the image caption
1401 # actually, this will parse them in any other parameters, too,
1402 # but it might be hard to fix that, and it doesn't matter ATM
1403 $text = $this->replaceExternalLinks($text);
1404 $text = $this->replaceInternalLinks($text);
1406 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1407 $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1408 $wgLinkCache->addImageLinkObj( $nt );
1410 wfProfileOut( "$fname-image" );
1413 wfProfileOut( "$fname-image" );
1417 if ( $ns == NS_CATEGORY
) {
1418 wfProfileIn( "$fname-category" );
1419 $t = $wgContLang->convertHtml( $nt->getText() );
1420 $s = rtrim($s . "\n"); # bug 87
1422 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1423 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1424 $wgLinkCache->resume();
1427 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1428 $sortkey = $this->mTitle
->getText();
1430 $sortkey = $this->mTitle
->getPrefixedText();
1435 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1436 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1437 $this->mOutput
->addCategoryLink( $t );
1440 * Strip the whitespace Category links produce, see bug 87
1441 * @todo We might want to use trim($tmp, "\n") here.
1443 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1445 wfProfileOut( "$fname-category" );
1450 if( ( $nt->getPrefixedText() === $selflink ) &&
1451 ( $nt->getFragment() === '' ) ) {
1452 # Self-links are handled specially; generally de-link and change to bold.
1453 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1457 # Special and Media are pseudo-namespaces; no pages actually exist in them
1458 if( $ns == NS_MEDIA
) {
1459 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1460 $wgLinkCache->addImageLinkObj( $nt );
1462 } elseif( $ns == NS_SPECIAL
) {
1463 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1466 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1468 wfProfileOut( $fname );
1473 * Make a link placeholder. The text returned can be later resolved to a real link with
1474 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1475 * parsing of interwiki links, and secondly to allow all extistence checks and
1476 * article length checks (for stub links) to be bundled into a single query.
1479 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1480 if ( ! is_object($nt) ) {
1482 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1484 # Separate the link trail from the rest of the link
1485 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1487 if ( $nt->isExternal() ) {
1488 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1489 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1490 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1492 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1493 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1494 $this->mLinkHolders
['queries'][] = $query;
1495 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1496 $this->mLinkHolders
['titles'][] = $nt;
1498 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1505 * Return true if subpage links should be expanded on this page.
1508 function areSubpagesAllowed() {
1509 # Some namespaces don't allow subpages
1510 global $wgNamespacesWithSubpages;
1511 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1515 * Handle link to subpage if necessary
1516 * @param string $target the source of the link
1517 * @param string &$text the link text, modified as necessary
1518 * @return string the full name of the link
1521 function maybeDoSubpageLink($target, &$text) {
1524 # :Foobar -- override special treatment of prefix (images, language links)
1525 # /Foobar -- convert to CurrentPage/Foobar
1526 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1527 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1528 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1530 $fname = 'Parser::maybeDoSubpageLink';
1531 wfProfileIn( $fname );
1532 $ret = $target; # default return value is no change
1534 # Some namespaces don't allow subpages,
1535 # so only perform processing if subpages are allowed
1536 if( $this->areSubpagesAllowed() ) {
1537 # Look at the first character
1538 if( $target != '' && $target{0} == '/' ) {
1539 # / at end means we don't want the slash to be shown
1540 if( substr( $target, -1, 1 ) == '/' ) {
1541 $target = substr( $target, 1, -1 );
1544 $noslash = substr( $target, 1 );
1547 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1548 if( '' === $text ) {
1550 } # this might be changed for ugliness reasons
1552 # check for .. subpage backlinks
1554 $nodotdot = $target;
1555 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1557 $nodotdot = substr( $nodotdot, 3 );
1559 if($dotdotcount > 0) {
1560 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1561 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1562 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1563 # / at the end means don't show full path
1564 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1565 $nodotdot = substr( $nodotdot, 0, -1 );
1566 if( '' === $text ) {
1570 $nodotdot = trim( $nodotdot );
1571 if( $nodotdot != '' ) {
1572 $ret .= '/' . $nodotdot;
1579 wfProfileOut( $fname );
1584 * Used by doBlockLevels()
1587 /* private */ function closeParagraph() {
1589 if ( '' != $this->mLastSection
) {
1590 $result = '</' . $this->mLastSection
. ">\n";
1592 $this->mInPre
= false;
1593 $this->mLastSection
= '';
1596 # getCommon() returns the length of the longest common substring
1597 # of both arguments, starting at the beginning of both.
1599 /* private */ function getCommon( $st1, $st2 ) {
1600 $fl = strlen( $st1 );
1601 $shorter = strlen( $st2 );
1602 if ( $fl < $shorter ) { $shorter = $fl; }
1604 for ( $i = 0; $i < $shorter; ++
$i ) {
1605 if ( $st1{$i} != $st2{$i} ) { break; }
1609 # These next three functions open, continue, and close the list
1610 # element appropriate to the prefix character passed into them.
1612 /* private */ function openList( $char ) {
1613 $result = $this->closeParagraph();
1615 if ( '*' == $char ) { $result .= '<ul><li>'; }
1616 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1617 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1618 else if ( ';' == $char ) {
1619 $result .= '<dl><dt>';
1620 $this->mDTopen
= true;
1622 else { $result = '<!-- ERR 1 -->'; }
1627 /* private */ function nextItem( $char ) {
1628 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1629 else if ( ':' == $char ||
';' == $char ) {
1631 if ( $this->mDTopen
) { $close = '</dt>'; }
1632 if ( ';' == $char ) {
1633 $this->mDTopen
= true;
1634 return $close . '<dt>';
1636 $this->mDTopen
= false;
1637 return $close . '<dd>';
1640 return '<!-- ERR 2 -->';
1643 /* private */ function closeList( $char ) {
1644 if ( '*' == $char ) { $text = '</li></ul>'; }
1645 else if ( '#' == $char ) { $text = '</li></ol>'; }
1646 else if ( ':' == $char ) {
1647 if ( $this->mDTopen
) {
1648 $this->mDTopen
= false;
1649 $text = '</dt></dl>';
1651 $text = '</dd></dl>';
1654 else { return '<!-- ERR 3 -->'; }
1660 * Make lists from lines starting with ':', '*', '#', etc.
1663 * @return string the lists rendered as HTML
1665 function doBlockLevels( $text, $linestart ) {
1666 $fname = 'Parser::doBlockLevels';
1667 wfProfileIn( $fname );
1669 # Parsing through the text line by line. The main thing
1670 # happening here is handling of block-level elements p, pre,
1671 # and making lists from lines starting with * # : etc.
1673 $textLines = explode( "\n", $text );
1675 $lastPrefix = $output = '';
1676 $this->mDTopen
= $inBlockElem = false;
1678 $paragraphStack = false;
1680 if ( !$linestart ) {
1681 $output .= array_shift( $textLines );
1683 foreach ( $textLines as $oLine ) {
1684 $lastPrefixLength = strlen( $lastPrefix );
1685 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1686 $preOpenMatch = preg_match('/<pre/i', $oLine );
1687 if ( !$this->mInPre
) {
1688 # Multiple prefixes may abut each other for nested lists.
1689 $prefixLength = strspn( $oLine, '*#:;' );
1690 $pref = substr( $oLine, 0, $prefixLength );
1693 $pref2 = str_replace( ';', ':', $pref );
1694 $t = substr( $oLine, $prefixLength );
1695 $this->mInPre
= !empty($preOpenMatch);
1697 # Don't interpret any other prefixes in preformatted text
1699 $pref = $pref2 = '';
1704 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1705 # Same as the last item, so no need to deal with nesting or opening stuff
1706 $output .= $this->nextItem( substr( $pref, -1 ) );
1707 $paragraphStack = false;
1709 if ( substr( $pref, -1 ) == ';') {
1710 # The one nasty exception: definition lists work like this:
1711 # ; title : definition text
1712 # So we check for : in the remainder text to split up the
1713 # title and definition, without b0rking links.
1715 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1717 $output .= $term . $this->nextItem( ':' );
1720 } elseif( $prefixLength ||
$lastPrefixLength ) {
1721 # Either open or close a level...
1722 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1723 $paragraphStack = false;
1725 while( $commonPrefixLength < $lastPrefixLength ) {
1726 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1727 --$lastPrefixLength;
1729 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1730 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1732 while ( $prefixLength > $commonPrefixLength ) {
1733 $char = substr( $pref, $commonPrefixLength, 1 );
1734 $output .= $this->openList( $char );
1736 if ( ';' == $char ) {
1737 # FIXME: This is dupe of code above
1738 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1740 $output .= $term . $this->nextItem( ':' );
1743 ++
$commonPrefixLength;
1745 $lastPrefix = $pref2;
1747 if( 0 == $prefixLength ) {
1748 wfProfileIn( "$fname-paragraph" );
1749 # No prefix (not in list)--go to paragraph mode
1750 $uniq_prefix = UNIQ_PREFIX
;
1751 // XXX: use a stack for nestable elements like span, table and div
1752 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1753 $closematch = preg_match(
1754 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1755 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1756 if ( $openmatch or $closematch ) {
1757 $paragraphStack = false;
1758 $output .= $this->closeParagraph();
1759 if ( $preOpenMatch and !$preCloseMatch ) {
1760 $this->mInPre
= true;
1762 if ( $closematch ) {
1763 $inBlockElem = false;
1765 $inBlockElem = true;
1767 } else if ( !$inBlockElem && !$this->mInPre
) {
1768 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1770 if ($this->mLastSection
!= 'pre') {
1771 $paragraphStack = false;
1772 $output .= $this->closeParagraph().'<pre>';
1773 $this->mLastSection
= 'pre';
1775 $t = substr( $t, 1 );
1778 if ( '' == trim($t) ) {
1779 if ( $paragraphStack ) {
1780 $output .= $paragraphStack.'<br />';
1781 $paragraphStack = false;
1782 $this->mLastSection
= 'p';
1784 if ($this->mLastSection
!= 'p' ) {
1785 $output .= $this->closeParagraph();
1786 $this->mLastSection
= '';
1787 $paragraphStack = '<p>';
1789 $paragraphStack = '</p><p>';
1793 if ( $paragraphStack ) {
1794 $output .= $paragraphStack;
1795 $paragraphStack = false;
1796 $this->mLastSection
= 'p';
1797 } else if ($this->mLastSection
!= 'p') {
1798 $output .= $this->closeParagraph().'<p>';
1799 $this->mLastSection
= 'p';
1804 wfProfileOut( "$fname-paragraph" );
1806 // somewhere above we forget to get out of pre block (bug 785)
1807 if($preCloseMatch && $this->mInPre
) {
1808 $this->mInPre
= false;
1810 if ($paragraphStack === false) {
1814 while ( $prefixLength ) {
1815 $output .= $this->closeList( $pref2{$prefixLength-1} );
1818 if ( '' != $this->mLastSection
) {
1819 $output .= '</' . $this->mLastSection
. '>';
1820 $this->mLastSection
= '';
1823 wfProfileOut( $fname );
1828 * Split up a string on ':', ignoring any occurences inside
1829 * <a>..</a> or <span>...</span>
1830 * @param string $str the string to split
1831 * @param string &$before set to everything before the ':'
1832 * @param string &$after set to everything after the ':'
1833 * return string the position of the ':', or false if none found
1835 function findColonNoLinks($str, &$before, &$after) {
1836 # I wonder if we should make this count all tags, not just <a>
1837 # and <span>. That would prevent us from matching a ':' that
1838 # comes in the middle of italics other such formatting....
1840 $fname = 'Parser::findColonNoLinks';
1841 wfProfileIn( $fname );
1844 $colon = strpos($str, ':', $pos);
1846 if ($colon !== false) {
1847 $before = substr($str, 0, $colon);
1848 $after = substr($str, $colon +
1);
1850 # Skip any ':' within <a> or <span> pairs
1851 $a = substr_count($before, '<a');
1852 $s = substr_count($before, '<span');
1853 $ca = substr_count($before, '</a>');
1854 $cs = substr_count($before, '</span>');
1856 if ($a <= $ca and $s <= $cs) {
1857 # Tags are balanced before ':'; ok
1862 } while ($colon !== false);
1863 wfProfileOut( $fname );
1868 * Return value of a magic variable (like PAGENAME)
1872 function getVariableValue( $index ) {
1873 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1876 * Some of these require message or data lookups and can be
1877 * expensive to check many times.
1879 static $varCache = array();
1880 if( isset( $varCache[$index] ) ) return $varCache[$index];
1883 case MAG_CURRENTMONTH
:
1884 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1885 case MAG_CURRENTMONTHNAME
:
1886 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1887 case MAG_CURRENTMONTHNAMEGEN
:
1888 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1889 case MAG_CURRENTMONTHABBREV
:
1890 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1891 case MAG_CURRENTDAY
:
1892 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1894 return $this->mTitle
->getText();
1896 return $this->mTitle
->getPartialURL();
1897 case MAG_REVISIONID
:
1898 return $wgArticle->getRevIdFetched();
1900 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1901 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1902 case MAG_CURRENTDAYNAME
:
1903 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1904 case MAG_CURRENTYEAR
:
1905 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1906 case MAG_CURRENTTIME
:
1907 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1908 case MAG_CURRENTWEEK
:
1909 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1910 case MAG_CURRENTDOW
:
1911 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1912 case MAG_NUMBEROFARTICLES
:
1913 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1914 case MAG_NUMBEROFFILES
:
1915 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1920 case MAG_SERVERNAME
:
1921 return $wgServerName;
1922 case MAG_SCRIPTPATH
:
1923 return $wgScriptPath;
1930 * initialise the magic variables (like CURRENTMONTHNAME)
1934 function initialiseVariables() {
1935 $fname = 'Parser::initialiseVariables';
1936 wfProfileIn( $fname );
1937 global $wgVariableIDs;
1938 $this->mVariables
= array();
1939 foreach ( $wgVariableIDs as $id ) {
1940 $mw =& MagicWord
::get( $id );
1941 $mw->addToArray( $this->mVariables
, $id );
1943 wfProfileOut( $fname );
1947 * parse any parentheses in format ((title|part|part))
1948 * and call callbacks to get a replacement text for any found piece
1950 * @param string $text The text to parse
1951 * @param array $callbacks rules in form:
1952 * '{' => array( # opening parentheses
1953 * 'end' => '}', # closing parentheses
1954 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1955 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1960 function replace_callback ($text, $callbacks) {
1961 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1962 $lastOpeningBrace = -1; # last not closed parentheses
1964 for ($i = 0; $i < strlen($text); $i++
) {
1965 # check for any opening brace
1968 foreach ($callbacks as $key => $value) {
1969 $pos = strpos ($text, $key, $i);
1970 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
1976 if ($lastOpeningBrace >= 0) {
1977 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
1979 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
1984 $pos = strpos ($text, '|', $i);
1986 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
1997 # found openning brace, lets add it to parentheses stack
1998 if (null != $rule) {
1999 $piece = array('brace' => $text[$i],
2000 'braceEnd' => $rule['end'],
2005 # count openning brace characters
2006 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2011 $piece['startAt'] = $i+
1;
2012 $piece['partStart'] = $i+
1;
2014 # we need to add to stack only if openning brace count is enough for any given rule
2015 foreach ($rule['cb'] as $cnt => $fn) {
2016 if ($piece['count'] >= $cnt) {
2017 $lastOpeningBrace ++
;
2018 $openingBraceStack[$lastOpeningBrace] = $piece;
2025 else if ($lastOpeningBrace >= 0) {
2026 # first check if it is a closing brace
2027 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2028 # lets check if it is enough characters for closing brace
2030 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2033 # if there are more closing parentheses than opening ones, we parse less
2034 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2035 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2037 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2039 $matchingCallback = null;
2040 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2041 if ($count >= $cnt && $matchingCount < $cnt) {
2042 $matchingCount = $cnt;
2043 $matchingCallback = $fn;
2047 if ($matchingCount == 0) {
2052 # lets set a title or last part (if '|' was found)
2053 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2054 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2056 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2058 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2059 $pieceEnd = $i +
$matchingCount;
2061 if( is_callable( $matchingCallback ) ) {
2063 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2064 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2065 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2066 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2068 # finally we can call a user callback and replace piece of text
2069 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2070 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2071 $i = $pieceStart +
strlen($replaceWith) - 1;
2074 # null value for callback means that parentheses should be parsed, but not replaced
2075 $i +
= $matchingCount - 1;
2078 # reset last openning parentheses, but keep it in case there are unused characters
2079 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2080 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2081 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2084 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2085 $openingBraceStack[$lastOpeningBrace--] = null;
2087 if ($matchingCount < $piece['count']) {
2088 $piece['count'] -= $matchingCount;
2089 $piece['startAt'] -= $matchingCount;
2090 $piece['partStart'] = $piece['startAt'];
2091 # do we still qualify for any callback with remaining count?
2092 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2093 if ($piece['count'] >= $cnt) {
2094 $lastOpeningBrace ++
;
2095 $openingBraceStack[$lastOpeningBrace] = $piece;
2103 # lets set a title if it is a first separator, or next part otherwise
2104 if ($text[$i] == '|') {
2105 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2106 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2107 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2110 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2112 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2121 * Replace magic variables, templates, and template arguments
2122 * with the appropriate text. Templates are substituted recursively,
2123 * taking care to avoid infinite loops.
2125 * Note that the substitution depends on value of $mOutputType:
2126 * OT_WIKI: only {{subst:}} templates
2127 * OT_MSG: only magic variables
2128 * OT_HTML: all templates and magic variables
2130 * @param string $tex The text to transform
2131 * @param array $args Key-value pairs representing template parameters to substitute
2134 function replaceVariables( $text, $args = array() ) {
2135 # Prevent too big inclusions
2136 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2140 $fname = 'Parser::replaceVariables';
2141 wfProfileIn( $fname );
2143 $titleChars = Title
::legalChars();
2145 # This function is called recursively. To keep track of arguments we need a stack:
2146 array_push( $this->mArgStack
, $args );
2148 $braceCallbacks = array();
2149 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2150 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2151 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2153 $callbacks = array();
2154 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2155 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2156 $text = $this->replace_callback ($text, $callbacks);
2158 array_pop( $this->mArgStack
);
2160 wfProfileOut( $fname );
2165 * Replace magic variables
2168 function variableSubstitution( $matches ) {
2169 $fname = 'parser::variableSubstitution';
2170 $varname = $matches[1];
2171 wfProfileIn( $fname );
2172 if ( !$this->mVariables
) {
2173 $this->initialiseVariables();
2176 if ( $this->mOutputType
== OT_WIKI
) {
2177 # Do only magic variables prefixed by SUBST
2178 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2179 if (!$mwSubst->matchStartAndRemove( $varname ))
2181 # Note that if we don't substitute the variable below,
2182 # we don't remove the {{subst:}} magic word, in case
2183 # it is a template rather than a magic variable.
2185 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2186 $id = $this->mVariables
[$varname];
2187 $text = $this->getVariableValue( $id );
2188 $this->mOutput
->mContainsOldMagic
= true;
2190 $text = $matches[0];
2192 wfProfileOut( $fname );
2196 # Split template arguments
2197 function getTemplateArgs( $argsString ) {
2198 if ( $argsString === '' ) {
2202 $args = explode( '|', substr( $argsString, 1 ) );
2204 # If any of the arguments contains a '[[' but no ']]', it needs to be
2205 # merged with the next arg because the '|' character between belongs
2206 # to the link syntax and not the template parameter syntax.
2207 $argc = count($args);
2209 for ( $i = 0; $i < $argc-1; $i++
) {
2210 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2211 $args[$i] .= '|'.$args[$i+
1];
2212 array_splice($args, $i+
1, 1);
2222 * Return the text of a template, after recursively
2223 * replacing any variables or templates within the template.
2225 * @param array $piece The parts of the template
2226 * $piece['text']: matched text
2227 * $piece['title']: the title, i.e. the part before the |
2228 * $piece['parts']: the parameter array
2229 * @return string the text of the template
2232 function braceSubstitution( $piece ) {
2233 global $wgLinkCache, $wgContLang;
2234 $fname = 'Parser::braceSubstitution';
2235 wfProfileIn( $fname );
2245 # $part1 is the bit before the first |, and must contain only title characters
2246 # $args is a list of arguments, starting from index 0, not including $part1
2248 $part1 = $piece['title'];
2249 # If the third subpattern matched anything, it will start with |
2251 if (null == $piece['parts']) {
2252 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2253 if ($replaceWith != $piece['text']) {
2254 $text = $replaceWith;
2260 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2261 $argc = count( $args );
2265 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2266 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2267 # One of two possibilities is true:
2268 # 1) Found SUBST but not in the PST phase
2269 # 2) Didn't find SUBST and in the PST phase
2270 # In either case, return without further processing
2271 $text = $piece['text'];
2277 # MSG, MSGNW and INT
2280 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2281 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2284 # Remove obsolete MSG:
2285 $mwMsg =& MagicWord
::get( MAG_MSG
);
2286 $mwMsg->matchStartAndRemove( $part1 );
2289 # Check if it is an internal message
2290 $mwInt =& MagicWord
::get( MAG_INT
);
2291 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2292 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2293 $text = $linestart . wfMsgReal( $part1, $args, true );
2301 # Check for NS: (namespace expansion)
2302 $mwNs = MagicWord
::get( MAG_NS
);
2303 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2304 if ( intval( $part1 ) ) {
2305 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2308 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2309 if ( !is_null( $index ) ) {
2310 $text = $linestart . $wgContLang->getNsText( $index );
2317 # LCFIRST, UCFIRST, LC and UC
2319 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2320 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2321 $lc =& MagicWord
::get( MAG_LC
);
2322 $uc =& MagicWord
::get( MAG_UC
);
2323 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2324 $text = $linestart . $wgContLang->lcfirst( $part1 );
2326 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2327 $text = $linestart . $wgContLang->ucfirst( $part1 );
2329 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2330 $text = $linestart . $wgContLang->lc( $part1 );
2332 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2333 $text = $linestart . $wgContLang->uc( $part1 );
2338 # LOCALURL and FULLURL
2340 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2341 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2342 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2343 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2346 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2347 $func = 'getLocalURL';
2348 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2349 $func = 'escapeLocalURL';
2350 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2351 $func = 'getFullURL';
2352 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2353 $func = 'escapeFullURL';
2358 if ( $func !== false ) {
2359 $title = Title
::newFromText( $part1 );
2360 if ( !is_null( $title ) ) {
2362 $text = $linestart . $title->$func( $args[0] );
2364 $text = $linestart . $title->$func();
2372 if ( !$found && $argc == 1 ) {
2373 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2374 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2375 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2381 if ( !$found && $argc >= 2 ) {
2382 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2383 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2384 if ($argc==2) {$args[2]=$args[1];}
2385 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2390 # Template table test
2392 # Did we encounter this template already? If yes, it is in the cache
2393 # and we need to check for loops.
2394 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2397 # Infinite loop test
2398 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2401 $text = $linestart .
2403 '<!-- WARNING: template loop detected -->';
2404 wfDebug( "$fname: template loop broken at '$part1'\n" );
2406 # set $text to cached message.
2407 $text = $linestart . $this->mTemplates
[$part1];
2411 # Load from database
2412 $replaceHeadings = false;
2414 $lastPathLevel = $this->mTemplatePath
;
2417 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2418 if ($subpage !== '') {
2419 $ns = $this->mTitle
->getNamespace();
2421 $title = Title
::newFromText( $part1, $ns );
2424 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2425 if ($interwiki != '' && $title->isTrans()) {
2426 return $this->scarytransclude($title, $interwiki);
2430 if ( !is_null( $title ) && !$title->isExternal() ) {
2431 # Check for excessive inclusion
2432 $dbk = $title->getPrefixedDBkey();
2433 if ( $this->incrementIncludeCount( $dbk ) ) {
2434 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2435 # Capture special page output
2436 $text = SpecialPage
::capturePath( $title );
2437 if ( is_string( $text ) ) {
2441 $this->disableCache();
2444 $article = new Article( $title );
2445 $articleContent = $article->fetchContent(0, false);
2446 if ( $articleContent !== false ) {
2448 $text = $articleContent;
2449 $replaceHeadings = true;
2454 # If the title is valid but undisplayable, make a link to it
2455 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2456 $text = '[['.$title->getPrefixedText().']]';
2460 # Template cache array insertion
2462 $this->mTemplates
[$part1] = $text;
2463 $text = $linestart . $text;
2468 # Recursive parsing, escaping and link table handling
2469 # Only for HTML output
2470 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2471 $text = wfEscapeWikiText( $text );
2472 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2473 # Clean up argument array
2474 $assocArgs = array();
2476 foreach( $args as $arg ) {
2477 $eqpos = strpos( $arg, '=' );
2478 if ( $eqpos === false ) {
2479 $assocArgs[$index++
] = $arg;
2481 $name = trim( substr( $arg, 0, $eqpos ) );
2482 $value = trim( substr( $arg, $eqpos+
1 ) );
2483 if ( $value === false ) {
2486 if ( $name !== false ) {
2487 $assocArgs[$name] = $value;
2492 # Add a new element to the templace recursion path
2493 $this->mTemplatePath
[$part1] = 1;
2495 if( $this->mOutputType
== OT_HTML
) {
2496 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2497 preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
2499 foreach ($m[1] as $piece)
2500 $text .= $this->trimOnlyinclude( $piece );
2502 # Remove <noinclude> sections and <includeonly> tags
2503 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2504 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2505 # Strip <nowiki>, <pre>, etc.
2506 $text = $this->strip( $text, $this->mStripState
);
2507 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2509 $text = $this->replaceVariables( $text, $assocArgs );
2511 # Resume the link cache and register the inclusion as a link
2512 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2513 $wgLinkCache->addLinkObj( $title );
2516 # If the template begins with a table or block-level
2517 # element, it should be treated as beginning a new line.
2518 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2519 $text = "\n" . $text;
2522 # Prune lower levels off the recursion check path
2523 $this->mTemplatePath
= $lastPathLevel;
2526 wfProfileOut( $fname );
2527 return $piece['text'];
2530 # Replace raw HTML by a placeholder
2531 # Add a blank line preceding, to prevent it from mucking up
2532 # immediately preceding headings
2533 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2535 # replace ==section headers==
2536 # XXX this needs to go away once we have a better parser.
2537 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2538 if( !is_null( $title ) )
2539 $encodedname = base64_encode($title->getPrefixedDBkey());
2541 $encodedname = base64_encode("");
2542 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2543 PREG_SPLIT_DELIM_CAPTURE
);
2546 for( $i = 0; $i < count($m); $i +
= 2 ) {
2548 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2550 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2554 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2555 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2556 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2564 # Prune lower levels off the recursion check path
2565 $this->mTemplatePath
= $lastPathLevel;
2568 wfProfileOut( $fname );
2569 return $piece['text'];
2571 wfProfileOut( $fname );
2577 * Trim the first and last newlines of a string, this is not equivalent
2578 * to trim( $str, "\n" ) which would trim them all.
2580 * @param string $str The string to trim
2583 function trimOnlyinclude( $str ) {
2584 $str = preg_replace( "/^\n/", '', $str );
2585 $str = preg_replace( "/\n$/", '', $str );
2590 * Translude an interwiki link.
2592 function scarytransclude($title, $interwiki) {
2593 global $wgEnableScaryTranscluding;
2595 if (!$wgEnableScaryTranscluding)
2596 return wfMsg('scarytranscludedisabled');
2598 $articlename = "Template:" . $title->getDBkey();
2599 $url = str_replace('$1', urlencode($articlename), $interwiki);
2600 if (strlen($url) > 255)
2601 return wfMsg('scarytranscludetoolong');
2602 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2603 $this->mIWTransData
[] = $text;
2604 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2607 function fetchScaryTemplateMaybeFromCache($url) {
2608 $dbr =& wfGetDB(DB_SLAVE
);
2609 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2610 array('tc_url' => $url));
2612 $time = $obj->tc_time
;
2613 $text = $obj->tc_contents
;
2614 if ($time && $time < (time() +
(60*60))) {
2619 $text = wfGetHTTP($url . '?action=render');
2621 return wfMsg('scarytranscludefailed', $url);
2623 $dbw =& wfGetDB(DB_MASTER
);
2624 $dbw->replace('transcache', array(), array(
2626 'tc_time' => time(),
2627 'tc_contents' => $text));
2633 * Triple brace replacement -- used for template arguments
2636 function argSubstitution( $matches ) {
2637 $arg = trim( $matches['title'] );
2638 $text = $matches['text'];
2639 $inputArgs = end( $this->mArgStack
);
2641 if ( array_key_exists( $arg, $inputArgs ) ) {
2642 $text = $inputArgs[$arg];
2643 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2644 $text = $matches['parts'][0];
2651 * Returns true if the function is allowed to include this entity
2654 function incrementIncludeCount( $dbk ) {
2655 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2656 $this->mIncludeCount
[$dbk] = 0;
2658 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2666 * This function accomplishes several tasks:
2667 * 1) Auto-number headings if that option is enabled
2668 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2669 * 3) Add a Table of contents on the top for users who have enabled the option
2670 * 4) Auto-anchor headings
2672 * It loops through all headlines, collects the necessary data, then splits up the
2673 * string and re-inserts the newly formatted headlines.
2675 * @param string $text
2676 * @param boolean $isMain
2679 function formatHeadings( $text, $isMain=true ) {
2680 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2682 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2684 $forceTocHere = false;
2685 if( !$this->mTitle
->userCanEdit() ) {
2688 $showEditLink = $this->mOptions
->getEditSection();
2691 # Inhibit editsection links if requested in the page
2692 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2693 if( $esw->matchAndRemove( $text ) ) {
2696 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2698 $mw =& MagicWord
::get( MAG_NOTOC
);
2699 if( $mw->matchAndRemove( $text ) ) {
2703 # Get all headlines for numbering them and adding funky stuff like [edit]
2704 # links - this is for later, but we need the number of headlines right now
2705 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2707 # if there are fewer than 4 headlines in the article, do not show TOC
2708 if( $numMatches < 4 ) {
2712 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2713 # override above conditions and always show TOC at that place
2715 $mw =& MagicWord
::get( MAG_TOC
);
2716 if($mw->match( $text ) ) {
2718 $forceTocHere = true;
2720 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2721 # override above conditions and always show TOC above first header
2722 $mw =& MagicWord
::get( MAG_FORCETOC
);
2723 if ($mw->matchAndRemove( $text ) ) {
2728 # Never ever show TOC if no headers
2729 if( $numMatches < 1 ) {
2733 # We need this to perform operations on the HTML
2734 $sk =& $this->mOptions
->getSkin();
2738 $sectionCount = 0; # headlineCount excluding template sections
2740 # Ugh .. the TOC should have neat indentation levels which can be
2741 # passed to the skin functions. These are determined here
2745 $sublevelCount = array();
2746 $levelCount = array();
2753 foreach( $matches[3] as $headline ) {
2755 $templatetitle = '';
2756 $templatesection = 0;
2759 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2761 $templatetitle = base64_decode($mat[1]);
2762 $templatesection = 1 +
(int)base64_decode($mat[2]);
2763 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2767 $prevlevel = $level;
2768 $prevtoclevel = $toclevel;
2770 $level = $matches[1][$headlineCount];
2772 if( $doNumberHeadings ||
$doShowToc ) {
2774 if ( $level > $prevlevel ) {
2775 # Increase TOC level
2777 $sublevelCount[$toclevel] = 0;
2778 $toc .= $sk->tocIndent();
2780 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2781 # Decrease TOC level, find level to jump to
2783 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2784 # Can only go down to level 1
2787 for ($i = $toclevel; $i > 0; $i--) {
2788 if ( $levelCount[$i] == $level ) {
2789 # Found last matching level
2793 elseif ( $levelCount[$i] < $level ) {
2794 # Found first matching level below current level
2801 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2804 # No change in level, end TOC line
2805 $toc .= $sk->tocLineEnd();
2808 $levelCount[$toclevel] = $level;
2810 # count number of headlines for each level
2811 @$sublevelCount[$toclevel]++
;
2813 for( $i = 1; $i <= $toclevel; $i++
) {
2814 if( !empty( $sublevelCount[$i] ) ) {
2818 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2824 # The canonized header is a version of the header text safe to use for links
2825 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2826 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2827 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2829 # Remove link placeholders by the link text.
2830 # <!--LINK number-->
2832 # link text with suffix
2833 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2834 "\$this->mLinkHolders['texts'][\$1]",
2835 $canonized_headline );
2836 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2837 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2838 $canonized_headline );
2841 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2842 $tocline = trim( $canonized_headline );
2843 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2844 $replacearray = array(
2848 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2849 $refers[$headlineCount] = $canonized_headline;
2851 # count how many in assoc. array so we can track dupes in anchors
2852 @$refers[$canonized_headline]++
;
2853 $refcount[$headlineCount]=$refers[$canonized_headline];
2855 # Don't number the heading if it is the only one (looks silly)
2856 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2857 # the two are different if the line contains a link
2858 $headline=$numbering . ' ' . $headline;
2861 # Create the anchor for linking from the TOC to the section
2862 $anchor = $canonized_headline;
2863 if($refcount[$headlineCount] > 1 ) {
2864 $anchor .= '_' . $refcount[$headlineCount];
2866 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2867 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2869 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2870 if ( empty( $head[$headlineCount] ) ) {
2871 $head[$headlineCount] = '';
2874 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2876 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2879 # give headline the correct <h#> tag
2880 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2888 $toc .= $sk->tocUnindent( $toclevel - 1 );
2889 $toc = $sk->tocList( $toc );
2892 # split up and insert constructed headlines
2894 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2897 foreach( $blocks as $block ) {
2898 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2899 # This is the [edit] link that appears for the top block of text when
2900 # section editing is enabled
2902 # Disabled because it broke block formatting
2903 # For example, a bullet point in the top line
2904 # $full .= $sk->editSectionLink(0);
2907 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2908 # Top anchor now in skin
2912 if( !empty( $head[$i] ) ) {
2918 $mw =& MagicWord
::get( MAG_TOC
);
2919 return $mw->replace( $toc, $full );
2926 * Return an HTML link for the "ISBN 123456" text
2929 function magicISBN( $text ) {
2930 $fname = 'Parser::magicISBN';
2931 wfProfileIn( $fname );
2933 $a = split( 'ISBN ', ' '.$text );
2934 if ( count ( $a ) < 2 ) {
2935 wfProfileOut( $fname );
2938 $text = substr( array_shift( $a ), 1);
2939 $valid = '0123456789-Xx';
2941 foreach ( $a as $x ) {
2942 $isbn = $blank = '' ;
2943 while ( ' ' == $x{0} ) {
2945 $x = substr( $x, 1 );
2947 if ( $x == '' ) { # blank isbn
2948 $text .= "ISBN $blank";
2951 while ( strstr( $valid, $x{0} ) != false ) {
2953 $x = substr( $x, 1 );
2955 $num = str_replace( '-', '', $isbn );
2956 $num = str_replace( ' ', '', $num );
2957 $num = str_replace( 'x', 'X', $num );
2960 $text .= "ISBN $blank$x";
2962 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2963 $text .= '<a href="' .
2964 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2965 "\" class=\"internal\">ISBN $isbn</a>";
2969 wfProfileOut( $fname );
2974 * Return an HTML link for the "RFC 1234" text
2977 * @param string $text Text to be processed
2978 * @param string $keyword Magic keyword to use (default RFC)
2979 * @param string $urlmsg Interface message to use (default rfcurl)
2982 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2984 $valid = '0123456789';
2987 $a = split( $keyword, ' '.$text );
2988 if ( count ( $a ) < 2 ) {
2991 $text = substr( array_shift( $a ), 1);
2993 /* Check if keyword is preceed by [[.
2994 * This test is made here cause of the array_shift above
2995 * that prevent the test to be done in the foreach.
2997 if ( substr( $text, -2 ) == '[[' ) {
3001 foreach ( $a as $x ) {
3002 /* token might be empty if we have RFC RFC 1234 */
3010 /** remove and save whitespaces in $blank */
3011 while ( $x{0} == ' ' ) {
3013 $x = substr( $x, 1 );
3016 /** remove and save the rfc number in $id */
3017 while ( strstr( $valid, $x{0} ) != false ) {
3019 $x = substr( $x, 1 );
3023 /* call back stripped spaces*/
3024 $text .= $keyword.$blank.$x;
3025 } elseif( $internal ) {
3027 $text .= $keyword.$id.$x;
3029 /* build the external link*/
3030 $url = wfMsg( $urlmsg, $id);
3031 $sk =& $this->mOptions
->getSkin();
3032 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3033 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3036 /* Check if the next RFC keyword is preceed by [[ */
3037 $internal = ( substr($x,-2) == '[[' );
3043 * Transform wiki markup when saving a page by doing \r\n -> \n
3044 * conversion, substitting signatures, {{subst:}} templates, etc.
3046 * @param string $text the text to transform
3047 * @param Title &$title the Title object for the current article
3048 * @param User &$user the User object describing the current user
3049 * @param ParserOptions $options parsing options
3050 * @param bool $clearState whether to clear the parser state first
3051 * @return string the altered wiki markup
3054 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3055 $this->mOptions
= $options;
3056 $this->mTitle
=& $title;
3057 $this->mOutputType
= OT_WIKI
;
3059 if ( $clearState ) {
3060 $this->clearState();
3063 $stripState = false;
3067 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3068 $text = $this->strip( $text, $stripState, true );
3069 $text = $this->pstPass2( $text, $user );
3070 $text = $this->unstrip( $text, $stripState );
3071 $text = $this->unstripNoWiki( $text, $stripState );
3076 * Pre-save transform helper function
3079 function pstPass2( $text, &$user ) {
3080 global $wgContLang, $wgLocaltimezone;
3082 # Variable replacement
3083 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3084 $text = $this->replaceVariables( $text );
3088 $n = $user->getName();
3089 $k = $user->getOption( 'nickname' );
3090 if ( '' == $k ) { $k = $n; }
3091 if ( isset( $wgLocaltimezone ) ) {
3092 $oldtz = getenv( 'TZ' );
3093 putenv( 'TZ='.$wgLocaltimezone );
3096 /* Note: This is the timestamp saved as hardcoded wikitext to
3097 * the database, we use $wgContLang here in order to give
3098 * everyone the same signiture and use the default one rather
3099 * than the one selected in each users preferences.
3101 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3102 ' (' . date( 'T' ) . ')';
3103 if ( isset( $wgLocaltimezone ) ) {
3104 putenv( 'TZ='.$oldtz );
3107 if( $user->getOption( 'fancysig' ) ) {
3110 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
3112 $text = preg_replace( '/~~~~~/', $d, $text );
3113 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3114 $text = preg_replace( '/~~~/', $sigText, $text );
3116 # Context links: [[|name]] and [[name (context)|]]
3118 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
3119 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
3120 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3121 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3123 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3124 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3125 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3126 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3128 $t = $this->mTitle
->getText();
3129 if ( preg_match( $conpat, $t, $m ) ) {
3132 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3133 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3134 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3136 if ( '' == $context ) {
3137 $text = preg_replace( $p2, '[[\\1]]', $text );
3139 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3142 # Trim trailing whitespace
3143 # MAG_END (__END__) tag allows for trailing
3144 # whitespace to be deliberately included
3145 $text = rtrim( $text );
3146 $mw =& MagicWord
::get( MAG_END
);
3147 $mw->matchAndRemove( $text );
3153 * Set up some variables which are usually set up in parse()
3154 * so that an external function can call some class members with confidence
3157 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3158 $this->mTitle
=& $title;
3159 $this->mOptions
= $options;
3160 $this->mOutputType
= $outputType;
3161 if ( $clearState ) {
3162 $this->clearState();
3167 * Transform a MediaWiki message by replacing magic variables.
3169 * @param string $text the text to transform
3170 * @param ParserOptions $options options
3171 * @return string the text with variables substituted
3174 function transformMsg( $text, $options ) {
3176 static $executing = false;
3178 # Guard against infinite recursion
3184 $this->mTitle
= $wgTitle;
3185 $this->mOptions
= $options;
3186 $this->mOutputType
= OT_MSG
;
3187 $this->clearState();
3188 $text = $this->replaceVariables( $text );
3195 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3196 * Callback will be called with the text within
3197 * Transform and return the text within
3200 function setHook( $tag, $callback ) {
3201 $oldVal = @$this->mTagHooks
[$tag];
3202 $this->mTagHooks
[$tag] = $callback;
3207 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3208 * Placeholders created in Skin::makeLinkObj()
3209 * Returns an array of links found, indexed by PDBK:
3213 * $options is a bit field, RLH_FOR_UPDATE to select for update
3215 function replaceLinkHolders( &$text, $options = 0 ) {
3216 global $wgUser, $wgLinkCache;
3217 global $wgOutputReplace;
3219 $fname = 'Parser::replaceLinkHolders';
3220 wfProfileIn( $fname );
3224 $sk = $this->mOptions
->getSkin();
3226 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3227 wfProfileIn( $fname.'-check' );
3228 $dbr =& wfGetDB( DB_SLAVE
);
3229 $page = $dbr->tableName( 'page' );
3230 $threshold = $wgUser->getOption('stubthreshold');
3233 asort( $this->mLinkHolders
['namespaces'] );
3237 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3239 $title = $this->mLinkHolders
['titles'][$key];
3241 # Skip invalid entries.
3242 # Result will be ugly, but prevents crash.
3243 if ( is_null( $title ) ) {
3246 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3248 # Check if it's in the link cache already
3249 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3250 $colours[$pdbk] = 1;
3251 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3252 $colours[$pdbk] = 0;
3254 # Not in the link cache, add it to the query
3255 if ( !isset( $current ) ) {
3257 $query = "SELECT page_id, page_namespace, page_title";
3258 if ( $threshold > 0 ) {
3259 $query .= ', page_len, page_is_redirect';
3261 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3262 } elseif ( $current != $val ) {
3264 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3269 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3274 if ( $options & RLH_FOR_UPDATE
) {
3275 $query .= ' FOR UPDATE';
3278 $res = $dbr->query( $query, $fname );
3280 # Fetch data and form into an associative array
3281 # non-existent = broken
3284 while ( $s = $dbr->fetchObject($res) ) {
3285 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3286 $pdbk = $title->getPrefixedDBkey();
3287 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3289 if ( $threshold > 0 ) {
3290 $size = $s->page_len
;
3291 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3292 $colours[$pdbk] = 1;
3294 $colours[$pdbk] = 2;
3297 $colours[$pdbk] = 1;
3301 wfProfileOut( $fname.'-check' );
3303 # Construct search and replace arrays
3304 wfProfileIn( $fname.'-construct' );
3305 $wgOutputReplace = array();
3306 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3307 $pdbk = $pdbks[$key];
3308 $searchkey = "<!--LINK $key-->";
3309 $title = $this->mLinkHolders
['titles'][$key];
3310 if ( empty( $colours[$pdbk] ) ) {
3311 $wgLinkCache->addBadLinkObj( $title );
3312 $colours[$pdbk] = 0;
3313 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3314 $this->mLinkHolders
['texts'][$key],
3315 $this->mLinkHolders
['queries'][$key] );
3316 } elseif ( $colours[$pdbk] == 1 ) {
3317 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3318 $this->mLinkHolders
['texts'][$key],
3319 $this->mLinkHolders
['queries'][$key] );
3320 } elseif ( $colours[$pdbk] == 2 ) {
3321 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3322 $this->mLinkHolders
['texts'][$key],
3323 $this->mLinkHolders
['queries'][$key] );
3326 wfProfileOut( $fname.'-construct' );
3329 wfProfileIn( $fname.'-replace' );
3331 $text = preg_replace_callback(
3332 '/(<!--LINK .*?-->)/',
3333 "wfOutputReplaceMatches",
3336 wfProfileOut( $fname.'-replace' );
3339 # Now process interwiki link holders
3340 # This is quite a bit simpler than internal links
3341 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3342 wfProfileIn( $fname.'-interwiki' );
3343 # Make interwiki link HTML
3344 $wgOutputReplace = array();
3345 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3346 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3347 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3350 $text = preg_replace_callback(
3351 '/<!--IWLINK (.*?)-->/',
3352 "wfOutputReplaceMatches",
3354 wfProfileOut( $fname.'-interwiki' );
3357 wfProfileOut( $fname );
3362 * Replace <!--LINK--> link placeholders with plain text of links
3363 * (not HTML-formatted).
3364 * @param string $text
3367 function replaceLinkHoldersText( $text ) {
3368 global $wgUser, $wgLinkCache;
3369 global $wgOutputReplace;
3371 $fname = 'Parser::replaceLinkHoldersText';
3372 wfProfileIn( $fname );
3374 $text = preg_replace_callback(
3375 '/<!--(LINK|IWLINK) (.*?)-->/',
3376 array( &$this, 'replaceLinkHoldersTextCallback' ),
3379 wfProfileOut( $fname );
3384 * @param array $matches
3388 function replaceLinkHoldersTextCallback( $matches ) {
3389 $type = $matches[1];
3391 if( $type == 'LINK' ) {
3392 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3393 return $this->mLinkHolders
['texts'][$key];
3395 } elseif( $type == 'IWLINK' ) {
3396 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3397 return $this->mInterwikiLinkHolders
['texts'][$key];
3404 * Renders an image gallery from a text with one line per image.
3405 * text labels may be given by using |-style alternative text. E.g.
3406 * Image:one.jpg|The number "1"
3407 * Image:tree.jpg|A tree
3408 * given as text will return the HTML of a gallery with two images,
3409 * labeled 'The number "1"' and
3414 function renderImageGallery( $text ) {
3416 global $wgUser, $wgTitle;
3417 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3418 $localParser = new Parser();
3420 global $wgLinkCache;
3421 $ig = new ImageGallery();
3422 $ig->setShowBytes( false );
3423 $ig->setShowFilename( false );
3424 $lines = explode( "\n", $text );
3426 foreach ( $lines as $line ) {
3427 # match lines like these:
3428 # Image:someimage.jpg|This is some image
3429 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3431 if ( count( $matches ) == 0 ) {
3434 $nt = Title
::newFromURL( $matches[1] );
3435 if( is_null( $nt ) ) {
3436 # Bogus title. Ignore these so we don't bomb out later.
3439 if ( isset( $matches[3] ) ) {
3440 $label = $matches[3];
3445 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3446 $html = $html->mText
;
3448 $ig->add( new Image( $nt ), $html );
3449 $wgLinkCache->addImageLinkObj( $nt );
3451 return $ig->toHTML();
3455 * Parse image options text and use it to make an image
3457 function makeImage( &$nt, $options ) {
3458 global $wgContLang, $wgUseImageResize;
3459 global $wgUser, $wgThumbLimits;
3463 # Check if the options text is of the form "options|alt text"
3465 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3466 # * left no resizing, just left align. label is used for alt= only
3467 # * right same, but right aligned
3468 # * none same, but not aligned
3469 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3470 # * center center the image
3471 # * framed Keep original image size, no magnify-button.
3473 $part = explode( '|', $options);
3475 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3476 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3477 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3478 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3479 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3480 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3481 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3482 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3485 $width = $height = $framed = $thumb = false;
3486 $manual_thumb = '' ;
3488 foreach( $part as $key => $val ) {
3489 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3491 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3492 # use manually specified thumbnail
3494 $manual_thumb = $match;
3495 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3496 # remember to set an alignment, don't render immediately
3498 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3499 # remember to set an alignment, don't render immediately
3501 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3502 # remember to set an alignment, don't render immediately
3504 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3505 # remember to set an alignment, don't render immediately
3507 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3508 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3509 # $match is the image width in pixels
3510 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3511 $width = intval( $m[1] );
3512 $height = intval( $m[2] );
3514 $width = intval($match);
3516 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3522 # Strip bad stuff out of the alt text
3523 $alt = $this->replaceLinkHoldersText( $caption );
3524 $alt = Sanitizer
::stripAllTags( $alt );
3526 # Linker does the rest
3527 $sk =& $this->mOptions
->getSkin();
3528 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3532 * Set a flag in the output object indicating that the content is dynamic and
3533 * shouldn't be cached.
3535 function disableCache() {
3536 $this->mOutput
->mCacheTime
= -1;
3540 * Callback from the Sanitizer for expanding items found in HTML attribute
3541 * values, so they can be safely tested and escaped.
3542 * @param string $text
3543 * @param array $args
3547 function attributeStripCallback( &$text, $args ) {
3548 $text = $this->replaceVariables( $text, $args );
3549 $text = $this->unstripForHTML( $text );
3553 function unstripForHTML( $text ) {
3554 $text = $this->unstrip( $text, $this->mStripState
);
3555 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3562 * @package MediaWiki
3566 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3567 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3568 var $mVersion; # Compatibility check
3569 var $mTitleText; # title text of the chosen language variant
3571 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3572 $containsOldMagic = false, $titletext = '' )
3574 $this->mText
= $text;
3575 $this->mLanguageLinks
= $languageLinks;
3576 $this->mCategoryLinks
= $categoryLinks;
3577 $this->mContainsOldMagic
= $containsOldMagic;
3578 $this->mCacheTime
= '';
3579 $this->mVersion
= MW_PARSER_VERSION
;
3580 $this->mTitleText
= $titletext;
3583 function getText() { return $this->mText
; }
3584 function getLanguageLinks() { return $this->mLanguageLinks
; }
3585 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3586 function getCacheTime() { return $this->mCacheTime
; }
3587 function getTitleText() { return $this->mTitleText
; }
3588 function containsOldMagic() { return $this->mContainsOldMagic
; }
3589 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3590 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3591 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3592 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3593 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3594 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3596 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3598 function merge( $other ) {
3599 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3600 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3601 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3605 * Return true if this cached output object predates the global or
3606 * per-article cache invalidation timestamps, or if it comes from
3607 * an incompatible older version.
3609 * @param string $touched the affected article's last touched timestamp
3613 function expired( $touched ) {
3614 global $wgCacheEpoch;
3615 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3616 $this->getCacheTime() <= $touched ||
3617 $this->getCacheTime() <= $wgCacheEpoch ||
3618 !isset( $this->mVersion
) ||
3619 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3624 * Set options of the Parser
3626 * @package MediaWiki
3630 # All variables are private
3631 var $mUseTeX; # Use texvc to expand <math> tags
3632 var $mUseDynamicDates; # Use DateFormatter to format dates
3633 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3634 var $mAllowExternalImages; # Allow external images inline
3635 var $mAllowExternalImagesFrom; # If not, any exception?
3636 var $mSkin; # Reference to the preferred skin
3637 var $mDateFormat; # Date format index
3638 var $mEditSection; # Create "edit section" links
3639 var $mNumberHeadings; # Automatically number headings
3640 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3642 function getUseTeX() { return $this->mUseTeX
; }
3643 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3644 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3645 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3646 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3647 function &getSkin() { return $this->mSkin
; }
3648 function getDateFormat() { return $this->mDateFormat
; }
3649 function getEditSection() { return $this->mEditSection
; }
3650 function getNumberHeadings() { return $this->mNumberHeadings
; }
3651 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3654 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3655 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3656 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3657 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3658 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3659 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3660 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3661 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3662 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3664 function setSkin( &$x ) { $this->mSkin
=& $x; }
3666 function ParserOptions() {
3668 $this->initialiseFromUser( $wgUser );
3672 * Get parser options
3675 function newFromUser( &$user ) {
3676 $popts = new ParserOptions
;
3677 $popts->initialiseFromUser( $user );
3681 /** Get user options */
3682 function initialiseFromUser( &$userInput ) {
3683 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3684 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3685 $fname = 'ParserOptions::initialiseFromUser';
3686 wfProfileIn( $fname );
3687 if ( !$userInput ) {
3689 $user->setLoaded( true );
3691 $user =& $userInput;
3694 $this->mUseTeX
= $wgUseTeX;
3695 $this->mUseDynamicDates
= $wgUseDynamicDates;
3696 $this->mInterwikiMagic
= $wgInterwikiMagic;
3697 $this->mAllowExternalImages
= $wgAllowExternalImages;
3698 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3699 wfProfileIn( $fname.'-skin' );
3700 $this->mSkin
=& $user->getSkin();
3701 wfProfileOut( $fname.'-skin' );
3702 $this->mDateFormat
= $user->getOption( 'date' );
3703 $this->mEditSection
= true;
3704 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3705 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3706 wfProfileOut( $fname );
3711 * Callback function used by Parser::replaceLinkHolders()
3712 * to substitute link placeholders.
3714 function &wfOutputReplaceMatches( $matches ) {
3715 global $wgOutputReplace;
3716 return $wgOutputReplace[$matches[1]];
3720 * Return the total number of articles
3722 function wfNumberOfArticles() {
3723 global $wgNumberOfArticles;
3726 return $wgNumberOfArticles;
3730 * Return the number of files
3732 function wfNumberOfFiles() {
3733 $fname = 'Parser::wfNumberOfFiles';
3735 wfProfileIn( $fname );
3736 $dbr =& wfGetDB( DB_SLAVE
);
3737 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3738 wfProfileOut( $fname );
3744 * Get various statistics from the database
3747 function wfLoadSiteStats() {
3748 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3749 $fname = 'wfLoadSiteStats';
3751 if ( -1 != $wgNumberOfArticles ) return;
3752 $dbr =& wfGetDB( DB_SLAVE
);
3753 $s = $dbr->selectRow( 'site_stats',
3754 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3755 array( 'ss_row_id' => 1 ), $fname
3758 if ( $s === false ) {
3761 $wgTotalViews = $s->ss_total_views
;
3762 $wgTotalEdits = $s->ss_total_edits
;
3763 $wgNumberOfArticles = $s->ss_good_articles
;
3769 * Basicly replacing " > and < with HTML entities ( ", >, <)
3771 * @param string $in Text that might contain HTML tags
3772 * @return string Escaped string
3774 function wfEscapeHTMLTagsOnly( $in ) {
3776 array( '"', '>', '<' ),
3777 array( '"', '>', '<' ),