3 * File for Parser and related classes
9 require_once( 'Sanitizer.php' );
12 * Update this version number when the ParserOutput format
13 * changes in an incompatible way, so the parser cache
14 * can automatically discard old data.
16 define( 'MW_PARSER_VERSION', '1.5.0' );
19 * Variable substitution O(N^2) attack
21 * Without countermeasures, it would be possible to attack the parser by saving
22 * a page filled with a large number of inclusions of large pages. The size of
23 * the generated page would be proportional to the square of the input size.
24 * Hence, we limit the number of inclusions of any given page, thus bringing any
25 * attack back to O(N).
28 define( 'MAX_INCLUDE_REPEAT', 100 );
29 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
31 define( 'RLH_FOR_UPDATE', 1 );
33 # Allowed values for $mOutputType
34 define( 'OT_HTML', 1 );
35 define( 'OT_WIKI', 2 );
36 define( 'OT_MSG' , 3 );
38 # string parameter for extractTags which will cause it
39 # to strip HTML comments in addition to regular
40 # <XML>-style tags. This should not be anything we
41 # may want to use in wikisyntax
42 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
44 # prefix for escaping, used in two functions at least
45 define( 'UNIQ_PREFIX', 'NaodW29');
47 # Constants needed for external link processing
48 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
49 define( 'HTTP_PROTOCOLS', 'http|https' );
50 # Everything except bracket, space, or control characters
51 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
53 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
54 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
55 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
56 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
57 define( 'EXT_IMAGE_REGEX',
58 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
59 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
60 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
66 * Processes wiki markup
69 * There are three main entry points into the Parser class:
71 * produces HTML output
73 * produces altered wiki markup.
75 * performs brace substitution on MediaWiki messages
78 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
80 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
83 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
84 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
87 * * only within ParserOptions
100 # Cleared with clearState():
101 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
102 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
105 var $mOptions, $mTitle, $mOutputType,
106 $mTemplates, // cache of already loaded templates, avoids
107 // multiple SQL queries for the same string
108 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
109 // in this path. Used for loop detection.
119 $this->mTemplates
= array();
120 $this->mTemplatePath
= array();
121 $this->mTagHooks
= array();
130 function clearState() {
131 $this->mOutput
= new ParserOutput
;
132 $this->mAutonumber
= 0;
133 $this->mLastSection
= '';
134 $this->mDTopen
= false;
135 $this->mVariables
= false;
136 $this->mIncludeCount
= array();
137 $this->mStripState
= array();
138 $this->mArgStack
= array();
139 $this->mInPre
= false;
143 * First pass--just handle <nowiki> sections, pass the rest off
144 * to internalParse() which does all the real work.
147 * @param string $text Text we want to parse
148 * @param Title &$title A title object
149 * @param array $options
150 * @param boolean $linestart
151 * @param boolean $clearState
152 * @return ParserOutput a ParserOutput
154 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
155 global $wgUseTidy, $wgContLang;
156 $fname = 'Parser::parse';
157 wfProfileIn( $fname );
163 $this->mOptions
= $options;
164 $this->mTitle
=& $title;
165 $this->mOutputType
= OT_HTML
;
168 global $fnord; $fnord = 1;
169 //$text = $this->strip( $text, $this->mStripState );
170 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
171 $x =& $this->mStripState
;
172 $text = $this->strip( $text, $x );
174 $text = $this->internalParse( $text, $linestart );
176 $dashReplace = array(
177 '/ - /' => " – ", # N dash
178 '/(?<=[0-9])-(?=[0-9])/' => "–", # N dash between numbers
179 '/ -- /' => " — " # M dash
181 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
184 $text = $this->unstrip( $text, $this->mStripState
);
185 # Clean up special characters, only run once, next-to-last before doBlockLevels
189 # french spaces, last one Guillemet-left
190 # only if there is something before the space
191 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
192 # french spaces, Guillemet-right
193 '/(\\302\\253) /' => '\\1 ',
194 '/<hr *>/i' => '<hr />',
195 '/<br *>/i' => '<br />',
196 '/<center *>/i' => '<div class="center">',
197 '/<\\/center *>/i' => '</div>',
199 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
200 $text = Sanitizer
::normalizeCharReferences( $text );
203 # french spaces, last one Guillemet-left
204 '/ (\\?|:|;|!|\\302\\273)/' => ' \\1',
205 # french spaces, Guillemet-right
206 '/(\\302\\253) /' => '\\1 ',
207 '/<center *>/i' => '<div class="center">',
208 '/<\\/center *>/i' => '</div>'
210 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
213 $text = $this->doBlockLevels( $text, $linestart );
215 $this->replaceLinkHolders( $text );
216 $text = $wgContLang->convert($text);
218 $text = $this->unstripNoWiki( $text, $this->mStripState
);
220 $text = Parser
::tidy($text);
223 $this->mOutput
->setText( $text );
224 wfProfileOut( $fname );
225 return $this->mOutput
;
229 * Get a random string
234 function getRandomString() {
235 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
239 * Replaces all occurrences of <$tag>content</$tag> in the text
240 * with a random marker and returns the new text. the output parameter
241 * $content will be an associative array filled with data on the form
242 * $unique_marker => content.
244 * If $content is already set, the additional entries will be appended
245 * If $tag is set to STRIP_COMMENTS, the function will extract
246 * <!-- HTML comments -->
251 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
252 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
259 while ( '' != $text ) {
260 if($tag==STRIP_COMMENTS
) {
261 $p = preg_split( '/<!--/', $text, 2 );
263 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
266 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
269 if($tag==STRIP_COMMENTS
) {
270 $q = preg_split( '/-->/i', $p[1], 2 );
272 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
274 $marker = $rnd . sprintf('%08X', $n++
);
275 $content[$marker] = $q[0];
276 $stripped .= $marker;
284 * Strips and renders nowiki, pre, math, hiero
285 * If $render is set, performs necessary rendering operations on plugins
286 * Returns the text, and fills an array with data needed in unstrip()
287 * If the $state is already a valid strip state, it adds to the state
289 * @param bool $stripcomments when set, HTML comments <!-- like this -->
290 * will be stripped in addition to other tags. This is important
291 * for section editing, where these comments cause confusion when
292 * counting the sections in the wikisource
296 function strip( $text, &$state, $stripcomments = false ) {
297 $render = ($this->mOutputType
== OT_HTML
);
298 $html_content = array();
299 $nowiki_content = array();
300 $math_content = array();
301 $pre_content = array();
302 $comment_content = array();
303 $ext_content = array();
304 $gallery_content = array();
306 # Replace any instances of the placeholders
307 $uniq_prefix = UNIQ_PREFIX
;
308 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
311 global $wgRawHtml, $wgWhitelistEdit;
312 if( $wgRawHtml && $wgWhitelistEdit ) {
313 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
314 foreach( $html_content as $marker => $content ) {
316 # Raw and unchecked for validity.
317 $html_content[$marker] = $content;
319 $html_content[$marker] = '<html>'.$content.'</html>';
325 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
326 foreach( $nowiki_content as $marker => $content ) {
328 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
330 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
335 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
336 foreach( $math_content as $marker => $content ){
338 if( $this->mOptions
->getUseTeX() ) {
339 $math_content[$marker] = renderMath( $content );
341 $math_content[$marker] = '<math>'.$content.'<math>';
344 $math_content[$marker] = '<math>'.$content.'</math>';
349 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
350 foreach( $pre_content as $marker => $content ){
352 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
354 $pre_content[$marker] = '<pre>'.$content.'</pre>';
359 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
360 foreach( $gallery_content as $marker => $content ) {
361 require_once( 'ImageGallery.php' );
363 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
365 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
371 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
372 foreach( $comment_content as $marker => $content ){
373 $comment_content[$marker] = '<!--'.$content.'-->';
378 foreach ( $this->mTagHooks
as $tag => $callback ) {
379 $ext_contents[$tag] = array();
380 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
381 foreach( $ext_content[$tag] as $marker => $content ) {
383 $ext_content[$tag][$marker] = $callback( $content );
385 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
390 # Merge state with the pre-existing state, if there is one
392 $state['html'] = $state['html'] +
$html_content;
393 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
394 $state['math'] = $state['math'] +
$math_content;
395 $state['pre'] = $state['pre'] +
$pre_content;
396 $state['comment'] = $state['comment'] +
$comment_content;
397 $state['gallery'] = $state['gallery'] +
$gallery_content;
399 foreach( $ext_content as $tag => $array ) {
400 if ( array_key_exists( $tag, $state ) ) {
401 $state[$tag] = $state[$tag] +
$array;
406 'html' => $html_content,
407 'nowiki' => $nowiki_content,
408 'math' => $math_content,
409 'pre' => $pre_content,
410 'comment' => $comment_content,
411 'gallery' => $gallery_content,
418 * restores pre, math, and hiero removed by strip()
420 * always call unstripNoWiki() after this one
423 function unstrip( $text, &$state ) {
424 # Must expand in reverse order, otherwise nested tags will be corrupted
425 $contentDict = end( $state );
426 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
427 if( key($state) != 'nowiki' && key($state) != 'html') {
428 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
429 $text = str_replace( key( $contentDict ), $content, $text );
438 * always call this after unstrip() to preserve the order
442 function unstripNoWiki( $text, &$state ) {
443 # Must expand in reverse order, otherwise nested tags will be corrupted
444 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
445 $text = str_replace( key( $state['nowiki'] ), $content, $text );
450 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
451 $text = str_replace( key( $state['html'] ), $content, $text );
459 * Add an item to the strip state
460 * Returns the unique tag which must be inserted into the stripped text
461 * The tag will be replaced with the original text in unstrip()
465 function insertStripItem( $text, &$state ) {
466 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
475 $state['item'][$rnd] = $text;
480 * interface with html tidy, used if $wgUseTidy = true
485 function tidy ( $text ) {
486 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
487 global $wgInputEncoding, $wgOutputEncoding;
488 $fname = 'Parser::tidy';
489 wfProfileIn( $fname );
493 switch(strtoupper($wgOutputEncoding)) {
495 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
498 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
504 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
505 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
506 '<head><title>test</title></head><body>'.$text.'</body></html>';
507 $descriptorspec = array(
508 0 => array('pipe', 'r'),
509 1 => array('pipe', 'w'),
510 2 => array('file', '/dev/null', 'a')
512 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
513 if (is_resource($process)) {
514 fwrite($pipes[0], $wrappedtext);
516 while (!feof($pipes[1])) {
517 $cleansource .= fgets($pipes[1], 1024);
520 $return_value = proc_close($process);
523 wfProfileOut( $fname );
525 if( $cleansource == '' && $text != '') {
526 wfDebug( "Tidy error detected!\n" );
527 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
534 * parse the wiki syntax used to render tables
538 function doTableStuff ( $t ) {
539 $fname = 'Parser::doTableStuff';
540 wfProfileIn( $fname );
542 $t = explode ( "\n" , $t ) ;
543 $td = array () ; # Is currently a td tag open?
544 $ltd = array () ; # Was it TD or TH?
545 $tr = array () ; # Is currently a tr tag open?
546 $ltr = array () ; # tr attributes
547 $indent_level = 0; # indent level of the table
548 foreach ( $t AS $k => $x )
551 $fc = substr ( $x , 0 , 1 ) ;
552 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
553 $indent_level = strlen( $matches[1] );
555 str_repeat( '<dl><dd>', $indent_level ) .
556 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
557 array_push ( $td , false ) ;
558 array_push ( $ltd , '' ) ;
559 array_push ( $tr , false ) ;
560 array_push ( $ltr , '' ) ;
562 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
563 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
564 $z = "</table>" . substr ( $x , 2) . "\n";
565 $l = array_pop ( $ltd ) ;
566 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
567 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
569 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
571 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
572 $x = substr ( $x , 1 ) ;
573 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
575 $l = array_pop ( $ltd ) ;
576 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
577 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
580 array_push ( $tr , false ) ;
581 array_push ( $td , false ) ;
582 array_push ( $ltd , '' ) ;
583 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
585 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
587 if ( '|+' == substr ( $x , 0 , 2 ) ) {
589 $x = substr ( $x , 1 ) ;
591 $after = substr ( $x , 1 ) ;
592 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
593 $after = explode ( '||' , $after ) ;
596 # Loop through each table cell
597 foreach ( $after AS $theline )
602 $tra = array_pop ( $ltr ) ;
603 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
604 array_push ( $tr , true ) ;
605 array_push ( $ltr , '' ) ;
608 $l = array_pop ( $ltd ) ;
609 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
610 if ( $fc == '|' ) $l = 'td' ;
611 else if ( $fc == '!' ) $l = 'th' ;
612 else if ( $fc == '+' ) $l = 'caption' ;
614 array_push ( $ltd , $l ) ;
617 $y = explode ( '|' , $theline , 2 ) ;
618 # Note that a '|' inside an invalid link should not
619 # be mistaken as delimiting cell parameters
620 if ( strpos( $y[0], '[[' ) !== false ) {
621 $y = array ($theline);
623 if ( count ( $y ) == 1 )
624 $y = "{$z}<{$l}>{$y[0]}" ;
625 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
627 array_push ( $td , true ) ;
632 # Closing open td, tr && table
633 while ( count ( $td ) > 0 )
635 if ( array_pop ( $td ) ) $t[] = '</td>' ;
636 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
640 $t = implode ( "\n" , $t ) ;
641 # $t = Sanitizer::removeHTMLtags( $t );
642 wfProfileOut( $fname );
647 * Helper function for parse() that transforms wiki markup into
648 * HTML. Only called for $mOutputType == OT_HTML.
652 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
655 $fname = 'Parser::internalParse';
656 wfProfileIn( $fname );
658 $text = Sanitizer
::removeHTMLtags( $text );
659 $text = $this->replaceVariables( $text, $args );
661 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
663 $text = $this->doHeadings( $text );
664 if($this->mOptions
->getUseDynamicDates()) {
665 global $wgDateFormatter;
666 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
668 $text = $this->doAllQuotes( $text );
669 $text = $this->replaceInternalLinks( $text );
670 $text = $this->replaceExternalLinks( $text );
672 # replaceInternalLinks may sometimes leave behind
673 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
674 $text = str_replace("http-noparse://","http://",$text);
676 $text = $this->doMagicLinks( $text );
677 $text = $this->doTableStuff( $text );
678 $text = $this->formatHeadings( $text, $isMain );
680 wfProfileOut( $fname );
685 * Replace special strings like "ISBN xxx" and "RFC xxx" with
686 * magic external links.
690 function &doMagicLinks( &$text ) {
691 $text = $this->magicISBN( $text );
692 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
693 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
698 * Parse ^^ tokens and return html
702 function doExponent( $text ) {
703 $fname = 'Parser::doExponent';
704 wfProfileIn( $fname );
705 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
706 wfProfileOut( $fname );
711 * Parse headers and return html
715 function doHeadings( $text ) {
716 $fname = 'Parser::doHeadings';
717 wfProfileIn( $fname );
718 for ( $i = 6; $i >= 1; --$i ) {
719 $h = substr( '======', 0, $i );
720 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
721 "<h{$i}>\\1</h{$i}>\\2", $text );
723 wfProfileOut( $fname );
728 * Replace single quotes with HTML markup
730 * @return string the altered text
732 function doAllQuotes( $text ) {
733 $fname = 'Parser::doAllQuotes';
734 wfProfileIn( $fname );
736 $lines = explode( "\n", $text );
737 foreach ( $lines as $line ) {
738 $outtext .= $this->doQuotes ( $line ) . "\n";
740 $outtext = substr($outtext, 0,-1);
741 wfProfileOut( $fname );
746 * Helper function for doAllQuotes()
749 function doQuotes( $text ) {
750 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
751 if ( count( $arr ) == 1 )
755 # First, do some preliminary work. This may shift some apostrophes from
756 # being mark-up to being text. It also counts the number of occurrences
757 # of bold and italics mark-ups.
761 foreach ( $arr as $r )
763 if ( ( $i %
2 ) == 1 )
765 # If there are ever four apostrophes, assume the first is supposed to
766 # be text, and the remaining three constitute mark-up for bold text.
767 if ( strlen( $arr[$i] ) == 4 )
772 # If there are more than 5 apostrophes in a row, assume they're all
773 # text except for the last 5.
774 else if ( strlen( $arr[$i] ) > 5 )
776 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
779 # Count the number of occurrences of bold and italics mark-ups.
780 # We are not counting sequences of five apostrophes.
781 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
782 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
783 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
788 # If there is an odd number of both bold and italics, it is likely
789 # that one of the bold ones was meant to be an apostrophe followed
790 # by italics. Which one we cannot know for certain, but it is more
791 # likely to be one that has a single-letter word before it.
792 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
795 $firstsingleletterword = -1;
796 $firstmultiletterword = -1;
798 foreach ( $arr as $r )
800 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
802 $x1 = substr ($arr[$i-1], -1);
803 $x2 = substr ($arr[$i-1], -2, 1);
805 if ($firstspace == -1) $firstspace = $i;
806 } else if ($x2 == ' ') {
807 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
809 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
815 # If there is a single-letter word, use it!
816 if ($firstsingleletterword > -1)
818 $arr [ $firstsingleletterword ] = "''";
819 $arr [ $firstsingleletterword-1 ] .= "'";
821 # If not, but there's a multi-letter word, use that one.
822 else if ($firstmultiletterword > -1)
824 $arr [ $firstmultiletterword ] = "''";
825 $arr [ $firstmultiletterword-1 ] .= "'";
827 # ... otherwise use the first one that has neither.
828 # (notice that it is possible for all three to be -1 if, for example,
829 # there is only one pentuple-apostrophe in the line)
830 else if ($firstspace > -1)
832 $arr [ $firstspace ] = "''";
833 $arr [ $firstspace-1 ] .= "'";
837 # Now let's actually convert our apostrophic mush to HTML!
846 if ($state == 'both')
853 if (strlen ($r) == 2)
856 { $output .= '</i>'; $state = ''; }
857 else if ($state == 'bi')
858 { $output .= '</i>'; $state = 'b'; }
859 else if ($state == 'ib')
860 { $output .= '</b></i><b>'; $state = 'b'; }
861 else if ($state == 'both')
862 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
863 else # $state can be 'b' or ''
864 { $output .= '<i>'; $state .= 'i'; }
866 else if (strlen ($r) == 3)
869 { $output .= '</b>'; $state = ''; }
870 else if ($state == 'bi')
871 { $output .= '</i></b><i>'; $state = 'i'; }
872 else if ($state == 'ib')
873 { $output .= '</b>'; $state = 'i'; }
874 else if ($state == 'both')
875 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
876 else # $state can be 'i' or ''
877 { $output .= '<b>'; $state .= 'b'; }
879 else if (strlen ($r) == 5)
882 { $output .= '</b><i>'; $state = 'i'; }
883 else if ($state == 'i')
884 { $output .= '</i><b>'; $state = 'b'; }
885 else if ($state == 'bi')
886 { $output .= '</i></b>'; $state = ''; }
887 else if ($state == 'ib')
888 { $output .= '</b></i>'; $state = ''; }
889 else if ($state == 'both')
890 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
891 else # ($state == '')
892 { $buffer = ''; $state = 'both'; }
897 # Now close all remaining tags. Notice that the order is important.
898 if ($state == 'b' ||
$state == 'ib')
900 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
904 if ($state == 'both')
905 $output .= '<b><i>'.$buffer.'</i></b>';
911 * Replace external links
913 * Note: this is all very hackish and the order of execution matters a lot.
914 * Make sure to run maintenance/parserTests.php if you change this code.
918 function replaceExternalLinks( $text ) {
919 $fname = 'Parser::replaceExternalLinks';
920 wfProfileIn( $fname );
922 $sk =& $this->mOptions
->getSkin();
924 $linktrail = $wgContLang->linkTrail();
926 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
928 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
931 while ( $i<count( $bits ) ) {
933 $protocol = $bits[$i++
];
935 $trail = $bits[$i++
];
937 # The characters '<' and '>' (which were escaped by
938 # removeHTMLtags()) should not be included in
939 # URLs, per RFC 2396.
940 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
941 $text = substr($url, $m2[0][1]) . ' ' . $text;
942 $url = substr($url, 0, $m2[0][1]);
945 # If the link text is an image URL, replace it with an <img> tag
946 # This happened by accident in the original parser, but some people used it extensively
947 $img = $this->maybeMakeImageLink( $text );
948 if ( $img !== false ) {
954 # Set linktype for CSS - if URL==text, link is essentially free
955 $linktype = ($text == $url) ?
'free' : 'text';
957 # No link text, e.g. [http://domain.tld/some.link]
959 # Autonumber if allowed
960 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
961 $text = '[' . ++
$this->mAutonumber
. ']';
962 $linktype = 'autonumber';
964 # Otherwise just use the URL
965 $text = htmlspecialchars( $url );
969 # Have link text, e.g. [http://domain.tld/some.link text]s
971 if ( preg_match( $linktrail, $trail, $m2 ) ) {
977 # Replace & from obsolete syntax with &.
978 # All HTML entities will be escaped by makeExternalLink()
979 # or maybeMakeImageLink()
980 $url = str_replace( '&', '&', $url );
982 # Process the trail (i.e. everything after this link up until start of the next link),
983 # replacing any non-bracketed links
984 $trail = $this->replaceFreeExternalLinks( $trail );
986 # Use the encoded URL
987 # This means that users can paste URLs directly into the text
988 # Funny characters like ö aren't valid in URLs anyway
989 # This was changed in August 2004
990 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
993 wfProfileOut( $fname );
998 * Replace anything that looks like a URL with a link
1001 function replaceFreeExternalLinks( $text ) {
1002 $fname = 'Parser::replaceFreeExternalLinks';
1003 wfProfileIn( $fname );
1005 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1006 $s = array_shift( $bits );
1009 $sk =& $this->mOptions
->getSkin();
1011 while ( $i < count( $bits ) ){
1012 $protocol = $bits[$i++
];
1013 $remainder = $bits[$i++
];
1015 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1016 # Found some characters after the protocol that look promising
1017 $url = $protocol . $m[1];
1020 # The characters '<' and '>' (which were escaped by
1021 # removeHTMLtags()) should not be included in
1022 # URLs, per RFC 2396.
1023 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1024 $trail = substr($url, $m2[0][1]) . $trail;
1025 $url = substr($url, 0, $m2[0][1]);
1028 # Move trailing punctuation to $trail
1030 # If there is no left bracket, then consider right brackets fair game too
1031 if ( strpos( $url, '(' ) === false ) {
1035 $numSepChars = strspn( strrev( $url ), $sep );
1036 if ( $numSepChars ) {
1037 $trail = substr( $url, -$numSepChars ) . $trail;
1038 $url = substr( $url, 0, -$numSepChars );
1041 # Replace & from obsolete syntax with &.
1042 # All HTML entities will be escaped by makeExternalLink()
1043 # or maybeMakeImageLink()
1044 $url = str_replace( '&', '&', $url );
1046 # Is this an external image?
1047 $text = $this->maybeMakeImageLink( $url );
1048 if ( $text === false ) {
1049 # Not an image, make a link
1050 $text = $sk->makeExternalLink( $url, $url, true, 'free' );
1052 $s .= $text . $trail;
1054 $s .= $protocol . $remainder;
1062 * make an image if it's allowed
1065 function maybeMakeImageLink( $url ) {
1066 $sk =& $this->mOptions
->getSkin();
1068 if ( $this->mOptions
->getAllowExternalImages() ) {
1069 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1071 $text = $sk->makeImage( htmlspecialchars( $url ) );
1078 * Process [[ ]] wikilinks
1082 function replaceInternalLinks( $s ) {
1083 global $wgLang, $wgContLang, $wgLinkCache;
1084 global $wgDisableLangConversion;
1085 static $fname = 'Parser::replaceInternalLinks' ;
1087 wfProfileIn( $fname );
1089 wfProfileIn( $fname.'-setup' );
1091 # the % is needed to support urlencoded titles as well
1092 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1094 $sk =& $this->mOptions
->getSkin();
1095 global $wgUseOldExistenceCheck;
1096 # "Post-parse link colour check" works only on wiki text since it's now
1097 # in Parser. Enable it, then disable it when we're done.
1098 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1100 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1102 #split the entire text string on occurences of [[
1103 $a = explode( '[[', ' ' . $s );
1104 #get the first element (all text up to first [[), and remove the space we added
1105 $s = array_shift( $a );
1106 $s = substr( $s, 1 );
1108 # Match a link having the form [[namespace:link|alternate]]trail
1110 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1111 # Match cases where there is no "]]", which might still be images
1112 static $e1_img = FALSE;
1113 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1114 # Match the end of a line for a word that's not followed by whitespace,
1115 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1116 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1118 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1120 if( is_null( $this->mTitle
) ) {
1121 wfDebugDieBacktrace( 'nooo' );
1123 $nottalk = !$this->mTitle
->isTalkPage();
1125 if ( $useLinkPrefixExtension ) {
1126 if ( preg_match( $e2, $s, $m ) ) {
1127 $first_prefix = $m[2];
1130 $first_prefix = false;
1136 $selflink = $this->mTitle
->getPrefixedText();
1137 wfProfileOut( $fname.'-setup' );
1139 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1140 $useSubpages = $this->areSubpagesAllowed();
1142 # Loop for each link
1143 for ($k = 0; isset( $a[$k] ); $k++
) {
1145 if ( $useLinkPrefixExtension ) {
1146 wfProfileIn( $fname.'-prefixhandling' );
1147 if ( preg_match( $e2, $s, $m ) ) {
1155 $prefix = $first_prefix;
1156 $first_prefix = false;
1158 wfProfileOut( $fname.'-prefixhandling' );
1161 $might_be_img = false;
1163 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1165 # fix up urlencoded title texts
1166 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1168 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1169 $might_be_img = true;
1171 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1173 } else { # Invalid form; output directly
1174 $s .= $prefix . '[[' . $line ;
1178 # Don't allow internal links to pages containing
1179 # PROTO: where PROTO is a valid URL protocol; these
1180 # should be external links.
1181 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1182 $s .= $prefix . '[[' . $line ;
1186 # Make subpage if necessary
1187 if( $useSubpages ) {
1188 $link = $this->maybeDoSubpageLink( $m[1], $text );
1193 $noforce = (substr($m[1], 0, 1) != ':');
1195 # Strip off leading ':'
1196 $link = substr($link, 1);
1199 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1201 $s .= $prefix . '[[' . $line;
1205 #check other language variants of the link
1206 #if the article does not exist
1207 if( $checkVariantLink
1208 && $nt->getArticleID() == 0 ) {
1209 $wgContLang->findVariantLink($link, $nt);
1212 $ns = $nt->getNamespace();
1213 $iw = $nt->getInterWiki();
1215 if ($might_be_img) { # if this is actually an invalid link
1216 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1218 while (isset ($a[$k+
1]) ) {
1219 #look at the next 'line' to see if we can close it there
1220 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1221 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1222 # the first ]] closes the inner link, the second the image
1224 $text .= '[[' . $m[1];
1227 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1228 #if there's exactly one ]] that's fine, we'll keep looking
1229 $text .= '[[' . $m[0];
1231 #if $next_line is invalid too, we need look no further
1232 $text .= '[[' . $next_line;
1237 # we couldn't find the end of this imageLink, so output it raw
1238 #but don't ignore what might be perfectly normal links in the text we've examined
1239 $text = $this->replaceInternalLinks($text);
1240 $s .= $prefix . '[[' . $link . '|' . $text;
1241 # note: no $trail, because without an end, there *is* no trail
1244 } else { #it's not an image, so output it raw
1245 $s .= $prefix . '[[' . $link . '|' . $text;
1246 # note: no $trail, because without an end, there *is* no trail
1251 $wasblank = ( '' == $text );
1252 if( $wasblank ) $text = $link;
1255 # Link not escaped by : , create the various objects
1259 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1260 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1261 $tmp = $prefix . $trail ;
1262 $s .= (trim($tmp) == '')?
'': $tmp;
1266 if ( $ns == NS_IMAGE
) {
1267 wfProfileIn( "$fname-image" );
1269 # recursively parse links inside the image caption
1270 # actually, this will parse them in any other parameters, too,
1271 # but it might be hard to fix that, and it doesn't matter ATM
1272 $text = $this->replaceExternalLinks($text);
1273 $text = $this->replaceInternalLinks($text);
1275 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1276 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1277 $wgLinkCache->addImageLinkObj( $nt );
1279 wfProfileOut( "$fname-image" );
1283 if ( $ns == NS_CATEGORY
) {
1284 wfProfileIn( "$fname-category" );
1285 $t = $nt->getText();
1287 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1288 $pPLC=$sk->postParseLinkColour();
1289 $sk->postParseLinkColour( false );
1290 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1291 $sk->postParseLinkColour( $pPLC );
1292 $wgLinkCache->resume();
1295 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1296 $sortkey = $this->mTitle
->getText();
1298 $sortkey = $this->mTitle
->getPrefixedText();
1303 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1304 $this->mOutput
->addCategoryLink( $t );
1305 $s .= $prefix . $trail ;
1307 wfProfileOut( "$fname-category" );
1312 if( ( $nt->getPrefixedText() === $selflink ) &&
1313 ( $nt->getFragment() === '' ) ) {
1314 # Self-links are handled specially; generally de-link and change to bold.
1315 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1319 # Special and Media are pseudo-namespaces; no pages actually exist in them
1320 if( $ns == NS_MEDIA
) {
1321 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1322 $wgLinkCache->addImageLinkObj( $nt );
1324 } elseif( $ns == NS_SPECIAL
) {
1325 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1328 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1330 $sk->postParseLinkColour( $saveParseColour );
1331 wfProfileOut( $fname );
1336 * Return true if subpage links should be expanded on this page.
1339 function areSubpagesAllowed() {
1340 # Some namespaces don't allow subpages
1341 global $wgNamespacesWithSubpages;
1342 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1346 * Handle link to subpage if necessary
1347 * @param string $target the source of the link
1348 * @param string &$text the link text, modified as necessary
1349 * @return string the full name of the link
1352 function maybeDoSubpageLink($target, &$text) {
1355 # :Foobar -- override special treatment of prefix (images, language links)
1356 # /Foobar -- convert to CurrentPage/Foobar
1357 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1358 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1359 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1361 $fname = 'Parser::maybeDoSubpageLink';
1362 wfProfileIn( $fname );
1363 $ret = $target; # default return value is no change
1365 # Some namespaces don't allow subpages,
1366 # so only perform processing if subpages are allowed
1367 if( $this->areSubpagesAllowed() ) {
1368 # Look at the first character
1369 if( $target != '' && $target{0} == '/' ) {
1370 # / at end means we don't want the slash to be shown
1371 if( substr( $target, -1, 1 ) == '/' ) {
1372 $target = substr( $target, 1, -1 );
1375 $noslash = substr( $target, 1 );
1378 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1379 if( '' === $text ) {
1381 } # this might be changed for ugliness reasons
1383 # check for .. subpage backlinks
1385 $nodotdot = $target;
1386 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1388 $nodotdot = substr( $nodotdot, 3 );
1390 if($dotdotcount > 0) {
1391 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1392 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1393 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1394 # / at the end means don't show full path
1395 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1396 $nodotdot = substr( $nodotdot, 0, -1 );
1397 if( '' === $text ) {
1401 $nodotdot = trim( $nodotdot );
1402 if( $nodotdot != '' ) {
1403 $ret .= '/' . $nodotdot;
1410 wfProfileOut( $fname );
1415 * Used by doBlockLevels()
1418 /* private */ function closeParagraph() {
1420 if ( '' != $this->mLastSection
) {
1421 $result = '</' . $this->mLastSection
. ">\n";
1423 $this->mInPre
= false;
1424 $this->mLastSection
= '';
1427 # getCommon() returns the length of the longest common substring
1428 # of both arguments, starting at the beginning of both.
1430 /* private */ function getCommon( $st1, $st2 ) {
1431 $fl = strlen( $st1 );
1432 $shorter = strlen( $st2 );
1433 if ( $fl < $shorter ) { $shorter = $fl; }
1435 for ( $i = 0; $i < $shorter; ++
$i ) {
1436 if ( $st1{$i} != $st2{$i} ) { break; }
1440 # These next three functions open, continue, and close the list
1441 # element appropriate to the prefix character passed into them.
1443 /* private */ function openList( $char ) {
1444 $result = $this->closeParagraph();
1446 if ( '*' == $char ) { $result .= '<ul><li>'; }
1447 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1448 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1449 else if ( ';' == $char ) {
1450 $result .= '<dl><dt>';
1451 $this->mDTopen
= true;
1453 else { $result = '<!-- ERR 1 -->'; }
1458 /* private */ function nextItem( $char ) {
1459 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1460 else if ( ':' == $char ||
';' == $char ) {
1462 if ( $this->mDTopen
) { $close = '</dt>'; }
1463 if ( ';' == $char ) {
1464 $this->mDTopen
= true;
1465 return $close . '<dt>';
1467 $this->mDTopen
= false;
1468 return $close . '<dd>';
1471 return '<!-- ERR 2 -->';
1474 /* private */ function closeList( $char ) {
1475 if ( '*' == $char ) { $text = '</li></ul>'; }
1476 else if ( '#' == $char ) { $text = '</li></ol>'; }
1477 else if ( ':' == $char ) {
1478 if ( $this->mDTopen
) {
1479 $this->mDTopen
= false;
1480 $text = '</dt></dl>';
1482 $text = '</dd></dl>';
1485 else { return '<!-- ERR 3 -->'; }
1491 * Make lists from lines starting with ':', '*', '#', etc.
1494 * @return string the lists rendered as HTML
1496 function doBlockLevels( $text, $linestart ) {
1497 $fname = 'Parser::doBlockLevels';
1498 wfProfileIn( $fname );
1500 # Parsing through the text line by line. The main thing
1501 # happening here is handling of block-level elements p, pre,
1502 # and making lists from lines starting with * # : etc.
1504 $textLines = explode( "\n", $text );
1506 $lastPrefix = $output = $lastLine = '';
1507 $this->mDTopen
= $inBlockElem = false;
1509 $paragraphStack = false;
1511 if ( !$linestart ) {
1512 $output .= array_shift( $textLines );
1514 foreach ( $textLines as $oLine ) {
1515 $lastPrefixLength = strlen( $lastPrefix );
1516 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1517 $preOpenMatch = preg_match('/<pre/i', $oLine );
1518 if ( !$this->mInPre
) {
1519 # Multiple prefixes may abut each other for nested lists.
1520 $prefixLength = strspn( $oLine, '*#:;' );
1521 $pref = substr( $oLine, 0, $prefixLength );
1524 $pref2 = str_replace( ';', ':', $pref );
1525 $t = substr( $oLine, $prefixLength );
1526 $this->mInPre
= !empty($preOpenMatch);
1528 # Don't interpret any other prefixes in preformatted text
1530 $pref = $pref2 = '';
1535 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1536 # Same as the last item, so no need to deal with nesting or opening stuff
1537 $output .= $this->nextItem( substr( $pref, -1 ) );
1538 $paragraphStack = false;
1540 if ( substr( $pref, -1 ) == ';') {
1541 # The one nasty exception: definition lists work like this:
1542 # ; title : definition text
1543 # So we check for : in the remainder text to split up the
1544 # title and definition, without b0rking links.
1545 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1547 $output .= $term . $this->nextItem( ':' );
1550 } elseif( $prefixLength ||
$lastPrefixLength ) {
1551 # Either open or close a level...
1552 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1553 $paragraphStack = false;
1555 while( $commonPrefixLength < $lastPrefixLength ) {
1556 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1557 --$lastPrefixLength;
1559 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1560 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1562 while ( $prefixLength > $commonPrefixLength ) {
1563 $char = substr( $pref, $commonPrefixLength, 1 );
1564 $output .= $this->openList( $char );
1566 if ( ';' == $char ) {
1567 # FIXME: This is dupe of code above
1568 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1570 $output .= $term . $this->nextItem( ':' );
1573 ++
$commonPrefixLength;
1575 $lastPrefix = $pref2;
1577 if( 0 == $prefixLength ) {
1578 wfProfileIn( "$fname-paragraph" );
1579 # No prefix (not in list)--go to paragraph mode
1580 $uniq_prefix = UNIQ_PREFIX
;
1581 // XXX: use a stack for nestable elements like span, table and div
1582 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1583 $closematch = preg_match(
1584 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1585 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1586 if ( $openmatch or $closematch ) {
1587 $paragraphStack = false;
1588 $output .= $this->closeParagraph();
1589 if($preOpenMatch and !$preCloseMatch) {
1590 $this->mInPre
= true;
1592 if ( $closematch ) {
1593 $inBlockElem = false;
1595 $inBlockElem = true;
1597 } else if ( !$inBlockElem && !$this->mInPre
) {
1598 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1600 if ($this->mLastSection
!= 'pre') {
1601 $paragraphStack = false;
1602 $output .= $this->closeParagraph().'<pre>';
1603 $this->mLastSection
= 'pre';
1605 $t = substr( $t, 1 );
1608 if ( '' == trim($t) ) {
1609 if ( $paragraphStack ) {
1610 $output .= $paragraphStack.'<br />';
1611 $paragraphStack = false;
1612 $this->mLastSection
= 'p';
1614 if ($this->mLastSection
!= 'p' ) {
1615 $output .= $this->closeParagraph();
1616 $this->mLastSection
= '';
1617 $paragraphStack = '<p>';
1619 $paragraphStack = '</p><p>';
1623 if ( $paragraphStack ) {
1624 $output .= $paragraphStack;
1625 $paragraphStack = false;
1626 $this->mLastSection
= 'p';
1627 } else if ($this->mLastSection
!= 'p') {
1628 $output .= $this->closeParagraph().'<p>';
1629 $this->mLastSection
= 'p';
1634 wfProfileOut( "$fname-paragraph" );
1636 if ($paragraphStack === false) {
1640 while ( $prefixLength ) {
1641 $output .= $this->closeList( $pref2{$prefixLength-1} );
1644 if ( '' != $this->mLastSection
) {
1645 $output .= '</' . $this->mLastSection
. '>';
1646 $this->mLastSection
= '';
1649 wfProfileOut( $fname );
1654 * Split up a string on ':', ignoring any occurences inside
1655 * <a>..</a> or <span>...</span>
1656 * @param string $str the string to split
1657 * @param string &$before set to everything before the ':'
1658 * @param string &$after set to everything after the ':'
1659 * return string the position of the ':', or false if none found
1661 function findColonNoLinks($str, &$before, &$after) {
1662 # I wonder if we should make this count all tags, not just <a>
1663 # and <span>. That would prevent us from matching a ':' that
1664 # comes in the middle of italics other such formatting....
1666 $fname = 'Parser::findColonNoLinks';
1667 wfProfileIn( $fname );
1670 $colon = strpos($str, ':', $pos);
1672 if ($colon !== false) {
1673 $before = substr($str, 0, $colon);
1674 $after = substr($str, $colon +
1);
1676 # Skip any ':' within <a> or <span> pairs
1677 $a = substr_count($before, '<a');
1678 $s = substr_count($before, '<span');
1679 $ca = substr_count($before, '</a>');
1680 $cs = substr_count($before, '</span>');
1682 if ($a <= $ca and $s <= $cs) {
1683 # Tags are balanced before ':'; ok
1688 } while ($colon !== false);
1689 wfProfileOut( $fname );
1694 * Return value of a magic variable (like PAGENAME)
1698 function getVariableValue( $index ) {
1699 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1702 * Some of these require message or data lookups and can be
1703 * expensive to check many times.
1705 static $varCache = array();
1706 if( isset( $varCache[$index] ) ) return $varCache[$index];
1709 case MAG_CURRENTMONTH
:
1710 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1711 case MAG_CURRENTMONTHNAME
:
1712 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1713 case MAG_CURRENTMONTHNAMEGEN
:
1714 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1715 case MAG_CURRENTMONTHABBREV
:
1716 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1717 case MAG_CURRENTDAY
:
1718 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1720 return $this->mTitle
->getText();
1722 return $this->mTitle
->getPartialURL();
1723 case MAG_REVISIONID
:
1724 return $wgArticle->getRevIdFetched();
1726 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1727 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1728 case MAG_CURRENTDAYNAME
:
1729 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1730 case MAG_CURRENTYEAR
:
1731 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1732 case MAG_CURRENTTIME
:
1733 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1734 case MAG_CURRENTWEEK
:
1735 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1736 case MAG_CURRENTDOW
:
1737 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1738 case MAG_NUMBEROFARTICLES
:
1739 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1750 * initialise the magic variables (like CURRENTMONTHNAME)
1754 function initialiseVariables() {
1755 $fname = 'Parser::initialiseVariables';
1756 wfProfileIn( $fname );
1757 global $wgVariableIDs;
1758 $this->mVariables
= array();
1759 foreach ( $wgVariableIDs as $id ) {
1760 $mw =& MagicWord
::get( $id );
1761 $mw->addToArray( $this->mVariables
, $id );
1763 wfProfileOut( $fname );
1767 * Replace magic variables, templates, and template arguments
1768 * with the appropriate text. Templates are substituted recursively,
1769 * taking care to avoid infinite loops.
1771 * Note that the substitution depends on value of $mOutputType:
1772 * OT_WIKI: only {{subst:}} templates
1773 * OT_MSG: only magic variables
1774 * OT_HTML: all templates and magic variables
1776 * @param string $tex The text to transform
1777 * @param array $args Key-value pairs representing template parameters to substitute
1780 function replaceVariables( $text, $args = array() ) {
1781 global $wgLang, $wgScript, $wgArticlePath;
1783 # Prevent too big inclusions
1784 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1788 $fname = 'Parser::replaceVariables';
1789 wfProfileIn( $fname );
1791 $titleChars = Title
::legalChars();
1793 # This function is called recursively. To keep track of arguments we need a stack:
1794 array_push( $this->mArgStack
, $args );
1796 # Variable substitution
1797 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1799 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1800 # Argument substitution
1801 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1803 # Template substitution
1804 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1805 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1807 array_pop( $this->mArgStack
);
1809 wfProfileOut( $fname );
1814 * Replace magic variables
1817 function variableSubstitution( $matches ) {
1818 $fname = 'parser::variableSubstitution';
1819 $varname = $matches[1];
1820 wfProfileIn( $fname );
1821 if ( !$this->mVariables
) {
1822 $this->initialiseVariables();
1825 if ( $this->mOutputType
== OT_WIKI
) {
1826 # Do only magic variables prefixed by SUBST
1827 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1828 if (!$mwSubst->matchStartAndRemove( $varname ))
1830 # Note that if we don't substitute the variable below,
1831 # we don't remove the {{subst:}} magic word, in case
1832 # it is a template rather than a magic variable.
1834 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1835 $id = $this->mVariables
[$varname];
1836 $text = $this->getVariableValue( $id );
1837 $this->mOutput
->mContainsOldMagic
= true;
1839 $text = $matches[0];
1841 wfProfileOut( $fname );
1845 # Split template arguments
1846 function getTemplateArgs( $argsString ) {
1847 if ( $argsString === '' ) {
1851 $args = explode( '|', substr( $argsString, 1 ) );
1853 # If any of the arguments contains a '[[' but no ']]', it needs to be
1854 # merged with the next arg because the '|' character between belongs
1855 # to the link syntax and not the template parameter syntax.
1856 $argc = count($args);
1858 for ( $i = 0; $i < $argc-1; $i++
) {
1859 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1860 $args[$i] .= '|'.$args[$i+
1];
1861 array_splice($args, $i+
1, 1);
1871 * Return the text of a template, after recursively
1872 * replacing any variables or templates within the template.
1874 * @param array $matches The parts of the template
1875 * $matches[1]: the title, i.e. the part before the |
1876 * $matches[2]: the parameters (including a leading |), if any
1877 * @return string the text of the template
1880 function braceSubstitution( $matches ) {
1881 global $wgLinkCache, $wgContLang;
1882 $fname = 'Parser::braceSubstitution';
1883 wfProfileIn( $fname );
1891 # Need to know if the template comes at the start of a line,
1892 # to treat the beginning of the template like the beginning
1893 # of a line for tables and block-level elements.
1894 $linestart = $matches[1];
1896 # $part1 is the bit before the first |, and must contain only title characters
1897 # $args is a list of arguments, starting from index 0, not including $part1
1899 $part1 = $matches[2];
1900 # If the third subpattern matched anything, it will start with |
1902 $args = $this->getTemplateArgs($matches[3]);
1903 $argc = count( $args );
1905 # Don't parse {{{}}} because that's only for template arguments
1906 if ( $linestart === '{' ) {
1907 $text = $matches[0];
1914 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1915 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1916 # One of two possibilities is true:
1917 # 1) Found SUBST but not in the PST phase
1918 # 2) Didn't find SUBST and in the PST phase
1919 # In either case, return without further processing
1920 $text = $matches[0];
1926 # MSG, MSGNW and INT
1929 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1930 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1933 # Remove obsolete MSG:
1934 $mwMsg =& MagicWord
::get( MAG_MSG
);
1935 $mwMsg->matchStartAndRemove( $part1 );
1938 # Check if it is an internal message
1939 $mwInt =& MagicWord
::get( MAG_INT
);
1940 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1941 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1942 $text = $linestart . wfMsgReal( $part1, $args, true );
1950 # Check for NS: (namespace expansion)
1951 $mwNs = MagicWord
::get( MAG_NS
);
1952 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1953 if ( intval( $part1 ) ) {
1954 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1957 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1958 if ( !is_null( $index ) ) {
1959 $text = $linestart . $wgContLang->getNsText( $index );
1966 # LOCALURL and LOCALURLE
1968 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1969 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1971 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1972 $func = 'getLocalURL';
1973 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1974 $func = 'escapeLocalURL';
1979 if ( $func !== '' ) {
1980 $title = Title
::newFromText( $part1 );
1981 if ( !is_null( $title ) ) {
1983 $text = $linestart . $title->$func( $args[0] );
1985 $text = $linestart . $title->$func();
1993 if ( !$found && $argc == 1 ) {
1994 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1995 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1996 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2001 # Template table test
2003 # Did we encounter this template already? If yes, it is in the cache
2004 # and we need to check for loops.
2005 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2008 # Infinite loop test
2009 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2012 $text = $linestart .
2014 '<!-- WARNING: template loop detected -->';
2015 wfDebug( "$fname: template loop broken at '$part1'\n" );
2017 # set $text to cached message.
2018 $text = $linestart . $this->mTemplates
[$part1];
2022 # Load from database
2023 $itcamefromthedatabase = false;
2024 $lastPathLevel = $this->mTemplatePath
;
2027 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2028 if ($subpage !== '') {
2029 $ns = $this->mTitle
->getNamespace();
2031 $title = Title
::newFromText( $part1, $ns );
2032 if ( !is_null( $title ) && !$title->isExternal() ) {
2033 # Check for excessive inclusion
2034 $dbk = $title->getPrefixedDBkey();
2035 if ( $this->incrementIncludeCount( $dbk ) ) {
2036 # This should never be reached.
2037 $article = new Article( $title );
2038 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2039 if ( $articleContent !== false ) {
2041 $text = $linestart . $articleContent;
2042 $itcamefromthedatabase = true;
2046 # If the title is valid but undisplayable, make a link to it
2047 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2048 $text = $linestart . '[['.$title->getPrefixedText().']]';
2052 # Template cache array insertion
2054 $this->mTemplates
[$part1] = $text;
2059 # Recursive parsing, escaping and link table handling
2060 # Only for HTML output
2061 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2062 $text = wfEscapeWikiText( $text );
2063 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2064 # Clean up argument array
2065 $assocArgs = array();
2067 foreach( $args as $arg ) {
2068 $eqpos = strpos( $arg, '=' );
2069 if ( $eqpos === false ) {
2070 $assocArgs[$index++
] = $arg;
2072 $name = trim( substr( $arg, 0, $eqpos ) );
2073 $value = trim( substr( $arg, $eqpos+
1 ) );
2074 if ( $value === false ) {
2077 if ( $name !== false ) {
2078 $assocArgs[$name] = $value;
2083 # Add a new element to the templace recursion path
2084 $this->mTemplatePath
[$part1] = 1;
2086 $text = $this->strip( $text, $this->mStripState
);
2087 $text = Sanitizer
::removeHTMLtags( $text );
2088 $text = $this->replaceVariables( $text, $assocArgs );
2090 # Resume the link cache and register the inclusion as a link
2091 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2092 $wgLinkCache->addLinkObj( $title );
2095 # If the template begins with a table or block-level
2096 # element, it should be treated as beginning a new line.
2097 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2098 $text = "\n" . $text;
2101 # Prune lower levels off the recursion check path
2102 $this->mTemplatePath
= $lastPathLevel;
2105 wfProfileOut( $fname );
2108 # replace ==section headers==
2109 # XXX this needs to go away once we have a better parser.
2110 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2111 if( !is_null( $title ) )
2112 $encodedname = base64_encode($title->getPrefixedDBkey());
2114 $encodedname = base64_encode("");
2115 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2116 PREG_SPLIT_DELIM_CAPTURE
);
2119 for( $i = 0; $i < count($m); $i +
= 2 ) {
2121 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2123 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2127 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2128 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2129 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2135 # Prune lower levels off the recursion check path
2136 $this->mTemplatePath
= $lastPathLevel;
2139 wfProfileOut( $fname );
2142 wfProfileOut( $fname );
2148 * Triple brace replacement -- used for template arguments
2151 function argSubstitution( $matches ) {
2152 $arg = trim( $matches[1] );
2153 $text = $matches[0];
2154 $inputArgs = end( $this->mArgStack
);
2156 if ( array_key_exists( $arg, $inputArgs ) ) {
2157 $text = $inputArgs[$arg];
2164 * Returns true if the function is allowed to include this entity
2167 function incrementIncludeCount( $dbk ) {
2168 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2169 $this->mIncludeCount
[$dbk] = 0;
2171 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2179 * This function accomplishes several tasks:
2180 * 1) Auto-number headings if that option is enabled
2181 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2182 * 3) Add a Table of contents on the top for users who have enabled the option
2183 * 4) Auto-anchor headings
2185 * It loops through all headlines, collects the necessary data, then splits up the
2186 * string and re-inserts the newly formatted headlines.
2188 * @param string $text
2189 * @param boolean $isMain
2192 function formatHeadings( $text, $isMain=true ) {
2193 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2195 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2197 $forceTocHere = false;
2198 if( !$this->mTitle
->userCanEdit() ) {
2201 $showEditLink = $this->mOptions
->getEditSection();
2204 # Inhibit editsection links if requested in the page
2205 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2206 if( $esw->matchAndRemove( $text ) ) {
2209 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2211 $mw =& MagicWord
::get( MAG_NOTOC
);
2212 if( $mw->matchAndRemove( $text ) ) {
2216 # Get all headlines for numbering them and adding funky stuff like [edit]
2217 # links - this is for later, but we need the number of headlines right now
2218 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2220 # if there are fewer than 4 headlines in the article, do not show TOC
2221 if( $numMatches < 4 ) {
2225 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2226 # override above conditions and always show TOC at that place
2228 $mw =& MagicWord
::get( MAG_TOC
);
2229 if($mw->match( $text ) ) {
2231 $forceTocHere = true;
2233 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2234 # override above conditions and always show TOC above first header
2235 $mw =& MagicWord
::get( MAG_FORCETOC
);
2236 if ($mw->matchAndRemove( $text ) ) {
2241 # Never ever show TOC if no headers
2242 if( $numMatches < 1 ) {
2246 # We need this to perform operations on the HTML
2247 $sk =& $this->mOptions
->getSkin();
2251 $sectionCount = 0; # headlineCount excluding template sections
2253 # Ugh .. the TOC should have neat indentation levels which can be
2254 # passed to the skin functions. These are determined here
2258 $sublevelCount = array();
2259 $levelCount = array();
2266 foreach( $matches[3] as $headline ) {
2268 $templatetitle = '';
2269 $templatesection = 0;
2272 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2274 $templatetitle = base64_decode($mat[1]);
2275 $templatesection = 1 +
(int)base64_decode($mat[2]);
2276 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2280 $prevlevel = $level;
2281 $prevtoclevel = $toclevel;
2283 $level = $matches[1][$headlineCount];
2285 if( $doNumberHeadings ||
$doShowToc ) {
2287 if ( $level > $prevlevel ) {
2288 # Increase TOC level
2290 $sublevelCount[$toclevel] = 0;
2291 $toc .= $sk->tocIndent();
2293 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2294 # Decrease TOC level, find level to jump to
2296 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2297 # Can only go down to level 1
2300 for ($i = $toclevel; $i > 0; $i--) {
2301 if ( $levelCount[$i] == $level ) {
2302 # Found last matching level
2306 elseif ( $levelCount[$i] < $level ) {
2307 # Found first matching level below current level
2314 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2317 # No change in level, end TOC line
2318 $toc .= $sk->tocLineEnd();
2321 $levelCount[$toclevel] = $level;
2323 # count number of headlines for each level
2324 @$sublevelCount[$toclevel]++
;
2326 for( $i = 1; $i <= $toclevel; $i++
) {
2327 if( !empty( $sublevelCount[$i] ) ) {
2331 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2337 # The canonized header is a version of the header text safe to use for links
2338 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2339 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2340 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2342 # Remove link placeholders by the link text.
2343 # <!--LINK number-->
2345 # link text with suffix
2346 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2347 "\$wgLinkHolders['texts'][\$1]",
2348 $canonized_headline );
2349 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2350 "\$wgInterwikiLinkHolders[\$1]",
2351 $canonized_headline );
2354 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2355 $tocline = trim( $canonized_headline );
2356 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2357 $replacearray = array(
2361 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2362 $refer[$headlineCount] = $canonized_headline;
2364 # count how many in assoc. array so we can track dupes in anchors
2365 @$refers[$canonized_headline]++
;
2366 $refcount[$headlineCount]=$refers[$canonized_headline];
2368 # Don't number the heading if it is the only one (looks silly)
2369 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2370 # the two are different if the line contains a link
2371 $headline=$numbering . ' ' . $headline;
2374 # Create the anchor for linking from the TOC to the section
2375 $anchor = $canonized_headline;
2376 if($refcount[$headlineCount] > 1 ) {
2377 $anchor .= '_' . $refcount[$headlineCount];
2379 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2380 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2382 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2383 if ( empty( $head[$headlineCount] ) ) {
2384 $head[$headlineCount] = '';
2387 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2389 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2392 # give headline the correct <h#> tag
2393 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2401 $toclines = $headlineCount;
2402 $toc .= $sk->tocUnindent( $toclevel - 1 );
2403 $toc = $sk->tocList( $toc );
2406 # split up and insert constructed headlines
2408 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2411 foreach( $blocks as $block ) {
2412 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2413 # This is the [edit] link that appears for the top block of text when
2414 # section editing is enabled
2416 # Disabled because it broke block formatting
2417 # For example, a bullet point in the top line
2418 # $full .= $sk->editSectionLink(0);
2421 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2422 # Top anchor now in skin
2426 if( !empty( $head[$i] ) ) {
2432 $mw =& MagicWord
::get( MAG_TOC
);
2433 return $mw->replace( $toc, $full );
2440 * Return an HTML link for the "ISBN 123456" text
2443 function magicISBN( $text ) {
2445 $fname = 'Parser::magicISBN';
2446 wfProfileIn( $fname );
2448 $a = split( 'ISBN ', ' '.$text );
2449 if ( count ( $a ) < 2 ) {
2450 wfProfileOut( $fname );
2453 $text = substr( array_shift( $a ), 1);
2454 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2456 foreach ( $a as $x ) {
2457 $isbn = $blank = '' ;
2458 while ( ' ' == $x{0} ) {
2460 $x = substr( $x, 1 );
2462 if ( $x == '' ) { # blank isbn
2463 $text .= "ISBN $blank";
2466 while ( strstr( $valid, $x{0} ) != false ) {
2468 $x = substr( $x, 1 );
2470 $num = str_replace( '-', '', $isbn );
2471 $num = str_replace( ' ', '', $num );
2474 $text .= "ISBN $blank$x";
2476 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2477 $text .= '<a href="' .
2478 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2479 "\" class=\"internal\">ISBN $isbn</a>";
2483 wfProfileOut( $fname );
2488 * Return an HTML link for the "RFC 1234" text
2490 * @param string $text text to be processed
2492 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2495 $valid = '0123456789';
2498 $a = split( $keyword, ' '.$text );
2499 if ( count ( $a ) < 2 ) {
2502 $text = substr( array_shift( $a ), 1);
2504 /* Check if keyword is preceed by [[.
2505 * This test is made here cause of the array_shift above
2506 * that prevent the test to be done in the foreach.
2508 if ( substr( $text, -2 ) == '[[' ) {
2512 foreach ( $a as $x ) {
2513 /* token might be empty if we have RFC RFC 1234 */
2521 /** remove and save whitespaces in $blank */
2522 while ( $x{0} == ' ' ) {
2524 $x = substr( $x, 1 );
2527 /** remove and save the rfc number in $id */
2528 while ( strstr( $valid, $x{0} ) != false ) {
2530 $x = substr( $x, 1 );
2534 /* call back stripped spaces*/
2535 $text .= $keyword.$blank.$x;
2536 } elseif( $internal ) {
2538 $text .= $keyword.$id.$x;
2540 /* build the external link*/
2541 $url = wfmsg( $urlmsg );
2542 $url = str_replace( '$1', $id, $url);
2543 $sk =& $this->mOptions
->getSkin();
2544 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2545 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2548 /* Check if the next RFC keyword is preceed by [[ */
2549 $internal = ( substr($x,-2) == '[[' );
2555 * Transform wiki markup when saving a page by doing \r\n -> \n
2556 * conversion, substitting signatures, {{subst:}} templates, etc.
2558 * @param string $text the text to transform
2559 * @param Title &$title the Title object for the current article
2560 * @param User &$user the User object describing the current user
2561 * @param ParserOptions $options parsing options
2562 * @param bool $clearState whether to clear the parser state first
2563 * @return string the altered wiki markup
2566 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2567 $this->mOptions
= $options;
2568 $this->mTitle
=& $title;
2569 $this->mOutputType
= OT_WIKI
;
2571 if ( $clearState ) {
2572 $this->clearState();
2575 $stripState = false;
2579 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2580 $text = $this->strip( $text, $stripState, false );
2581 $text = $this->pstPass2( $text, $user );
2582 $text = $this->unstrip( $text, $stripState );
2583 $text = $this->unstripNoWiki( $text, $stripState );
2588 * Pre-save transform helper function
2591 function pstPass2( $text, &$user ) {
2592 global $wgLang, $wgContLang, $wgLocaltimezone;
2594 # Variable replacement
2595 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2596 $text = $this->replaceVariables( $text );
2600 $n = $user->getName();
2601 $k = $user->getOption( 'nickname' );
2602 if ( '' == $k ) { $k = $n; }
2603 if ( isset( $wgLocaltimezone ) ) {
2604 $oldtz = getenv( 'TZ' );
2605 putenv( 'TZ='.$wgLocaltimezone );
2607 /* Note: this is an ugly timezone hack for the European wikis */
2608 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2609 ' (' . date( 'T' ) . ')';
2610 if ( isset( $wgLocaltimezone ) ) {
2611 putenv( 'TZ='.$oldtzs );
2614 if( $user->getOption( 'fancysig' ) ) {
2617 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2619 $text = preg_replace( '/~~~~~/', $d, $text );
2620 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2621 $text = preg_replace( '/~~~/', $sigText, $text );
2623 # Context links: [[|name]] and [[name (context)|]]
2625 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2626 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2627 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2628 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2630 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2631 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2632 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2633 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2635 $t = $this->mTitle
->getText();
2636 if ( preg_match( $conpat, $t, $m ) ) {
2639 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2640 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2641 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2643 if ( '' == $context ) {
2644 $text = preg_replace( $p2, '[[\\1]]', $text );
2646 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2649 # Trim trailing whitespace
2650 # MAG_END (__END__) tag allows for trailing
2651 # whitespace to be deliberately included
2652 $text = rtrim( $text );
2653 $mw =& MagicWord
::get( MAG_END
);
2654 $mw->matchAndRemove( $text );
2660 * Set up some variables which are usually set up in parse()
2661 * so that an external function can call some class members with confidence
2664 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2665 $this->mTitle
=& $title;
2666 $this->mOptions
= $options;
2667 $this->mOutputType
= $outputType;
2668 if ( $clearState ) {
2669 $this->clearState();
2674 * Transform a MediaWiki message by replacing magic variables.
2676 * @param string $text the text to transform
2677 * @param ParserOptions $options options
2678 * @return string the text with variables substituted
2681 function transformMsg( $text, $options ) {
2683 static $executing = false;
2685 # Guard against infinite recursion
2691 $this->mTitle
= $wgTitle;
2692 $this->mOptions
= $options;
2693 $this->mOutputType
= OT_MSG
;
2694 $this->clearState();
2695 $text = $this->replaceVariables( $text );
2702 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2703 * Callback will be called with the text within
2704 * Transform and return the text within
2707 function setHook( $tag, $callback ) {
2708 $oldVal = @$this->mTagHooks
[$tag];
2709 $this->mTagHooks
[$tag] = $callback;
2714 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2715 * Placeholders created in Skin::makeLinkObj()
2716 * Returns an array of links found, indexed by PDBK:
2720 * $options is a bit field, RLH_FOR_UPDATE to select for update
2722 function replaceLinkHolders( &$text, $options = 0 ) {
2723 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2724 global $wgInterwikiLinkHolders;
2725 global $outputReplace;
2727 if ( $wgUseOldExistenceCheck ) {
2731 $fname = 'Parser::replaceLinkHolders';
2732 wfProfileIn( $fname );
2737 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2738 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2739 wfProfileIn( $fname.'-check' );
2740 $dbr =& wfGetDB( DB_SLAVE
);
2741 $page = $dbr->tableName( 'page' );
2742 $sk = $wgUser->getSkin();
2743 $threshold = $wgUser->getOption('stubthreshold');
2746 asort( $wgLinkHolders['namespaces'] );
2750 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2752 $title = $wgLinkHolders['titles'][$key];
2754 # Skip invalid entries.
2755 # Result will be ugly, but prevents crash.
2756 if ( is_null( $title ) ) {
2759 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2761 # Check if it's in the link cache already
2762 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2763 $colours[$pdbk] = 1;
2764 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2765 $colours[$pdbk] = 0;
2767 # Not in the link cache, add it to the query
2768 if ( !isset( $current ) ) {
2770 $query = "SELECT page_id, page_namespace, page_title";
2771 if ( $threshold > 0 ) {
2772 $query .= ', page_len, page_is_redirect';
2774 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2775 } elseif ( $current != $val ) {
2777 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2782 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2787 if ( $options & RLH_FOR_UPDATE
) {
2788 $query .= ' FOR UPDATE';
2791 $res = $dbr->query( $query, $fname );
2793 # Fetch data and form into an associative array
2794 # non-existent = broken
2797 while ( $s = $dbr->fetchObject($res) ) {
2798 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2799 $pdbk = $title->getPrefixedDBkey();
2800 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2802 if ( $threshold > 0 ) {
2803 $size = $s->page_len
;
2804 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2805 $colours[$pdbk] = 1;
2807 $colours[$pdbk] = 2;
2810 $colours[$pdbk] = 1;
2814 wfProfileOut( $fname.'-check' );
2816 # Construct search and replace arrays
2817 wfProfileIn( $fname.'-construct' );
2818 $outputReplace = array();
2819 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2820 $pdbk = $pdbks[$key];
2821 $searchkey = '<!--LINK '.$key.'-->';
2822 $title = $wgLinkHolders['titles'][$key];
2823 if ( empty( $colours[$pdbk] ) ) {
2824 $wgLinkCache->addBadLink( $pdbk );
2825 $colours[$pdbk] = 0;
2826 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2827 $wgLinkHolders['texts'][$key],
2828 $wgLinkHolders['queries'][$key] );
2829 } elseif ( $colours[$pdbk] == 1 ) {
2830 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2831 $wgLinkHolders['texts'][$key],
2832 $wgLinkHolders['queries'][$key] );
2833 } elseif ( $colours[$pdbk] == 2 ) {
2834 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2835 $wgLinkHolders['texts'][$key],
2836 $wgLinkHolders['queries'][$key] );
2839 wfProfileOut( $fname.'-construct' );
2842 wfProfileIn( $fname.'-replace' );
2844 $text = preg_replace_callback(
2845 '/(<!--LINK .*?-->)/',
2846 "outputReplaceMatches",
2848 wfProfileOut( $fname.'-replace' );
2851 if ( !empty( $wgInterwikiLinkHolders ) ) {
2852 wfProfileIn( $fname.'-interwiki' );
2853 $outputReplace = $wgInterwikiLinkHolders;
2854 $text = preg_replace_callback(
2855 '/<!--IWLINK (.*?)-->/',
2856 "outputReplaceMatches",
2858 wfProfileOut( $fname.'-interwiki' );
2861 wfProfileOut( $fname );
2866 * Renders an image gallery from a text with one line per image.
2867 * text labels may be given by using |-style alternative text. E.g.
2868 * Image:one.jpg|The number "1"
2869 * Image:tree.jpg|A tree
2870 * given as text will return the HTML of a gallery with two images,
2871 * labeled 'The number "1"' and
2874 function renderImageGallery( $text ) {
2876 global $wgUser, $wgParser, $wgTitle;
2877 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2879 global $wgLinkCache;
2880 $ig = new ImageGallery();
2881 $ig->setShowBytes( false );
2882 $ig->setShowFilename( false );
2883 $lines = explode( "\n", $text );
2885 foreach ( $lines as $line ) {
2886 # match lines like these:
2887 # Image:someimage.jpg|This is some image
2888 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2890 if ( count( $matches ) == 0 ) {
2893 $nt = Title
::newFromURL( $matches[1] );
2894 if( is_null( $nt ) ) {
2895 # Bogus title. Ignore these so we don't bomb out later.
2898 if ( isset( $matches[3] ) ) {
2899 $label = $matches[3];
2904 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
2905 $html = $html->mText
;
2907 $ig->add( Image
::newFromTitle( $nt ), $html );
2908 $wgLinkCache->addImageLinkObj( $nt );
2910 return $ig->toHTML();
2916 * @package MediaWiki
2920 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2921 var $mCacheTime; # Used in ParserCache
2922 var $mVersion; # Compatibility check
2924 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2925 $containsOldMagic = false )
2927 $this->mText
= $text;
2928 $this->mLanguageLinks
= $languageLinks;
2929 $this->mCategoryLinks
= $categoryLinks;
2930 $this->mContainsOldMagic
= $containsOldMagic;
2931 $this->mCacheTime
= '';
2932 $this->mVersion
= MW_PARSER_VERSION
;
2935 function getText() { return $this->mText
; }
2936 function getLanguageLinks() { return $this->mLanguageLinks
; }
2937 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
2938 function getCacheTime() { return $this->mCacheTime
; }
2939 function containsOldMagic() { return $this->mContainsOldMagic
; }
2940 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2941 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2942 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2943 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2944 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2945 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
2947 function merge( $other ) {
2948 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2949 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2950 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2954 * Return true if this cached output object predates the global or
2955 * per-article cache invalidation timestamps, or if it comes from
2956 * an incompatible older version.
2958 * @param string $touched the affected article's last touched timestamp
2962 function expired( $touched ) {
2963 global $wgCacheEpoch;
2964 return $this->getCacheTime() <= $touched ||
2965 $this->getCacheTime() <= $wgCacheEpoch ||
2966 !isset( $this->mVersion
) ||
2967 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
2972 * Set options of the Parser
2974 * @package MediaWiki
2978 # All variables are private
2979 var $mUseTeX; # Use texvc to expand <math> tags
2980 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2981 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2982 var $mAllowExternalImages; # Allow external images inline
2983 var $mSkin; # Reference to the preferred skin
2984 var $mDateFormat; # Date format index
2985 var $mEditSection; # Create "edit section" links
2986 var $mNumberHeadings; # Automatically number headings
2988 function getUseTeX() { return $this->mUseTeX
; }
2989 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2990 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2991 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2992 function getSkin() { return $this->mSkin
; }
2993 function getDateFormat() { return $this->mDateFormat
; }
2994 function getEditSection() { return $this->mEditSection
; }
2995 function getNumberHeadings() { return $this->mNumberHeadings
; }
2997 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2998 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2999 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3000 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3001 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3002 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3003 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3005 function setSkin( &$x ) { $this->mSkin
=& $x; }
3008 * Get parser options
3011 function newFromUser( &$user ) {
3012 $popts = new ParserOptions
;
3013 $popts->initialiseFromUser( $user );
3017 /** Get user options */
3018 function initialiseFromUser( &$userInput ) {
3019 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3020 $fname = 'ParserOptions::initialiseFromUser';
3021 wfProfileIn( $fname );
3022 if ( !$userInput ) {
3024 $user->setLoaded( true );
3026 $user =& $userInput;
3029 $this->mUseTeX
= $wgUseTeX;
3030 $this->mUseDynamicDates
= $wgUseDynamicDates;
3031 $this->mInterwikiMagic
= $wgInterwikiMagic;
3032 $this->mAllowExternalImages
= $wgAllowExternalImages;
3033 wfProfileIn( $fname.'-skin' );
3034 $this->mSkin
=& $user->getSkin();
3035 wfProfileOut( $fname.'-skin' );
3036 $this->mDateFormat
= $user->getOption( 'date' );
3037 $this->mEditSection
= $user->getOption( 'editsection' );
3038 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3039 wfProfileOut( $fname );
3044 * Callback function used by Parser::replaceLinkHolders()
3045 * to substitute link placeholders.
3047 function &outputReplaceMatches( $matches ) {
3048 global $outputReplace;
3049 return $outputReplace[$matches[1]];
3053 * Return the total number of articles
3055 function wfNumberOfArticles() {
3056 global $wgNumberOfArticles;
3059 return $wgNumberOfArticles;
3063 * Get various statistics from the database
3066 function wfLoadSiteStats() {
3067 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3068 $fname = 'wfLoadSiteStats';
3070 if ( -1 != $wgNumberOfArticles ) return;
3071 $dbr =& wfGetDB( DB_SLAVE
);
3072 $s = $dbr->selectRow( 'site_stats',
3073 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3074 array( 'ss_row_id' => 1 ), $fname
3077 if ( $s === false ) {
3080 $wgTotalViews = $s->ss_total_views
;
3081 $wgTotalEdits = $s->ss_total_edits
;
3082 $wgNumberOfArticles = $s->ss_good_articles
;
3088 * Basicly replacing " > and < with HTML entities ( ", >, <)
3090 * @param string $in Text that might contain HTML tags
3091 * @return string Escaped string
3093 function wfEscapeHTMLTagsOnly( $in ) {
3095 array( '"', '>', '<' ),
3096 array( '"', '>', '<' ),