3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.5.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # prefix for escaping, used in two functions at least
47 define( 'UNIQ_PREFIX', 'NaodW29');
49 # Constants needed for external link processing
50 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone, $wgAllowSpecialInclusion*
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
113 var $mIWTransData = array();
123 $this->mTemplates
= array();
124 $this->mTemplatePath
= array();
125 $this->mTagHooks
= array();
134 function clearState() {
135 $this->mOutput
= new ParserOutput
;
136 $this->mAutonumber
= 0;
137 $this->mLastSection
= '';
138 $this->mDTopen
= false;
139 $this->mVariables
= false;
140 $this->mIncludeCount
= array();
141 $this->mStripState
= array();
142 $this->mArgStack
= array();
143 $this->mInPre
= false;
144 $this->mInterwikiLinkHolders
= array(
148 $this->mLinkHolders
= array(
149 'namespaces' => array(),
151 'queries' => array(),
158 * First pass--just handle <nowiki> sections, pass the rest off
159 * to internalParse() which does all the real work.
162 * @param string $text Text we want to parse
163 * @param Title &$title A title object
164 * @param array $options
165 * @param boolean $linestart
166 * @param boolean $clearState
167 * @return ParserOutput a ParserOutput
169 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
170 global $wgUseTidy, $wgContLang;
171 $fname = 'Parser::parse';
172 wfProfileIn( $fname );
178 $this->mOptions
= $options;
179 $this->mTitle
=& $title;
180 $this->mOutputType
= OT_HTML
;
182 $this->mStripState
= NULL;
184 //$text = $this->strip( $text, $this->mStripState );
185 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
186 $x =& $this->mStripState
;
188 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
189 $text = $this->strip( $text, $x );
190 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
192 $text = $this->internalParse( $text );
194 $text = $this->unstrip( $text, $this->mStripState
);
196 # Clean up special characters, only run once, next-to-last before doBlockLevels
198 # french spaces, last one Guillemet-left
199 # only if there is something before the space
200 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
201 # french spaces, Guillemet-right
202 '/(\\302\\253) /' => '\\1 ',
203 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
205 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
208 $text = $this->doBlockLevels( $text, $linestart );
210 $this->replaceLinkHolders( $text );
212 # the position of the convert() call should not be changed. it
213 # assumes that the links are all replaces and the only thing left
214 # is the <nowiki> mark.
215 $text = $wgContLang->convert($text);
216 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
218 $text = $this->unstripNoWiki( $text, $this->mStripState
);
220 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
222 $text = Sanitizer
::normalizeCharReferences( $text );
225 $text = Parser
::tidy($text);
228 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
230 $this->mOutput
->setText( $text );
231 wfProfileOut( $fname );
232 return $this->mOutput
;
236 * Get a random string
241 function getRandomString() {
242 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
246 * Replaces all occurrences of <$tag>content</$tag> in the text
247 * with a random marker and returns the new text. the output parameter
248 * $content will be an associative array filled with data on the form
249 * $unique_marker => content.
251 * If $content is already set, the additional entries will be appended
252 * If $tag is set to STRIP_COMMENTS, the function will extract
253 * <!-- HTML comments -->
258 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
259 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
274 if( $tag == STRIP_COMMENTS
) {
278 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
279 $end = "/<\\/$tag\\s*>/i";
282 while ( '' != $text ) {
283 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
285 if( count( $p ) < 3 ) {
291 $marker = $rnd . sprintf('%08X', $n++
);
292 $stripped .= $marker;
294 $tags[$marker] = "<$tag$attributes>";
295 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
297 $q = preg_split( $end, $inside, 2 );
298 $content[$marker] = $q[0];
299 if( count( $q ) < 2 ) {
300 # No end tag -- let it run out to the end of the text.
310 * Wrapper function for extractTagsAndParams
311 * for cases where $tags and $params isn't needed
312 * i.e. where tags will never have params, like <nowiki>
317 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
318 $dummy_tags = array();
319 $dummy_params = array();
321 return Parser
::extractTagsAndParams( $tag, $text, $content,
322 $dummy_tags, $dummy_params, $uniq_prefix );
326 * Strips and renders nowiki, pre, math, hiero
327 * If $render is set, performs necessary rendering operations on plugins
328 * Returns the text, and fills an array with data needed in unstrip()
329 * If the $state is already a valid strip state, it adds to the state
331 * @param bool $stripcomments when set, HTML comments <!-- like this -->
332 * will be stripped in addition to other tags. This is important
333 * for section editing, where these comments cause confusion when
334 * counting the sections in the wikisource
338 function strip( $text, &$state, $stripcomments = false ) {
339 $render = ($this->mOutputType
== OT_HTML
);
340 $html_content = array();
341 $nowiki_content = array();
342 $math_content = array();
343 $pre_content = array();
344 $comment_content = array();
345 $ext_content = array();
347 $ext_params = array();
348 $gallery_content = array();
350 # Replace any instances of the placeholders
351 $uniq_prefix = UNIQ_PREFIX
;
352 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
357 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
358 foreach( $html_content as $marker => $content ) {
360 # Raw and unchecked for validity.
361 $html_content[$marker] = $content;
363 $html_content[$marker] = '<html>'.$content.'</html>';
369 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
370 foreach( $nowiki_content as $marker => $content ) {
372 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
374 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
379 if( $this->mOptions
->getUseTeX() ) {
380 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
381 foreach( $math_content as $marker => $content ){
383 $math_content[$marker] = renderMath( $content );
385 $math_content[$marker] = '<math>'.$content.'</math>';
391 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
392 foreach( $pre_content as $marker => $content ){
394 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
396 $pre_content[$marker] = '<pre>'.$content.'</pre>';
401 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
402 foreach( $gallery_content as $marker => $content ) {
403 require_once( 'ImageGallery.php' );
405 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
407 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
413 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
414 foreach( $comment_content as $marker => $content ){
415 $comment_content[$marker] = '<!--'.$content.'-->';
420 foreach ( $this->mTagHooks
as $tag => $callback ) {
421 $ext_content[$tag] = array();
422 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
423 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
424 foreach( $ext_content[$tag] as $marker => $content ) {
425 $full_tag = $ext_tags[$tag][$marker];
426 $params = $ext_params[$tag][$marker];
428 $ext_content[$tag][$marker] = $callback( $content, $params, $this );
430 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
435 # Merge state with the pre-existing state, if there is one
437 $state['html'] = $state['html'] +
$html_content;
438 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
439 $state['math'] = $state['math'] +
$math_content;
440 $state['pre'] = $state['pre'] +
$pre_content;
441 $state['comment'] = $state['comment'] +
$comment_content;
442 $state['gallery'] = $state['gallery'] +
$gallery_content;
444 foreach( $ext_content as $tag => $array ) {
445 if ( array_key_exists( $tag, $state ) ) {
446 $state[$tag] = $state[$tag] +
$array;
451 'html' => $html_content,
452 'nowiki' => $nowiki_content,
453 'math' => $math_content,
454 'pre' => $pre_content,
455 'comment' => $comment_content,
456 'gallery' => $gallery_content,
463 * restores pre, math, and hiero removed by strip()
465 * always call unstripNoWiki() after this one
468 function unstrip( $text, &$state ) {
469 if ( !is_array( $state ) ) {
473 # Must expand in reverse order, otherwise nested tags will be corrupted
474 $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 ) {
1125 $fname = 'Parser::replaceFreeExternalLinks';
1126 wfProfileIn( $fname );
1128 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1129 $s = array_shift( $bits );
1132 $sk =& $this->mOptions
->getSkin();
1134 while ( $i < count( $bits ) ){
1135 $protocol = $bits[$i++
];
1136 $remainder = $bits[$i++
];
1138 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1139 # Found some characters after the protocol that look promising
1140 $url = $protocol . $m[1];
1143 # The characters '<' and '>' (which were escaped by
1144 # removeHTMLtags()) should not be included in
1145 # URLs, per RFC 2396.
1146 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1147 $trail = substr($url, $m2[0][1]) . $trail;
1148 $url = substr($url, 0, $m2[0][1]);
1151 # Move trailing punctuation to $trail
1153 # If there is no left bracket, then consider right brackets fair game too
1154 if ( strpos( $url, '(' ) === false ) {
1158 $numSepChars = strspn( strrev( $url ), $sep );
1159 if ( $numSepChars ) {
1160 $trail = substr( $url, -$numSepChars ) . $trail;
1161 $url = substr( $url, 0, -$numSepChars );
1164 # Replace & from obsolete syntax with &.
1165 # All HTML entities will be escaped by makeExternalLink()
1166 # or maybeMakeExternalImage()
1167 $url = str_replace( '&', '&', $url );
1169 # Is this an external image?
1170 $text = $this->maybeMakeExternalImage( $url );
1171 if ( $text === false ) {
1172 # Not an image, make a link
1173 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1175 $s .= $text . $trail;
1177 $s .= $protocol . $remainder;
1180 wfProfileOut( $fname );
1185 * make an image if it's allowed, either through the global
1186 * option or through the exception
1189 function maybeMakeExternalImage( $url ) {
1190 $sk =& $this->mOptions
->getSkin();
1191 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1192 $imagesexception = !empty($imagesfrom);
1194 if ( $this->mOptions
->getAllowExternalImages()
1195 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1196 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1198 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1205 * Process [[ ]] wikilinks
1209 function replaceInternalLinks( $s ) {
1210 global $wgContLang, $wgLinkCache;
1211 static $fname = 'Parser::replaceInternalLinks' ;
1213 wfProfileIn( $fname );
1215 wfProfileIn( $fname.'-setup' );
1217 # the % is needed to support urlencoded titles as well
1218 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1220 $sk =& $this->mOptions
->getSkin();
1222 #split the entire text string on occurences of [[
1223 $a = explode( '[[', ' ' . $s );
1224 #get the first element (all text up to first [[), and remove the space we added
1225 $s = array_shift( $a );
1226 $s = substr( $s, 1 );
1228 # Match a link having the form [[namespace:link|alternate]]trail
1230 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1231 # Match cases where there is no "]]", which might still be images
1232 static $e1_img = FALSE;
1233 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1234 # Match the end of a line for a word that's not followed by whitespace,
1235 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1236 $e2 = wfMsgForContent( 'linkprefix' );
1238 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1240 if( is_null( $this->mTitle
) ) {
1241 wfDebugDieBacktrace( 'nooo' );
1243 $nottalk = !$this->mTitle
->isTalkPage();
1245 if ( $useLinkPrefixExtension ) {
1246 if ( preg_match( $e2, $s, $m ) ) {
1247 $first_prefix = $m[2];
1249 $first_prefix = false;
1255 $selflink = $this->mTitle
->getPrefixedText();
1256 wfProfileOut( $fname.'-setup' );
1258 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1259 $useSubpages = $this->areSubpagesAllowed();
1261 # Loop for each link
1262 for ($k = 0; isset( $a[$k] ); $k++
) {
1264 if ( $useLinkPrefixExtension ) {
1265 wfProfileIn( $fname.'-prefixhandling' );
1266 if ( preg_match( $e2, $s, $m ) ) {
1274 $prefix = $first_prefix;
1275 $first_prefix = false;
1277 wfProfileOut( $fname.'-prefixhandling' );
1280 $might_be_img = false;
1282 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1284 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1285 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1286 # the real problem is with the $e1 regex
1289 # Still some problems for cases where the ] is meant to be outside punctuation,
1290 # and no image is in sight. See bug 2095.
1292 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1293 $text .= ']'; # so that replaceExternalLinks($text) works later
1296 # fix up urlencoded title texts
1297 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1299 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1300 $might_be_img = true;
1302 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1304 } else { # Invalid form; output directly
1305 $s .= $prefix . '[[' . $line ;
1309 # Don't allow internal links to pages containing
1310 # PROTO: where PROTO is a valid URL protocol; these
1311 # should be external links.
1312 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1313 $s .= $prefix . '[[' . $line ;
1317 # Make subpage if necessary
1318 if( $useSubpages ) {
1319 $link = $this->maybeDoSubpageLink( $m[1], $text );
1324 $noforce = (substr($m[1], 0, 1) != ':');
1326 # Strip off leading ':'
1327 $link = substr($link, 1);
1330 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1332 $s .= $prefix . '[[' . $line;
1336 #check other language variants of the link
1337 #if the article does not exist
1338 if( $checkVariantLink
1339 && $nt->getArticleID() == 0 ) {
1340 $wgContLang->findVariantLink($link, $nt);
1343 $ns = $nt->getNamespace();
1344 $iw = $nt->getInterWiki();
1346 if ($might_be_img) { # if this is actually an invalid link
1347 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1349 while (isset ($a[$k+
1]) ) {
1350 #look at the next 'line' to see if we can close it there
1351 $spliced = array_splice( $a, $k +
1, 1 );
1352 $next_line = array_shift( $spliced );
1353 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1354 # the first ]] closes the inner link, the second the image
1356 $text .= '[[' . $m[1];
1359 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1360 #if there's exactly one ]] that's fine, we'll keep looking
1361 $text .= '[[' . $m[0];
1363 #if $next_line is invalid too, we need look no further
1364 $text .= '[[' . $next_line;
1369 # we couldn't find the end of this imageLink, so output it raw
1370 #but don't ignore what might be perfectly normal links in the text we've examined
1371 $text = $this->replaceInternalLinks($text);
1372 $s .= $prefix . '[[' . $link . '|' . $text;
1373 # note: no $trail, because without an end, there *is* no trail
1376 } else { #it's not an image, so output it raw
1377 $s .= $prefix . '[[' . $link . '|' . $text;
1378 # note: no $trail, because without an end, there *is* no trail
1383 $wasblank = ( '' == $text );
1384 if( $wasblank ) $text = $link;
1387 # Link not escaped by : , create the various objects
1391 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1392 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1393 $s = rtrim($s . "\n");
1394 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1398 if ( $ns == NS_IMAGE
) {
1399 wfProfileIn( "$fname-image" );
1400 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1401 # recursively parse links inside the image caption
1402 # actually, this will parse them in any other parameters, too,
1403 # but it might be hard to fix that, and it doesn't matter ATM
1404 $text = $this->replaceExternalLinks($text);
1405 $text = $this->replaceInternalLinks($text);
1407 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1408 $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1409 $wgLinkCache->addImageLinkObj( $nt );
1411 wfProfileOut( "$fname-image" );
1414 wfProfileOut( "$fname-image" );
1418 if ( $ns == NS_CATEGORY
) {
1419 wfProfileIn( "$fname-category" );
1420 $t = $wgContLang->convertHtml( $nt->getText() );
1421 $s = rtrim($s . "\n"); # bug 87
1423 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1424 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1425 $wgLinkCache->resume();
1428 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1429 $sortkey = $this->mTitle
->getText();
1431 $sortkey = $this->mTitle
->getPrefixedText();
1436 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1437 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1438 $this->mOutput
->addCategoryLink( $t );
1441 * Strip the whitespace Category links produce, see bug 87
1442 * @todo We might want to use trim($tmp, "\n") here.
1444 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1446 wfProfileOut( "$fname-category" );
1451 if( ( $nt->getPrefixedText() === $selflink ) &&
1452 ( $nt->getFragment() === '' ) ) {
1453 # Self-links are handled specially; generally de-link and change to bold.
1454 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1458 # Special and Media are pseudo-namespaces; no pages actually exist in them
1459 if( $ns == NS_MEDIA
) {
1460 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1461 $wgLinkCache->addImageLinkObj( $nt );
1463 } elseif( $ns == NS_SPECIAL
) {
1464 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1467 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1469 wfProfileOut( $fname );
1474 * Make a link placeholder. The text returned can be later resolved to a real link with
1475 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1476 * parsing of interwiki links, and secondly to allow all extistence checks and
1477 * article length checks (for stub links) to be bundled into a single query.
1480 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1481 if ( ! is_object($nt) ) {
1483 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1485 # Separate the link trail from the rest of the link
1486 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1488 if ( $nt->isExternal() ) {
1489 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1490 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1491 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1493 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1494 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1495 $this->mLinkHolders
['queries'][] = $query;
1496 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1497 $this->mLinkHolders
['titles'][] = $nt;
1499 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1506 * Return true if subpage links should be expanded on this page.
1509 function areSubpagesAllowed() {
1510 # Some namespaces don't allow subpages
1511 global $wgNamespacesWithSubpages;
1512 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1516 * Handle link to subpage if necessary
1517 * @param string $target the source of the link
1518 * @param string &$text the link text, modified as necessary
1519 * @return string the full name of the link
1522 function maybeDoSubpageLink($target, &$text) {
1525 # :Foobar -- override special treatment of prefix (images, language links)
1526 # /Foobar -- convert to CurrentPage/Foobar
1527 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1528 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1529 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1531 $fname = 'Parser::maybeDoSubpageLink';
1532 wfProfileIn( $fname );
1533 $ret = $target; # default return value is no change
1535 # Some namespaces don't allow subpages,
1536 # so only perform processing if subpages are allowed
1537 if( $this->areSubpagesAllowed() ) {
1538 # Look at the first character
1539 if( $target != '' && $target{0} == '/' ) {
1540 # / at end means we don't want the slash to be shown
1541 if( substr( $target, -1, 1 ) == '/' ) {
1542 $target = substr( $target, 1, -1 );
1545 $noslash = substr( $target, 1 );
1548 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1549 if( '' === $text ) {
1551 } # this might be changed for ugliness reasons
1553 # check for .. subpage backlinks
1555 $nodotdot = $target;
1556 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1558 $nodotdot = substr( $nodotdot, 3 );
1560 if($dotdotcount > 0) {
1561 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1562 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1563 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1564 # / at the end means don't show full path
1565 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1566 $nodotdot = substr( $nodotdot, 0, -1 );
1567 if( '' === $text ) {
1571 $nodotdot = trim( $nodotdot );
1572 if( $nodotdot != '' ) {
1573 $ret .= '/' . $nodotdot;
1580 wfProfileOut( $fname );
1585 * Used by doBlockLevels()
1588 /* private */ function closeParagraph() {
1590 if ( '' != $this->mLastSection
) {
1591 $result = '</' . $this->mLastSection
. ">\n";
1593 $this->mInPre
= false;
1594 $this->mLastSection
= '';
1597 # getCommon() returns the length of the longest common substring
1598 # of both arguments, starting at the beginning of both.
1600 /* private */ function getCommon( $st1, $st2 ) {
1601 $fl = strlen( $st1 );
1602 $shorter = strlen( $st2 );
1603 if ( $fl < $shorter ) { $shorter = $fl; }
1605 for ( $i = 0; $i < $shorter; ++
$i ) {
1606 if ( $st1{$i} != $st2{$i} ) { break; }
1610 # These next three functions open, continue, and close the list
1611 # element appropriate to the prefix character passed into them.
1613 /* private */ function openList( $char ) {
1614 $result = $this->closeParagraph();
1616 if ( '*' == $char ) { $result .= '<ul><li>'; }
1617 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1618 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1619 else if ( ';' == $char ) {
1620 $result .= '<dl><dt>';
1621 $this->mDTopen
= true;
1623 else { $result = '<!-- ERR 1 -->'; }
1628 /* private */ function nextItem( $char ) {
1629 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1630 else if ( ':' == $char ||
';' == $char ) {
1632 if ( $this->mDTopen
) { $close = '</dt>'; }
1633 if ( ';' == $char ) {
1634 $this->mDTopen
= true;
1635 return $close . '<dt>';
1637 $this->mDTopen
= false;
1638 return $close . '<dd>';
1641 return '<!-- ERR 2 -->';
1644 /* private */ function closeList( $char ) {
1645 if ( '*' == $char ) { $text = '</li></ul>'; }
1646 else if ( '#' == $char ) { $text = '</li></ol>'; }
1647 else if ( ':' == $char ) {
1648 if ( $this->mDTopen
) {
1649 $this->mDTopen
= false;
1650 $text = '</dt></dl>';
1652 $text = '</dd></dl>';
1655 else { return '<!-- ERR 3 -->'; }
1661 * Make lists from lines starting with ':', '*', '#', etc.
1664 * @return string the lists rendered as HTML
1666 function doBlockLevels( $text, $linestart ) {
1667 $fname = 'Parser::doBlockLevels';
1668 wfProfileIn( $fname );
1670 # Parsing through the text line by line. The main thing
1671 # happening here is handling of block-level elements p, pre,
1672 # and making lists from lines starting with * # : etc.
1674 $textLines = explode( "\n", $text );
1676 $lastPrefix = $output = '';
1677 $this->mDTopen
= $inBlockElem = false;
1679 $paragraphStack = false;
1681 if ( !$linestart ) {
1682 $output .= array_shift( $textLines );
1684 foreach ( $textLines as $oLine ) {
1685 $lastPrefixLength = strlen( $lastPrefix );
1686 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1687 $preOpenMatch = preg_match('/<pre/i', $oLine );
1688 if ( !$this->mInPre
) {
1689 # Multiple prefixes may abut each other for nested lists.
1690 $prefixLength = strspn( $oLine, '*#:;' );
1691 $pref = substr( $oLine, 0, $prefixLength );
1694 $pref2 = str_replace( ';', ':', $pref );
1695 $t = substr( $oLine, $prefixLength );
1696 $this->mInPre
= !empty($preOpenMatch);
1698 # Don't interpret any other prefixes in preformatted text
1700 $pref = $pref2 = '';
1705 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1706 # Same as the last item, so no need to deal with nesting or opening stuff
1707 $output .= $this->nextItem( substr( $pref, -1 ) );
1708 $paragraphStack = false;
1710 if ( substr( $pref, -1 ) == ';') {
1711 # The one nasty exception: definition lists work like this:
1712 # ; title : definition text
1713 # So we check for : in the remainder text to split up the
1714 # title and definition, without b0rking links.
1716 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1718 $output .= $term . $this->nextItem( ':' );
1721 } elseif( $prefixLength ||
$lastPrefixLength ) {
1722 # Either open or close a level...
1723 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1724 $paragraphStack = false;
1726 while( $commonPrefixLength < $lastPrefixLength ) {
1727 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1728 --$lastPrefixLength;
1730 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1731 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1733 while ( $prefixLength > $commonPrefixLength ) {
1734 $char = substr( $pref, $commonPrefixLength, 1 );
1735 $output .= $this->openList( $char );
1737 if ( ';' == $char ) {
1738 # FIXME: This is dupe of code above
1739 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1741 $output .= $term . $this->nextItem( ':' );
1744 ++
$commonPrefixLength;
1746 $lastPrefix = $pref2;
1748 if( 0 == $prefixLength ) {
1749 wfProfileIn( "$fname-paragraph" );
1750 # No prefix (not in list)--go to paragraph mode
1751 $uniq_prefix = UNIQ_PREFIX
;
1752 // XXX: use a stack for nestable elements like span, table and div
1753 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1754 $closematch = preg_match(
1755 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1756 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1757 if ( $openmatch or $closematch ) {
1758 $paragraphStack = false;
1759 $output .= $this->closeParagraph();
1760 if ( $preOpenMatch and !$preCloseMatch ) {
1761 $this->mInPre
= true;
1763 if ( $closematch ) {
1764 $inBlockElem = false;
1766 $inBlockElem = true;
1768 } else if ( !$inBlockElem && !$this->mInPre
) {
1769 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1771 if ($this->mLastSection
!= 'pre') {
1772 $paragraphStack = false;
1773 $output .= $this->closeParagraph().'<pre>';
1774 $this->mLastSection
= 'pre';
1776 $t = substr( $t, 1 );
1779 if ( '' == trim($t) ) {
1780 if ( $paragraphStack ) {
1781 $output .= $paragraphStack.'<br />';
1782 $paragraphStack = false;
1783 $this->mLastSection
= 'p';
1785 if ($this->mLastSection
!= 'p' ) {
1786 $output .= $this->closeParagraph();
1787 $this->mLastSection
= '';
1788 $paragraphStack = '<p>';
1790 $paragraphStack = '</p><p>';
1794 if ( $paragraphStack ) {
1795 $output .= $paragraphStack;
1796 $paragraphStack = false;
1797 $this->mLastSection
= 'p';
1798 } else if ($this->mLastSection
!= 'p') {
1799 $output .= $this->closeParagraph().'<p>';
1800 $this->mLastSection
= 'p';
1805 wfProfileOut( "$fname-paragraph" );
1807 // somewhere above we forget to get out of pre block (bug 785)
1808 if($preCloseMatch && $this->mInPre
) {
1809 $this->mInPre
= false;
1811 if ($paragraphStack === false) {
1815 while ( $prefixLength ) {
1816 $output .= $this->closeList( $pref2{$prefixLength-1} );
1819 if ( '' != $this->mLastSection
) {
1820 $output .= '</' . $this->mLastSection
. '>';
1821 $this->mLastSection
= '';
1824 wfProfileOut( $fname );
1829 * Split up a string on ':', ignoring any occurences inside
1830 * <a>..</a> or <span>...</span>
1831 * @param string $str the string to split
1832 * @param string &$before set to everything before the ':'
1833 * @param string &$after set to everything after the ':'
1834 * return string the position of the ':', or false if none found
1836 function findColonNoLinks($str, &$before, &$after) {
1837 # I wonder if we should make this count all tags, not just <a>
1838 # and <span>. That would prevent us from matching a ':' that
1839 # comes in the middle of italics other such formatting....
1841 $fname = 'Parser::findColonNoLinks';
1842 wfProfileIn( $fname );
1845 $colon = strpos($str, ':', $pos);
1847 if ($colon !== false) {
1848 $before = substr($str, 0, $colon);
1849 $after = substr($str, $colon +
1);
1851 # Skip any ':' within <a> or <span> pairs
1852 $a = substr_count($before, '<a');
1853 $s = substr_count($before, '<span');
1854 $ca = substr_count($before, '</a>');
1855 $cs = substr_count($before, '</span>');
1857 if ($a <= $ca and $s <= $cs) {
1858 # Tags are balanced before ':'; ok
1863 } while ($colon !== false);
1864 wfProfileOut( $fname );
1869 * Return value of a magic variable (like PAGENAME)
1873 function getVariableValue( $index ) {
1874 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1877 * Some of these require message or data lookups and can be
1878 * expensive to check many times.
1880 static $varCache = array();
1881 if( isset( $varCache[$index] ) ) return $varCache[$index];
1884 case MAG_CURRENTMONTH
:
1885 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1886 case MAG_CURRENTMONTHNAME
:
1887 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1888 case MAG_CURRENTMONTHNAMEGEN
:
1889 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1890 case MAG_CURRENTMONTHABBREV
:
1891 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1892 case MAG_CURRENTDAY
:
1893 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1895 return $this->mTitle
->getText();
1897 return $this->mTitle
->getPartialURL();
1898 case MAG_REVISIONID
:
1899 return $wgArticle->getRevIdFetched();
1901 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1902 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1903 case MAG_CURRENTDAYNAME
:
1904 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1905 case MAG_CURRENTYEAR
:
1906 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1907 case MAG_CURRENTTIME
:
1908 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1909 case MAG_CURRENTWEEK
:
1910 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1911 case MAG_CURRENTDOW
:
1912 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1913 case MAG_NUMBEROFARTICLES
:
1914 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1915 case MAG_NUMBEROFFILES
:
1916 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1921 case MAG_SERVERNAME
:
1922 return $wgServerName;
1923 case MAG_SCRIPTPATH
:
1924 return $wgScriptPath;
1931 * initialise the magic variables (like CURRENTMONTHNAME)
1935 function initialiseVariables() {
1936 $fname = 'Parser::initialiseVariables';
1937 wfProfileIn( $fname );
1938 global $wgVariableIDs;
1939 $this->mVariables
= array();
1940 foreach ( $wgVariableIDs as $id ) {
1941 $mw =& MagicWord
::get( $id );
1942 $mw->addToArray( $this->mVariables
, $id );
1944 wfProfileOut( $fname );
1948 * parse any parentheses in format ((title|part|part))
1949 * and call callbacks to get a replacement text for any found piece
1951 * @param string $text The text to parse
1952 * @param array $callbacks rules in form:
1953 * '{' => array( # opening parentheses
1954 * 'end' => '}', # closing parentheses
1955 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1956 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1961 function replace_callback ($text, $callbacks) {
1962 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1963 $lastOpeningBrace = -1; # last not closed parentheses
1965 for ($i = 0; $i < strlen($text); $i++
) {
1966 # check for any opening brace
1969 foreach ($callbacks as $key => $value) {
1970 $pos = strpos ($text, $key, $i);
1971 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
1977 if ($lastOpeningBrace >= 0) {
1978 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
1980 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
1985 $pos = strpos ($text, '|', $i);
1987 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
1998 # found openning brace, lets add it to parentheses stack
1999 if (null != $rule) {
2000 $piece = array('brace' => $text[$i],
2001 'braceEnd' => $rule['end'],
2006 # count openning brace characters
2007 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2012 $piece['startAt'] = $i+
1;
2013 $piece['partStart'] = $i+
1;
2015 # we need to add to stack only if openning brace count is enough for any given rule
2016 foreach ($rule['cb'] as $cnt => $fn) {
2017 if ($piece['count'] >= $cnt) {
2018 $lastOpeningBrace ++
;
2019 $openingBraceStack[$lastOpeningBrace] = $piece;
2026 else if ($lastOpeningBrace >= 0) {
2027 # first check if it is a closing brace
2028 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2029 # lets check if it is enough characters for closing brace
2031 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2034 # if there are more closing parentheses than opening ones, we parse less
2035 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2036 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2038 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2040 $matchingCallback = null;
2041 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2042 if ($count >= $cnt && $matchingCount < $cnt) {
2043 $matchingCount = $cnt;
2044 $matchingCallback = $fn;
2048 if ($matchingCount == 0) {
2053 # lets set a title or last part (if '|' was found)
2054 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2055 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2057 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2059 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2060 $pieceEnd = $i +
$matchingCount;
2062 if( is_callable( $matchingCallback ) ) {
2064 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2065 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2066 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2067 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2069 # finally we can call a user callback and replace piece of text
2070 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2071 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2072 $i = $pieceStart +
strlen($replaceWith) - 1;
2075 # null value for callback means that parentheses should be parsed, but not replaced
2076 $i +
= $matchingCount - 1;
2079 # reset last openning parentheses, but keep it in case there are unused characters
2080 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2081 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2082 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2085 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2086 $openingBraceStack[$lastOpeningBrace--] = null;
2088 if ($matchingCount < $piece['count']) {
2089 $piece['count'] -= $matchingCount;
2090 $piece['startAt'] -= $matchingCount;
2091 $piece['partStart'] = $piece['startAt'];
2092 # do we still qualify for any callback with remaining count?
2093 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2094 if ($piece['count'] >= $cnt) {
2095 $lastOpeningBrace ++
;
2096 $openingBraceStack[$lastOpeningBrace] = $piece;
2104 # lets set a title if it is a first separator, or next part otherwise
2105 if ($text[$i] == '|') {
2106 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2107 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2108 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2111 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2113 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2122 * Replace magic variables, templates, and template arguments
2123 * with the appropriate text. Templates are substituted recursively,
2124 * taking care to avoid infinite loops.
2126 * Note that the substitution depends on value of $mOutputType:
2127 * OT_WIKI: only {{subst:}} templates
2128 * OT_MSG: only magic variables
2129 * OT_HTML: all templates and magic variables
2131 * @param string $tex The text to transform
2132 * @param array $args Key-value pairs representing template parameters to substitute
2135 function replaceVariables( $text, $args = array() ) {
2136 # Prevent too big inclusions
2137 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2141 $fname = 'Parser::replaceVariables';
2142 wfProfileIn( $fname );
2144 $titleChars = Title
::legalChars();
2146 # This function is called recursively. To keep track of arguments we need a stack:
2147 array_push( $this->mArgStack
, $args );
2149 $braceCallbacks = array();
2150 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2151 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2152 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2154 $callbacks = array();
2155 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2156 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2157 $text = $this->replace_callback ($text, $callbacks);
2159 array_pop( $this->mArgStack
);
2161 wfProfileOut( $fname );
2166 * Replace magic variables
2169 function variableSubstitution( $matches ) {
2170 $fname = 'parser::variableSubstitution';
2171 $varname = $matches[1];
2172 wfProfileIn( $fname );
2173 if ( !$this->mVariables
) {
2174 $this->initialiseVariables();
2177 if ( $this->mOutputType
== OT_WIKI
) {
2178 # Do only magic variables prefixed by SUBST
2179 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2180 if (!$mwSubst->matchStartAndRemove( $varname ))
2182 # Note that if we don't substitute the variable below,
2183 # we don't remove the {{subst:}} magic word, in case
2184 # it is a template rather than a magic variable.
2186 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2187 $id = $this->mVariables
[$varname];
2188 $text = $this->getVariableValue( $id );
2189 $this->mOutput
->mContainsOldMagic
= true;
2191 $text = $matches[0];
2193 wfProfileOut( $fname );
2197 # Split template arguments
2198 function getTemplateArgs( $argsString ) {
2199 if ( $argsString === '' ) {
2203 $args = explode( '|', substr( $argsString, 1 ) );
2205 # If any of the arguments contains a '[[' but no ']]', it needs to be
2206 # merged with the next arg because the '|' character between belongs
2207 # to the link syntax and not the template parameter syntax.
2208 $argc = count($args);
2210 for ( $i = 0; $i < $argc-1; $i++
) {
2211 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2212 $args[$i] .= '|'.$args[$i+
1];
2213 array_splice($args, $i+
1, 1);
2223 * Return the text of a template, after recursively
2224 * replacing any variables or templates within the template.
2226 * @param array $piece The parts of the template
2227 * $piece['text']: matched text
2228 * $piece['title']: the title, i.e. the part before the |
2229 * $piece['parts']: the parameter array
2230 * @return string the text of the template
2233 function braceSubstitution( $piece ) {
2234 global $wgLinkCache, $wgContLang;
2235 $fname = 'Parser::braceSubstitution';
2236 wfProfileIn( $fname );
2246 # $part1 is the bit before the first |, and must contain only title characters
2247 # $args is a list of arguments, starting from index 0, not including $part1
2249 $part1 = $piece['title'];
2250 # If the third subpattern matched anything, it will start with |
2252 if (null == $piece['parts']) {
2253 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2254 if ($replaceWith != $piece['text']) {
2255 $text = $replaceWith;
2261 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2262 $argc = count( $args );
2266 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2267 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2268 # One of two possibilities is true:
2269 # 1) Found SUBST but not in the PST phase
2270 # 2) Didn't find SUBST and in the PST phase
2271 # In either case, return without further processing
2272 $text = $piece['text'];
2278 # MSG, MSGNW and INT
2281 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2282 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2285 # Remove obsolete MSG:
2286 $mwMsg =& MagicWord
::get( MAG_MSG
);
2287 $mwMsg->matchStartAndRemove( $part1 );
2290 # Check if it is an internal message
2291 $mwInt =& MagicWord
::get( MAG_INT
);
2292 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2293 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2294 $text = $linestart . wfMsgReal( $part1, $args, true );
2302 # Check for NS: (namespace expansion)
2303 $mwNs = MagicWord
::get( MAG_NS
);
2304 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2305 if ( intval( $part1 ) ) {
2306 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2309 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2310 if ( !is_null( $index ) ) {
2311 $text = $linestart . $wgContLang->getNsText( $index );
2318 # LCFIRST, UCFIRST, LC and UC
2320 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2321 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2322 $lc =& MagicWord
::get( MAG_LC
);
2323 $uc =& MagicWord
::get( MAG_UC
);
2324 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2325 $text = $linestart . $wgContLang->lcfirst( $part1 );
2327 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2328 $text = $linestart . $wgContLang->ucfirst( $part1 );
2330 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2331 $text = $linestart . $wgContLang->lc( $part1 );
2333 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2334 $text = $linestart . $wgContLang->uc( $part1 );
2339 # LOCALURL and FULLURL
2341 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2342 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2343 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2344 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2347 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2348 $func = 'getLocalURL';
2349 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2350 $func = 'escapeLocalURL';
2351 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2352 $func = 'getFullURL';
2353 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2354 $func = 'escapeFullURL';
2359 if ( $func !== false ) {
2360 $title = Title
::newFromText( $part1 );
2361 if ( !is_null( $title ) ) {
2363 $text = $linestart . $title->$func( $args[0] );
2365 $text = $linestart . $title->$func();
2373 if ( !$found && $argc == 1 ) {
2374 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2375 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2376 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2382 if ( !$found && $argc >= 2 ) {
2383 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2384 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2385 if ($argc==2) {$args[2]=$args[1];}
2386 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2391 # Template table test
2393 # Did we encounter this template already? If yes, it is in the cache
2394 # and we need to check for loops.
2395 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2398 # Infinite loop test
2399 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2402 $text = $linestart .
2404 '<!-- WARNING: template loop detected -->';
2405 wfDebug( "$fname: template loop broken at '$part1'\n" );
2407 # set $text to cached message.
2408 $text = $linestart . $this->mTemplates
[$part1];
2412 # Load from database
2413 $replaceHeadings = false;
2415 $lastPathLevel = $this->mTemplatePath
;
2418 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2419 if ($subpage !== '') {
2420 $ns = $this->mTitle
->getNamespace();
2422 $title = Title
::newFromText( $part1, $ns );
2425 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2426 if ($interwiki != '' && $title->isTrans()) {
2427 return $this->scarytransclude($title, $interwiki);
2431 if ( !is_null( $title ) && !$title->isExternal() ) {
2432 # Check for excessive inclusion
2433 $dbk = $title->getPrefixedDBkey();
2434 if ( $this->incrementIncludeCount( $dbk ) ) {
2435 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2436 # Capture special page output
2437 $text = SpecialPage
::capturePath( $title );
2438 if ( is_string( $text ) ) {
2442 $this->disableCache();
2445 $article = new Article( $title );
2446 $articleContent = $article->fetchContent(0, false);
2447 if ( $articleContent !== false ) {
2449 $text = $articleContent;
2450 $replaceHeadings = true;
2455 # If the title is valid but undisplayable, make a link to it
2456 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2457 $text = '[['.$title->getPrefixedText().']]';
2461 # Template cache array insertion
2463 $this->mTemplates
[$part1] = $text;
2464 $text = $linestart . $text;
2469 # Recursive parsing, escaping and link table handling
2470 # Only for HTML output
2471 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2472 $text = wfEscapeWikiText( $text );
2473 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2474 # Clean up argument array
2475 $assocArgs = array();
2477 foreach( $args as $arg ) {
2478 $eqpos = strpos( $arg, '=' );
2479 if ( $eqpos === false ) {
2480 $assocArgs[$index++
] = $arg;
2482 $name = trim( substr( $arg, 0, $eqpos ) );
2483 $value = trim( substr( $arg, $eqpos+
1 ) );
2484 if ( $value === false ) {
2487 if ( $name !== false ) {
2488 $assocArgs[$name] = $value;
2493 # Add a new element to the templace recursion path
2494 $this->mTemplatePath
[$part1] = 1;
2496 if( $this->mOutputType
== OT_HTML
) {
2497 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2498 preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
2500 foreach ($m[1] as $piece)
2503 # Remove <noinclude> sections and <includeonly> tags
2504 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2505 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2506 # Strip <nowiki>, <pre>, etc.
2507 $text = $this->strip( $text, $this->mStripState
);
2508 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2510 $text = $this->replaceVariables( $text, $assocArgs );
2512 # Resume the link cache and register the inclusion as a link
2513 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2514 $wgLinkCache->addLinkObj( $title );
2517 # If the template begins with a table or block-level
2518 # element, it should be treated as beginning a new line.
2519 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2520 $text = "\n" . $text;
2523 # Prune lower levels off the recursion check path
2524 $this->mTemplatePath
= $lastPathLevel;
2527 wfProfileOut( $fname );
2528 return $piece['text'];
2531 # Replace raw HTML by a placeholder
2532 # Add a blank line preceding, to prevent it from mucking up
2533 # immediately preceding headings
2534 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2536 # replace ==section headers==
2537 # XXX this needs to go away once we have a better parser.
2538 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2539 if( !is_null( $title ) )
2540 $encodedname = base64_encode($title->getPrefixedDBkey());
2542 $encodedname = base64_encode("");
2543 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2544 PREG_SPLIT_DELIM_CAPTURE
);
2547 for( $i = 0; $i < count($m); $i +
= 2 ) {
2549 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2551 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2555 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2556 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2557 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2565 # Prune lower levels off the recursion check path
2566 $this->mTemplatePath
= $lastPathLevel;
2569 wfProfileOut( $fname );
2570 return $piece['text'];
2572 wfProfileOut( $fname );
2578 * Translude an interwiki link.
2580 function scarytransclude($title, $interwiki) {
2581 global $wgEnableScaryTranscluding;
2583 if (!$wgEnableScaryTranscluding)
2584 return wfMsg('scarytranscludedisabled');
2586 $articlename = "Template:" . $title->getDBkey();
2587 $url = str_replace('$1', urlencode($articlename), $interwiki);
2588 if (strlen($url) > 255)
2589 return wfMsg('scarytranscludetoolong');
2590 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2591 $this->mIWTransData
[] = $text;
2592 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2595 function fetchScaryTemplateMaybeFromCache($url) {
2596 $dbr =& wfGetDB(DB_SLAVE
);
2597 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2598 array('tc_url' => $url));
2600 $time = $obj->tc_time
;
2601 $text = $obj->tc_contents
;
2602 if ($time && $time < (time() +
(60*60))) {
2607 $text = wfGetHTTP($url . '?action=render');
2609 return wfMsg('scarytranscludefailed', $url);
2611 $dbw =& wfGetDB(DB_MASTER
);
2612 $dbw->replace('transcache', array(), array(
2614 'tc_time' => time(),
2615 'tc_contents' => $text));
2621 * Triple brace replacement -- used for template arguments
2624 function argSubstitution( $matches ) {
2625 $arg = trim( $matches['title'] );
2626 $text = $matches['text'];
2627 $inputArgs = end( $this->mArgStack
);
2629 if ( array_key_exists( $arg, $inputArgs ) ) {
2630 $text = $inputArgs[$arg];
2631 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2632 $text = $matches['parts'][0];
2639 * Returns true if the function is allowed to include this entity
2642 function incrementIncludeCount( $dbk ) {
2643 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2644 $this->mIncludeCount
[$dbk] = 0;
2646 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2654 * This function accomplishes several tasks:
2655 * 1) Auto-number headings if that option is enabled
2656 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2657 * 3) Add a Table of contents on the top for users who have enabled the option
2658 * 4) Auto-anchor headings
2660 * It loops through all headlines, collects the necessary data, then splits up the
2661 * string and re-inserts the newly formatted headlines.
2663 * @param string $text
2664 * @param boolean $isMain
2667 function formatHeadings( $text, $isMain=true ) {
2668 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2670 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2672 $forceTocHere = false;
2673 if( !$this->mTitle
->userCanEdit() ) {
2676 $showEditLink = $this->mOptions
->getEditSection();
2679 # Inhibit editsection links if requested in the page
2680 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2681 if( $esw->matchAndRemove( $text ) ) {
2684 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2686 $mw =& MagicWord
::get( MAG_NOTOC
);
2687 if( $mw->matchAndRemove( $text ) ) {
2691 # Get all headlines for numbering them and adding funky stuff like [edit]
2692 # links - this is for later, but we need the number of headlines right now
2693 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2695 # if there are fewer than 4 headlines in the article, do not show TOC
2696 if( $numMatches < 4 ) {
2700 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2701 # override above conditions and always show TOC at that place
2703 $mw =& MagicWord
::get( MAG_TOC
);
2704 if($mw->match( $text ) ) {
2706 $forceTocHere = true;
2708 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2709 # override above conditions and always show TOC above first header
2710 $mw =& MagicWord
::get( MAG_FORCETOC
);
2711 if ($mw->matchAndRemove( $text ) ) {
2716 # Never ever show TOC if no headers
2717 if( $numMatches < 1 ) {
2721 # We need this to perform operations on the HTML
2722 $sk =& $this->mOptions
->getSkin();
2726 $sectionCount = 0; # headlineCount excluding template sections
2728 # Ugh .. the TOC should have neat indentation levels which can be
2729 # passed to the skin functions. These are determined here
2733 $sublevelCount = array();
2734 $levelCount = array();
2741 foreach( $matches[3] as $headline ) {
2743 $templatetitle = '';
2744 $templatesection = 0;
2747 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2749 $templatetitle = base64_decode($mat[1]);
2750 $templatesection = 1 +
(int)base64_decode($mat[2]);
2751 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2755 $prevlevel = $level;
2756 $prevtoclevel = $toclevel;
2758 $level = $matches[1][$headlineCount];
2760 if( $doNumberHeadings ||
$doShowToc ) {
2762 if ( $level > $prevlevel ) {
2763 # Increase TOC level
2765 $sublevelCount[$toclevel] = 0;
2766 $toc .= $sk->tocIndent();
2768 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2769 # Decrease TOC level, find level to jump to
2771 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2772 # Can only go down to level 1
2775 for ($i = $toclevel; $i > 0; $i--) {
2776 if ( $levelCount[$i] == $level ) {
2777 # Found last matching level
2781 elseif ( $levelCount[$i] < $level ) {
2782 # Found first matching level below current level
2789 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2792 # No change in level, end TOC line
2793 $toc .= $sk->tocLineEnd();
2796 $levelCount[$toclevel] = $level;
2798 # count number of headlines for each level
2799 @$sublevelCount[$toclevel]++
;
2801 for( $i = 1; $i <= $toclevel; $i++
) {
2802 if( !empty( $sublevelCount[$i] ) ) {
2806 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2812 # The canonized header is a version of the header text safe to use for links
2813 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2814 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2815 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2817 # Remove link placeholders by the link text.
2818 # <!--LINK number-->
2820 # link text with suffix
2821 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2822 "\$this->mLinkHolders['texts'][\$1]",
2823 $canonized_headline );
2824 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2825 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2826 $canonized_headline );
2829 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2830 $tocline = trim( $canonized_headline );
2831 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2832 $replacearray = array(
2836 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2837 $refers[$headlineCount] = $canonized_headline;
2839 # count how many in assoc. array so we can track dupes in anchors
2840 @$refers[$canonized_headline]++
;
2841 $refcount[$headlineCount]=$refers[$canonized_headline];
2843 # Don't number the heading if it is the only one (looks silly)
2844 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2845 # the two are different if the line contains a link
2846 $headline=$numbering . ' ' . $headline;
2849 # Create the anchor for linking from the TOC to the section
2850 $anchor = $canonized_headline;
2851 if($refcount[$headlineCount] > 1 ) {
2852 $anchor .= '_' . $refcount[$headlineCount];
2854 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2855 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2857 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2858 if ( empty( $head[$headlineCount] ) ) {
2859 $head[$headlineCount] = '';
2862 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2864 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2867 # give headline the correct <h#> tag
2868 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2876 $toc .= $sk->tocUnindent( $toclevel - 1 );
2877 $toc = $sk->tocList( $toc );
2880 # split up and insert constructed headlines
2882 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2885 foreach( $blocks as $block ) {
2886 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2887 # This is the [edit] link that appears for the top block of text when
2888 # section editing is enabled
2890 # Disabled because it broke block formatting
2891 # For example, a bullet point in the top line
2892 # $full .= $sk->editSectionLink(0);
2895 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2896 # Top anchor now in skin
2900 if( !empty( $head[$i] ) ) {
2906 $mw =& MagicWord
::get( MAG_TOC
);
2907 return $mw->replace( $toc, $full );
2914 * Return an HTML link for the "ISBN 123456" text
2917 function magicISBN( $text ) {
2918 $fname = 'Parser::magicISBN';
2919 wfProfileIn( $fname );
2921 $a = split( 'ISBN ', ' '.$text );
2922 if ( count ( $a ) < 2 ) {
2923 wfProfileOut( $fname );
2926 $text = substr( array_shift( $a ), 1);
2927 $valid = '0123456789-Xx';
2929 foreach ( $a as $x ) {
2930 $isbn = $blank = '' ;
2931 while ( ' ' == $x{0} ) {
2933 $x = substr( $x, 1 );
2935 if ( $x == '' ) { # blank isbn
2936 $text .= "ISBN $blank";
2939 while ( strstr( $valid, $x{0} ) != false ) {
2941 $x = substr( $x, 1 );
2943 $num = str_replace( '-', '', $isbn );
2944 $num = str_replace( ' ', '', $num );
2945 $num = str_replace( 'x', 'X', $num );
2948 $text .= "ISBN $blank$x";
2950 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2951 $text .= '<a href="' .
2952 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2953 "\" class=\"internal\">ISBN $isbn</a>";
2957 wfProfileOut( $fname );
2962 * Return an HTML link for the "RFC 1234" text
2965 * @param string $text Text to be processed
2966 * @param string $keyword Magic keyword to use (default RFC)
2967 * @param string $urlmsg Interface message to use (default rfcurl)
2970 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2972 $valid = '0123456789';
2975 $a = split( $keyword, ' '.$text );
2976 if ( count ( $a ) < 2 ) {
2979 $text = substr( array_shift( $a ), 1);
2981 /* Check if keyword is preceed by [[.
2982 * This test is made here cause of the array_shift above
2983 * that prevent the test to be done in the foreach.
2985 if ( substr( $text, -2 ) == '[[' ) {
2989 foreach ( $a as $x ) {
2990 /* token might be empty if we have RFC RFC 1234 */
2998 /** remove and save whitespaces in $blank */
2999 while ( $x{0} == ' ' ) {
3001 $x = substr( $x, 1 );
3004 /** remove and save the rfc number in $id */
3005 while ( strstr( $valid, $x{0} ) != false ) {
3007 $x = substr( $x, 1 );
3011 /* call back stripped spaces*/
3012 $text .= $keyword.$blank.$x;
3013 } elseif( $internal ) {
3015 $text .= $keyword.$id.$x;
3017 /* build the external link*/
3018 $url = wfMsg( $urlmsg, $id);
3019 $sk =& $this->mOptions
->getSkin();
3020 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3021 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3024 /* Check if the next RFC keyword is preceed by [[ */
3025 $internal = ( substr($x,-2) == '[[' );
3031 * Transform wiki markup when saving a page by doing \r\n -> \n
3032 * conversion, substitting signatures, {{subst:}} templates, etc.
3034 * @param string $text the text to transform
3035 * @param Title &$title the Title object for the current article
3036 * @param User &$user the User object describing the current user
3037 * @param ParserOptions $options parsing options
3038 * @param bool $clearState whether to clear the parser state first
3039 * @return string the altered wiki markup
3042 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3043 $this->mOptions
= $options;
3044 $this->mTitle
=& $title;
3045 $this->mOutputType
= OT_WIKI
;
3047 if ( $clearState ) {
3048 $this->clearState();
3051 $stripState = false;
3055 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3056 $text = $this->strip( $text, $stripState, false );
3057 $text = $this->pstPass2( $text, $user );
3058 $text = $this->unstrip( $text, $stripState );
3059 $text = $this->unstripNoWiki( $text, $stripState );
3064 * Pre-save transform helper function
3067 function pstPass2( $text, &$user ) {
3068 global $wgContLang, $wgLocaltimezone;
3070 # Variable replacement
3071 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3072 $text = $this->replaceVariables( $text );
3076 $n = $user->getName();
3077 $k = $user->getOption( 'nickname' );
3078 if ( '' == $k ) { $k = $n; }
3079 if ( isset( $wgLocaltimezone ) ) {
3080 $oldtz = getenv( 'TZ' );
3081 putenv( 'TZ='.$wgLocaltimezone );
3084 /* Note: This is the timestamp saved as hardcoded wikitext to
3085 * the database, we use $wgContLang here in order to give
3086 * everyone the same signiture and use the default one rather
3087 * than the one selected in each users preferences.
3089 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3090 ' (' . date( 'T' ) . ')';
3091 if ( isset( $wgLocaltimezone ) ) {
3092 putenv( 'TZ='.$oldtz );
3095 if( $user->getOption( 'fancysig' ) ) {
3098 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
3100 $text = preg_replace( '/~~~~~/', $d, $text );
3101 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3102 $text = preg_replace( '/~~~/', $sigText, $text );
3104 # Context links: [[|name]] and [[name (context)|]]
3106 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
3107 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
3108 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3109 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3111 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3112 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3113 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3114 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3116 $t = $this->mTitle
->getText();
3117 if ( preg_match( $conpat, $t, $m ) ) {
3120 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3121 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3122 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3124 if ( '' == $context ) {
3125 $text = preg_replace( $p2, '[[\\1]]', $text );
3127 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3130 # Trim trailing whitespace
3131 # MAG_END (__END__) tag allows for trailing
3132 # whitespace to be deliberately included
3133 $text = rtrim( $text );
3134 $mw =& MagicWord
::get( MAG_END
);
3135 $mw->matchAndRemove( $text );
3141 * Set up some variables which are usually set up in parse()
3142 * so that an external function can call some class members with confidence
3145 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3146 $this->mTitle
=& $title;
3147 $this->mOptions
= $options;
3148 $this->mOutputType
= $outputType;
3149 if ( $clearState ) {
3150 $this->clearState();
3155 * Transform a MediaWiki message by replacing magic variables.
3157 * @param string $text the text to transform
3158 * @param ParserOptions $options options
3159 * @return string the text with variables substituted
3162 function transformMsg( $text, $options ) {
3164 static $executing = false;
3166 # Guard against infinite recursion
3172 $this->mTitle
= $wgTitle;
3173 $this->mOptions
= $options;
3174 $this->mOutputType
= OT_MSG
;
3175 $this->clearState();
3176 $text = $this->replaceVariables( $text );
3183 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3184 * Callback will be called with the text within
3185 * Transform and return the text within
3188 function setHook( $tag, $callback ) {
3189 $oldVal = @$this->mTagHooks
[$tag];
3190 $this->mTagHooks
[$tag] = $callback;
3195 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3196 * Placeholders created in Skin::makeLinkObj()
3197 * Returns an array of links found, indexed by PDBK:
3201 * $options is a bit field, RLH_FOR_UPDATE to select for update
3203 function replaceLinkHolders( &$text, $options = 0 ) {
3204 global $wgUser, $wgLinkCache;
3205 global $wgOutputReplace;
3207 $fname = 'Parser::replaceLinkHolders';
3208 wfProfileIn( $fname );
3212 $sk = $this->mOptions
->getSkin();
3214 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3215 wfProfileIn( $fname.'-check' );
3216 $dbr =& wfGetDB( DB_SLAVE
);
3217 $page = $dbr->tableName( 'page' );
3218 $threshold = $wgUser->getOption('stubthreshold');
3221 asort( $this->mLinkHolders
['namespaces'] );
3225 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3227 $title = $this->mLinkHolders
['titles'][$key];
3229 # Skip invalid entries.
3230 # Result will be ugly, but prevents crash.
3231 if ( is_null( $title ) ) {
3234 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3236 # Check if it's in the link cache already
3237 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3238 $colours[$pdbk] = 1;
3239 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3240 $colours[$pdbk] = 0;
3242 # Not in the link cache, add it to the query
3243 if ( !isset( $current ) ) {
3245 $query = "SELECT page_id, page_namespace, page_title";
3246 if ( $threshold > 0 ) {
3247 $query .= ', page_len, page_is_redirect';
3249 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3250 } elseif ( $current != $val ) {
3252 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3257 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3262 if ( $options & RLH_FOR_UPDATE
) {
3263 $query .= ' FOR UPDATE';
3266 $res = $dbr->query( $query, $fname );
3268 # Fetch data and form into an associative array
3269 # non-existent = broken
3272 while ( $s = $dbr->fetchObject($res) ) {
3273 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3274 $pdbk = $title->getPrefixedDBkey();
3275 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3277 if ( $threshold > 0 ) {
3278 $size = $s->page_len
;
3279 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3280 $colours[$pdbk] = 1;
3282 $colours[$pdbk] = 2;
3285 $colours[$pdbk] = 1;
3289 wfProfileOut( $fname.'-check' );
3291 # Construct search and replace arrays
3292 wfProfileIn( $fname.'-construct' );
3293 $wgOutputReplace = array();
3294 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3295 $pdbk = $pdbks[$key];
3296 $searchkey = "<!--LINK $key-->";
3297 $title = $this->mLinkHolders
['titles'][$key];
3298 if ( empty( $colours[$pdbk] ) ) {
3299 $wgLinkCache->addBadLinkObj( $title );
3300 $colours[$pdbk] = 0;
3301 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3302 $this->mLinkHolders
['texts'][$key],
3303 $this->mLinkHolders
['queries'][$key] );
3304 } elseif ( $colours[$pdbk] == 1 ) {
3305 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3306 $this->mLinkHolders
['texts'][$key],
3307 $this->mLinkHolders
['queries'][$key] );
3308 } elseif ( $colours[$pdbk] == 2 ) {
3309 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3310 $this->mLinkHolders
['texts'][$key],
3311 $this->mLinkHolders
['queries'][$key] );
3314 wfProfileOut( $fname.'-construct' );
3317 wfProfileIn( $fname.'-replace' );
3319 $text = preg_replace_callback(
3320 '/(<!--LINK .*?-->)/',
3321 "wfOutputReplaceMatches",
3324 wfProfileOut( $fname.'-replace' );
3327 # Now process interwiki link holders
3328 # This is quite a bit simpler than internal links
3329 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3330 wfProfileIn( $fname.'-interwiki' );
3331 # Make interwiki link HTML
3332 $wgOutputReplace = array();
3333 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3334 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3335 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3338 $text = preg_replace_callback(
3339 '/<!--IWLINK (.*?)-->/',
3340 "wfOutputReplaceMatches",
3342 wfProfileOut( $fname.'-interwiki' );
3345 wfProfileOut( $fname );
3350 * Replace <!--LINK--> link placeholders with plain text of links
3351 * (not HTML-formatted).
3352 * @param string $text
3355 function replaceLinkHoldersText( $text ) {
3356 global $wgUser, $wgLinkCache;
3357 global $wgOutputReplace;
3359 $fname = 'Parser::replaceLinkHoldersText';
3360 wfProfileIn( $fname );
3362 $text = preg_replace_callback(
3363 '/<!--(LINK|IWLINK) (.*?)-->/',
3364 array( &$this, 'replaceLinkHoldersTextCallback' ),
3367 wfProfileOut( $fname );
3372 * @param array $matches
3376 function replaceLinkHoldersTextCallback( $matches ) {
3377 $type = $matches[1];
3379 if( $type == 'LINK' ) {
3380 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3381 return $this->mLinkHolders
['texts'][$key];
3383 } elseif( $type == 'IWLINK' ) {
3384 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3385 return $this->mInterwikiLinkHolders
['texts'][$key];
3392 * Renders an image gallery from a text with one line per image.
3393 * text labels may be given by using |-style alternative text. E.g.
3394 * Image:one.jpg|The number "1"
3395 * Image:tree.jpg|A tree
3396 * given as text will return the HTML of a gallery with two images,
3397 * labeled 'The number "1"' and
3402 function renderImageGallery( $text ) {
3404 global $wgUser, $wgTitle;
3405 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3406 $localParser = new Parser();
3408 global $wgLinkCache;
3409 $ig = new ImageGallery();
3410 $ig->setShowBytes( false );
3411 $ig->setShowFilename( false );
3412 $lines = explode( "\n", $text );
3414 foreach ( $lines as $line ) {
3415 # match lines like these:
3416 # Image:someimage.jpg|This is some image
3417 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3419 if ( count( $matches ) == 0 ) {
3422 $nt = Title
::newFromURL( $matches[1] );
3423 if( is_null( $nt ) ) {
3424 # Bogus title. Ignore these so we don't bomb out later.
3427 if ( isset( $matches[3] ) ) {
3428 $label = $matches[3];
3433 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3434 $html = $html->mText
;
3436 $ig->add( new Image( $nt ), $html );
3437 $wgLinkCache->addImageLinkObj( $nt );
3439 return $ig->toHTML();
3443 * Parse image options text and use it to make an image
3445 function makeImage( &$nt, $options ) {
3446 global $wgContLang, $wgUseImageResize;
3447 global $wgUser, $wgThumbLimits;
3451 # Check if the options text is of the form "options|alt text"
3453 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3454 # * left no resizing, just left align. label is used for alt= only
3455 # * right same, but right aligned
3456 # * none same, but not aligned
3457 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3458 # * center center the image
3459 # * framed Keep original image size, no magnify-button.
3461 $part = explode( '|', $options);
3463 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3464 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3465 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3466 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3467 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3468 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3469 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3470 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3473 $width = $height = $framed = $thumb = false;
3474 $manual_thumb = '' ;
3476 foreach( $part as $key => $val ) {
3477 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3479 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3480 # use manually specified thumbnail
3482 $manual_thumb = $match;
3483 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3484 # remember to set an alignment, don't render immediately
3486 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3487 # remember to set an alignment, don't render immediately
3489 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3490 # remember to set an alignment, don't render immediately
3492 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3493 # remember to set an alignment, don't render immediately
3495 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3496 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3497 # $match is the image width in pixels
3498 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3499 $width = intval( $m[1] );
3500 $height = intval( $m[2] );
3502 $width = intval($match);
3504 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3510 # Strip bad stuff out of the alt text
3511 $alt = $this->replaceLinkHoldersText( $caption );
3512 $alt = Sanitizer
::stripAllTags( $alt );
3514 # Linker does the rest
3515 $sk =& $this->mOptions
->getSkin();
3516 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3520 * Set a flag in the output object indicating that the content is dynamic and
3521 * shouldn't be cached.
3523 function disableCache() {
3524 $this->mOutput
->mCacheTime
= -1;
3528 * Callback from the Sanitizer for expanding items found in HTML attribute
3529 * values, so they can be safely tested and escaped.
3530 * @param string $text
3531 * @param array $args
3535 function attributeStripCallback( &$text, $args ) {
3536 $text = $this->replaceVariables( $text, $args );
3537 $text = $this->unstripForHTML( $text );
3541 function unstripForHTML( $text ) {
3542 $text = $this->unstrip( $text, $this->mStripState
);
3543 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3550 * @package MediaWiki
3554 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3555 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3556 var $mVersion; # Compatibility check
3557 var $mTitleText; # title text of the chosen language variant
3559 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3560 $containsOldMagic = false, $titletext = '' )
3562 $this->mText
= $text;
3563 $this->mLanguageLinks
= $languageLinks;
3564 $this->mCategoryLinks
= $categoryLinks;
3565 $this->mContainsOldMagic
= $containsOldMagic;
3566 $this->mCacheTime
= '';
3567 $this->mVersion
= MW_PARSER_VERSION
;
3568 $this->mTitleText
= $titletext;
3571 function getText() { return $this->mText
; }
3572 function getLanguageLinks() { return $this->mLanguageLinks
; }
3573 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3574 function getCacheTime() { return $this->mCacheTime
; }
3575 function getTitleText() { return $this->mTitleText
; }
3576 function containsOldMagic() { return $this->mContainsOldMagic
; }
3577 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3578 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3579 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3580 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3581 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3582 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3584 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3586 function merge( $other ) {
3587 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3588 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3589 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3593 * Return true if this cached output object predates the global or
3594 * per-article cache invalidation timestamps, or if it comes from
3595 * an incompatible older version.
3597 * @param string $touched the affected article's last touched timestamp
3601 function expired( $touched ) {
3602 global $wgCacheEpoch;
3603 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3604 $this->getCacheTime() <= $touched ||
3605 $this->getCacheTime() <= $wgCacheEpoch ||
3606 !isset( $this->mVersion
) ||
3607 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3612 * Set options of the Parser
3614 * @package MediaWiki
3618 # All variables are private
3619 var $mUseTeX; # Use texvc to expand <math> tags
3620 var $mUseDynamicDates; # Use DateFormatter to format dates
3621 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3622 var $mAllowExternalImages; # Allow external images inline
3623 var $mAllowExternalImagesFrom; # If not, any exception?
3624 var $mSkin; # Reference to the preferred skin
3625 var $mDateFormat; # Date format index
3626 var $mEditSection; # Create "edit section" links
3627 var $mNumberHeadings; # Automatically number headings
3628 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3630 function getUseTeX() { return $this->mUseTeX
; }
3631 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3632 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3633 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3634 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3635 function &getSkin() { return $this->mSkin
; }
3636 function getDateFormat() { return $this->mDateFormat
; }
3637 function getEditSection() { return $this->mEditSection
; }
3638 function getNumberHeadings() { return $this->mNumberHeadings
; }
3639 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3642 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3643 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3644 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3645 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3646 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3647 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3648 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3649 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3650 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3652 function setSkin( &$x ) { $this->mSkin
=& $x; }
3654 function ParserOptions() {
3656 $this->initialiseFromUser( $wgUser );
3660 * Get parser options
3663 function newFromUser( &$user ) {
3664 $popts = new ParserOptions
;
3665 $popts->initialiseFromUser( $user );
3669 /** Get user options */
3670 function initialiseFromUser( &$userInput ) {
3671 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3672 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3673 $fname = 'ParserOptions::initialiseFromUser';
3674 wfProfileIn( $fname );
3675 if ( !$userInput ) {
3677 $user->setLoaded( true );
3679 $user =& $userInput;
3682 $this->mUseTeX
= $wgUseTeX;
3683 $this->mUseDynamicDates
= $wgUseDynamicDates;
3684 $this->mInterwikiMagic
= $wgInterwikiMagic;
3685 $this->mAllowExternalImages
= $wgAllowExternalImages;
3686 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3687 wfProfileIn( $fname.'-skin' );
3688 $this->mSkin
=& $user->getSkin();
3689 wfProfileOut( $fname.'-skin' );
3690 $this->mDateFormat
= $user->getOption( 'date' );
3691 $this->mEditSection
= true;
3692 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3693 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3694 wfProfileOut( $fname );
3699 * Callback function used by Parser::replaceLinkHolders()
3700 * to substitute link placeholders.
3702 function &wfOutputReplaceMatches( $matches ) {
3703 global $wgOutputReplace;
3704 return $wgOutputReplace[$matches[1]];
3708 * Return the total number of articles
3710 function wfNumberOfArticles() {
3711 global $wgNumberOfArticles;
3714 return $wgNumberOfArticles;
3718 * Return the number of files
3720 function wfNumberOfFiles() {
3721 $fname = 'Parser::wfNumberOfFiles';
3723 wfProfileIn( $fname );
3724 $dbr =& wfGetDB( DB_SLAVE
);
3725 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3726 wfProfileOut( $fname );
3732 * Get various statistics from the database
3735 function wfLoadSiteStats() {
3736 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3737 $fname = 'wfLoadSiteStats';
3739 if ( -1 != $wgNumberOfArticles ) return;
3740 $dbr =& wfGetDB( DB_SLAVE
);
3741 $s = $dbr->selectRow( 'site_stats',
3742 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3743 array( 'ss_row_id' => 1 ), $fname
3746 if ( $s === false ) {
3749 $wgTotalViews = $s->ss_total_views
;
3750 $wgTotalEdits = $s->ss_total_edits
;
3751 $wgNumberOfArticles = $s->ss_good_articles
;
3757 * Basicly replacing " > and < with HTML entities ( ", >, <)
3759 * @param string $in Text that might contain HTML tags
3760 * @return string Escaped string
3762 function wfEscapeHTMLTagsOnly( $in ) {
3764 array( '"', '>', '<' ),
3765 array( '"', '>', '<' ),