7d76377be6b20af57435f65f325accdee1af2332
3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.5.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # prefix for escaping, used in two functions at least
47 define( 'UNIQ_PREFIX', 'NaodW29');
49 # Constants needed for external link processing
50 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.$wgUrlProtocols.')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone, $wgAllowSpecialInclusion*
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
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 $contentDict = end( $state );
475 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
476 if( key($state) != 'nowiki' && key($state) != 'html') {
477 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
478 $text = str_replace( key( $contentDict ), $content, $text );
487 * always call this after unstrip() to preserve the order
491 function unstripNoWiki( $text, &$state ) {
492 if ( !is_array( $state ) ) {
496 # Must expand in reverse order, otherwise nested tags will be corrupted
497 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
498 $text = str_replace( key( $state['nowiki'] ), $content, $text );
503 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
504 $text = str_replace( key( $state['html'] ), $content, $text );
512 * Add an item to the strip state
513 * Returns the unique tag which must be inserted into the stripped text
514 * The tag will be replaced with the original text in unstrip()
518 function insertStripItem( $text, &$state ) {
519 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
526 'comment' => array(),
527 'gallery' => array(),
530 $state['item'][$rnd] = $text;
535 * Interface with html tidy, used if $wgUseTidy = true.
536 * If tidy isn't able to correct the markup, the original will be
537 * returned in all its glory with a warning comment appended.
539 * Either the external tidy program or the in-process tidy extension
540 * will be used depending on availability. Override the default
541 * $wgTidyInternal setting to disable the internal if it's not working.
543 * @param string $text Hideous HTML input
544 * @return string Corrected HTML output
548 function tidy( $text ) {
549 global $wgTidyInternal;
550 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
551 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
552 '<head><title>test</title></head><body>'.$text.'</body></html>';
553 if( $wgTidyInternal ) {
554 $correctedtext = Parser
::internalTidy( $wrappedtext );
556 $correctedtext = Parser
::externalTidy( $wrappedtext );
558 if( is_null( $correctedtext ) ) {
559 wfDebug( "Tidy error detected!\n" );
560 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
562 return $correctedtext;
566 * Spawn an external HTML tidy process and get corrected markup back from it.
571 function externalTidy( $text ) {
572 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
573 $fname = 'Parser::externalTidy';
574 wfProfileIn( $fname );
579 $descriptorspec = array(
580 0 => array('pipe', 'r'),
581 1 => array('pipe', 'w'),
582 2 => array('file', '/dev/null', 'a')
585 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
586 if (is_resource($process)) {
587 fwrite($pipes[0], $text);
589 while (!feof($pipes[1])) {
590 $cleansource .= fgets($pipes[1], 1024);
593 proc_close($process);
596 wfProfileOut( $fname );
598 if( $cleansource == '' && $text != '') {
599 // Some kind of error happened, so we couldn't get the corrected text.
600 // Just give up; we'll use the source text and append a warning.
608 * Use the HTML tidy PECL extension to use the tidy library in-process,
609 * saving the overhead of spawning a new process. Currently written to
610 * the PHP 4.3.x version of the extension, may not work on PHP 5.
612 * 'pear install tidy' should be able to compile the extension module.
617 function internalTidy( $text ) {
619 $fname = 'Parser::internalTidy';
620 wfProfileIn( $fname );
622 tidy_load_config( $wgTidyConf );
623 tidy_set_encoding( 'utf8' );
624 tidy_parse_string( $text );
626 if( tidy_get_status() == 2 ) {
627 // 2 is magic number for fatal error
628 // http://www.php.net/manual/en/function.tidy-get-status.php
631 $cleansource = tidy_get_output();
633 wfProfileOut( $fname );
638 * parse the wiki syntax used to render tables
642 function doTableStuff ( $t ) {
643 $fname = 'Parser::doTableStuff';
644 wfProfileIn( $fname );
646 $t = explode ( "\n" , $t ) ;
647 $td = array () ; # Is currently a td tag open?
648 $ltd = array () ; # Was it TD or TH?
649 $tr = array () ; # Is currently a tr tag open?
650 $ltr = array () ; # tr attributes
651 $indent_level = 0; # indent level of the table
652 foreach ( $t AS $k => $x )
655 $fc = substr ( $x , 0 , 1 ) ;
656 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
657 $indent_level = strlen( $matches[1] );
659 $attributes = $this->unstripForHTML( $matches[2] );
661 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
662 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
663 array_push ( $td , false ) ;
664 array_push ( $ltd , '' ) ;
665 array_push ( $tr , false ) ;
666 array_push ( $ltr , '' ) ;
668 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
669 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
670 $z = "</table>" . substr ( $x , 2);
671 $l = array_pop ( $ltd ) ;
672 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
673 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
675 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
677 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
678 $x = substr ( $x , 1 ) ;
679 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
681 $l = array_pop ( $ltd ) ;
682 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
683 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
686 array_push ( $tr , false ) ;
687 array_push ( $td , false ) ;
688 array_push ( $ltd , '' ) ;
689 $attributes = $this->unstripForHTML( $x );
690 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
692 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
694 if ( '|+' == substr ( $x , 0 , 2 ) ) {
696 $x = substr ( $x , 1 ) ;
698 $after = substr ( $x , 1 ) ;
699 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
700 $after = explode ( '||' , $after ) ;
703 # Loop through each table cell
704 foreach ( $after AS $theline )
709 $tra = array_pop ( $ltr ) ;
710 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
711 array_push ( $tr , true ) ;
712 array_push ( $ltr , '' ) ;
715 $l = array_pop ( $ltd ) ;
716 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
717 if ( $fc == '|' ) $l = 'td' ;
718 else if ( $fc == '!' ) $l = 'th' ;
719 else if ( $fc == '+' ) $l = 'caption' ;
721 array_push ( $ltd , $l ) ;
724 $y = explode ( '|' , $theline , 2 ) ;
725 # Note that a '|' inside an invalid link should not
726 # be mistaken as delimiting cell parameters
727 if ( strpos( $y[0], '[[' ) !== false ) {
728 $y = array ($theline);
730 if ( count ( $y ) == 1 )
731 $y = "{$z}<{$l}>{$y[0]}" ;
733 $attributes = $this->unstripForHTML( $y[0] );
734 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
737 array_push ( $td , true ) ;
742 # Closing open td, tr && table
743 while ( count ( $td ) > 0 )
745 if ( array_pop ( $td ) ) $t[] = '</td>' ;
746 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
750 $t = implode ( "\n" , $t ) ;
751 wfProfileOut( $fname );
756 * Helper function for parse() that transforms wiki markup into
757 * HTML. Only called for $mOutputType == OT_HTML.
761 function internalParse( $text ) {
765 $fname = 'Parser::internalParse';
766 wfProfileIn( $fname );
768 # Remove <noinclude> tags and <includeonly> sections
769 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
770 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
771 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
773 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
774 $text = $this->replaceVariables( $text, $args );
776 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
778 $text = $this->doHeadings( $text );
779 if($this->mOptions
->getUseDynamicDates()) {
780 $df =& DateFormatter
::getInstance();
781 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
783 $text = $this->doAllQuotes( $text );
784 $text = $this->replaceInternalLinks( $text );
785 $text = $this->replaceExternalLinks( $text );
787 # replaceInternalLinks may sometimes leave behind
788 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
789 $text = str_replace(UNIQ_PREFIX
."NOPARSE", "", $text);
791 $text = $this->doMagicLinks( $text );
792 $text = $this->doTableStuff( $text );
793 $text = $this->formatHeadings( $text, $isMain );
795 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
796 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
798 wfProfileOut( $fname );
802 function scarySubstitution($matches) {
803 # return "[[".$matches[0]."]]";
804 return $this->mIWTransData
[(int)$matches[0]];
808 * Replace special strings like "ISBN xxx" and "RFC xxx" with
809 * magic external links.
813 function &doMagicLinks( &$text ) {
814 $text = $this->magicISBN( $text );
815 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
816 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
821 * Parse ^^ tokens and return html
825 function doExponent( $text ) {
826 $fname = 'Parser::doExponent';
827 wfProfileIn( $fname );
828 $text = preg_replace('/\^\^(.*?)\^\^/','<small><sup>\\1</sup></small>', $text);
829 wfProfileOut( $fname );
834 * Parse headers and return html
838 function doHeadings( $text ) {
839 $fname = 'Parser::doHeadings';
840 wfProfileIn( $fname );
841 for ( $i = 6; $i >= 1; --$i ) {
842 $h = substr( '======', 0, $i );
843 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
844 "<h{$i}>\\1</h{$i}>\\2", $text );
846 wfProfileOut( $fname );
851 * Replace single quotes with HTML markup
853 * @return string the altered text
855 function doAllQuotes( $text ) {
856 $fname = 'Parser::doAllQuotes';
857 wfProfileIn( $fname );
859 $lines = explode( "\n", $text );
860 foreach ( $lines as $line ) {
861 $outtext .= $this->doQuotes ( $line ) . "\n";
863 $outtext = substr($outtext, 0,-1);
864 wfProfileOut( $fname );
869 * Helper function for doAllQuotes()
872 function doQuotes( $text ) {
873 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
874 if ( count( $arr ) == 1 )
878 # First, do some preliminary work. This may shift some apostrophes from
879 # being mark-up to being text. It also counts the number of occurrences
880 # of bold and italics mark-ups.
884 foreach ( $arr as $r )
886 if ( ( $i %
2 ) == 1 )
888 # If there are ever four apostrophes, assume the first is supposed to
889 # be text, and the remaining three constitute mark-up for bold text.
890 if ( strlen( $arr[$i] ) == 4 )
895 # If there are more than 5 apostrophes in a row, assume they're all
896 # text except for the last 5.
897 else if ( strlen( $arr[$i] ) > 5 )
899 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
902 # Count the number of occurrences of bold and italics mark-ups.
903 # We are not counting sequences of five apostrophes.
904 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
905 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
906 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
911 # If there is an odd number of both bold and italics, it is likely
912 # that one of the bold ones was meant to be an apostrophe followed
913 # by italics. Which one we cannot know for certain, but it is more
914 # likely to be one that has a single-letter word before it.
915 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
918 $firstsingleletterword = -1;
919 $firstmultiletterword = -1;
921 foreach ( $arr as $r )
923 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
925 $x1 = substr ($arr[$i-1], -1);
926 $x2 = substr ($arr[$i-1], -2, 1);
928 if ($firstspace == -1) $firstspace = $i;
929 } else if ($x2 == ' ') {
930 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
932 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
938 # If there is a single-letter word, use it!
939 if ($firstsingleletterword > -1)
941 $arr [ $firstsingleletterword ] = "''";
942 $arr [ $firstsingleletterword-1 ] .= "'";
944 # If not, but there's a multi-letter word, use that one.
945 else if ($firstmultiletterword > -1)
947 $arr [ $firstmultiletterword ] = "''";
948 $arr [ $firstmultiletterword-1 ] .= "'";
950 # ... otherwise use the first one that has neither.
951 # (notice that it is possible for all three to be -1 if, for example,
952 # there is only one pentuple-apostrophe in the line)
953 else if ($firstspace > -1)
955 $arr [ $firstspace ] = "''";
956 $arr [ $firstspace-1 ] .= "'";
960 # Now let's actually convert our apostrophic mush to HTML!
969 if ($state == 'both')
976 if (strlen ($r) == 2)
979 { $output .= '</i>'; $state = ''; }
980 else if ($state == 'bi')
981 { $output .= '</i>'; $state = 'b'; }
982 else if ($state == 'ib')
983 { $output .= '</b></i><b>'; $state = 'b'; }
984 else if ($state == 'both')
985 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
986 else # $state can be 'b' or ''
987 { $output .= '<i>'; $state .= 'i'; }
989 else if (strlen ($r) == 3)
992 { $output .= '</b>'; $state = ''; }
993 else if ($state == 'bi')
994 { $output .= '</i></b><i>'; $state = 'i'; }
995 else if ($state == 'ib')
996 { $output .= '</b>'; $state = 'i'; }
997 else if ($state == 'both')
998 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
999 else # $state can be 'i' or ''
1000 { $output .= '<b>'; $state .= 'b'; }
1002 else if (strlen ($r) == 5)
1005 { $output .= '</b><i>'; $state = 'i'; }
1006 else if ($state == 'i')
1007 { $output .= '</i><b>'; $state = 'b'; }
1008 else if ($state == 'bi')
1009 { $output .= '</i></b>'; $state = ''; }
1010 else if ($state == 'ib')
1011 { $output .= '</b></i>'; $state = ''; }
1012 else if ($state == 'both')
1013 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1014 else # ($state == '')
1015 { $buffer = ''; $state = 'both'; }
1020 # Now close all remaining tags. Notice that the order is important.
1021 if ($state == 'b' ||
$state == 'ib')
1023 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1027 if ($state == 'both')
1028 $output .= '<b><i>'.$buffer.'</i></b>';
1034 * Replace external links
1036 * Note: this is all very hackish and the order of execution matters a lot.
1037 * Make sure to run maintenance/parserTests.php if you change this code.
1041 function replaceExternalLinks( $text ) {
1043 $fname = 'Parser::replaceExternalLinks';
1044 wfProfileIn( $fname );
1046 $sk =& $this->mOptions
->getSkin();
1048 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1050 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1053 while ( $i<count( $bits ) ) {
1055 $protocol = $bits[$i++
];
1056 $text = $bits[$i++
];
1057 $trail = $bits[$i++
];
1059 # The characters '<' and '>' (which were escaped by
1060 # removeHTMLtags()) should not be included in
1061 # URLs, per RFC 2396.
1062 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1063 $text = substr($url, $m2[0][1]) . ' ' . $text;
1064 $url = substr($url, 0, $m2[0][1]);
1067 # If the link text is an image URL, replace it with an <img> tag
1068 # This happened by accident in the original parser, but some people used it extensively
1069 $img = $this->maybeMakeExternalImage( $text );
1070 if ( $img !== false ) {
1076 # Set linktype for CSS - if URL==text, link is essentially free
1077 $linktype = ($text == $url) ?
'free' : 'text';
1079 # No link text, e.g. [http://domain.tld/some.link]
1080 if ( $text == '' ) {
1081 # Autonumber if allowed
1082 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1083 $text = '[' . ++
$this->mAutonumber
. ']';
1084 $linktype = 'autonumber';
1086 # Otherwise just use the URL
1087 $text = htmlspecialchars( $url );
1091 # Have link text, e.g. [http://domain.tld/some.link text]s
1093 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1096 $text = $wgContLang->markNoConversion($text);
1098 # Replace & from obsolete syntax with &.
1099 # All HTML entities will be escaped by makeExternalLink()
1100 # or maybeMakeExternalImage()
1101 $url = str_replace( '&', '&', $url );
1103 # Process the trail (i.e. everything after this link up until start of the next link),
1104 # replacing any non-bracketed links
1105 $trail = $this->replaceFreeExternalLinks( $trail );
1108 # Use the encoded URL
1109 # This means that users can paste URLs directly into the text
1110 # Funny characters like ö aren't valid in URLs anyway
1111 # This was changed in August 2004
1112 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1115 wfProfileOut( $fname );
1120 * Replace anything that looks like a URL with a link
1123 function replaceFreeExternalLinks( $text ) {
1124 global $wgUrlProtocols;
1126 $fname = 'Parser::replaceFreeExternalLinks';
1127 wfProfileIn( $fname );
1129 $bits = preg_split( '/(\b(?:'.$wgUrlProtocols.'))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1130 $s = array_shift( $bits );
1133 $sk =& $this->mOptions
->getSkin();
1135 while ( $i < count( $bits ) ){
1136 $protocol = $bits[$i++
];
1137 $remainder = $bits[$i++
];
1139 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1140 # Found some characters after the protocol that look promising
1141 $url = $protocol . $m[1];
1144 # The characters '<' and '>' (which were escaped by
1145 # removeHTMLtags()) should not be included in
1146 # URLs, per RFC 2396.
1147 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1148 $trail = substr($url, $m2[0][1]) . $trail;
1149 $url = substr($url, 0, $m2[0][1]);
1152 # Move trailing punctuation to $trail
1154 # If there is no left bracket, then consider right brackets fair game too
1155 if ( strpos( $url, '(' ) === false ) {
1159 $numSepChars = strspn( strrev( $url ), $sep );
1160 if ( $numSepChars ) {
1161 $trail = substr( $url, -$numSepChars ) . $trail;
1162 $url = substr( $url, 0, -$numSepChars );
1165 # Replace & from obsolete syntax with &.
1166 # All HTML entities will be escaped by makeExternalLink()
1167 # or maybeMakeExternalImage()
1168 $url = str_replace( '&', '&', $url );
1170 # Is this an external image?
1171 $text = $this->maybeMakeExternalImage( $url );
1172 if ( $text === false ) {
1173 # Not an image, make a link
1174 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1176 $s .= $text . $trail;
1178 $s .= $protocol . $remainder;
1181 wfProfileOut( $fname );
1186 * make an image if it's allowed
1189 function maybeMakeExternalImage( $url ) {
1190 $sk =& $this->mOptions
->getSkin();
1192 if ( $this->mOptions
->getAllowExternalImages() ) {
1193 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1195 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1202 * Process [[ ]] wikilinks
1206 function replaceInternalLinks( $s ) {
1207 global $wgContLang, $wgLinkCache, $wgUrlProtocols;
1208 static $fname = 'Parser::replaceInternalLinks' ;
1210 wfProfileIn( $fname );
1212 wfProfileIn( $fname.'-setup' );
1214 # the % is needed to support urlencoded titles as well
1215 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1217 $sk =& $this->mOptions
->getSkin();
1219 #split the entire text string on occurences of [[
1220 $a = explode( '[[', ' ' . $s );
1221 #get the first element (all text up to first [[), and remove the space we added
1222 $s = array_shift( $a );
1223 $s = substr( $s, 1 );
1225 # Match a link having the form [[namespace:link|alternate]]trail
1227 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1228 # Match cases where there is no "]]", which might still be images
1229 static $e1_img = FALSE;
1230 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1231 # Match the end of a line for a word that's not followed by whitespace,
1232 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1233 $e2 = wfMsgForContent( 'linkprefix' );
1235 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1237 if( is_null( $this->mTitle
) ) {
1238 wfDebugDieBacktrace( 'nooo' );
1240 $nottalk = !$this->mTitle
->isTalkPage();
1242 if ( $useLinkPrefixExtension ) {
1243 if ( preg_match( $e2, $s, $m ) ) {
1244 $first_prefix = $m[2];
1246 $first_prefix = false;
1252 $selflink = $this->mTitle
->getPrefixedText();
1253 wfProfileOut( $fname.'-setup' );
1255 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1256 $useSubpages = $this->areSubpagesAllowed();
1258 # Loop for each link
1259 for ($k = 0; isset( $a[$k] ); $k++
) {
1261 if ( $useLinkPrefixExtension ) {
1262 wfProfileIn( $fname.'-prefixhandling' );
1263 if ( preg_match( $e2, $s, $m ) ) {
1271 $prefix = $first_prefix;
1272 $first_prefix = false;
1274 wfProfileOut( $fname.'-prefixhandling' );
1277 $might_be_img = false;
1279 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1281 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1282 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1283 # the real problem is with the $e1 regex
1286 # Still some problems for cases where the ] is meant to be outside punctuation,
1287 # and no image is in sight. See bug 2095.
1289 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1290 $text .= ']'; # so that replaceExternalLinks($text) works later
1293 # fix up urlencoded title texts
1294 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1296 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1297 $might_be_img = true;
1299 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1301 } else { # Invalid form; output directly
1302 $s .= $prefix . '[[' . $line ;
1306 # Don't allow internal links to pages containing
1307 # PROTO: where PROTO is a valid URL protocol; these
1308 # should be external links.
1309 if (preg_match('/^(\b(?:'.$wgUrlProtocols.'))/', $m[1])) {
1310 $s .= $prefix . '[[' . $line ;
1314 # Make subpage if necessary
1315 if( $useSubpages ) {
1316 $link = $this->maybeDoSubpageLink( $m[1], $text );
1321 $noforce = (substr($m[1], 0, 1) != ':');
1323 # Strip off leading ':'
1324 $link = substr($link, 1);
1327 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1329 $s .= $prefix . '[[' . $line;
1333 #check other language variants of the link
1334 #if the article does not exist
1335 if( $checkVariantLink
1336 && $nt->getArticleID() == 0 ) {
1337 $wgContLang->findVariantLink($link, $nt);
1340 $ns = $nt->getNamespace();
1341 $iw = $nt->getInterWiki();
1343 if ($might_be_img) { # if this is actually an invalid link
1344 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1346 while (isset ($a[$k+
1]) ) {
1347 #look at the next 'line' to see if we can close it there
1348 $spliced = array_splice( $a, $k +
1, 1 );
1349 $next_line = array_shift( $spliced );
1350 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1351 # the first ]] closes the inner link, the second the image
1353 $text .= '[[' . $m[1];
1356 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1357 #if there's exactly one ]] that's fine, we'll keep looking
1358 $text .= '[[' . $m[0];
1360 #if $next_line is invalid too, we need look no further
1361 $text .= '[[' . $next_line;
1366 # we couldn't find the end of this imageLink, so output it raw
1367 #but don't ignore what might be perfectly normal links in the text we've examined
1368 $text = $this->replaceInternalLinks($text);
1369 $s .= $prefix . '[[' . $link . '|' . $text;
1370 # note: no $trail, because without an end, there *is* no trail
1373 } else { #it's not an image, so output it raw
1374 $s .= $prefix . '[[' . $link . '|' . $text;
1375 # note: no $trail, because without an end, there *is* no trail
1380 $wasblank = ( '' == $text );
1381 if( $wasblank ) $text = $link;
1384 # Link not escaped by : , create the various objects
1388 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1389 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1390 $s = rtrim($s . "\n");
1391 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1395 if ( $ns == NS_IMAGE
) {
1396 wfProfileIn( "$fname-image" );
1397 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1398 # recursively parse links inside the image caption
1399 # actually, this will parse them in any other parameters, too,
1400 # but it might be hard to fix that, and it doesn't matter ATM
1401 $text = $this->replaceExternalLinks($text);
1402 $text = $this->replaceInternalLinks($text);
1404 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1405 $s .= $prefix . preg_replace("/\b($wgUrlProtocols)/", UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1406 $wgLinkCache->addImageLinkObj( $nt );
1408 wfProfileOut( "$fname-image" );
1411 wfProfileOut( "$fname-image" );
1415 if ( $ns == NS_CATEGORY
) {
1416 wfProfileIn( "$fname-category" );
1417 $t = $wgContLang->convertHtml( $nt->getText() );
1418 $s = rtrim($s . "\n"); # bug 87
1420 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1421 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1422 $wgLinkCache->resume();
1425 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1426 $sortkey = $this->mTitle
->getText();
1428 $sortkey = $this->mTitle
->getPrefixedText();
1433 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1434 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1435 $this->mOutput
->addCategoryLink( $t );
1438 * Strip the whitespace Category links produce, see bug 87
1439 * @todo We might want to use trim($tmp, "\n") here.
1441 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1443 wfProfileOut( "$fname-category" );
1448 if( ( $nt->getPrefixedText() === $selflink ) &&
1449 ( $nt->getFragment() === '' ) ) {
1450 # Self-links are handled specially; generally de-link and change to bold.
1451 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1455 # Special and Media are pseudo-namespaces; no pages actually exist in them
1456 if( $ns == NS_MEDIA
) {
1457 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1458 $wgLinkCache->addImageLinkObj( $nt );
1460 } elseif( $ns == NS_SPECIAL
) {
1461 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1464 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1466 wfProfileOut( $fname );
1471 * Make a link placeholder. The text returned can be later resolved to a real link with
1472 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1473 * parsing of interwiki links, and secondly to allow all extistence checks and
1474 * article length checks (for stub links) to be bundled into a single query.
1477 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1478 if ( ! is_object($nt) ) {
1480 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1482 # Separate the link trail from the rest of the link
1483 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1485 if ( $nt->isExternal() ) {
1486 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1487 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1488 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1490 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1491 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1492 $this->mLinkHolders
['queries'][] = $query;
1493 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1494 $this->mLinkHolders
['titles'][] = $nt;
1496 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1503 * Return true if subpage links should be expanded on this page.
1506 function areSubpagesAllowed() {
1507 # Some namespaces don't allow subpages
1508 global $wgNamespacesWithSubpages;
1509 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1513 * Handle link to subpage if necessary
1514 * @param string $target the source of the link
1515 * @param string &$text the link text, modified as necessary
1516 * @return string the full name of the link
1519 function maybeDoSubpageLink($target, &$text) {
1522 # :Foobar -- override special treatment of prefix (images, language links)
1523 # /Foobar -- convert to CurrentPage/Foobar
1524 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1525 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1526 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1528 $fname = 'Parser::maybeDoSubpageLink';
1529 wfProfileIn( $fname );
1530 $ret = $target; # default return value is no change
1532 # Some namespaces don't allow subpages,
1533 # so only perform processing if subpages are allowed
1534 if( $this->areSubpagesAllowed() ) {
1535 # Look at the first character
1536 if( $target != '' && $target{0} == '/' ) {
1537 # / at end means we don't want the slash to be shown
1538 if( substr( $target, -1, 1 ) == '/' ) {
1539 $target = substr( $target, 1, -1 );
1542 $noslash = substr( $target, 1 );
1545 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1546 if( '' === $text ) {
1548 } # this might be changed for ugliness reasons
1550 # check for .. subpage backlinks
1552 $nodotdot = $target;
1553 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1555 $nodotdot = substr( $nodotdot, 3 );
1557 if($dotdotcount > 0) {
1558 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1559 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1560 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1561 # / at the end means don't show full path
1562 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1563 $nodotdot = substr( $nodotdot, 0, -1 );
1564 if( '' === $text ) {
1568 $nodotdot = trim( $nodotdot );
1569 if( $nodotdot != '' ) {
1570 $ret .= '/' . $nodotdot;
1577 wfProfileOut( $fname );
1582 * Used by doBlockLevels()
1585 /* private */ function closeParagraph() {
1587 if ( '' != $this->mLastSection
) {
1588 $result = '</' . $this->mLastSection
. ">\n";
1590 $this->mInPre
= false;
1591 $this->mLastSection
= '';
1594 # getCommon() returns the length of the longest common substring
1595 # of both arguments, starting at the beginning of both.
1597 /* private */ function getCommon( $st1, $st2 ) {
1598 $fl = strlen( $st1 );
1599 $shorter = strlen( $st2 );
1600 if ( $fl < $shorter ) { $shorter = $fl; }
1602 for ( $i = 0; $i < $shorter; ++
$i ) {
1603 if ( $st1{$i} != $st2{$i} ) { break; }
1607 # These next three functions open, continue, and close the list
1608 # element appropriate to the prefix character passed into them.
1610 /* private */ function openList( $char ) {
1611 $result = $this->closeParagraph();
1613 if ( '*' == $char ) { $result .= '<ul><li>'; }
1614 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1615 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1616 else if ( ';' == $char ) {
1617 $result .= '<dl><dt>';
1618 $this->mDTopen
= true;
1620 else { $result = '<!-- ERR 1 -->'; }
1625 /* private */ function nextItem( $char ) {
1626 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1627 else if ( ':' == $char ||
';' == $char ) {
1629 if ( $this->mDTopen
) { $close = '</dt>'; }
1630 if ( ';' == $char ) {
1631 $this->mDTopen
= true;
1632 return $close . '<dt>';
1634 $this->mDTopen
= false;
1635 return $close . '<dd>';
1638 return '<!-- ERR 2 -->';
1641 /* private */ function closeList( $char ) {
1642 if ( '*' == $char ) { $text = '</li></ul>'; }
1643 else if ( '#' == $char ) { $text = '</li></ol>'; }
1644 else if ( ':' == $char ) {
1645 if ( $this->mDTopen
) {
1646 $this->mDTopen
= false;
1647 $text = '</dt></dl>';
1649 $text = '</dd></dl>';
1652 else { return '<!-- ERR 3 -->'; }
1658 * Make lists from lines starting with ':', '*', '#', etc.
1661 * @return string the lists rendered as HTML
1663 function doBlockLevels( $text, $linestart ) {
1664 $fname = 'Parser::doBlockLevels';
1665 wfProfileIn( $fname );
1667 # Parsing through the text line by line. The main thing
1668 # happening here is handling of block-level elements p, pre,
1669 # and making lists from lines starting with * # : etc.
1671 $textLines = explode( "\n", $text );
1673 $lastPrefix = $output = '';
1674 $this->mDTopen
= $inBlockElem = false;
1676 $paragraphStack = false;
1678 if ( !$linestart ) {
1679 $output .= array_shift( $textLines );
1681 foreach ( $textLines as $oLine ) {
1682 $lastPrefixLength = strlen( $lastPrefix );
1683 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1684 $preOpenMatch = preg_match('/<pre/i', $oLine );
1685 if ( !$this->mInPre
) {
1686 # Multiple prefixes may abut each other for nested lists.
1687 $prefixLength = strspn( $oLine, '*#:;' );
1688 $pref = substr( $oLine, 0, $prefixLength );
1691 $pref2 = str_replace( ';', ':', $pref );
1692 $t = substr( $oLine, $prefixLength );
1693 $this->mInPre
= !empty($preOpenMatch);
1695 # Don't interpret any other prefixes in preformatted text
1697 $pref = $pref2 = '';
1702 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1703 # Same as the last item, so no need to deal with nesting or opening stuff
1704 $output .= $this->nextItem( substr( $pref, -1 ) );
1705 $paragraphStack = false;
1707 if ( substr( $pref, -1 ) == ';') {
1708 # The one nasty exception: definition lists work like this:
1709 # ; title : definition text
1710 # So we check for : in the remainder text to split up the
1711 # title and definition, without b0rking links.
1713 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1715 $output .= $term . $this->nextItem( ':' );
1718 } elseif( $prefixLength ||
$lastPrefixLength ) {
1719 # Either open or close a level...
1720 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1721 $paragraphStack = false;
1723 while( $commonPrefixLength < $lastPrefixLength ) {
1724 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1725 --$lastPrefixLength;
1727 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1728 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1730 while ( $prefixLength > $commonPrefixLength ) {
1731 $char = substr( $pref, $commonPrefixLength, 1 );
1732 $output .= $this->openList( $char );
1734 if ( ';' == $char ) {
1735 # FIXME: This is dupe of code above
1736 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1738 $output .= $term . $this->nextItem( ':' );
1741 ++
$commonPrefixLength;
1743 $lastPrefix = $pref2;
1745 if( 0 == $prefixLength ) {
1746 wfProfileIn( "$fname-paragraph" );
1747 # No prefix (not in list)--go to paragraph mode
1748 $uniq_prefix = UNIQ_PREFIX
;
1749 // XXX: use a stack for nestable elements like span, table and div
1750 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1751 $closematch = preg_match(
1752 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1753 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1754 if ( $openmatch or $closematch ) {
1755 $paragraphStack = false;
1756 $output .= $this->closeParagraph();
1757 if ( $preOpenMatch and !$preCloseMatch ) {
1758 $this->mInPre
= true;
1760 if ( $closematch ) {
1761 $inBlockElem = false;
1763 $inBlockElem = true;
1765 } else if ( !$inBlockElem && !$this->mInPre
) {
1766 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1768 if ($this->mLastSection
!= 'pre') {
1769 $paragraphStack = false;
1770 $output .= $this->closeParagraph().'<pre>';
1771 $this->mLastSection
= 'pre';
1773 $t = substr( $t, 1 );
1776 if ( '' == trim($t) ) {
1777 if ( $paragraphStack ) {
1778 $output .= $paragraphStack.'<br />';
1779 $paragraphStack = false;
1780 $this->mLastSection
= 'p';
1782 if ($this->mLastSection
!= 'p' ) {
1783 $output .= $this->closeParagraph();
1784 $this->mLastSection
= '';
1785 $paragraphStack = '<p>';
1787 $paragraphStack = '</p><p>';
1791 if ( $paragraphStack ) {
1792 $output .= $paragraphStack;
1793 $paragraphStack = false;
1794 $this->mLastSection
= 'p';
1795 } else if ($this->mLastSection
!= 'p') {
1796 $output .= $this->closeParagraph().'<p>';
1797 $this->mLastSection
= 'p';
1802 wfProfileOut( "$fname-paragraph" );
1804 // somewhere above we forget to get out of pre block (bug 785)
1805 if($preCloseMatch && $this->mInPre
) {
1806 $this->mInPre
= false;
1808 if ($paragraphStack === false) {
1812 while ( $prefixLength ) {
1813 $output .= $this->closeList( $pref2{$prefixLength-1} );
1816 if ( '' != $this->mLastSection
) {
1817 $output .= '</' . $this->mLastSection
. '>';
1818 $this->mLastSection
= '';
1821 wfProfileOut( $fname );
1826 * Split up a string on ':', ignoring any occurences inside
1827 * <a>..</a> or <span>...</span>
1828 * @param string $str the string to split
1829 * @param string &$before set to everything before the ':'
1830 * @param string &$after set to everything after the ':'
1831 * return string the position of the ':', or false if none found
1833 function findColonNoLinks($str, &$before, &$after) {
1834 # I wonder if we should make this count all tags, not just <a>
1835 # and <span>. That would prevent us from matching a ':' that
1836 # comes in the middle of italics other such formatting....
1838 $fname = 'Parser::findColonNoLinks';
1839 wfProfileIn( $fname );
1842 $colon = strpos($str, ':', $pos);
1844 if ($colon !== false) {
1845 $before = substr($str, 0, $colon);
1846 $after = substr($str, $colon +
1);
1848 # Skip any ':' within <a> or <span> pairs
1849 $a = substr_count($before, '<a');
1850 $s = substr_count($before, '<span');
1851 $ca = substr_count($before, '</a>');
1852 $cs = substr_count($before, '</span>');
1854 if ($a <= $ca and $s <= $cs) {
1855 # Tags are balanced before ':'; ok
1860 } while ($colon !== false);
1861 wfProfileOut( $fname );
1866 * Return value of a magic variable (like PAGENAME)
1870 function getVariableValue( $index ) {
1871 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1874 * Some of these require message or data lookups and can be
1875 * expensive to check many times.
1877 static $varCache = array();
1878 if( isset( $varCache[$index] ) ) return $varCache[$index];
1881 case MAG_CURRENTMONTH
:
1882 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1883 case MAG_CURRENTMONTHNAME
:
1884 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1885 case MAG_CURRENTMONTHNAMEGEN
:
1886 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1887 case MAG_CURRENTMONTHABBREV
:
1888 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1889 case MAG_CURRENTDAY
:
1890 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1892 return $this->mTitle
->getText();
1894 return $this->mTitle
->getPartialURL();
1895 case MAG_REVISIONID
:
1896 return $wgArticle->getRevIdFetched();
1898 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1899 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1900 case MAG_CURRENTDAYNAME
:
1901 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1902 case MAG_CURRENTYEAR
:
1903 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1904 case MAG_CURRENTTIME
:
1905 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1906 case MAG_CURRENTWEEK
:
1907 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1908 case MAG_CURRENTDOW
:
1909 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1910 case MAG_NUMBEROFARTICLES
:
1911 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1912 case MAG_NUMBEROFFILES
:
1913 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1918 case MAG_SERVERNAME
:
1919 return $wgServerName;
1920 case MAG_SCRIPTPATH
:
1921 return $wgScriptPath;
1928 * initialise the magic variables (like CURRENTMONTHNAME)
1932 function initialiseVariables() {
1933 $fname = 'Parser::initialiseVariables';
1934 wfProfileIn( $fname );
1935 global $wgVariableIDs;
1936 $this->mVariables
= array();
1937 foreach ( $wgVariableIDs as $id ) {
1938 $mw =& MagicWord
::get( $id );
1939 $mw->addToArray( $this->mVariables
, $id );
1941 wfProfileOut( $fname );
1945 * parse any parentheses in format ((title|part|part))
1946 * and call callbacks to get a replacement text for any found piece
1948 * @param string $text The text to parse
1949 * @param array $callbacks rules in form:
1950 * '{' => array( # opening parentheses
1951 * 'end' => '}', # closing parentheses
1952 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1953 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1958 function replace_callback ($text, $callbacks) {
1959 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1960 $lastOpeningBrace = -1; # last not closed parentheses
1962 for ($i = 0; $i < strlen($text); $i++
) {
1963 # check for any opening brace
1966 foreach ($callbacks as $key => $value) {
1967 $pos = strpos ($text, $key, $i);
1968 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
1974 if ($lastOpeningBrace >= 0) {
1975 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
1977 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
1982 $pos = strpos ($text, '|', $i);
1984 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
1995 # found openning brace, lets add it to parentheses stack
1996 if (null != $rule) {
1997 $piece = array('brace' => $text[$i],
1998 'braceEnd' => $rule['end'],
2003 # count openning brace characters
2004 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2009 $piece['startAt'] = $i+
1;
2010 $piece['partStart'] = $i+
1;
2012 # we need to add to stack only if openning brace count is enough for any given rule
2013 foreach ($rule['cb'] as $cnt => $fn) {
2014 if ($piece['count'] >= $cnt) {
2015 $lastOpeningBrace ++
;
2016 $openingBraceStack[$lastOpeningBrace] = $piece;
2023 else if ($lastOpeningBrace >= 0) {
2024 # first check if it is a closing brace
2025 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2026 # lets check if it is enough characters for closing brace
2028 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2031 # if there are more closing parentheses than opening ones, we parse less
2032 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2033 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2035 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2037 $matchingCallback = null;
2038 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2039 if ($count >= $cnt && $matchingCount < $cnt) {
2040 $matchingCount = $cnt;
2041 $matchingCallback = $fn;
2045 if ($matchingCount == 0) {
2050 # lets set a title or last part (if '|' was found)
2051 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2052 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2054 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2056 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2057 $pieceEnd = $i +
$matchingCount;
2059 if( is_callable( $matchingCallback ) ) {
2061 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2062 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2063 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2064 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2066 # finally we can call a user callback and replace piece of text
2067 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2068 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2069 $i = $pieceStart +
strlen($replaceWith) - 1;
2072 # null value for callback means that parentheses should be parsed, but not replaced
2073 $i +
= $matchingCount - 1;
2076 # reset last openning parentheses, but keep it in case there are unused characters
2077 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2078 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2079 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2082 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2083 $openingBraceStack[$lastOpeningBrace--] = null;
2085 if ($matchingCount < $piece['count']) {
2086 $piece['count'] -= $matchingCount;
2087 $piece['startAt'] -= $matchingCount;
2088 $piece['partStart'] = $piece['startAt'];
2089 # do we still qualify for any callback with remaining count?
2090 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2091 if ($piece['count'] >= $cnt) {
2092 $lastOpeningBrace ++
;
2093 $openingBraceStack[$lastOpeningBrace] = $piece;
2101 # lets set a title if it is a first separator, or next part otherwise
2102 if ($text[$i] == '|') {
2103 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2104 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2105 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2108 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2110 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2119 * Replace magic variables, templates, and template arguments
2120 * with the appropriate text. Templates are substituted recursively,
2121 * taking care to avoid infinite loops.
2123 * Note that the substitution depends on value of $mOutputType:
2124 * OT_WIKI: only {{subst:}} templates
2125 * OT_MSG: only magic variables
2126 * OT_HTML: all templates and magic variables
2128 * @param string $tex The text to transform
2129 * @param array $args Key-value pairs representing template parameters to substitute
2132 function replaceVariables( $text, $args = array() ) {
2133 # Prevent too big inclusions
2134 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2138 $fname = 'Parser::replaceVariables';
2139 wfProfileIn( $fname );
2141 $titleChars = Title
::legalChars();
2143 # This function is called recursively. To keep track of arguments we need a stack:
2144 array_push( $this->mArgStack
, $args );
2146 $braceCallbacks = array();
2147 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2148 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2149 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2151 $callbacks = array();
2152 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2153 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2154 $text = $this->replace_callback ($text, $callbacks);
2156 array_pop( $this->mArgStack
);
2158 wfProfileOut( $fname );
2163 * Replace magic variables
2166 function variableSubstitution( $matches ) {
2167 $fname = 'parser::variableSubstitution';
2168 $varname = $matches[1];
2169 wfProfileIn( $fname );
2170 if ( !$this->mVariables
) {
2171 $this->initialiseVariables();
2174 if ( $this->mOutputType
== OT_WIKI
) {
2175 # Do only magic variables prefixed by SUBST
2176 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2177 if (!$mwSubst->matchStartAndRemove( $varname ))
2179 # Note that if we don't substitute the variable below,
2180 # we don't remove the {{subst:}} magic word, in case
2181 # it is a template rather than a magic variable.
2183 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2184 $id = $this->mVariables
[$varname];
2185 $text = $this->getVariableValue( $id );
2186 $this->mOutput
->mContainsOldMagic
= true;
2188 $text = $matches[0];
2190 wfProfileOut( $fname );
2194 # Split template arguments
2195 function getTemplateArgs( $argsString ) {
2196 if ( $argsString === '' ) {
2200 $args = explode( '|', substr( $argsString, 1 ) );
2202 # If any of the arguments contains a '[[' but no ']]', it needs to be
2203 # merged with the next arg because the '|' character between belongs
2204 # to the link syntax and not the template parameter syntax.
2205 $argc = count($args);
2207 for ( $i = 0; $i < $argc-1; $i++
) {
2208 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2209 $args[$i] .= '|'.$args[$i+
1];
2210 array_splice($args, $i+
1, 1);
2220 * Return the text of a template, after recursively
2221 * replacing any variables or templates within the template.
2223 * @param array $piece The parts of the template
2224 * $piece['text']: matched text
2225 * $piece['title']: the title, i.e. the part before the |
2226 * $piece['parts']: the parameter array
2227 * @return string the text of the template
2230 function braceSubstitution( $piece ) {
2231 global $wgLinkCache, $wgContLang;
2232 $fname = 'Parser::braceSubstitution';
2233 wfProfileIn( $fname );
2243 # $part1 is the bit before the first |, and must contain only title characters
2244 # $args is a list of arguments, starting from index 0, not including $part1
2246 $part1 = $piece['title'];
2247 # If the third subpattern matched anything, it will start with |
2249 if (null == $piece['parts']) {
2250 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2251 if ($replaceWith != $piece['text']) {
2252 $text = $replaceWith;
2258 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2259 $argc = count( $args );
2263 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2264 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2265 # One of two possibilities is true:
2266 # 1) Found SUBST but not in the PST phase
2267 # 2) Didn't find SUBST and in the PST phase
2268 # In either case, return without further processing
2269 $text = $piece['text'];
2275 # MSG, MSGNW and INT
2278 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2279 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2282 # Remove obsolete MSG:
2283 $mwMsg =& MagicWord
::get( MAG_MSG
);
2284 $mwMsg->matchStartAndRemove( $part1 );
2287 # Check if it is an internal message
2288 $mwInt =& MagicWord
::get( MAG_INT
);
2289 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2290 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2291 $text = $linestart . wfMsgReal( $part1, $args, true );
2299 # Check for NS: (namespace expansion)
2300 $mwNs = MagicWord
::get( MAG_NS
);
2301 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2302 if ( intval( $part1 ) ) {
2303 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2306 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2307 if ( !is_null( $index ) ) {
2308 $text = $linestart . $wgContLang->getNsText( $index );
2315 # LCFIRST, UCFIRST, LC and UC
2317 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2318 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2319 $lc =& MagicWord
::get( MAG_LC
);
2320 $uc =& MagicWord
::get( MAG_UC
);
2321 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2322 $text = $linestart . $wgContLang->lcfirst( $part1 );
2324 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2325 $text = $linestart . $wgContLang->ucfirst( $part1 );
2327 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2328 $text = $linestart . $wgContLang->lc( $part1 );
2330 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2331 $text = $linestart . $wgContLang->uc( $part1 );
2336 # LOCALURL and FULLURL
2338 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2339 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2340 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2341 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2344 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2345 $func = 'getLocalURL';
2346 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2347 $func = 'escapeLocalURL';
2348 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2349 $func = 'getFullURL';
2350 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2351 $func = 'escapeFullURL';
2356 if ( $func !== false ) {
2357 $title = Title
::newFromText( $part1 );
2358 if ( !is_null( $title ) ) {
2360 $text = $linestart . $title->$func( $args[0] );
2362 $text = $linestart . $title->$func();
2370 if ( !$found && $argc == 1 ) {
2371 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2372 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2373 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2379 if ( !$found && $argc >= 2 ) {
2380 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2381 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2382 if ($argc==2) {$args[2]=$args[1];}
2383 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2388 # Template table test
2390 # Did we encounter this template already? If yes, it is in the cache
2391 # and we need to check for loops.
2392 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2395 # Infinite loop test
2396 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2399 $text = $linestart .
2401 '<!-- WARNING: template loop detected -->';
2402 wfDebug( "$fname: template loop broken at '$part1'\n" );
2404 # set $text to cached message.
2405 $text = $linestart . $this->mTemplates
[$part1];
2409 # Load from database
2410 $replaceHeadings = false;
2412 $lastPathLevel = $this->mTemplatePath
;
2415 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2416 if ($subpage !== '') {
2417 $ns = $this->mTitle
->getNamespace();
2419 $title = Title
::newFromText( $part1, $ns );
2422 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2423 if ($interwiki != '' && $title->isTrans()) {
2424 return $this->scarytransclude($title, $interwiki);
2428 if ( !is_null( $title ) && !$title->isExternal() ) {
2429 # Check for excessive inclusion
2430 $dbk = $title->getPrefixedDBkey();
2431 if ( $this->incrementIncludeCount( $dbk ) ) {
2432 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2433 # Capture special page output
2434 $text = SpecialPage
::capturePath( $title );
2435 if ( is_string( $text ) ) {
2439 $this->disableCache();
2442 $article = new Article( $title );
2443 $articleContent = $article->fetchContent(0, false);
2444 if ( $articleContent !== false ) {
2446 $text = $articleContent;
2447 $replaceHeadings = true;
2452 # If the title is valid but undisplayable, make a link to it
2453 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2454 $text = '[['.$title->getPrefixedText().']]';
2458 # Template cache array insertion
2460 $this->mTemplates
[$part1] = $text;
2461 $text = $linestart . $text;
2466 # Recursive parsing, escaping and link table handling
2467 # Only for HTML output
2468 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2469 $text = wfEscapeWikiText( $text );
2470 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2471 # Clean up argument array
2472 $assocArgs = array();
2474 foreach( $args as $arg ) {
2475 $eqpos = strpos( $arg, '=' );
2476 if ( $eqpos === false ) {
2477 $assocArgs[$index++
] = $arg;
2479 $name = trim( substr( $arg, 0, $eqpos ) );
2480 $value = trim( substr( $arg, $eqpos+
1 ) );
2481 if ( $value === false ) {
2484 if ( $name !== false ) {
2485 $assocArgs[$name] = $value;
2490 # Add a new element to the templace recursion path
2491 $this->mTemplatePath
[$part1] = 1;
2493 if( $this->mOutputType
== OT_HTML
) {
2494 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2495 preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
2497 foreach ($m[1] as $piece)
2500 # Remove <noinclude> sections and <includeonly> tags
2501 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2502 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2503 # Strip <nowiki>, <pre>, etc.
2504 $text = $this->strip( $text, $this->mStripState
);
2505 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2507 $text = $this->replaceVariables( $text, $assocArgs );
2509 # Resume the link cache and register the inclusion as a link
2510 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2511 $wgLinkCache->addLinkObj( $title );
2514 # If the template begins with a table or block-level
2515 # element, it should be treated as beginning a new line.
2516 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2517 $text = "\n" . $text;
2520 # Prune lower levels off the recursion check path
2521 $this->mTemplatePath
= $lastPathLevel;
2524 wfProfileOut( $fname );
2525 return $piece['text'];
2528 # Replace raw HTML by a placeholder
2529 # Add a blank line preceding, to prevent it from mucking up
2530 # immediately preceding headings
2531 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2533 # replace ==section headers==
2534 # XXX this needs to go away once we have a better parser.
2535 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2536 if( !is_null( $title ) )
2537 $encodedname = base64_encode($title->getPrefixedDBkey());
2539 $encodedname = base64_encode("");
2540 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2541 PREG_SPLIT_DELIM_CAPTURE
);
2544 for( $i = 0; $i < count($m); $i +
= 2 ) {
2546 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2548 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2552 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2553 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2554 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2562 # Prune lower levels off the recursion check path
2563 $this->mTemplatePath
= $lastPathLevel;
2566 wfProfileOut( $fname );
2567 return $piece['text'];
2569 wfProfileOut( $fname );
2575 * Translude an interwiki link.
2577 function scarytransclude($title, $interwiki) {
2578 global $wgEnableScaryTranscluding;
2580 if (!$wgEnableScaryTranscluding)
2581 return wfMsg('scarytranscludedisabled');
2583 $articlename = "Template:" . $title->getDBkey();
2584 $url = str_replace('$1', urlencode($articlename), $interwiki);
2585 if (strlen($url) > 255)
2586 return wfMsg('scarytranscludetoolong');
2587 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2588 $this->mIWTransData
[] = $text;
2589 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2592 function fetchScaryTemplateMaybeFromCache($url) {
2593 $dbr =& wfGetDB(DB_SLAVE
);
2594 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2595 array('tc_url' => $url));
2597 $time = $obj->tc_time
;
2598 $text = $obj->tc_contents
;
2599 if ($time && $time < (time() +
(60*60))) {
2604 $text = wfGetHTTP($url . '?action=render');
2606 return wfMsg('scarytranscludefailed', $url);
2608 $dbw =& wfGetDB(DB_MASTER
);
2609 $dbw->replace('transcache', array(), array(
2611 'tc_time' => time(),
2612 'tc_contents' => $text));
2618 * Triple brace replacement -- used for template arguments
2621 function argSubstitution( $matches ) {
2622 $arg = trim( $matches['title'] );
2623 $text = $matches['text'];
2624 $inputArgs = end( $this->mArgStack
);
2626 if ( array_key_exists( $arg, $inputArgs ) ) {
2627 $text = $inputArgs[$arg];
2628 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2629 $text = $matches['parts'][0];
2636 * Returns true if the function is allowed to include this entity
2639 function incrementIncludeCount( $dbk ) {
2640 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2641 $this->mIncludeCount
[$dbk] = 0;
2643 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2651 * This function accomplishes several tasks:
2652 * 1) Auto-number headings if that option is enabled
2653 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2654 * 3) Add a Table of contents on the top for users who have enabled the option
2655 * 4) Auto-anchor headings
2657 * It loops through all headlines, collects the necessary data, then splits up the
2658 * string and re-inserts the newly formatted headlines.
2660 * @param string $text
2661 * @param boolean $isMain
2664 function formatHeadings( $text, $isMain=true ) {
2665 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2667 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2669 $forceTocHere = false;
2670 if( !$this->mTitle
->userCanEdit() ) {
2673 $showEditLink = $this->mOptions
->getEditSection();
2676 # Inhibit editsection links if requested in the page
2677 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2678 if( $esw->matchAndRemove( $text ) ) {
2681 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2683 $mw =& MagicWord
::get( MAG_NOTOC
);
2684 if( $mw->matchAndRemove( $text ) ) {
2688 # Get all headlines for numbering them and adding funky stuff like [edit]
2689 # links - this is for later, but we need the number of headlines right now
2690 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2692 # if there are fewer than 4 headlines in the article, do not show TOC
2693 if( $numMatches < 4 ) {
2697 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2698 # override above conditions and always show TOC at that place
2700 $mw =& MagicWord
::get( MAG_TOC
);
2701 if($mw->match( $text ) ) {
2703 $forceTocHere = true;
2705 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2706 # override above conditions and always show TOC above first header
2707 $mw =& MagicWord
::get( MAG_FORCETOC
);
2708 if ($mw->matchAndRemove( $text ) ) {
2713 # Never ever show TOC if no headers
2714 if( $numMatches < 1 ) {
2718 # We need this to perform operations on the HTML
2719 $sk =& $this->mOptions
->getSkin();
2723 $sectionCount = 0; # headlineCount excluding template sections
2725 # Ugh .. the TOC should have neat indentation levels which can be
2726 # passed to the skin functions. These are determined here
2730 $sublevelCount = array();
2731 $levelCount = array();
2738 foreach( $matches[3] as $headline ) {
2740 $templatetitle = '';
2741 $templatesection = 0;
2744 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2746 $templatetitle = base64_decode($mat[1]);
2747 $templatesection = 1 +
(int)base64_decode($mat[2]);
2748 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2752 $prevlevel = $level;
2753 $prevtoclevel = $toclevel;
2755 $level = $matches[1][$headlineCount];
2757 if( $doNumberHeadings ||
$doShowToc ) {
2759 if ( $level > $prevlevel ) {
2760 # Increase TOC level
2762 $sublevelCount[$toclevel] = 0;
2763 $toc .= $sk->tocIndent();
2765 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2766 # Decrease TOC level, find level to jump to
2768 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2769 # Can only go down to level 1
2772 for ($i = $toclevel; $i > 0; $i--) {
2773 if ( $levelCount[$i] == $level ) {
2774 # Found last matching level
2778 elseif ( $levelCount[$i] < $level ) {
2779 # Found first matching level below current level
2786 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2789 # No change in level, end TOC line
2790 $toc .= $sk->tocLineEnd();
2793 $levelCount[$toclevel] = $level;
2795 # count number of headlines for each level
2796 @$sublevelCount[$toclevel]++
;
2798 for( $i = 1; $i <= $toclevel; $i++
) {
2799 if( !empty( $sublevelCount[$i] ) ) {
2803 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2809 # The canonized header is a version of the header text safe to use for links
2810 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2811 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2812 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2814 # Remove link placeholders by the link text.
2815 # <!--LINK number-->
2817 # link text with suffix
2818 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2819 "\$this->mLinkHolders['texts'][\$1]",
2820 $canonized_headline );
2821 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2822 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2823 $canonized_headline );
2826 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2827 $tocline = trim( $canonized_headline );
2828 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2829 $replacearray = array(
2833 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2834 $refers[$headlineCount] = $canonized_headline;
2836 # count how many in assoc. array so we can track dupes in anchors
2837 @$refers[$canonized_headline]++
;
2838 $refcount[$headlineCount]=$refers[$canonized_headline];
2840 # Don't number the heading if it is the only one (looks silly)
2841 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2842 # the two are different if the line contains a link
2843 $headline=$numbering . ' ' . $headline;
2846 # Create the anchor for linking from the TOC to the section
2847 $anchor = $canonized_headline;
2848 if($refcount[$headlineCount] > 1 ) {
2849 $anchor .= '_' . $refcount[$headlineCount];
2851 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2852 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2854 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2855 if ( empty( $head[$headlineCount] ) ) {
2856 $head[$headlineCount] = '';
2859 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2861 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2864 # give headline the correct <h#> tag
2865 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2873 $toc .= $sk->tocUnindent( $toclevel - 1 );
2874 $toc = $sk->tocList( $toc );
2877 # split up and insert constructed headlines
2879 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2882 foreach( $blocks as $block ) {
2883 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2884 # This is the [edit] link that appears for the top block of text when
2885 # section editing is enabled
2887 # Disabled because it broke block formatting
2888 # For example, a bullet point in the top line
2889 # $full .= $sk->editSectionLink(0);
2892 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2893 # Top anchor now in skin
2897 if( !empty( $head[$i] ) ) {
2903 $mw =& MagicWord
::get( MAG_TOC
);
2904 return $mw->replace( $toc, $full );
2911 * Return an HTML link for the "ISBN 123456" text
2914 function magicISBN( $text ) {
2915 $fname = 'Parser::magicISBN';
2916 wfProfileIn( $fname );
2918 $a = split( 'ISBN ', ' '.$text );
2919 if ( count ( $a ) < 2 ) {
2920 wfProfileOut( $fname );
2923 $text = substr( array_shift( $a ), 1);
2924 $valid = '0123456789-Xx';
2926 foreach ( $a as $x ) {
2927 $isbn = $blank = '' ;
2928 while ( ' ' == $x{0} ) {
2930 $x = substr( $x, 1 );
2932 if ( $x == '' ) { # blank isbn
2933 $text .= "ISBN $blank";
2936 while ( strstr( $valid, $x{0} ) != false ) {
2938 $x = substr( $x, 1 );
2940 $num = str_replace( '-', '', $isbn );
2941 $num = str_replace( ' ', '', $num );
2942 $num = str_replace( 'x', 'X', $num );
2945 $text .= "ISBN $blank$x";
2947 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2948 $text .= '<a href="' .
2949 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2950 "\" class=\"internal\">ISBN $isbn</a>";
2954 wfProfileOut( $fname );
2959 * Return an HTML link for the "RFC 1234" text
2962 * @param string $text Text to be processed
2963 * @param string $keyword Magic keyword to use (default RFC)
2964 * @param string $urlmsg Interface message to use (default rfcurl)
2967 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2969 $valid = '0123456789';
2972 $a = split( $keyword, ' '.$text );
2973 if ( count ( $a ) < 2 ) {
2976 $text = substr( array_shift( $a ), 1);
2978 /* Check if keyword is preceed by [[.
2979 * This test is made here cause of the array_shift above
2980 * that prevent the test to be done in the foreach.
2982 if ( substr( $text, -2 ) == '[[' ) {
2986 foreach ( $a as $x ) {
2987 /* token might be empty if we have RFC RFC 1234 */
2995 /** remove and save whitespaces in $blank */
2996 while ( $x{0} == ' ' ) {
2998 $x = substr( $x, 1 );
3001 /** remove and save the rfc number in $id */
3002 while ( strstr( $valid, $x{0} ) != false ) {
3004 $x = substr( $x, 1 );
3008 /* call back stripped spaces*/
3009 $text .= $keyword.$blank.$x;
3010 } elseif( $internal ) {
3012 $text .= $keyword.$id.$x;
3014 /* build the external link*/
3015 $url = wfMsg( $urlmsg, $id);
3016 $sk =& $this->mOptions
->getSkin();
3017 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3018 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3021 /* Check if the next RFC keyword is preceed by [[ */
3022 $internal = ( substr($x,-2) == '[[' );
3028 * Transform wiki markup when saving a page by doing \r\n -> \n
3029 * conversion, substitting signatures, {{subst:}} templates, etc.
3031 * @param string $text the text to transform
3032 * @param Title &$title the Title object for the current article
3033 * @param User &$user the User object describing the current user
3034 * @param ParserOptions $options parsing options
3035 * @param bool $clearState whether to clear the parser state first
3036 * @return string the altered wiki markup
3039 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3040 $this->mOptions
= $options;
3041 $this->mTitle
=& $title;
3042 $this->mOutputType
= OT_WIKI
;
3044 if ( $clearState ) {
3045 $this->clearState();
3048 $stripState = false;
3052 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3053 $text = $this->strip( $text, $stripState, false );
3054 $text = $this->pstPass2( $text, $user );
3055 $text = $this->unstrip( $text, $stripState );
3056 $text = $this->unstripNoWiki( $text, $stripState );
3061 * Pre-save transform helper function
3064 function pstPass2( $text, &$user ) {
3065 global $wgContLang, $wgLocaltimezone;
3067 # Variable replacement
3068 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3069 $text = $this->replaceVariables( $text );
3073 $n = $user->getName();
3074 $k = $user->getOption( 'nickname' );
3075 if ( '' == $k ) { $k = $n; }
3076 if ( isset( $wgLocaltimezone ) ) {
3077 $oldtz = getenv( 'TZ' );
3078 putenv( 'TZ='.$wgLocaltimezone );
3081 /* Note: This is the timestamp saved as hardcoded wikitext to
3082 * the database, we use $wgContLang here in order to give
3083 * everyone the same signiture and use the default one rather
3084 * than the one selected in each users preferences.
3086 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3087 ' (' . date( 'T' ) . ')';
3088 if ( isset( $wgLocaltimezone ) ) {
3089 putenv( 'TZ='.$oldtz );
3092 if( $user->getOption( 'fancysig' ) ) {
3095 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
3097 $text = preg_replace( '/~~~~~/', $d, $text );
3098 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3099 $text = preg_replace( '/~~~/', $sigText, $text );
3101 # Context links: [[|name]] and [[name (context)|]]
3103 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
3104 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
3105 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3106 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3108 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3109 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3110 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3111 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3113 $t = $this->mTitle
->getText();
3114 if ( preg_match( $conpat, $t, $m ) ) {
3117 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3118 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3119 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3121 if ( '' == $context ) {
3122 $text = preg_replace( $p2, '[[\\1]]', $text );
3124 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3127 # Trim trailing whitespace
3128 # MAG_END (__END__) tag allows for trailing
3129 # whitespace to be deliberately included
3130 $text = rtrim( $text );
3131 $mw =& MagicWord
::get( MAG_END
);
3132 $mw->matchAndRemove( $text );
3138 * Set up some variables which are usually set up in parse()
3139 * so that an external function can call some class members with confidence
3142 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3143 $this->mTitle
=& $title;
3144 $this->mOptions
= $options;
3145 $this->mOutputType
= $outputType;
3146 if ( $clearState ) {
3147 $this->clearState();
3152 * Transform a MediaWiki message by replacing magic variables.
3154 * @param string $text the text to transform
3155 * @param ParserOptions $options options
3156 * @return string the text with variables substituted
3159 function transformMsg( $text, $options ) {
3161 static $executing = false;
3163 # Guard against infinite recursion
3169 $this->mTitle
= $wgTitle;
3170 $this->mOptions
= $options;
3171 $this->mOutputType
= OT_MSG
;
3172 $this->clearState();
3173 $text = $this->replaceVariables( $text );
3180 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3181 * Callback will be called with the text within
3182 * Transform and return the text within
3185 function setHook( $tag, $callback ) {
3186 $oldVal = @$this->mTagHooks
[$tag];
3187 $this->mTagHooks
[$tag] = $callback;
3192 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3193 * Placeholders created in Skin::makeLinkObj()
3194 * Returns an array of links found, indexed by PDBK:
3198 * $options is a bit field, RLH_FOR_UPDATE to select for update
3200 function replaceLinkHolders( &$text, $options = 0 ) {
3201 global $wgUser, $wgLinkCache;
3202 global $wgOutputReplace;
3204 $fname = 'Parser::replaceLinkHolders';
3205 wfProfileIn( $fname );
3209 $sk = $this->mOptions
->getSkin();
3211 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3212 wfProfileIn( $fname.'-check' );
3213 $dbr =& wfGetDB( DB_SLAVE
);
3214 $page = $dbr->tableName( 'page' );
3215 $threshold = $wgUser->getOption('stubthreshold');
3218 asort( $this->mLinkHolders
['namespaces'] );
3222 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3224 $title = $this->mLinkHolders
['titles'][$key];
3226 # Skip invalid entries.
3227 # Result will be ugly, but prevents crash.
3228 if ( is_null( $title ) ) {
3231 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3233 # Check if it's in the link cache already
3234 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3235 $colours[$pdbk] = 1;
3236 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3237 $colours[$pdbk] = 0;
3239 # Not in the link cache, add it to the query
3240 if ( !isset( $current ) ) {
3242 $query = "SELECT page_id, page_namespace, page_title";
3243 if ( $threshold > 0 ) {
3244 $query .= ', page_len, page_is_redirect';
3246 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3247 } elseif ( $current != $val ) {
3249 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3254 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3259 if ( $options & RLH_FOR_UPDATE
) {
3260 $query .= ' FOR UPDATE';
3263 $res = $dbr->query( $query, $fname );
3265 # Fetch data and form into an associative array
3266 # non-existent = broken
3269 while ( $s = $dbr->fetchObject($res) ) {
3270 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3271 $pdbk = $title->getPrefixedDBkey();
3272 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3274 if ( $threshold > 0 ) {
3275 $size = $s->page_len
;
3276 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3277 $colours[$pdbk] = 1;
3279 $colours[$pdbk] = 2;
3282 $colours[$pdbk] = 1;
3286 wfProfileOut( $fname.'-check' );
3288 # Construct search and replace arrays
3289 wfProfileIn( $fname.'-construct' );
3290 $wgOutputReplace = array();
3291 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3292 $pdbk = $pdbks[$key];
3293 $searchkey = "<!--LINK $key-->";
3294 $title = $this->mLinkHolders
['titles'][$key];
3295 if ( empty( $colours[$pdbk] ) ) {
3296 $wgLinkCache->addBadLinkObj( $title );
3297 $colours[$pdbk] = 0;
3298 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3299 $this->mLinkHolders
['texts'][$key],
3300 $this->mLinkHolders
['queries'][$key] );
3301 } elseif ( $colours[$pdbk] == 1 ) {
3302 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3303 $this->mLinkHolders
['texts'][$key],
3304 $this->mLinkHolders
['queries'][$key] );
3305 } elseif ( $colours[$pdbk] == 2 ) {
3306 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3307 $this->mLinkHolders
['texts'][$key],
3308 $this->mLinkHolders
['queries'][$key] );
3311 wfProfileOut( $fname.'-construct' );
3314 wfProfileIn( $fname.'-replace' );
3316 $text = preg_replace_callback(
3317 '/(<!--LINK .*?-->)/',
3318 "wfOutputReplaceMatches",
3321 wfProfileOut( $fname.'-replace' );
3324 # Now process interwiki link holders
3325 # This is quite a bit simpler than internal links
3326 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3327 wfProfileIn( $fname.'-interwiki' );
3328 # Make interwiki link HTML
3329 $wgOutputReplace = array();
3330 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3331 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3332 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3335 $text = preg_replace_callback(
3336 '/<!--IWLINK (.*?)-->/',
3337 "wfOutputReplaceMatches",
3339 wfProfileOut( $fname.'-interwiki' );
3342 wfProfileOut( $fname );
3347 * Replace <!--LINK--> link placeholders with plain text of links
3348 * (not HTML-formatted).
3349 * @param string $text
3352 function replaceLinkHoldersText( $text ) {
3353 global $wgUser, $wgLinkCache;
3354 global $wgOutputReplace;
3356 $fname = 'Parser::replaceLinkHoldersText';
3357 wfProfileIn( $fname );
3359 $text = preg_replace_callback(
3360 '/<!--(LINK|IWLINK) (.*?)-->/',
3361 array( &$this, 'replaceLinkHoldersTextCallback' ),
3364 wfProfileOut( $fname );
3369 * @param array $matches
3373 function replaceLinkHoldersTextCallback( $matches ) {
3374 $type = $matches[1];
3376 if( $type == 'LINK' ) {
3377 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3378 return $this->mLinkHolders
['texts'][$key];
3380 } elseif( $type == 'IWLINK' ) {
3381 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3382 return $this->mInterwikiLinkHolders
['texts'][$key];
3389 * Renders an image gallery from a text with one line per image.
3390 * text labels may be given by using |-style alternative text. E.g.
3391 * Image:one.jpg|The number "1"
3392 * Image:tree.jpg|A tree
3393 * given as text will return the HTML of a gallery with two images,
3394 * labeled 'The number "1"' and
3399 function renderImageGallery( $text ) {
3401 global $wgUser, $wgTitle;
3402 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3403 $localParser = new Parser();
3405 global $wgLinkCache;
3406 $ig = new ImageGallery();
3407 $ig->setShowBytes( false );
3408 $ig->setShowFilename( false );
3409 $lines = explode( "\n", $text );
3411 foreach ( $lines as $line ) {
3412 # match lines like these:
3413 # Image:someimage.jpg|This is some image
3414 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3416 if ( count( $matches ) == 0 ) {
3419 $nt = Title
::newFromURL( $matches[1] );
3420 if( is_null( $nt ) ) {
3421 # Bogus title. Ignore these so we don't bomb out later.
3424 if ( isset( $matches[3] ) ) {
3425 $label = $matches[3];
3430 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3431 $html = $html->mText
;
3433 $ig->add( new Image( $nt ), $html );
3434 $wgLinkCache->addImageLinkObj( $nt );
3436 return $ig->toHTML();
3440 * Parse image options text and use it to make an image
3442 function makeImage( &$nt, $options ) {
3443 global $wgContLang, $wgUseImageResize;
3444 global $wgUser, $wgThumbLimits;
3448 # Check if the options text is of the form "options|alt text"
3450 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3451 # * left no resizing, just left align. label is used for alt= only
3452 # * right same, but right aligned
3453 # * none same, but not aligned
3454 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3455 # * center center the image
3456 # * framed Keep original image size, no magnify-button.
3458 $part = explode( '|', $options);
3460 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3461 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3462 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3463 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3464 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3465 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3466 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3467 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3470 $width = $height = $framed = $thumb = false;
3471 $manual_thumb = '' ;
3473 foreach( $part as $key => $val ) {
3474 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3476 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3477 # use manually specified thumbnail
3479 $manual_thumb = $match;
3480 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3481 # remember to set an alignment, don't render immediately
3483 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3484 # remember to set an alignment, don't render immediately
3486 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3487 # remember to set an alignment, don't render immediately
3489 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3490 # remember to set an alignment, don't render immediately
3492 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3493 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3494 # $match is the image width in pixels
3495 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3496 $width = intval( $m[1] );
3497 $height = intval( $m[2] );
3499 $width = intval($match);
3501 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3507 # Strip bad stuff out of the alt text
3508 $alt = $this->replaceLinkHoldersText( $caption );
3509 $alt = Sanitizer
::stripAllTags( $alt );
3511 # Linker does the rest
3512 $sk =& $this->mOptions
->getSkin();
3513 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3517 * Set a flag in the output object indicating that the content is dynamic and
3518 * shouldn't be cached.
3520 function disableCache() {
3521 $this->mOutput
->mCacheTime
= -1;
3525 * Callback from the Sanitizer for expanding items found in HTML attribute
3526 * values, so they can be safely tested and escaped.
3527 * @param string $text
3528 * @param array $args
3532 function attributeStripCallback( &$text, $args ) {
3533 $text = $this->replaceVariables( $text, $args );
3534 $text = $this->unstripForHTML( $text );
3538 function unstripForHTML( $text ) {
3539 $text = $this->unstrip( $text, $this->mStripState
);
3540 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3547 * @package MediaWiki
3551 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3552 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3553 var $mVersion; # Compatibility check
3554 var $mTitleText; # title text of the chosen language variant
3556 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3557 $containsOldMagic = false, $titletext = '' )
3559 $this->mText
= $text;
3560 $this->mLanguageLinks
= $languageLinks;
3561 $this->mCategoryLinks
= $categoryLinks;
3562 $this->mContainsOldMagic
= $containsOldMagic;
3563 $this->mCacheTime
= '';
3564 $this->mVersion
= MW_PARSER_VERSION
;
3565 $this->mTitleText
= $titletext;
3568 function getText() { return $this->mText
; }
3569 function getLanguageLinks() { return $this->mLanguageLinks
; }
3570 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3571 function getCacheTime() { return $this->mCacheTime
; }
3572 function getTitleText() { return $this->mTitleText
; }
3573 function containsOldMagic() { return $this->mContainsOldMagic
; }
3574 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3575 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3576 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3577 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3578 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3579 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3581 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3583 function merge( $other ) {
3584 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3585 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3586 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3590 * Return true if this cached output object predates the global or
3591 * per-article cache invalidation timestamps, or if it comes from
3592 * an incompatible older version.
3594 * @param string $touched the affected article's last touched timestamp
3598 function expired( $touched ) {
3599 global $wgCacheEpoch;
3600 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3601 $this->getCacheTime() <= $touched ||
3602 $this->getCacheTime() <= $wgCacheEpoch ||
3603 !isset( $this->mVersion
) ||
3604 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3609 * Set options of the Parser
3611 * @package MediaWiki
3615 # All variables are private
3616 var $mUseTeX; # Use texvc to expand <math> tags
3617 var $mUseDynamicDates; # Use DateFormatter to format dates
3618 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3619 var $mAllowExternalImages; # Allow external images inline
3620 var $mSkin; # Reference to the preferred skin
3621 var $mDateFormat; # Date format index
3622 var $mEditSection; # Create "edit section" links
3623 var $mNumberHeadings; # Automatically number headings
3624 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3626 function getUseTeX() { return $this->mUseTeX
; }
3627 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3628 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3629 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3630 function &getSkin() { return $this->mSkin
; }
3631 function getDateFormat() { return $this->mDateFormat
; }
3632 function getEditSection() { return $this->mEditSection
; }
3633 function getNumberHeadings() { return $this->mNumberHeadings
; }
3634 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3637 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3638 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3639 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3640 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3641 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3642 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3643 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3644 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3646 function setSkin( &$x ) { $this->mSkin
=& $x; }
3648 function ParserOptions() {
3650 $this->initialiseFromUser( $wgUser );
3654 * Get parser options
3657 function newFromUser( &$user ) {
3658 $popts = new ParserOptions
;
3659 $popts->initialiseFromUser( $user );
3663 /** Get user options */
3664 function initialiseFromUser( &$userInput ) {
3665 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3666 $wgAllowSpecialInclusion;
3667 $fname = 'ParserOptions::initialiseFromUser';
3668 wfProfileIn( $fname );
3669 if ( !$userInput ) {
3671 $user->setLoaded( true );
3673 $user =& $userInput;
3676 $this->mUseTeX
= $wgUseTeX;
3677 $this->mUseDynamicDates
= $wgUseDynamicDates;
3678 $this->mInterwikiMagic
= $wgInterwikiMagic;
3679 $this->mAllowExternalImages
= $wgAllowExternalImages;
3680 wfProfileIn( $fname.'-skin' );
3681 $this->mSkin
=& $user->getSkin();
3682 wfProfileOut( $fname.'-skin' );
3683 $this->mDateFormat
= $user->getOption( 'date' );
3684 $this->mEditSection
= true;
3685 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3686 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3687 wfProfileOut( $fname );
3692 * Callback function used by Parser::replaceLinkHolders()
3693 * to substitute link placeholders.
3695 function &wfOutputReplaceMatches( $matches ) {
3696 global $wgOutputReplace;
3697 return $wgOutputReplace[$matches[1]];
3701 * Return the total number of articles
3703 function wfNumberOfArticles() {
3704 global $wgNumberOfArticles;
3707 return $wgNumberOfArticles;
3711 * Return the number of files
3713 function wfNumberOfFiles() {
3714 $fname = 'Parser::wfNumberOfFiles';
3716 wfProfileIn( $fname );
3717 $dbr =& wfGetDB( DB_SLAVE
);
3718 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3719 wfProfileOut( $fname );
3725 * Get various statistics from the database
3728 function wfLoadSiteStats() {
3729 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3730 $fname = 'wfLoadSiteStats';
3732 if ( -1 != $wgNumberOfArticles ) return;
3733 $dbr =& wfGetDB( DB_SLAVE
);
3734 $s = $dbr->selectRow( 'site_stats',
3735 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3736 array( 'ss_row_id' => 1 ), $fname
3739 if ( $s === false ) {
3742 $wgTotalViews = $s->ss_total_views
;
3743 $wgTotalEdits = $s->ss_total_edits
;
3744 $wgNumberOfArticles = $s->ss_good_articles
;
3750 * Basicly replacing " > and < with HTML entities ( ", >, <)
3752 * @param string $in Text that might contain HTML tags
3753 * @return string Escaped string
3755 function wfEscapeHTMLTagsOnly( $in ) {
3757 array( '"', '>', '<' ),
3758 array( '"', '>', '<' ),