3 // require_once('Tokenizer.php');
7 # Processes wiki markup
9 # There are two main entry points into the Parser class:
11 # produces HTML output
13 # produces altered wiki markup.
16 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
18 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
21 # $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
22 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
25 # * only within ParserOptions
27 #----------------------------------------
28 # Variable substitution O(N^2) attack
29 #-----------------------------------------
30 # Without countermeasures, it would be possible to attack the parser by saving
31 # a page filled with a large number of inclusions of large pages. The size of
32 # the generated page would be proportional to the square of the input size.
33 # Hence, we limit the number of inclusions of any given page, thus bringing any
34 # attack back to O(N).
35 define( 'MAX_INCLUDE_REPEAT', 100 );
36 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
38 # Allowed values for $mOutputType
39 define( 'OT_HTML', 1 );
40 define( 'OT_WIKI', 2 );
41 define( 'OT_MSG' , 3 );
43 # string parameter for extractTags which will cause it
44 # to strip HTML comments in addition to regular
45 # <XML>-style tags. This should not be anything we
46 # may want to use in wikisyntax
47 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
49 # prefix for escaping, used in two functions at least
50 define( 'UNIQ_PREFIX', 'NaodW29');
52 # Constants needed for external link processing
53 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
54 define( 'HTTP_PROTOCOLS', 'http|https' );
55 # Everything except bracket, space, or control characters
56 define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
57 define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
59 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
60 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
61 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
62 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
63 define( 'EXT_IMAGE_REGEX',
64 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
65 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
66 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
74 # Cleared with clearState():
75 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
76 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
79 var $mOptions, $mTitle, $mOutputType,
80 $mTemplates, // cache of already loaded templates, avoids
81 // multiple SQL queries for the same string
82 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
83 // in this path. Used for loop detection.
86 $this->mTemplates
= array();
87 $this->mTemplatePath
= array();
88 $this->mTagHooks
= array();
92 function clearState() {
93 $this->mOutput
= new ParserOutput
;
94 $this->mAutonumber
= 0;
95 $this->mLastSection
= "";
96 $this->mDTopen
= false;
97 $this->mVariables
= false;
98 $this->mIncludeCount
= array();
99 $this->mStripState
= array();
100 $this->mArgStack
= array();
101 $this->mInPre
= false;
104 # First pass--just handle <nowiki> sections, pass the rest off
105 # to internalParse() which does all the real work.
107 # Returns a ParserOutput
109 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
111 $fname = 'Parser::parse';
112 wfProfileIn( $fname );
118 $this->mOptions
= $options;
119 $this->mTitle
=& $title;
120 $this->mOutputType
= OT_HTML
;
123 $text = $this->strip( $text, $this->mStripState
);
124 $text = $this->internalParse( $text, $linestart );
125 $text = $this->unstrip( $text, $this->mStripState
);
126 # Clean up special characters, only run once, next-to-last before doBlockLevels
129 # french spaces, last one Guillemet-left
130 # only if there is something before the space
131 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
132 # french spaces, Guillemet-right
133 "/(\\302\\253) /i"=>"\\1 ",
134 '/<hr *>/i' => '<hr />',
135 '/<br *>/i' => '<br />',
136 '/<center *>/i' => '<div class="center">',
137 '/<\\/center *>/i' => '</div>',
138 # Clean up spare ampersands; note that we probably ought to be
139 # more careful about named entities.
140 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
142 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
145 # french spaces, last one Guillemet-left
146 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
147 # french spaces, Guillemet-right
148 '/(\\302\\253) /i' => '\\1 ',
149 '/<center *>/i' => '<div class="center">',
150 '/<\\/center *>/i' => '</div>'
152 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
155 $text = $this->doBlockLevels( $text, $linestart );
156 $text = $this->unstripNoWiki( $text, $this->mStripState
);
158 $text = $this->tidy($text);
160 $this->mOutput
->setText( $text );
161 wfProfileOut( $fname );
162 return $this->mOutput
;
165 /* static */ function getRandomString() {
166 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
169 # Replaces all occurrences of <$tag>content</$tag> in the text
170 # with a random marker and returns the new text. the output parameter
171 # $content will be an associative array filled with data on the form
172 # $unique_marker => content.
174 # If $content is already set, the additional entries will be appended
176 # If $tag is set to STRIP_COMMENTS, the function will extract
177 # <!-- HTML comments -->
179 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ''){
180 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
187 while ( '' != $text ) {
188 if($tag==STRIP_COMMENTS
) {
189 $p = preg_split( '/<!--/i', $text, 2 );
191 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
194 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
197 if($tag==STRIP_COMMENTS
) {
198 $q = preg_split( '/-->/i', $p[1], 2 );
200 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
202 $marker = $rnd . sprintf('%08X', $n++
);
203 $content[$marker] = $q[0];
204 $stripped .= $marker;
211 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
212 # If $render is set, performs necessary rendering operations on plugins
213 # Returns the text, and fills an array with data needed in unstrip()
214 # If the $state is already a valid strip state, it adds to the state
216 # When $stripcomments is set, HTML comments <!-- like this -->
217 # will be stripped in addition to other tags. This is important
218 # for section editing, where these comments cause confusion when
219 # counting the sections in the wikisource
220 function strip( $text, &$state, $stripcomments = false ) {
221 $render = ($this->mOutputType
== OT_HTML
);
222 $html_content = array();
223 $nowiki_content = array();
224 $math_content = array();
225 $pre_content = array();
226 $comment_content = array();
227 $ext_content = array();
229 # Replace any instances of the placeholders
230 $uniq_prefix = UNIQ_PREFIX
;
231 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
236 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
237 foreach( $html_content as $marker => $content ) {
239 # Raw and unchecked for validity.
240 $html_content[$marker] = $content;
242 $html_content[$marker] = '<html>'.$content.'</html>';
248 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
249 foreach( $nowiki_content as $marker => $content ) {
251 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
253 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
258 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
259 foreach( $math_content as $marker => $content ){
261 if( $this->mOptions
->getUseTeX() ) {
262 $math_content[$marker] = renderMath( $content );
264 $math_content[$marker] = '<math>'.$content.'<math>';
267 $math_content[$marker] = '<math>'.$content.'</math>';
272 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
273 foreach( $pre_content as $marker => $content ){
275 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
277 $pre_content[$marker] = '<pre>'.$content.'</pre>';
283 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
284 foreach( $comment_content as $marker => $content ){
285 $comment_content[$marker] = '<!--'.$content.'-->';
290 foreach ( $this->mTagHooks
as $tag => $callback ) {
291 $ext_contents[$tag] = array();
292 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
293 foreach( $ext_content[$tag] as $marker => $content ) {
295 $ext_content[$tag][$marker] = $callback( $content );
297 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
302 # Merge state with the pre-existing state, if there is one
304 $state['html'] = $state['html'] +
$html_content;
305 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
306 $state['math'] = $state['math'] +
$math_content;
307 $state['pre'] = $state['pre'] +
$pre_content;
308 $state['comment'] = $state['comment'] +
$comment_content;
310 foreach( $ext_content as $tag => $array ) {
311 if ( array_key_exists( $tag, $state ) ) {
312 $state[$tag] = $state[$tag] +
$array;
317 'html' => $html_content,
318 'nowiki' => $nowiki_content,
319 'math' => $math_content,
320 'pre' => $pre_content,
321 'comment' => $comment_content,
327 # always call unstripNoWiki() after this one
328 function unstrip( $text, &$state ) {
329 # Must expand in reverse order, otherwise nested tags will be corrupted
330 $contentDict = end( $state );
331 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
332 if( key($state) != 'nowiki' && key($state) != 'html') {
333 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
334 $text = str_replace( key( $contentDict ), $content, $text );
341 # always call this after unstrip() to preserve the order
342 function unstripNoWiki( $text, &$state ) {
343 # Must expand in reverse order, otherwise nested tags will be corrupted
344 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
345 $text = str_replace( key( $state['nowiki'] ), $content, $text );
350 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
351 $text = str_replace( key( $state['html'] ), $content, $text );
358 # Add an item to the strip state
359 # Returns the unique tag which must be inserted into the stripped text
360 # The tag will be replaced with the original text in unstrip()
361 function insertStripItem( $text, &$state ) {
362 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
371 $state['item'][$rnd] = $text;
375 # Return allowed HTML attributes
376 function getHTMLattrs () {
377 $htmlattrs = array( # Allowed attributes--no scripting, etc.
378 'title', 'align', 'lang', 'dir', 'width', 'height',
379 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
380 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
381 /* FONT */ 'type', 'start', 'value', 'compact',
382 /* For various lists, mostly deprecated but safe */
383 'summary', 'width', 'border', 'frame', 'rules',
384 'cellspacing', 'cellpadding', 'valign', 'char',
385 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
386 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
387 'id', 'class', 'name', 'style' /* For CSS */
392 # Remove non approved attributes and javascript in css
393 function fixTagAttributes ( $t ) {
394 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
395 $htmlattrs = $this->getHTMLattrs() ;
397 # Strip non-approved attributes from the tag
399 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
400 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
403 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
405 # Strip javascript "expression" from stylesheets. Brute force approach:
406 # If anythin offensive is found, all attributes of the HTML tag are dropped
409 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
410 wfMungeToUtf8( $t ) ) )
418 # interface with html tidy, used if $wgUseTidy = true
419 function tidy ( $text ) {
420 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
421 global $wgInputEncoding, $wgOutputEncoding;
422 $fname = 'Parser::tidy';
423 wfProfileIn( $fname );
426 switch(strtoupper($wgOutputEncoding)) {
428 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
431 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
434 $wgTidyOpts .= ' -raw';
437 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
438 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
439 '<head><title>test</title></head><body>'.$text.'</body></html>';
440 $descriptorspec = array(
441 0 => array('pipe', 'r'),
442 1 => array('pipe', 'w'),
443 2 => array('file', '/dev/null', 'a')
445 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
446 if (is_resource($process)) {
447 fwrite($pipes[0], $wrappedtext);
449 while (!feof($pipes[1])) {
450 $cleansource .= fgets($pipes[1], 1024);
453 $return_value = proc_close($process);
456 wfProfileOut( $fname );
458 if( $cleansource == '' && $text != '') {
459 wfDebug( "Tidy error detected!\n" );
460 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
466 # parse the wiki syntax used to render tables
467 function doTableStuff ( $t ) {
468 $fname = 'Parser::doTableStuff';
469 wfProfileIn( $fname );
471 $t = explode ( "\n" , $t ) ;
472 $td = array () ; # Is currently a td tag open?
473 $ltd = array () ; # Was it TD or TH?
474 $tr = array () ; # Is currently a tr tag open?
475 $ltr = array () ; # tr attributes
476 $indent_level = 0; # indent level of the table
477 foreach ( $t AS $k => $x )
480 $fc = substr ( $x , 0 , 1 ) ;
481 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
482 $indent_level = strlen( $matches[1] );
484 str_repeat( '<dl><dd>', $indent_level ) .
485 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
486 array_push ( $td , false ) ;
487 array_push ( $ltd , '' ) ;
488 array_push ( $tr , false ) ;
489 array_push ( $ltr , '' ) ;
491 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
492 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
494 $l = array_pop ( $ltd ) ;
495 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
496 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
498 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
500 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
501 $x = substr ( $x , 1 ) ;
502 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
504 $l = array_pop ( $ltd ) ;
505 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
506 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
509 array_push ( $tr , false ) ;
510 array_push ( $td , false ) ;
511 array_push ( $ltd , '' ) ;
512 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
514 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
515 if ( '|+' == substr ( $x , 0 , 2 ) ) {
517 $x = substr ( $x , 1 ) ;
519 $after = substr ( $x , 1 ) ;
520 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
521 $after = explode ( '||' , $after ) ;
523 foreach ( $after AS $theline )
528 $tra = array_pop ( $ltr ) ;
529 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
530 array_push ( $tr , true ) ;
531 array_push ( $ltr , '' ) ;
534 $l = array_pop ( $ltd ) ;
535 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
536 if ( $fc == '|' ) $l = 'td' ;
537 else if ( $fc == '!' ) $l = 'th' ;
538 else if ( $fc == '+' ) $l = 'caption' ;
540 array_push ( $ltd , $l ) ;
541 $y = explode ( '|' , $theline , 2 ) ;
542 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
543 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
545 array_push ( $td , true ) ;
550 # Closing open td, tr && table
551 while ( count ( $td ) > 0 )
553 if ( array_pop ( $td ) ) $t[] = '</td>' ;
554 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
558 $t = implode ( "\n" , $t ) ;
559 # $t = $this->removeHTMLtags( $t );
560 wfProfileOut( $fname );
564 # Parses the text and adds the result to the strip state
565 # Returns the strip tag
566 function stripParse( $text, $newline, $args ) {
567 $text = $this->strip( $text, $this->mStripState
);
568 $text = $this->internalParse( $text, (bool)$newline, $args, false );
569 return $newline.$this->insertStripItem( $text, $this->mStripState
);
572 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
573 $fname = 'Parser::internalParse';
574 wfProfileIn( $fname );
576 $text = $this->removeHTMLtags( $text );
577 $text = $this->replaceVariables( $text, $args );
579 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
581 $text = $this->doHeadings( $text );
582 if($this->mOptions
->getUseDynamicDates()) {
583 global $wgDateFormatter;
584 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
586 $text = $this->doAllQuotes( $text );
587 $text = $this->replaceExternalLinks( $text );
588 $text = $this->doMagicLinks( $text );
589 $text = $this->replaceInternalLinks ( $text );
590 $text = $this->replaceInternalLinks ( $text );
592 $text = $this->unstrip( $text, $this->mStripState
);
593 $text = $this->unstripNoWiki( $text, $this->mStripState
);
595 $text = $this->doTableStuff( $text );
596 $text = $this->formatHeadings( $text, $isMain );
597 $sk =& $this->mOptions
->getSkin();
598 $text = $sk->transformContent( $text );
600 wfProfileOut( $fname );
604 /* private */ function &doMagicLinks( &$text ) {
605 global $wgUseGeoMode;
606 $text = $this->magicISBN( $text );
607 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
608 $text = $this->magicGEO( $text );
610 $text = $this->magicRFC( $text );
614 # Parse ^^ tokens and return html
615 /* private */ function doExponent ( $text ) {
616 $fname = 'Parser::doExponent';
617 wfProfileIn( $fname);
618 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
619 wfProfileOut( $fname);
623 # Parse headers and return html
624 /* private */ function doHeadings( $text ) {
625 $fname = 'Parser::doHeadings';
626 wfProfileIn( $fname );
627 for ( $i = 6; $i >= 1; --$i ) {
628 $h = substr( '======', 0, $i );
629 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
630 "<h{$i}>\\1</h{$i}>\\2", $text );
632 wfProfileOut( $fname );
636 /* private */ function doAllQuotes( $text ) {
637 $fname = 'Parser::doAllQuotes';
638 wfProfileIn( $fname );
640 $lines = explode( "\n", $text );
641 foreach ( $lines as $line ) {
642 $outtext .= $this->doQuotes ( $line ) . "\n";
644 $outtext = substr($outtext, 0,-1);
645 wfProfileOut( $fname );
649 /* private */ function doQuotes( $text ) {
650 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
651 if (count ($arr) == 1)
655 # First, do some preliminary work. This may shift some apostrophes from
656 # being mark-up to being text. It also counts the number of occurrences
657 # of bold and italics mark-ups.
665 # If there are ever four apostrophes, assume the first is supposed to
666 # be text, and the remaining three constitute mark-up for bold text.
667 if (strlen ($arr[$i]) == 4)
672 # If there are more than 5 apostrophes in a row, assume they're all
673 # text except for the last 5.
674 else if (strlen ($arr[$i]) > 5)
676 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
679 # Count the number of occurrences of bold and italics mark-ups.
680 # We are not counting sequences of five apostrophes.
681 if (strlen ($arr[$i]) == 2) $numitalics++
; else
682 if (strlen ($arr[$i]) == 3) $numbold++
; else
683 if (strlen ($arr[$i]) == 5) { $numitalics++
; $numbold++
; }
688 # If there is an odd number of both bold and italics, it is likely
689 # that one of the bold ones was meant to be an apostrophe followed
690 # by italics. Which one we cannot know for certain, but it is more
691 # likely to be one that has a single-letter word before it.
692 if (($numbold %
2 == 1) && ($numitalics %
2 == 1))
695 $firstsingleletterword = -1;
696 $firstmultiletterword = -1;
700 if (($i %
2 == 1) and (strlen ($r) == 3))
702 $x1 = substr ($arr[$i-1], -1);
703 $x2 = substr ($arr[$i-1], -2, 1);
705 if ($firstspace == -1) $firstspace = $i;
706 } else if ($x2 == ' ') {
707 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
709 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
715 # If there is a single-letter word, use it!
716 if ($firstsingleletterword > -1)
718 $arr [ $firstsingleletterword ] = "''";
719 $arr [ $firstsingleletterword-1 ] .= "'";
721 # If not, but there's a multi-letter word, use that one.
722 else if ($firstmultiletterword > -1)
724 $arr [ $firstmultiletterword ] = "''";
725 $arr [ $firstmultiletterword-1 ] .= "'";
727 # ... otherwise use the first one that has neither.
728 # (notice that it is possible for all three to be -1 if, for example,
729 # there is only one pentuple-apostrophe in the line)
730 else if ($firstspace > -1)
732 $arr [ $firstspace ] = "''";
733 $arr [ $firstspace-1 ] .= "'";
737 # Now let's actually convert our apostrophic mush to HTML!
746 if ($state == 'both')
753 if (strlen ($r) == 2)
756 { $output .= '</em>'; $state = ''; }
757 else if ($state == 'strongem')
758 { $output .= '</em>'; $state = 'strong'; }
759 else if ($state == 'emstrong')
760 { $output .= '</strong></em><strong>'; $state = 'strong'; }
761 else if ($state == 'both')
762 { $output .= '<strong><em>'.$buffer.'</em>'; $state = 'strong'; }
763 else # $state can be 'strong' or ''
764 { $output .= '<em>'; $state .= 'em'; }
766 else if (strlen ($r) == 3)
768 if ($state == 'strong')
769 { $output .= '</strong>'; $state = ''; }
770 else if ($state == 'strongem')
771 { $output .= '</em></strong><em>'; $state = 'em'; }
772 else if ($state == 'emstrong')
773 { $output .= '</strong>'; $state = 'em'; }
774 else if ($state == 'both')
775 { $output .= '<em><strong>'.$buffer.'</strong>'; $state = 'em'; }
776 else # $state can be 'em' or ''
777 { $output .= '<strong>'; $state .= 'strong'; }
779 else if (strlen ($r) == 5)
781 if ($state == 'strong')
782 { $output .= '</strong><em>'; $state = 'em'; }
783 else if ($state == 'em')
784 { $output .= '</em><strong>'; $state = 'strong'; }
785 else if ($state == 'strongem')
786 { $output .= '</em></strong>'; $state = ''; }
787 else if ($state == 'emstrong')
788 { $output .= '</strong></em>'; $state = ''; }
789 else if ($state == 'both')
790 { $output .= '<em><strong>'.$buffer.'</strong></em>'; $state = ''; }
791 else # ($state == '')
792 { $buffer = ''; $state = 'both'; }
797 # Now close all remaining tags. Notice that the order is important.
798 if ($state == 'strong' ||
$state == 'emstrong')
799 $output .= '</strong>';
800 if ($state == 'em' ||
$state == 'strongem' ||
$state == 'emstrong')
802 if ($state == 'strongem')
803 $output .= '</strong>';
804 if ($state == 'both')
805 $output .= '<strong><em>'.$buffer.'</em></strong>';
810 # Note: we have to do external links before the internal ones,
811 # and otherwise take great care in the order of things here, so
812 # that we don't end up interpreting some URLs twice.
814 /* private */ function replaceExternalLinks( $text ) {
815 $fname = 'Parser::replaceExternalLinks';
816 wfProfileIn( $fname );
818 $sk =& $this->mOptions
->getSkin();
819 $linktrail = wfMsg('linktrail');
820 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
822 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
825 while ( $i<count( $bits ) ) {
827 $protocol = $bits[$i++
];
829 $trail = $bits[$i++
];
831 # If the link text is an image URL, replace it with an <img> tag
832 # This happened by accident in the original parser, but some people used it extensively
833 $img = $this->maybeMakeImageLink( $text );
834 if ( $img !== false ) {
840 # No link text, e.g. [http://domain.tld/some.link]
842 # Autonumber if allowed
843 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
844 $text = '[' . ++
$this->mAutonumber
. ']';
846 # Otherwise just use the URL
847 $text = htmlspecialchars( $url );
850 # Have link text, e.g. [http://domain.tld/some.link text]s
852 if ( preg_match( $linktrail, $trail, $m2 ) ) {
858 $encUrl = htmlspecialchars( $url );
859 # Bit in parentheses showing the URL for the printable version
860 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
863 # Expand the URL for printable version
864 if ( ! $sk->suppressUrlExpansion() ) {
865 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
871 # Process the trail (i.e. everything after this link up until start of the next link),
872 # replacing any non-bracketed links
873 $trail = $this->replaceFreeExternalLinks( $trail );
875 $la = $sk->getExternalLinkAttributes( $url, $text );
877 # Use the encoded URL
878 # This means that users can paste URLs directly into the text
879 # Funny characters like ö aren't valid in URLs anyway
880 # This was changed in August 2004
881 $s .= "<a href=\"{$url}\" {$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
884 wfProfileOut( $fname );
888 # Replace anything that looks like a URL with a link
889 function replaceFreeExternalLinks( $text ) {
890 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
891 $s = array_shift( $bits );
894 $sk =& $this->mOptions
->getSkin();
896 while ( $i < count( $bits ) ){
897 $protocol = $bits[$i++
];
898 $remainder = $bits[$i++
];
900 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
901 # Found some characters after the protocol that look promising
902 $url = $protocol . $m[1];
905 # Move trailing punctuation to $trail
907 # If there is no left bracket, then consider right brackets fair game too
908 if ( strpos( $url, '(' ) === false ) {
912 $numSepChars = strspn( strrev( $url ), $sep );
913 if ( $numSepChars ) {
914 $trail = substr( $url, -$numSepChars ) . $trail;
915 $url = substr( $url, 0, -$numSepChars );
918 # Replace & from obsolete syntax with &
919 $url = str_replace( '&', '&', $url );
921 # Is this an external image?
922 $text = $this->maybeMakeImageLink( $url );
923 if ( $text === false ) {
924 # Not an image, make a link
925 $text = $sk->makeExternalLink( $url, $url );
927 $s .= $text . $trail;
929 $s .= $protocol . $remainder;
935 # make an image if it's allowed
936 function maybeMakeImageLink( $url ) {
937 $sk =& $this->mOptions
->getSkin();
939 if ( $this->mOptions
->getAllowExternalImages() ) {
940 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
942 $text = $sk->makeImage( htmlspecialchars( $url ) );
948 # The wikilinks [[ ]] are procedeed here.
949 /* private */ function replaceInternalLinks( $s ) {
950 global $wgLang, $wgLinkCache;
951 global $wgNamespacesWithSubpages, $wgLanguageCode;
952 static $fname = 'Parser::replaceInternalLinks' ;
953 wfProfileIn( $fname );
955 wfProfileIn( $fname.'-setup' );
957 # the % is needed to support urlencoded titles as well
958 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
959 $sk =& $this->mOptions
->getSkin();
961 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
963 $a = explode( '[[', ' ' . $s );
964 $s = array_shift( $a );
965 $s = substr( $s, 1 );
967 # Match a link having the form [[namespace:link|alternate]]trail
969 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
970 # Match the end of a line for a word that's not followed by whitespace,
971 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
972 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
974 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
975 # Special and Media are pseudo-namespaces; no pages actually exist in them
977 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
979 if ( $useLinkPrefixExtension ) {
980 if ( preg_match( $e2, $s, $m ) ) {
981 $first_prefix = $m[2];
984 $first_prefix = false;
990 wfProfileOut( $fname.'-setup' );
992 # start procedeeding each line
993 foreach ( $a as $line ) {
994 wfProfileIn( $fname.'-prefixhandling' );
995 if ( $useLinkPrefixExtension ) {
996 if ( preg_match( $e2, $s, $m ) ) {
1004 $prefix = $first_prefix;
1005 $first_prefix = false;
1008 wfProfileOut( $fname.'-prefixhandling' );
1010 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1012 # fix up urlencoded title texts
1013 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1015 } else { # Invalid form; output directly
1016 $s .= $prefix . '[[' . $line ;
1022 # :Foobar -- override special treatment of prefix (images, language links)
1023 # /Foobar -- convert to CurrentPage/Foobar
1024 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1026 # Look at the first character
1027 $c = substr($m[1],0,1);
1028 $noforce = ($c != ':');
1032 # / at end means we don't want the slash to be shown
1033 if(substr($m[1],-1,1)=='/') {
1034 $m[1]=substr($m[1],1,strlen($m[1])-2);
1037 $noslash=substr($m[1],1);
1040 # Some namespaces don't allow subpages
1041 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) {
1042 # subpages allowed here
1043 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1046 } # this might be changed for ugliness reasons
1048 # no subpage allowed, use standard link
1052 } elseif( $noforce ) { # no subpage
1055 # We don't want to keep the first character
1056 $link = substr( $m[1], 1 );
1059 $wasblank = ( '' == $text );
1060 if( $wasblank ) $text = $link;
1062 $nt = Title
::newFromText( $link );
1064 $s .= $prefix . '[[' . $line;
1068 $ns = $nt->getNamespace();
1069 $iw = $nt->getInterWiki();
1071 # Link not escaped by : , create the various objects
1075 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1076 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1077 $tmp = $prefix . $trail ;
1078 $s .= (trim($tmp) == '')?
'': $tmp;
1082 if ( $ns == NS_IMAGE
) {
1083 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1084 $wgLinkCache->addImageLinkObj( $nt );
1088 if ( $ns == NS_CATEGORY
) {
1089 $t = $nt->getText() ;
1090 $nnt = Title
::newFromText ( Namespace::getCanonicalName(NS_CATEGORY
).':'.$t ) ;
1092 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1093 $pPLC=$sk->postParseLinkColour();
1094 $sk->postParseLinkColour( false );
1095 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1096 $sk->postParseLinkColour( $pPLC );
1097 $wgLinkCache->resume();
1099 $sortkey = $wasblank ?
$this->mTitle
->getPrefixedText() : $text;
1100 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1101 $this->mOutput
->mCategoryLinks
[] = $t ;
1102 $s .= $prefix . $trail ;
1107 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
1108 ( strpos( $link, '#' ) == FALSE ) ) {
1109 # Self-links are handled specially; generally de-link and change to bold.
1110 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1114 if( $ns == NS_MEDIA
) {
1115 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1116 $wgLinkCache->addImageLinkObj( $nt );
1118 } elseif( $ns == NS_SPECIAL
) {
1119 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1122 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1124 wfProfileOut( $fname );
1128 # Some functions here used by doBlockLevels()
1130 /* private */ function closeParagraph() {
1132 if ( '' != $this->mLastSection
) {
1133 $result = '</' . $this->mLastSection
. ">\n";
1135 $this->mInPre
= false;
1136 $this->mLastSection
= '';
1139 # getCommon() returns the length of the longest common substring
1140 # of both arguments, starting at the beginning of both.
1142 /* private */ function getCommon( $st1, $st2 ) {
1143 $fl = strlen( $st1 );
1144 $shorter = strlen( $st2 );
1145 if ( $fl < $shorter ) { $shorter = $fl; }
1147 for ( $i = 0; $i < $shorter; ++
$i ) {
1148 if ( $st1{$i} != $st2{$i} ) { break; }
1152 # These next three functions open, continue, and close the list
1153 # element appropriate to the prefix character passed into them.
1155 /* private */ function openList( $char ) {
1156 $result = $this->closeParagraph();
1158 if ( '*' == $char ) { $result .= '<ul><li>'; }
1159 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1160 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1161 else if ( ';' == $char ) {
1162 $result .= '<dl><dt>';
1163 $this->mDTopen
= true;
1165 else { $result = '<!-- ERR 1 -->'; }
1170 /* private */ function nextItem( $char ) {
1171 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1172 else if ( ':' == $char ||
';' == $char ) {
1174 if ( $this->mDTopen
) { $close = '</dt>'; }
1175 if ( ';' == $char ) {
1176 $this->mDTopen
= true;
1177 return $close . '<dt>';
1179 $this->mDTopen
= false;
1180 return $close . '<dd>';
1183 return '<!-- ERR 2 -->';
1186 /* private */ function closeList( $char ) {
1187 if ( '*' == $char ) { $text = '</li></ul>'; }
1188 else if ( '#' == $char ) { $text = '</li></ol>'; }
1189 else if ( ':' == $char ) {
1190 if ( $this->mDTopen
) {
1191 $this->mDTopen
= false;
1192 $text = '</dt></dl>';
1194 $text = '</dd></dl>';
1197 else { return '<!-- ERR 3 -->'; }
1201 /* private */ function doBlockLevels( $text, $linestart ) {
1202 $fname = 'Parser::doBlockLevels';
1203 wfProfileIn( $fname );
1205 # Parsing through the text line by line. The main thing
1206 # happening here is handling of block-level elements p, pre,
1207 # and making lists from lines starting with * # : etc.
1209 $textLines = explode( "\n", $text );
1211 $lastPrefix = $output = $lastLine = '';
1212 $this->mDTopen
= $inBlockElem = false;
1214 $paragraphStack = false;
1216 if ( !$linestart ) {
1217 $output .= array_shift( $textLines );
1219 foreach ( $textLines as $oLine ) {
1220 $lastPrefixLength = strlen( $lastPrefix );
1221 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1222 $preOpenMatch = preg_match('/<pre/i', $oLine );
1223 if ( !$this->mInPre
) {
1224 # Multiple prefixes may abut each other for nested lists.
1225 $prefixLength = strspn( $oLine, '*#:;' );
1226 $pref = substr( $oLine, 0, $prefixLength );
1229 $pref2 = str_replace( ';', ':', $pref );
1230 $t = substr( $oLine, $prefixLength );
1231 $this->mInPre
= !empty($preOpenMatch);
1233 # Don't interpret any other prefixes in preformatted text
1235 $pref = $pref2 = '';
1240 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1241 # Same as the last item, so no need to deal with nesting or opening stuff
1242 $output .= $this->nextItem( substr( $pref, -1 ) );
1243 $paragraphStack = false;
1245 if ( substr( $pref, -1 ) == ';') {
1246 # The one nasty exception: definition lists work like this:
1247 # ; title : definition text
1248 # So we check for : in the remainder text to split up the
1249 # title and definition, without b0rking links.
1250 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1251 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1253 $output .= $term . $this->nextItem( ':' );
1257 } elseif( $prefixLength ||
$lastPrefixLength ) {
1258 # Either open or close a level...
1259 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1260 $paragraphStack = false;
1262 while( $commonPrefixLength < $lastPrefixLength ) {
1263 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1264 --$lastPrefixLength;
1266 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1267 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1269 while ( $prefixLength > $commonPrefixLength ) {
1270 $char = substr( $pref, $commonPrefixLength, 1 );
1271 $output .= $this->openList( $char );
1273 if ( ';' == $char ) {
1274 # FIXME: This is dupe of code above
1275 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1277 $output .= $term . $this->nextItem( ':' );
1281 ++
$commonPrefixLength;
1283 $lastPrefix = $pref2;
1285 if( 0 == $prefixLength ) {
1286 # No prefix (not in list)--go to paragraph mode
1287 $uniq_prefix = UNIQ_PREFIX
;
1288 // XXX: use a stack for nestable elements like span, table and div
1289 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1290 $closematch = preg_match(
1291 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1292 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1293 if ( $openmatch or $closematch ) {
1294 $paragraphStack = false;
1295 $output .= $this->closeParagraph();
1296 if($preOpenMatch and !$preCloseMatch) {
1297 $this->mInPre
= true;
1299 if ( $closematch ) {
1300 $inBlockElem = false;
1302 $inBlockElem = true;
1304 } else if ( !$inBlockElem && !$this->mInPre
) {
1305 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1307 if ($this->mLastSection
!= 'pre') {
1308 $paragraphStack = false;
1309 $output .= $this->closeParagraph().'<pre>';
1310 $this->mLastSection
= 'pre';
1314 if ( '' == trim($t) ) {
1315 if ( $paragraphStack ) {
1316 $output .= $paragraphStack.'<br />';
1317 $paragraphStack = false;
1318 $this->mLastSection
= 'p';
1320 if ($this->mLastSection
!= 'p' ) {
1321 $output .= $this->closeParagraph();
1322 $this->mLastSection
= '';
1323 $paragraphStack = '<p>';
1325 $paragraphStack = '</p><p>';
1329 if ( $paragraphStack ) {
1330 $output .= $paragraphStack;
1331 $paragraphStack = false;
1332 $this->mLastSection
= 'p';
1333 } else if ($this->mLastSection
!= 'p') {
1334 $output .= $this->closeParagraph().'<p>';
1335 $this->mLastSection
= 'p';
1341 if ($paragraphStack === false) {
1345 while ( $prefixLength ) {
1346 $output .= $this->closeList( $pref2{$prefixLength-1} );
1349 if ( '' != $this->mLastSection
) {
1350 $output .= '</' . $this->mLastSection
. '>';
1351 $this->mLastSection
= '';
1354 wfProfileOut( $fname );
1358 # Return value of a magic variable (like PAGENAME)
1359 function getVariableValue( $index ) {
1360 global $wgLang, $wgSitename, $wgServer;
1363 case MAG_CURRENTMONTH
:
1364 return $wgLang->formatNum( date( 'm' ) );
1365 case MAG_CURRENTMONTHNAME
:
1366 return $wgLang->getMonthName( date('n') );
1367 case MAG_CURRENTMONTHNAMEGEN
:
1368 return $wgLang->getMonthNameGen( date('n') );
1369 case MAG_CURRENTDAY
:
1370 return $wgLang->formatNum( date('j') );
1372 return $this->mTitle
->getText();
1374 return $this->mTitle
->getPartialURL();
1376 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1377 return $wgLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1378 case MAG_CURRENTDAYNAME
:
1379 return $wgLang->getWeekdayName( date('w')+
1 );
1380 case MAG_CURRENTYEAR
:
1381 return $wgLang->formatNum( date( 'Y' ) );
1382 case MAG_CURRENTTIME
:
1383 return $wgLang->time( wfTimestampNow(), false );
1384 case MAG_NUMBEROFARTICLES
:
1385 return $wgLang->formatNum( wfNumberOfArticles() );
1395 # initialise the magic variables (like CURRENTMONTHNAME)
1396 function initialiseVariables() {
1397 global $wgVariableIDs;
1398 $this->mVariables
= array();
1399 foreach ( $wgVariableIDs as $id ) {
1400 $mw =& MagicWord
::get( $id );
1401 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1405 /* private */ function replaceVariables( $text, $args = array() ) {
1406 global $wgLang, $wgScript, $wgArticlePath;
1408 # Prevent too big inclusions
1409 if(strlen($text)> MAX_INCLUDE_SIZE
)
1412 $fname = 'Parser::replaceVariables';
1413 wfProfileIn( $fname );
1416 $titleChars = Title
::legalChars();
1417 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1419 # This function is called recursively. To keep track of arguments we need a stack:
1420 array_push( $this->mArgStack
, $args );
1422 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1423 $GLOBALS['wgCurParser'] =& $this;
1426 if ( $this->mOutputType
== OT_HTML
) {
1427 # Variable substitution
1428 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1430 # Argument substitution
1431 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1433 # Template substitution
1434 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1435 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1437 array_pop( $this->mArgStack
);
1439 wfProfileOut( $fname );
1443 function variableSubstitution( $matches ) {
1444 if ( !$this->mVariables
) {
1445 $this->initialiseVariables();
1447 if ( array_key_exists( $matches[1], $this->mVariables
) ) {
1448 $text = $this->mVariables
[$matches[1]];
1449 $this->mOutput
->mContainsOldMagic
= true;
1451 $text = $matches[0];
1456 # Split template arguments
1457 function getTemplateArgs( $argsString ) {
1458 if ( $argsString === '' ) {
1462 $args = explode( '|', substr( $argsString, 1 ) );
1464 # If any of the arguments contains a '[[' but no ']]', it needs to be
1465 # merged with the next arg because the '|' character between belongs
1466 # to the link syntax and not the template parameter syntax.
1467 $argc = count($args);
1469 for ( $i = 0; $i < $argc-1; $i++
) {
1470 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1471 $args[$i] .= '|'.$args[$i+
1];
1472 array_splice($args, $i+
1, 1);
1481 function braceSubstitution( $matches ) {
1482 global $wgLinkCache, $wgLang;
1483 $fname = 'Parser::braceSubstitution';
1490 # $newline is an optional newline character before the braces
1491 # $part1 is the bit before the first |, and must contain only title characters
1492 # $args is a list of arguments, starting from index 0, not including $part1
1494 $newline = $matches[1];
1495 $part1 = $matches[2];
1496 # If the third subpattern matched anything, it will start with |
1498 $args = $this->getTemplateArgs($matches[3]);
1499 $argc = count( $args );
1502 if ( strpos( $matches[0], '{{{' ) !== false ) {
1503 $text = $matches[0];
1510 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1511 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1512 if ( $this->mOutputType
!= OT_WIKI
) {
1513 # Invalid SUBST not replaced at PST time
1514 # Return without further processing
1515 $text = $matches[0];
1519 } elseif ( $this->mOutputType
== OT_WIKI
) {
1520 # SUBST not found in PST pass, do nothing
1521 $text = $matches[0];
1526 # MSG, MSGNW and INT
1529 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1530 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1533 # Remove obsolete MSG:
1534 $mwMsg =& MagicWord
::get( MAG_MSG
);
1535 $mwMsg->matchStartAndRemove( $part1 );
1538 # Check if it is an internal message
1539 $mwInt =& MagicWord
::get( MAG_INT
);
1540 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1541 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1542 $text = wfMsgReal( $part1, $args, true );
1550 # Check for NS: (namespace expansion)
1551 $mwNs = MagicWord
::get( MAG_NS
);
1552 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1553 if ( intval( $part1 ) ) {
1554 $text = $wgLang->getNsText( intval( $part1 ) );
1557 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1558 if ( !is_null( $index ) ) {
1559 $text = $wgLang->getNsText( $index );
1566 # LOCALURL and LOCALURLE
1568 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1569 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1571 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1572 $func = 'getLocalURL';
1573 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1574 $func = 'escapeLocalURL';
1579 if ( $func !== '' ) {
1580 $title = Title
::newFromText( $part1 );
1581 if ( !is_null( $title ) ) {
1583 $text = $title->$func( $args[0] );
1585 $text = $title->$func();
1592 # Internal variables
1593 if ( !$this->mVariables
) {
1594 $this->initialiseVariables();
1596 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1597 $text = $this->mVariables
[$part1];
1599 $this->mOutput
->mContainsOldMagic
= true;
1602 # Template table test
1604 # Did we encounter this template already? If yes, it is in the cache
1605 # and we need to check for loops.
1606 if ( isset( $this->mTemplates
[$part1] ) ) {
1607 # Infinite loop test
1608 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1612 # set $text to cached message.
1613 $text = $this->mTemplates
[$part1];
1617 # Load from database
1619 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1620 if ( !is_null( $title ) && !$title->isExternal() ) {
1621 # Check for excessive inclusion
1622 $dbk = $title->getPrefixedDBkey();
1623 if ( $this->incrementIncludeCount( $dbk ) ) {
1624 # This should never be reached.
1625 $article = new Article( $title );
1626 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1627 if ( $articleContent !== false ) {
1629 $text = $articleContent;
1633 # If the title is valid but undisplayable, make a link to it
1634 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1635 $text = '[['.$title->getPrefixedText().']]';
1639 # Template cache array insertion
1640 $this->mTemplates
[$part1] = $text;
1644 # Recursive parsing, escaping and link table handling
1645 # Only for HTML output
1646 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1647 $text = wfEscapeWikiText( $text );
1648 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1649 # Clean up argument array
1650 $assocArgs = array();
1652 foreach( $args as $arg ) {
1653 $eqpos = strpos( $arg, '=' );
1654 if ( $eqpos === false ) {
1655 $assocArgs[$index++
] = $arg;
1657 $name = trim( substr( $arg, 0, $eqpos ) );
1658 $value = trim( substr( $arg, $eqpos+
1 ) );
1659 if ( $value === false ) {
1662 if ( $name !== false ) {
1663 $assocArgs[$name] = $value;
1668 # Do not enter included links in link table
1669 if ( !is_null( $title ) ) {
1670 $wgLinkCache->suspend();
1673 # Add a new element to the templace recursion path
1674 $this->mTemplatePath
[$part1] = 1;
1676 $text = $this->stripParse( $text, $newline, $assocArgs );
1678 # Resume the link cache and register the inclusion as a link
1679 if ( !is_null( $title ) ) {
1680 $wgLinkCache->resume();
1681 $wgLinkCache->addLinkObj( $title );
1684 # Empties the template path
1685 $this->mTemplatePath
= array();
1694 # Triple brace replacement -- used for template arguments
1695 function argSubstitution( $matches ) {
1696 $newline = $matches[1];
1697 $arg = trim( $matches[2] );
1698 $text = $matches[0];
1699 $inputArgs = end( $this->mArgStack
);
1701 if ( array_key_exists( $arg, $inputArgs ) ) {
1702 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1708 # Returns true if the function is allowed to include this entity
1709 function incrementIncludeCount( $dbk ) {
1710 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1711 $this->mIncludeCount
[$dbk] = 0;
1713 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1721 # Cleans up HTML, removes dangerous tags and attributes
1722 /* private */ function removeHTMLtags( $text ) {
1723 global $wgUseTidy, $wgUserHtml;
1724 $fname = 'Parser::removeHTMLtags';
1725 wfProfileIn( $fname );
1728 $htmlpairs = array( # Tags that must be closed
1729 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1730 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1731 'strike', 'strong', 'tt', 'var', 'div', 'center',
1732 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1733 'ruby', 'rt' , 'rb' , 'rp', 'p'
1735 $htmlsingle = array(
1736 'br', 'hr', 'li', 'dt', 'dd'
1738 $htmlnest = array( # Tags that can be nested--??
1739 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1740 'dl', 'font', 'big', 'small', 'sub', 'sup'
1742 $tabletags = array( # Can only appear inside table
1746 $htmlpairs = array();
1747 $htmlsingle = array();
1748 $htmlnest = array();
1749 $tabletags = array();
1752 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1753 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1755 $htmlattrs = $this->getHTMLattrs () ;
1757 # Remove HTML comments
1758 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1760 $bits = explode( '<', $text );
1761 $text = array_shift( $bits );
1763 $tagstack = array(); $tablestack = array();
1764 foreach ( $bits as $x ) {
1765 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1766 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1768 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1769 error_reporting( $prev );
1772 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1776 if ( ! in_array( $t, $htmlsingle ) &&
1777 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
1778 @array_push
( $tagstack, $ot );
1781 if ( $t == 'table' ) {
1782 $tagstack = array_pop( $tablestack );
1787 # Keep track for later
1788 if ( in_array( $t, $tabletags ) &&
1789 ! in_array( 'table', $tagstack ) ) {
1791 } else if ( in_array( $t, $tagstack ) &&
1792 ! in_array ( $t , $htmlnest ) ) {
1794 } else if ( ! in_array( $t, $htmlsingle ) ) {
1795 if ( $t == 'table' ) {
1796 array_push( $tablestack, $tagstack );
1797 $tagstack = array();
1799 array_push( $tagstack, $t );
1801 # Strip non-approved attributes from the tag
1802 $newparams = $this->fixTagAttributes($params);
1806 $rest = str_replace( '>', '>', $rest );
1807 $text .= "<$slash$t $newparams$brace$rest";
1811 $text .= '<' . str_replace( '>', '>', $x);
1813 # Close off any remaining tags
1814 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1816 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1819 # this might be possible using tidy itself
1820 foreach ( $bits as $x ) {
1821 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1823 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1824 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1825 $newparams = $this->fixTagAttributes($params);
1826 $rest = str_replace( '>', '>', $rest );
1827 $text .= "<$slash$t $newparams$brace$rest";
1829 $text .= '<' . str_replace( '>', '>', $x);
1833 wfProfileOut( $fname );
1838 # This function accomplishes several tasks:
1839 # 1) Auto-number headings if that option is enabled
1840 # 2) Add an [edit] link to sections for logged in users who have enabled the option
1841 # 3) Add a Table of contents on the top for users who have enabled the option
1842 # 4) Auto-anchor headings
1844 # It loops through all headlines, collects the necessary data, then splits up the
1845 # string and re-inserts the newly formatted headlines.
1846 /* private */ function formatHeadings( $text, $isMain=true ) {
1847 global $wgInputEncoding, $wgMaxTocLevel;
1848 #print "<pre>{$text}</pre>\n";
1850 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1851 $doShowToc = $this->mOptions
->getShowToc();
1852 $forceTocHere = false;
1853 if( !$this->mTitle
->userCanEdit() ) {
1855 $rightClickHack = 0;
1857 $showEditLink = $this->mOptions
->getEditSection();
1858 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1861 # Inhibit editsection links if requested in the page
1862 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1863 if( $esw->matchAndRemove( $text ) ) {
1866 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1868 $mw =& MagicWord
::get( MAG_NOTOC
);
1869 if( $mw->matchAndRemove( $text ) ) {
1873 # never add the TOC to the Main Page. This is an entry page that should not
1874 # be more than 1-2 screens large anyway
1875 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
1879 # Get all headlines for numbering them and adding funky stuff like [edit]
1880 # links - this is for later, but we need the number of headlines right now
1881 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1883 # if there are fewer than 4 headlines in the article, do not show TOC
1884 if( $numMatches < 4 ) {
1888 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
1889 # override above conditions and always show TOC at that place
1890 $mw =& MagicWord
::get( MAG_TOC
);
1891 if ($mw->match( $text ) ) {
1893 $forceTocHere = true;
1895 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1896 # override above conditions and always show TOC above first header
1897 $mw =& MagicWord
::get( MAG_FORCETOC
);
1898 if ($mw->matchAndRemove( $text ) ) {
1905 # We need this to perform operations on the HTML
1906 $sk =& $this->mOptions
->getSkin();
1911 # Ugh .. the TOC should have neat indentation levels which can be
1912 # passed to the skin functions. These are determined here
1917 $sublevelCount = array();
1920 foreach( $matches[3] as $headline ) {
1923 $prevlevel = $level;
1925 $level = $matches[1][$headlineCount];
1926 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1927 # reset when we enter a new level
1928 $sublevelCount[$level] = 0;
1929 $toc .= $sk->tocIndent( $level - $prevlevel );
1930 $toclevel +
= $level - $prevlevel;
1932 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1933 # reset when we step back a level
1934 $sublevelCount[$level+
1]=0;
1935 $toc .= $sk->tocUnindent( $prevlevel - $level );
1936 $toclevel -= $prevlevel - $level;
1938 # count number of headlines for each level
1939 @$sublevelCount[$level]++
;
1940 if( $doNumberHeadings ||
$doShowToc ) {
1942 for( $i = 1; $i <= $level; $i++
) {
1943 if( !empty( $sublevelCount[$i] ) ) {
1947 $numbering .= $sublevelCount[$i];
1953 # The canonized header is a version of the header text safe to use for links
1954 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1955 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
1956 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
1958 # Remove link placeholders by the link text.
1959 # <!--LINK namespace page_title link text with suffix-->
1961 # link text with suffix
1962 $canonized_headline = preg_replace( '/<!--LINK [0-9]* [^ ]* *(.*?)-->/','$1', $canonized_headline );
1964 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
1965 $tocline = trim( $canonized_headline );
1966 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
1967 $replacearray = array(
1971 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
1972 $refer[$headlineCount] = $canonized_headline;
1974 # count how many in assoc. array so we can track dupes in anchors
1975 @$refers[$canonized_headline]++
;
1976 $refcount[$headlineCount]=$refers[$canonized_headline];
1978 # Prepend the number to the heading text
1980 if( $doNumberHeadings ||
$doShowToc ) {
1981 $tocline = $numbering . ' ' . $tocline;
1983 # Don't number the heading if it is the only one (looks silly)
1984 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1985 # the two are different if the line contains a link
1986 $headline=$numbering . ' ' . $headline;
1990 # Create the anchor for linking from the TOC to the section
1991 $anchor = $canonized_headline;
1992 if($refcount[$headlineCount] > 1 ) {
1993 $anchor .= '_' . $refcount[$headlineCount];
1995 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
1996 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1998 if( $showEditLink ) {
1999 if ( empty( $head[$headlineCount] ) ) {
2000 $head[$headlineCount] = '';
2002 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
2005 # Add the edit section span
2006 if( $rightClickHack ) {
2007 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
2010 # give headline the correct <h#> tag
2011 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2017 $toclines = $headlineCount;
2018 $toc .= $sk->tocUnindent( $toclevel );
2019 $toc = $sk->tocTable( $toc );
2022 # split up and insert constructed headlines
2024 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2027 foreach( $blocks as $block ) {
2028 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2029 # This is the [edit] link that appears for the top block of text when
2030 # section editing is enabled
2032 # Disabled because it broke block formatting
2033 # For example, a bullet point in the top line
2034 # $full .= $sk->editSectionLink(0);
2037 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2038 # Top anchor now in skin
2042 if( !empty( $head[$i] ) ) {
2048 $mw =& MagicWord
::get( MAG_TOC
);
2049 return $mw->replace( $toc, $full );
2055 # Return an HTML link for the "ISBN 123456" text
2056 /* private */ function magicISBN( $text ) {
2058 $fname = 'Parser::magicISBN';
2059 wfProfileIn( $fname );
2061 $a = split( 'ISBN ', ' '.$text );
2062 if ( count ( $a ) < 2 ) {
2063 wfProfileOut( $fname );
2066 $text = substr( array_shift( $a ), 1);
2067 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2069 foreach ( $a as $x ) {
2070 $isbn = $blank = '' ;
2071 while ( ' ' == $x{0} ) {
2073 $x = substr( $x, 1 );
2075 while ( strstr( $valid, $x{0} ) != false ) {
2077 $x = substr( $x, 1 );
2079 $num = str_replace( '-', '', $isbn );
2080 $num = str_replace( ' ', '', $num );
2083 $text .= "ISBN $blank$x";
2085 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2086 $text .= '<a href="' .
2087 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2088 "\" class=\"internal\">ISBN $isbn</a>";
2092 wfProfileOut( $fname );
2096 # Return an HTML link for the "GEO ..." text
2097 /* private */ function magicGEO( $text ) {
2098 global $wgLang, $wgUseGeoMode;
2099 $fname = 'Parser::magicGEO';
2100 wfProfileIn( $fname );
2102 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2103 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2104 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2105 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2106 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2107 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2109 $a = split( 'GEO ', ' '.$text );
2110 if ( count ( $a ) < 2 ) {
2111 wfProfileOut( $fname );
2114 $text = substr( array_shift( $a ), 1);
2115 $valid = '0123456789.+-:';
2117 foreach ( $a as $x ) {
2118 $geo = $blank = '' ;
2119 while ( ' ' == $x{0} ) {
2121 $x = substr( $x, 1 );
2123 while ( strstr( $valid, $x{0} ) != false ) {
2125 $x = substr( $x, 1 );
2127 $num = str_replace( '+', '', $geo );
2128 $num = str_replace( ' ', '', $num );
2130 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2131 $text .= "GEO $blank$x";
2133 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2134 $text .= '<a href="' .
2135 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2136 "\" class=\"internal\">GEO $geo</a>";
2140 wfProfileOut( $fname );
2144 # Return an HTML link for the "RFC 1234" text
2145 /* private */ function magicRFC( $text ) {
2148 $a = split( 'RFC ', ' '.$text );
2149 if ( count ( $a ) < 2 ) return $text;
2150 $text = substr( array_shift( $a ), 1);
2151 $valid = '0123456789';
2153 foreach ( $a as $x ) {
2154 $rfc = $blank = '' ;
2155 while ( ' ' == $x{0} ) {
2157 $x = substr( $x, 1 );
2159 while ( strstr( $valid, $x{0} ) != false ) {
2161 $x = substr( $x, 1 );
2165 $text .= "RFC $blank$x";
2167 $url = wfmsg( 'rfcurl' );
2168 $url = str_replace( '$1', $rfc, $url);
2169 $sk =& $this->mOptions
->getSkin();
2170 $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
2171 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2177 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2178 $this->mOptions
= $options;
2179 $this->mTitle
=& $title;
2180 $this->mOutputType
= OT_WIKI
;
2182 if ( $clearState ) {
2183 $this->clearState();
2186 $stripState = false;
2190 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2194 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2195 "/<br *?>/i" => "<br />",
2197 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2199 $text = $this->strip( $text, $stripState, false );
2200 $text = $this->pstPass2( $text, $user );
2201 $text = $this->unstrip( $text, $stripState );
2202 $text = $this->unstripNoWiki( $text, $stripState );
2206 /* private */ function pstPass2( $text, &$user ) {
2207 global $wgLang, $wgLocaltimezone, $wgCurParser;
2209 # Variable replacement
2210 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2211 $text = $this->replaceVariables( $text );
2215 $n = $user->getName();
2216 $k = $user->getOption( 'nickname' );
2217 if ( '' == $k ) { $k = $n; }
2218 if(isset($wgLocaltimezone)) {
2219 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2221 /* Note: this is an ugly timezone hack for the European wikis */
2222 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2223 ' (' . date( 'T' ) . ')';
2224 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2226 $text = preg_replace( '/~~~~~/', $d, $text );
2227 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2228 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2230 # Context links: [[|name]] and [[name (context)|]]
2232 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2233 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2234 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2235 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2237 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2238 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2239 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2240 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2241 # [[ns:page (cont)|]]
2243 $t = $this->mTitle
->getText();
2244 if ( preg_match( $conpat, $t, $m ) ) {
2247 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2248 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2249 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2251 if ( '' == $context ) {
2252 $text = preg_replace( $p2, '[[\\1]]', $text );
2254 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2258 $mw =& MagicWord::get( MAG_SUBST );
2259 $wgCurParser = $this->fork();
2260 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2261 $this->merge( $wgCurParser );
2264 # Trim trailing whitespace
2265 # MAG_END (__END__) tag allows for trailing
2266 # whitespace to be deliberately included
2267 $text = rtrim( $text );
2268 $mw =& MagicWord
::get( MAG_END
);
2269 $mw->matchAndRemove( $text );
2274 # Set up some variables which are usually set up in parse()
2275 # so that an external function can call some class members with confidence
2276 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2277 $this->mTitle
=& $title;
2278 $this->mOptions
= $options;
2279 $this->mOutputType
= $outputType;
2280 if ( $clearState ) {
2281 $this->clearState();
2285 function transformMsg( $text, $options ) {
2287 static $executing = false;
2289 # Guard against infinite recursion
2295 $this->mTitle
= $wgTitle;
2296 $this->mOptions
= $options;
2297 $this->mOutputType
= OT_MSG
;
2298 $this->clearState();
2299 $text = $this->replaceVariables( $text );
2305 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2306 # Callback will be called with the text within
2307 # Transform and return the text within
2308 function setHook( $tag, $callback ) {
2309 $oldVal = @$this->mTagHooks
[$tag];
2310 $this->mTagHooks
[$tag] = $callback;
2317 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2318 var $mCacheTime; # Used in ParserCache
2320 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2321 $containsOldMagic = false )
2323 $this->mText
= $text;
2324 $this->mLanguageLinks
= $languageLinks;
2325 $this->mCategoryLinks
= $categoryLinks;
2326 $this->mContainsOldMagic
= $containsOldMagic;
2327 $this->mCacheTime
= '';
2330 function getText() { return $this->mText
; }
2331 function getLanguageLinks() { return $this->mLanguageLinks
; }
2332 function getCategoryLinks() { return $this->mCategoryLinks
; }
2333 function getCacheTime() { return $this->mCacheTime
; }
2334 function containsOldMagic() { return $this->mContainsOldMagic
; }
2335 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2336 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2337 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2338 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2339 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2341 function merge( $other ) {
2342 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2343 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2344 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2351 # All variables are private
2352 var $mUseTeX; # Use texvc to expand <math> tags
2353 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2354 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2355 var $mAllowExternalImages; # Allow external images inline
2356 var $mSkin; # Reference to the preferred skin
2357 var $mDateFormat; # Date format index
2358 var $mEditSection; # Create "edit section" links
2359 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2360 var $mNumberHeadings; # Automatically number headings
2361 var $mShowToc; # Show table of contents
2363 function getUseTeX() { return $this->mUseTeX
; }
2364 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2365 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2366 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2367 function getSkin() { return $this->mSkin
; }
2368 function getDateFormat() { return $this->mDateFormat
; }
2369 function getEditSection() { return $this->mEditSection
; }
2370 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2371 function getNumberHeadings() { return $this->mNumberHeadings
; }
2372 function getShowToc() { return $this->mShowToc
; }
2374 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2375 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2376 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2377 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2378 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2379 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2380 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2381 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2382 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2384 function setSkin( &$x ) { $this->mSkin
=& $x; }
2386 # Get parser options
2387 /* static */ function newFromUser( &$user ) {
2388 $popts = new ParserOptions
;
2389 $popts->initialiseFromUser( $user );
2394 function initialiseFromUser( &$userInput ) {
2395 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2397 $fname = 'ParserOptions::initialiseFromUser';
2398 wfProfileIn( $fname );
2399 if ( !$userInput ) {
2401 $user->setLoaded( true );
2403 $user =& $userInput;
2406 $this->mUseTeX
= $wgUseTeX;
2407 $this->mUseDynamicDates
= $wgUseDynamicDates;
2408 $this->mInterwikiMagic
= $wgInterwikiMagic;
2409 $this->mAllowExternalImages
= $wgAllowExternalImages;
2410 wfProfileIn( $fname.'-skin' );
2411 $this->mSkin
=& $user->getSkin();
2412 wfProfileOut( $fname.'-skin' );
2413 $this->mDateFormat
= $user->getOption( 'date' );
2414 $this->mEditSection
= $user->getOption( 'editsection' );
2415 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2416 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2417 $this->mShowToc
= $user->getOption( 'showtoc' );
2418 wfProfileOut( $fname );
2424 # Regex callbacks, used in Parser::replaceVariables
2425 function wfBraceSubstitution( $matches ) {
2426 global $wgCurParser;
2427 return $wgCurParser->braceSubstitution( $matches );
2430 function wfArgSubstitution( $matches ) {
2431 global $wgCurParser;
2432 return $wgCurParser->argSubstitution( $matches );
2435 function wfVariableSubstitution( $matches ) {
2436 global $wgCurParser;
2437 return $wgCurParser->variableSubstitution( $matches );
2440 # Return the total number of articles
2441 function wfNumberOfArticles() {
2442 global $wgNumberOfArticles;
2445 return $wgNumberOfArticles;
2448 # Get various statistics from the database
2449 /* private */ function wfLoadSiteStats() {
2450 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2451 $fname = 'wfLoadSiteStats';
2453 if ( -1 != $wgNumberOfArticles ) return;
2454 $dbr =& wfGetDB( DB_SLAVE
);
2455 $s = $dbr->getArray( 'site_stats',
2456 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2457 array( 'ss_row_id' => 1 ), $fname
2460 if ( $s === false ) {
2463 $wgTotalViews = $s->ss_total_views
;
2464 $wgTotalEdits = $s->ss_total_edits
;
2465 $wgNumberOfArticles = $s->ss_good_articles
;
2469 function wfEscapeHTMLTagsOnly( $in ) {
2471 array( '"', '>', '<' ),
2472 array( '"', '>', '<' ),