870ed18e62a612b363707820142dab4b72a6ae4c
3 // require_once('Tokenizer.php');
8 * Processes wiki markup
10 * There are two main entry points into the Parser class:
12 * produces HTML output
14 * produces altered wiki markup.
17 * objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
19 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
22 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
23 * $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
26 * * only within ParserOptions
32 * Variable substitution O(N^2) attack
34 * Without countermeasures, it would be possible to attack the parser by saving
35 * a page filled with a large number of inclusions of large pages. The size of
36 * the generated page would be proportional to the square of the input size.
37 * Hence, we limit the number of inclusions of any given page, thus bringing any
38 * attack back to O(N).
40 define( 'MAX_INCLUDE_REPEAT', 100 );
41 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
43 # Allowed values for $mOutputType
44 define( 'OT_HTML', 1 );
45 define( 'OT_WIKI', 2 );
46 define( 'OT_MSG' , 3 );
48 # string parameter for extractTags which will cause it
49 # to strip HTML comments in addition to regular
50 # <XML>-style tags. This should not be anything we
51 # may want to use in wikisyntax
52 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
54 # prefix for escaping, used in two functions at least
55 define( 'UNIQ_PREFIX', 'NaodW29');
57 # Constants needed for external link processing
58 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
59 define( 'HTTP_PROTOCOLS', 'http|https' );
60 # Everything except bracket, space, or control characters
61 define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
62 define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
64 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
65 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
66 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
67 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
68 define( 'EXT_IMAGE_REGEX',
69 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
70 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
71 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
83 # Cleared with clearState():
84 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
85 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
88 var $mOptions, $mTitle, $mOutputType,
89 $mTemplates, // cache of already loaded templates, avoids
90 // multiple SQL queries for the same string
91 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
92 // in this path. Used for loop detection.
95 $this->mTemplates
= array();
96 $this->mTemplatePath
= array();
97 $this->mTagHooks
= array();
101 function clearState() {
102 $this->mOutput
= new ParserOutput
;
103 $this->mAutonumber
= 0;
104 $this->mLastSection
= "";
105 $this->mDTopen
= false;
106 $this->mVariables
= false;
107 $this->mIncludeCount
= array();
108 $this->mStripState
= array();
109 $this->mArgStack
= array();
110 $this->mInPre
= false;
113 # First pass--just handle <nowiki> sections, pass the rest off
114 # to internalParse() which does all the real work.
116 # Returns a ParserOutput
118 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
120 $fname = 'Parser::parse';
121 wfProfileIn( $fname );
127 $this->mOptions
= $options;
128 $this->mTitle
=& $title;
129 $this->mOutputType
= OT_HTML
;
132 $text = $this->strip( $text, $this->mStripState
);
133 $text = $this->internalParse( $text, $linestart );
134 $text = $this->unstrip( $text, $this->mStripState
);
135 # Clean up special characters, only run once, next-to-last before doBlockLevels
138 # french spaces, last one Guillemet-left
139 # only if there is something before the space
140 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
141 # french spaces, Guillemet-right
142 "/(\\302\\253) /i"=>"\\1 ",
143 '/<hr *>/i' => '<hr />',
144 '/<br *>/i' => '<br />',
145 '/<center *>/i' => '<div class="center">',
146 '/<\\/center *>/i' => '</div>',
147 # Clean up spare ampersands; note that we probably ought to be
148 # more careful about named entities.
149 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
151 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
154 # french spaces, last one Guillemet-left
155 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
156 # french spaces, Guillemet-right
157 '/(\\302\\253) /i' => '\\1 ',
158 '/<center *>/i' => '<div class="center">',
159 '/<\\/center *>/i' => '</div>'
161 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
164 $text = $this->doBlockLevels( $text, $linestart );
165 $text = $this->unstripNoWiki( $text, $this->mStripState
);
167 $text = $this->tidy($text);
169 $this->mOutput
->setText( $text );
170 wfProfileOut( $fname );
171 return $this->mOutput
;
174 /* static */ function getRandomString() {
175 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
178 # Replaces all occurrences of <$tag>content</$tag> in the text
179 # with a random marker and returns the new text. the output parameter
180 # $content will be an associative array filled with data on the form
181 # $unique_marker => content.
183 # If $content is already set, the additional entries will be appended
185 # If $tag is set to STRIP_COMMENTS, the function will extract
186 # <!-- HTML comments -->
188 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ''){
189 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
196 while ( '' != $text ) {
197 if($tag==STRIP_COMMENTS
) {
198 $p = preg_split( '/<!--/i', $text, 2 );
200 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
203 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
206 if($tag==STRIP_COMMENTS
) {
207 $q = preg_split( '/-->/i', $p[1], 2 );
209 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
211 $marker = $rnd . sprintf('%08X', $n++
);
212 $content[$marker] = $q[0];
213 $stripped .= $marker;
220 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
221 # If $render is set, performs necessary rendering operations on plugins
222 # Returns the text, and fills an array with data needed in unstrip()
223 # If the $state is already a valid strip state, it adds to the state
225 # When $stripcomments is set, HTML comments <!-- like this -->
226 # will be stripped in addition to other tags. This is important
227 # for section editing, where these comments cause confusion when
228 # counting the sections in the wikisource
229 function strip( $text, &$state, $stripcomments = false ) {
230 $render = ($this->mOutputType
== OT_HTML
);
231 $html_content = array();
232 $nowiki_content = array();
233 $math_content = array();
234 $pre_content = array();
235 $comment_content = array();
236 $ext_content = array();
238 # Replace any instances of the placeholders
239 $uniq_prefix = UNIQ_PREFIX
;
240 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
243 global $wgRawHtml, $wgWhitelistEdit;
244 if( $wgRawHtml && $wgWhitelistEdit ) {
245 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
246 foreach( $html_content as $marker => $content ) {
248 # Raw and unchecked for validity.
249 $html_content[$marker] = $content;
251 $html_content[$marker] = '<html>'.$content.'</html>';
257 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
258 foreach( $nowiki_content as $marker => $content ) {
260 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
262 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
267 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
268 foreach( $math_content as $marker => $content ){
270 if( $this->mOptions
->getUseTeX() ) {
271 $math_content[$marker] = renderMath( $content );
273 $math_content[$marker] = '<math>'.$content.'<math>';
276 $math_content[$marker] = '<math>'.$content.'</math>';
281 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
282 foreach( $pre_content as $marker => $content ){
284 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
286 $pre_content[$marker] = '<pre>'.$content.'</pre>';
292 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
293 foreach( $comment_content as $marker => $content ){
294 $comment_content[$marker] = '<!--'.$content.'-->';
299 foreach ( $this->mTagHooks
as $tag => $callback ) {
300 $ext_contents[$tag] = array();
301 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
302 foreach( $ext_content[$tag] as $marker => $content ) {
304 $ext_content[$tag][$marker] = $callback( $content );
306 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
311 # Merge state with the pre-existing state, if there is one
313 $state['html'] = $state['html'] +
$html_content;
314 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
315 $state['math'] = $state['math'] +
$math_content;
316 $state['pre'] = $state['pre'] +
$pre_content;
317 $state['comment'] = $state['comment'] +
$comment_content;
319 foreach( $ext_content as $tag => $array ) {
320 if ( array_key_exists( $tag, $state ) ) {
321 $state[$tag] = $state[$tag] +
$array;
326 'html' => $html_content,
327 'nowiki' => $nowiki_content,
328 'math' => $math_content,
329 'pre' => $pre_content,
330 'comment' => $comment_content,
336 # always call unstripNoWiki() after this one
337 function unstrip( $text, &$state ) {
338 # Must expand in reverse order, otherwise nested tags will be corrupted
339 $contentDict = end( $state );
340 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
341 if( key($state) != 'nowiki' && key($state) != 'html') {
342 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
343 $text = str_replace( key( $contentDict ), $content, $text );
350 # always call this after unstrip() to preserve the order
351 function unstripNoWiki( $text, &$state ) {
352 # Must expand in reverse order, otherwise nested tags will be corrupted
353 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
354 $text = str_replace( key( $state['nowiki'] ), $content, $text );
359 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
360 $text = str_replace( key( $state['html'] ), $content, $text );
367 # Add an item to the strip state
368 # Returns the unique tag which must be inserted into the stripped text
369 # The tag will be replaced with the original text in unstrip()
370 function insertStripItem( $text, &$state ) {
371 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
380 $state['item'][$rnd] = $text;
384 # Return allowed HTML attributes
385 function getHTMLattrs () {
386 $htmlattrs = array( # Allowed attributes--no scripting, etc.
387 'title', 'align', 'lang', 'dir', 'width', 'height',
388 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
389 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
390 /* FONT */ 'type', 'start', 'value', 'compact',
391 /* For various lists, mostly deprecated but safe */
392 'summary', 'width', 'border', 'frame', 'rules',
393 'cellspacing', 'cellpadding', 'valign', 'char',
394 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
395 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
396 'id', 'class', 'name', 'style' /* For CSS */
401 # Remove non approved attributes and javascript in css
402 function fixTagAttributes ( $t ) {
403 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
404 $htmlattrs = $this->getHTMLattrs() ;
406 # Strip non-approved attributes from the tag
408 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
409 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
412 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
414 # Strip javascript "expression" from stylesheets. Brute force approach:
415 # If anythin offensive is found, all attributes of the HTML tag are dropped
418 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
419 wfMungeToUtf8( $t ) ) )
427 # interface with html tidy, used if $wgUseTidy = true
428 function tidy ( $text ) {
429 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
430 global $wgInputEncoding, $wgOutputEncoding;
431 $fname = 'Parser::tidy';
432 wfProfileIn( $fname );
435 switch(strtoupper($wgOutputEncoding)) {
437 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
440 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
443 $wgTidyOpts .= ' -raw';
446 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
447 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
448 '<head><title>test</title></head><body>'.$text.'</body></html>';
449 $descriptorspec = array(
450 0 => array('pipe', 'r'),
451 1 => array('pipe', 'w'),
452 2 => array('file', '/dev/null', 'a')
454 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
455 if (is_resource($process)) {
456 fwrite($pipes[0], $wrappedtext);
458 while (!feof($pipes[1])) {
459 $cleansource .= fgets($pipes[1], 1024);
462 $return_value = proc_close($process);
465 wfProfileOut( $fname );
467 if( $cleansource == '' && $text != '') {
468 wfDebug( "Tidy error detected!\n" );
469 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
475 # parse the wiki syntax used to render tables
476 function doTableStuff ( $t ) {
477 $fname = 'Parser::doTableStuff';
478 wfProfileIn( $fname );
480 $t = explode ( "\n" , $t ) ;
481 $td = array () ; # Is currently a td tag open?
482 $ltd = array () ; # Was it TD or TH?
483 $tr = array () ; # Is currently a tr tag open?
484 $ltr = array () ; # tr attributes
485 $indent_level = 0; # indent level of the table
486 foreach ( $t AS $k => $x )
489 $fc = substr ( $x , 0 , 1 ) ;
490 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
491 $indent_level = strlen( $matches[1] );
493 str_repeat( '<dl><dd>', $indent_level ) .
494 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
495 array_push ( $td , false ) ;
496 array_push ( $ltd , '' ) ;
497 array_push ( $tr , false ) ;
498 array_push ( $ltr , '' ) ;
500 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
501 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
503 $l = array_pop ( $ltd ) ;
504 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
505 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
507 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
509 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
510 $x = substr ( $x , 1 ) ;
511 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
513 $l = array_pop ( $ltd ) ;
514 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
515 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
518 array_push ( $tr , false ) ;
519 array_push ( $td , false ) ;
520 array_push ( $ltd , '' ) ;
521 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
523 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
524 if ( '|+' == substr ( $x , 0 , 2 ) ) {
526 $x = substr ( $x , 1 ) ;
528 $after = substr ( $x , 1 ) ;
529 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
530 $after = explode ( '||' , $after ) ;
532 foreach ( $after AS $theline )
537 $tra = array_pop ( $ltr ) ;
538 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
539 array_push ( $tr , true ) ;
540 array_push ( $ltr , '' ) ;
543 $l = array_pop ( $ltd ) ;
544 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
545 if ( $fc == '|' ) $l = 'td' ;
546 else if ( $fc == '!' ) $l = 'th' ;
547 else if ( $fc == '+' ) $l = 'caption' ;
549 array_push ( $ltd , $l ) ;
550 $y = explode ( '|' , $theline , 2 ) ;
551 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
552 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
554 array_push ( $td , true ) ;
559 # Closing open td, tr && table
560 while ( count ( $td ) > 0 )
562 if ( array_pop ( $td ) ) $t[] = '</td>' ;
563 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
567 $t = implode ( "\n" , $t ) ;
568 # $t = $this->removeHTMLtags( $t );
569 wfProfileOut( $fname );
573 # Parses the text and adds the result to the strip state
574 # Returns the strip tag
575 function stripParse( $text, $newline, $args ) {
576 $text = $this->strip( $text, $this->mStripState
);
577 $text = $this->internalParse( $text, (bool)$newline, $args, false );
578 return $newline.$this->insertStripItem( $text, $this->mStripState
);
581 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
582 $fname = 'Parser::internalParse';
583 wfProfileIn( $fname );
585 $text = $this->removeHTMLtags( $text );
586 $text = $this->replaceVariables( $text, $args );
588 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
590 $text = $this->doHeadings( $text );
591 if($this->mOptions
->getUseDynamicDates()) {
592 global $wgDateFormatter;
593 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
595 $text = $this->doAllQuotes( $text );
596 $text = $this->replaceExternalLinks( $text );
597 $text = $this->doMagicLinks( $text );
598 $text = $this->replaceInternalLinks ( $text );
599 $text = $this->replaceInternalLinks ( $text );
601 $text = $this->unstrip( $text, $this->mStripState
);
602 $text = $this->unstripNoWiki( $text, $this->mStripState
);
604 $text = $this->doTableStuff( $text );
605 $text = $this->formatHeadings( $text, $isMain );
606 $sk =& $this->mOptions
->getSkin();
607 $text = $sk->transformContent( $text );
609 wfProfileOut( $fname );
613 /* private */ function &doMagicLinks( &$text ) {
614 global $wgUseGeoMode;
615 $text = $this->magicISBN( $text );
616 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
617 $text = $this->magicGEO( $text );
619 $text = $this->magicRFC( $text );
623 # Parse ^^ tokens and return html
624 /* private */ function doExponent ( $text ) {
625 $fname = 'Parser::doExponent';
626 wfProfileIn( $fname);
627 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
628 wfProfileOut( $fname);
632 # Parse headers and return html
633 /* private */ function doHeadings( $text ) {
634 $fname = 'Parser::doHeadings';
635 wfProfileIn( $fname );
636 for ( $i = 6; $i >= 1; --$i ) {
637 $h = substr( '======', 0, $i );
638 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
639 "<h{$i}>\\1</h{$i}>\\2", $text );
641 wfProfileOut( $fname );
645 /* private */ function doAllQuotes( $text ) {
646 $fname = 'Parser::doAllQuotes';
647 wfProfileIn( $fname );
649 $lines = explode( "\n", $text );
650 foreach ( $lines as $line ) {
651 $outtext .= $this->doQuotes ( $line ) . "\n";
653 $outtext = substr($outtext, 0,-1);
654 wfProfileOut( $fname );
658 /* private */ function doQuotes( $text ) {
659 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
660 if (count ($arr) == 1)
664 # First, do some preliminary work. This may shift some apostrophes from
665 # being mark-up to being text. It also counts the number of occurrences
666 # of bold and italics mark-ups.
674 # If there are ever four apostrophes, assume the first is supposed to
675 # be text, and the remaining three constitute mark-up for bold text.
676 if (strlen ($arr[$i]) == 4)
681 # If there are more than 5 apostrophes in a row, assume they're all
682 # text except for the last 5.
683 else if (strlen ($arr[$i]) > 5)
685 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
688 # Count the number of occurrences of bold and italics mark-ups.
689 # We are not counting sequences of five apostrophes.
690 if (strlen ($arr[$i]) == 2) $numitalics++
; else
691 if (strlen ($arr[$i]) == 3) $numbold++
; else
692 if (strlen ($arr[$i]) == 5) { $numitalics++
; $numbold++
; }
697 # If there is an odd number of both bold and italics, it is likely
698 # that one of the bold ones was meant to be an apostrophe followed
699 # by italics. Which one we cannot know for certain, but it is more
700 # likely to be one that has a single-letter word before it.
701 if (($numbold %
2 == 1) && ($numitalics %
2 == 1))
704 $firstsingleletterword = -1;
705 $firstmultiletterword = -1;
709 if (($i %
2 == 1) and (strlen ($r) == 3))
711 $x1 = substr ($arr[$i-1], -1);
712 $x2 = substr ($arr[$i-1], -2, 1);
714 if ($firstspace == -1) $firstspace = $i;
715 } else if ($x2 == ' ') {
716 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
718 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
724 # If there is a single-letter word, use it!
725 if ($firstsingleletterword > -1)
727 $arr [ $firstsingleletterword ] = "''";
728 $arr [ $firstsingleletterword-1 ] .= "'";
730 # If not, but there's a multi-letter word, use that one.
731 else if ($firstmultiletterword > -1)
733 $arr [ $firstmultiletterword ] = "''";
734 $arr [ $firstmultiletterword-1 ] .= "'";
736 # ... otherwise use the first one that has neither.
737 # (notice that it is possible for all three to be -1 if, for example,
738 # there is only one pentuple-apostrophe in the line)
739 else if ($firstspace > -1)
741 $arr [ $firstspace ] = "''";
742 $arr [ $firstspace-1 ] .= "'";
746 # Now let's actually convert our apostrophic mush to HTML!
755 if ($state == 'both')
762 if (strlen ($r) == 2)
765 { $output .= '</i>'; $state = ''; }
766 else if ($state == 'bi')
767 { $output .= '</i>'; $state = 'b'; }
768 else if ($state == 'ib')
769 { $output .= '</b></i><b>'; $state = 'b'; }
770 else if ($state == 'both')
771 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
772 else # $state can be 'b' or ''
773 { $output .= '<i>'; $state .= 'i'; }
775 else if (strlen ($r) == 3)
778 { $output .= '</b>'; $state = ''; }
779 else if ($state == 'bi')
780 { $output .= '</i></b><i>'; $state = 'i'; }
781 else if ($state == 'ib')
782 { $output .= '</b>'; $state = 'i'; }
783 else if ($state == 'both')
784 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
785 else # $state can be 'i' or ''
786 { $output .= '<b>'; $state .= 'b'; }
788 else if (strlen ($r) == 5)
791 { $output .= '</b><i>'; $state = 'i'; }
792 else if ($state == 'i')
793 { $output .= '</i><b>'; $state = 'b'; }
794 else if ($state == 'bi')
795 { $output .= '</i></b>'; $state = ''; }
796 else if ($state == 'ib')
797 { $output .= '</b></i>'; $state = ''; }
798 else if ($state == 'both')
799 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
800 else # ($state == '')
801 { $buffer = ''; $state = 'both'; }
806 # Now close all remaining tags. Notice that the order is important.
807 if ($state == 'b' ||
$state == 'ib')
809 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
813 if ($state == 'both')
814 $output .= '<b><i>'.$buffer.'</i></b>';
819 # Note: we have to do external links before the internal ones,
820 # and otherwise take great care in the order of things here, so
821 # that we don't end up interpreting some URLs twice.
823 /* private */ function replaceExternalLinks( $text ) {
824 $fname = 'Parser::replaceExternalLinks';
825 wfProfileIn( $fname );
827 $sk =& $this->mOptions
->getSkin();
828 $linktrail = wfMsg('linktrail');
829 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
831 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
834 while ( $i<count( $bits ) ) {
836 $protocol = $bits[$i++
];
838 $trail = $bits[$i++
];
840 # If the link text is an image URL, replace it with an <img> tag
841 # This happened by accident in the original parser, but some people used it extensively
842 $img = $this->maybeMakeImageLink( $text );
843 if ( $img !== false ) {
849 # No link text, e.g. [http://domain.tld/some.link]
851 # Autonumber if allowed
852 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
853 $text = '[' . ++
$this->mAutonumber
. ']';
855 # Otherwise just use the URL
856 $text = htmlspecialchars( $url );
859 # Have link text, e.g. [http://domain.tld/some.link text]s
861 if ( preg_match( $linktrail, $trail, $m2 ) ) {
867 $encUrl = htmlspecialchars( $url );
868 # Bit in parentheses showing the URL for the printable version
869 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
872 # Expand the URL for printable version
873 if ( ! $sk->suppressUrlExpansion() ) {
874 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
880 # Process the trail (i.e. everything after this link up until start of the next link),
881 # replacing any non-bracketed links
882 $trail = $this->replaceFreeExternalLinks( $trail );
884 $la = $sk->getExternalLinkAttributes( $url, $text );
886 # Use the encoded URL
887 # This means that users can paste URLs directly into the text
888 # Funny characters like ö aren't valid in URLs anyway
889 # This was changed in August 2004
890 $s .= "<a href=\"{$url}\" {$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
893 wfProfileOut( $fname );
897 # Replace anything that looks like a URL with a link
898 function replaceFreeExternalLinks( $text ) {
899 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
900 $s = array_shift( $bits );
903 $sk =& $this->mOptions
->getSkin();
905 while ( $i < count( $bits ) ){
906 $protocol = $bits[$i++
];
907 $remainder = $bits[$i++
];
909 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
910 # Found some characters after the protocol that look promising
911 $url = $protocol . $m[1];
914 # Move trailing punctuation to $trail
916 # If there is no left bracket, then consider right brackets fair game too
917 if ( strpos( $url, '(' ) === false ) {
921 $numSepChars = strspn( strrev( $url ), $sep );
922 if ( $numSepChars ) {
923 $trail = substr( $url, -$numSepChars ) . $trail;
924 $url = substr( $url, 0, -$numSepChars );
927 # Replace & from obsolete syntax with &
928 $url = str_replace( '&', '&', $url );
930 # Is this an external image?
931 $text = $this->maybeMakeImageLink( $url );
932 if ( $text === false ) {
933 # Not an image, make a link
934 $text = $sk->makeExternalLink( $url, $url );
936 $s .= $text . $trail;
938 $s .= $protocol . $remainder;
944 # make an image if it's allowed
945 function maybeMakeImageLink( $url ) {
946 $sk =& $this->mOptions
->getSkin();
948 if ( $this->mOptions
->getAllowExternalImages() ) {
949 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
951 $text = $sk->makeImage( htmlspecialchars( $url ) );
957 # The wikilinks [[ ]] are procedeed here.
958 /* private */ function replaceInternalLinks( $s ) {
959 global $wgLang, $wgLinkCache;
960 global $wgNamespacesWithSubpages, $wgLanguageCode;
961 static $fname = 'Parser::replaceInternalLinks' ;
962 wfProfileIn( $fname );
964 wfProfileIn( $fname.'-setup' );
966 # the % is needed to support urlencoded titles as well
967 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
968 $sk =& $this->mOptions
->getSkin();
970 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
972 $a = explode( '[[', ' ' . $s );
973 $s = array_shift( $a );
974 $s = substr( $s, 1 );
976 # Match a link having the form [[namespace:link|alternate]]trail
978 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
979 # Match the end of a line for a word that's not followed by whitespace,
980 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
981 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
983 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
984 # Special and Media are pseudo-namespaces; no pages actually exist in them
986 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
988 if ( $useLinkPrefixExtension ) {
989 if ( preg_match( $e2, $s, $m ) ) {
990 $first_prefix = $m[2];
993 $first_prefix = false;
999 wfProfileOut( $fname.'-setup' );
1001 # start procedeeding each line
1002 foreach ( $a as $line ) {
1003 wfProfileIn( $fname.'-prefixhandling' );
1004 if ( $useLinkPrefixExtension ) {
1005 if ( preg_match( $e2, $s, $m ) ) {
1013 $prefix = $first_prefix;
1014 $first_prefix = false;
1017 wfProfileOut( $fname.'-prefixhandling' );
1019 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1021 # fix up urlencoded title texts
1022 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1024 } else { # Invalid form; output directly
1025 $s .= $prefix . '[[' . $line ;
1031 # :Foobar -- override special treatment of prefix (images, language links)
1032 # /Foobar -- convert to CurrentPage/Foobar
1033 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1035 # Look at the first character
1036 $c = substr($m[1],0,1);
1037 $noforce = ($c != ':');
1041 # / at end means we don't want the slash to be shown
1042 if(substr($m[1],-1,1)=='/') {
1043 $m[1]=substr($m[1],1,strlen($m[1])-2);
1046 $noslash=substr($m[1],1);
1049 # Some namespaces don't allow subpages
1050 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) {
1051 # subpages allowed here
1052 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1055 } # this might be changed for ugliness reasons
1057 # no subpage allowed, use standard link
1061 } elseif( $noforce ) { # no subpage
1064 # We don't want to keep the first character
1065 $link = substr( $m[1], 1 );
1068 $wasblank = ( '' == $text );
1069 if( $wasblank ) $text = $link;
1071 $nt = Title
::newFromText( $link );
1073 $s .= $prefix . '[[' . $line;
1077 $ns = $nt->getNamespace();
1078 $iw = $nt->getInterWiki();
1080 # Link not escaped by : , create the various objects
1084 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1085 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1086 $tmp = $prefix . $trail ;
1087 $s .= (trim($tmp) == '')?
'': $tmp;
1091 if ( $ns == NS_IMAGE
) {
1092 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1093 $wgLinkCache->addImageLinkObj( $nt );
1097 if ( $ns == NS_CATEGORY
) {
1098 $t = $nt->getText() ;
1099 $nnt = Title
::newFromText ( Namespace::getCanonicalName(NS_CATEGORY
).':'.$t ) ;
1101 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1102 $pPLC=$sk->postParseLinkColour();
1103 $sk->postParseLinkColour( false );
1104 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1105 $sk->postParseLinkColour( $pPLC );
1106 $wgLinkCache->resume();
1109 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1110 $sortkey = $this->mTitle
->getText();
1112 $sortkey = $this->mTitle
->getPrefixedText();
1117 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1118 $this->mOutput
->mCategoryLinks
[] = $t ;
1119 $s .= $prefix . $trail ;
1124 if( ( $nt->getPrefixedText() === $this->mTitle
->getPrefixedText() ) &&
1125 ( strpos( $link, '#' ) === FALSE ) ) {
1126 # Self-links are handled specially; generally de-link and change to bold.
1127 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1131 if( $ns == NS_MEDIA
) {
1132 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1133 $wgLinkCache->addImageLinkObj( $nt );
1135 } elseif( $ns == NS_SPECIAL
) {
1136 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1139 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1141 wfProfileOut( $fname );
1145 # Some functions here used by doBlockLevels()
1147 /* private */ function closeParagraph() {
1149 if ( '' != $this->mLastSection
) {
1150 $result = '</' . $this->mLastSection
. ">\n";
1152 $this->mInPre
= false;
1153 $this->mLastSection
= '';
1156 # getCommon() returns the length of the longest common substring
1157 # of both arguments, starting at the beginning of both.
1159 /* private */ function getCommon( $st1, $st2 ) {
1160 $fl = strlen( $st1 );
1161 $shorter = strlen( $st2 );
1162 if ( $fl < $shorter ) { $shorter = $fl; }
1164 for ( $i = 0; $i < $shorter; ++
$i ) {
1165 if ( $st1{$i} != $st2{$i} ) { break; }
1169 # These next three functions open, continue, and close the list
1170 # element appropriate to the prefix character passed into them.
1172 /* private */ function openList( $char ) {
1173 $result = $this->closeParagraph();
1175 if ( '*' == $char ) { $result .= '<ul><li>'; }
1176 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1177 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1178 else if ( ';' == $char ) {
1179 $result .= '<dl><dt>';
1180 $this->mDTopen
= true;
1182 else { $result = '<!-- ERR 1 -->'; }
1187 /* private */ function nextItem( $char ) {
1188 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1189 else if ( ':' == $char ||
';' == $char ) {
1191 if ( $this->mDTopen
) { $close = '</dt>'; }
1192 if ( ';' == $char ) {
1193 $this->mDTopen
= true;
1194 return $close . '<dt>';
1196 $this->mDTopen
= false;
1197 return $close . '<dd>';
1200 return '<!-- ERR 2 -->';
1203 /* private */ function closeList( $char ) {
1204 if ( '*' == $char ) { $text = '</li></ul>'; }
1205 else if ( '#' == $char ) { $text = '</li></ol>'; }
1206 else if ( ':' == $char ) {
1207 if ( $this->mDTopen
) {
1208 $this->mDTopen
= false;
1209 $text = '</dt></dl>';
1211 $text = '</dd></dl>';
1214 else { return '<!-- ERR 3 -->'; }
1218 /* private */ function doBlockLevels( $text, $linestart ) {
1219 $fname = 'Parser::doBlockLevels';
1220 wfProfileIn( $fname );
1222 # Parsing through the text line by line. The main thing
1223 # happening here is handling of block-level elements p, pre,
1224 # and making lists from lines starting with * # : etc.
1226 $textLines = explode( "\n", $text );
1228 $lastPrefix = $output = $lastLine = '';
1229 $this->mDTopen
= $inBlockElem = false;
1231 $paragraphStack = false;
1233 if ( !$linestart ) {
1234 $output .= array_shift( $textLines );
1236 foreach ( $textLines as $oLine ) {
1237 $lastPrefixLength = strlen( $lastPrefix );
1238 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1239 $preOpenMatch = preg_match('/<pre/i', $oLine );
1240 if ( !$this->mInPre
) {
1241 # Multiple prefixes may abut each other for nested lists.
1242 $prefixLength = strspn( $oLine, '*#:;' );
1243 $pref = substr( $oLine, 0, $prefixLength );
1246 $pref2 = str_replace( ';', ':', $pref );
1247 $t = substr( $oLine, $prefixLength );
1248 $this->mInPre
= !empty($preOpenMatch);
1250 # Don't interpret any other prefixes in preformatted text
1252 $pref = $pref2 = '';
1257 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1258 # Same as the last item, so no need to deal with nesting or opening stuff
1259 $output .= $this->nextItem( substr( $pref, -1 ) );
1260 $paragraphStack = false;
1262 if ( substr( $pref, -1 ) == ';') {
1263 # The one nasty exception: definition lists work like this:
1264 # ; title : definition text
1265 # So we check for : in the remainder text to split up the
1266 # title and definition, without b0rking links.
1267 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1268 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1270 $output .= $term . $this->nextItem( ':' );
1274 } elseif( $prefixLength ||
$lastPrefixLength ) {
1275 # Either open or close a level...
1276 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1277 $paragraphStack = false;
1279 while( $commonPrefixLength < $lastPrefixLength ) {
1280 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1281 --$lastPrefixLength;
1283 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1284 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1286 while ( $prefixLength > $commonPrefixLength ) {
1287 $char = substr( $pref, $commonPrefixLength, 1 );
1288 $output .= $this->openList( $char );
1290 if ( ';' == $char ) {
1291 # FIXME: This is dupe of code above
1292 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1294 $output .= $term . $this->nextItem( ':' );
1298 ++
$commonPrefixLength;
1300 $lastPrefix = $pref2;
1302 if( 0 == $prefixLength ) {
1303 # No prefix (not in list)--go to paragraph mode
1304 $uniq_prefix = UNIQ_PREFIX
;
1305 // XXX: use a stack for nestable elements like span, table and div
1306 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1307 $closematch = preg_match(
1308 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1309 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1310 if ( $openmatch or $closematch ) {
1311 $paragraphStack = false;
1312 $output .= $this->closeParagraph();
1313 if($preOpenMatch and !$preCloseMatch) {
1314 $this->mInPre
= true;
1316 if ( $closematch ) {
1317 $inBlockElem = false;
1319 $inBlockElem = true;
1321 } else if ( !$inBlockElem && !$this->mInPre
) {
1322 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1324 if ($this->mLastSection
!= 'pre') {
1325 $paragraphStack = false;
1326 $output .= $this->closeParagraph().'<pre>';
1327 $this->mLastSection
= 'pre';
1329 $t = substr( $t, 1 );
1332 if ( '' == trim($t) ) {
1333 if ( $paragraphStack ) {
1334 $output .= $paragraphStack.'<br />';
1335 $paragraphStack = false;
1336 $this->mLastSection
= 'p';
1338 if ($this->mLastSection
!= 'p' ) {
1339 $output .= $this->closeParagraph();
1340 $this->mLastSection
= '';
1341 $paragraphStack = '<p>';
1343 $paragraphStack = '</p><p>';
1347 if ( $paragraphStack ) {
1348 $output .= $paragraphStack;
1349 $paragraphStack = false;
1350 $this->mLastSection
= 'p';
1351 } else if ($this->mLastSection
!= 'p') {
1352 $output .= $this->closeParagraph().'<p>';
1353 $this->mLastSection
= 'p';
1359 if ($paragraphStack === false) {
1363 while ( $prefixLength ) {
1364 $output .= $this->closeList( $pref2{$prefixLength-1} );
1367 if ( '' != $this->mLastSection
) {
1368 $output .= '</' . $this->mLastSection
. '>';
1369 $this->mLastSection
= '';
1372 wfProfileOut( $fname );
1376 # Return value of a magic variable (like PAGENAME)
1377 function getVariableValue( $index ) {
1378 global $wgLang, $wgSitename, $wgServer;
1381 case MAG_CURRENTMONTH
:
1382 return $wgLang->formatNum( date( 'm' ) );
1383 case MAG_CURRENTMONTHNAME
:
1384 return $wgLang->getMonthName( date('n') );
1385 case MAG_CURRENTMONTHNAMEGEN
:
1386 return $wgLang->getMonthNameGen( date('n') );
1387 case MAG_CURRENTDAY
:
1388 return $wgLang->formatNum( date('j') );
1390 return $this->mTitle
->getText();
1392 return $this->mTitle
->getPartialURL();
1394 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1395 return $wgLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1396 case MAG_CURRENTDAYNAME
:
1397 return $wgLang->getWeekdayName( date('w')+
1 );
1398 case MAG_CURRENTYEAR
:
1399 return $wgLang->formatNum( date( 'Y' ) );
1400 case MAG_CURRENTTIME
:
1401 return $wgLang->time( wfTimestampNow(), false );
1402 case MAG_NUMBEROFARTICLES
:
1403 return $wgLang->formatNum( wfNumberOfArticles() );
1413 # initialise the magic variables (like CURRENTMONTHNAME)
1414 function initialiseVariables() {
1415 global $wgVariableIDs;
1416 $this->mVariables
= array();
1417 foreach ( $wgVariableIDs as $id ) {
1418 $mw =& MagicWord
::get( $id );
1419 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1423 /* private */ function replaceVariables( $text, $args = array() ) {
1424 global $wgLang, $wgScript, $wgArticlePath;
1426 # Prevent too big inclusions
1427 if(strlen($text)> MAX_INCLUDE_SIZE
)
1430 $fname = 'Parser::replaceVariables';
1431 wfProfileIn( $fname );
1434 $titleChars = Title
::legalChars();
1435 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1437 # This function is called recursively. To keep track of arguments we need a stack:
1438 array_push( $this->mArgStack
, $args );
1440 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1441 $GLOBALS['wgCurParser'] =& $this;
1443 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_MSG
) {
1444 # Variable substitution
1445 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1448 if ( $this->mOutputType
== OT_HTML
) {
1449 # Argument substitution
1450 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1452 # Template substitution
1453 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1454 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1456 array_pop( $this->mArgStack
);
1458 wfProfileOut( $fname );
1462 function variableSubstitution( $matches ) {
1463 if ( !$this->mVariables
) {
1464 $this->initialiseVariables();
1466 if ( array_key_exists( $matches[1], $this->mVariables
) ) {
1467 $text = $this->mVariables
[$matches[1]];
1468 $this->mOutput
->mContainsOldMagic
= true;
1470 $text = $matches[0];
1475 # Split template arguments
1476 function getTemplateArgs( $argsString ) {
1477 if ( $argsString === '' ) {
1481 $args = explode( '|', substr( $argsString, 1 ) );
1483 # If any of the arguments contains a '[[' but no ']]', it needs to be
1484 # merged with the next arg because the '|' character between belongs
1485 # to the link syntax and not the template parameter syntax.
1486 $argc = count($args);
1488 for ( $i = 0; $i < $argc-1; $i++
) {
1489 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1490 $args[$i] .= '|'.$args[$i+
1];
1491 array_splice($args, $i+
1, 1);
1500 function braceSubstitution( $matches ) {
1501 global $wgLinkCache, $wgLang;
1502 $fname = 'Parser::braceSubstitution';
1509 # $newline is an optional newline character before the braces
1510 # $part1 is the bit before the first |, and must contain only title characters
1511 # $args is a list of arguments, starting from index 0, not including $part1
1513 $newline = $matches[1];
1514 $part1 = $matches[2];
1515 # If the third subpattern matched anything, it will start with |
1517 $args = $this->getTemplateArgs($matches[3]);
1518 $argc = count( $args );
1521 if ( strpos( $matches[0], '{{{' ) !== false ) {
1522 $text = $matches[0];
1529 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1530 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1531 if ( $this->mOutputType
!= OT_WIKI
) {
1532 # Invalid SUBST not replaced at PST time
1533 # Return without further processing
1534 $text = $matches[0];
1538 } elseif ( $this->mOutputType
== OT_WIKI
) {
1539 # SUBST not found in PST pass, do nothing
1540 $text = $matches[0];
1545 # MSG, MSGNW and INT
1548 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1549 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1552 # Remove obsolete MSG:
1553 $mwMsg =& MagicWord
::get( MAG_MSG
);
1554 $mwMsg->matchStartAndRemove( $part1 );
1557 # Check if it is an internal message
1558 $mwInt =& MagicWord
::get( MAG_INT
);
1559 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1560 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1561 $text = wfMsgReal( $part1, $args, true );
1569 # Check for NS: (namespace expansion)
1570 $mwNs = MagicWord
::get( MAG_NS
);
1571 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1572 if ( intval( $part1 ) ) {
1573 $text = $wgLang->getNsText( intval( $part1 ) );
1576 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1577 if ( !is_null( $index ) ) {
1578 $text = $wgLang->getNsText( $index );
1585 # LOCALURL and LOCALURLE
1587 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1588 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1590 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1591 $func = 'getLocalURL';
1592 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1593 $func = 'escapeLocalURL';
1598 if ( $func !== '' ) {
1599 $title = Title
::newFromText( $part1 );
1600 if ( !is_null( $title ) ) {
1602 $text = $title->$func( $args[0] );
1604 $text = $title->$func();
1611 # Internal variables
1612 if ( !$this->mVariables
) {
1613 $this->initialiseVariables();
1615 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1616 $text = $this->mVariables
[$part1];
1618 $this->mOutput
->mContainsOldMagic
= true;
1622 if ( !$found && $argc == 1 ) {
1623 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1624 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1625 $text = $wgLang->convertGrammar( $args[0], $part1 );
1630 # Template table test
1632 # Did we encounter this template already? If yes, it is in the cache
1633 # and we need to check for loops.
1634 if ( isset( $this->mTemplates
[$part1] ) ) {
1635 # Infinite loop test
1636 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1640 # set $text to cached message.
1641 $text = $this->mTemplates
[$part1];
1645 # Load from database
1647 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1648 if ( !is_null( $title ) && !$title->isExternal() ) {
1649 # Check for excessive inclusion
1650 $dbk = $title->getPrefixedDBkey();
1651 if ( $this->incrementIncludeCount( $dbk ) ) {
1652 # This should never be reached.
1653 $article = new Article( $title );
1654 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1655 if ( $articleContent !== false ) {
1657 $text = $articleContent;
1661 # If the title is valid but undisplayable, make a link to it
1662 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1663 $text = '[['.$title->getPrefixedText().']]';
1667 # Template cache array insertion
1668 $this->mTemplates
[$part1] = $text;
1672 # Recursive parsing, escaping and link table handling
1673 # Only for HTML output
1674 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1675 $text = wfEscapeWikiText( $text );
1676 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1677 # Clean up argument array
1678 $assocArgs = array();
1680 foreach( $args as $arg ) {
1681 $eqpos = strpos( $arg, '=' );
1682 if ( $eqpos === false ) {
1683 $assocArgs[$index++
] = $arg;
1685 $name = trim( substr( $arg, 0, $eqpos ) );
1686 $value = trim( substr( $arg, $eqpos+
1 ) );
1687 if ( $value === false ) {
1690 if ( $name !== false ) {
1691 $assocArgs[$name] = $value;
1696 # Do not enter included links in link table
1697 if ( !is_null( $title ) ) {
1698 $wgLinkCache->suspend();
1701 # Add a new element to the templace recursion path
1702 $this->mTemplatePath
[$part1] = 1;
1704 $text = $this->stripParse( $text, $newline, $assocArgs );
1706 # Resume the link cache and register the inclusion as a link
1707 if ( !is_null( $title ) ) {
1708 $wgLinkCache->resume();
1709 $wgLinkCache->addLinkObj( $title );
1713 # Empties the template path
1714 $this->mTemplatePath
= array();
1723 # Triple brace replacement -- used for template arguments
1724 function argSubstitution( $matches ) {
1725 $newline = $matches[1];
1726 $arg = trim( $matches[2] );
1727 $text = $matches[0];
1728 $inputArgs = end( $this->mArgStack
);
1730 if ( array_key_exists( $arg, $inputArgs ) ) {
1731 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1737 # Returns true if the function is allowed to include this entity
1738 function incrementIncludeCount( $dbk ) {
1739 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1740 $this->mIncludeCount
[$dbk] = 0;
1742 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1750 # Cleans up HTML, removes dangerous tags and attributes
1751 /* private */ function removeHTMLtags( $text ) {
1752 global $wgUseTidy, $wgUserHtml;
1753 $fname = 'Parser::removeHTMLtags';
1754 wfProfileIn( $fname );
1757 $htmlpairs = array( # Tags that must be closed
1758 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1759 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1760 'strike', 'strong', 'tt', 'var', 'div', 'center',
1761 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1762 'ruby', 'rt' , 'rb' , 'rp', 'p'
1764 $htmlsingle = array(
1765 'br', 'hr', 'li', 'dt', 'dd'
1767 $htmlnest = array( # Tags that can be nested--??
1768 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1769 'dl', 'font', 'big', 'small', 'sub', 'sup'
1771 $tabletags = array( # Can only appear inside table
1775 $htmlpairs = array();
1776 $htmlsingle = array();
1777 $htmlnest = array();
1778 $tabletags = array();
1781 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1782 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1784 $htmlattrs = $this->getHTMLattrs () ;
1786 # Remove HTML comments
1787 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1789 $bits = explode( '<', $text );
1790 $text = array_shift( $bits );
1792 $tagstack = array(); $tablestack = array();
1793 foreach ( $bits as $x ) {
1794 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1795 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1797 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1798 error_reporting( $prev );
1801 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1805 if ( ! in_array( $t, $htmlsingle ) &&
1806 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
1807 @array_push
( $tagstack, $ot );
1810 if ( $t == 'table' ) {
1811 $tagstack = array_pop( $tablestack );
1816 # Keep track for later
1817 if ( in_array( $t, $tabletags ) &&
1818 ! in_array( 'table', $tagstack ) ) {
1820 } else if ( in_array( $t, $tagstack ) &&
1821 ! in_array ( $t , $htmlnest ) ) {
1823 } else if ( ! in_array( $t, $htmlsingle ) ) {
1824 if ( $t == 'table' ) {
1825 array_push( $tablestack, $tagstack );
1826 $tagstack = array();
1828 array_push( $tagstack, $t );
1830 # Strip non-approved attributes from the tag
1831 $newparams = $this->fixTagAttributes($params);
1835 $rest = str_replace( '>', '>', $rest );
1836 $text .= "<$slash$t $newparams$brace$rest";
1840 $text .= '<' . str_replace( '>', '>', $x);
1842 # Close off any remaining tags
1843 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1845 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1848 # this might be possible using tidy itself
1849 foreach ( $bits as $x ) {
1850 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1852 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1853 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1854 $newparams = $this->fixTagAttributes($params);
1855 $rest = str_replace( '>', '>', $rest );
1856 $text .= "<$slash$t $newparams$brace$rest";
1858 $text .= '<' . str_replace( '>', '>', $x);
1862 wfProfileOut( $fname );
1867 # This function accomplishes several tasks:
1868 # 1) Auto-number headings if that option is enabled
1869 # 2) Add an [edit] link to sections for logged in users who have enabled the option
1870 # 3) Add a Table of contents on the top for users who have enabled the option
1871 # 4) Auto-anchor headings
1873 # It loops through all headlines, collects the necessary data, then splits up the
1874 # string and re-inserts the newly formatted headlines.
1875 /* private */ function formatHeadings( $text, $isMain=true ) {
1876 global $wgInputEncoding, $wgMaxTocLevel, $wgLang;
1878 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1879 $doShowToc = $this->mOptions
->getShowToc();
1880 $forceTocHere = false;
1881 if( !$this->mTitle
->userCanEdit() ) {
1883 $rightClickHack = 0;
1885 $showEditLink = $this->mOptions
->getEditSection();
1886 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1889 # Inhibit editsection links if requested in the page
1890 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1891 if( $esw->matchAndRemove( $text ) ) {
1894 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1896 $mw =& MagicWord
::get( MAG_NOTOC
);
1897 if( $mw->matchAndRemove( $text ) ) {
1901 # never add the TOC to the Main Page. This is an entry page that should not
1902 # be more than 1-2 screens large anyway
1903 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
1907 # Get all headlines for numbering them and adding funky stuff like [edit]
1908 # links - this is for later, but we need the number of headlines right now
1909 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1911 # if there are fewer than 4 headlines in the article, do not show TOC
1912 if( $numMatches < 4 ) {
1916 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
1917 # override above conditions and always show TOC at that place
1918 $mw =& MagicWord
::get( MAG_TOC
);
1919 if ($mw->match( $text ) ) {
1921 $forceTocHere = true;
1923 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1924 # override above conditions and always show TOC above first header
1925 $mw =& MagicWord
::get( MAG_FORCETOC
);
1926 if ($mw->matchAndRemove( $text ) ) {
1933 # We need this to perform operations on the HTML
1934 $sk =& $this->mOptions
->getSkin();
1939 # Ugh .. the TOC should have neat indentation levels which can be
1940 # passed to the skin functions. These are determined here
1945 $sublevelCount = array();
1948 foreach( $matches[3] as $headline ) {
1951 $prevlevel = $level;
1953 $level = $matches[1][$headlineCount];
1954 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1955 # reset when we enter a new level
1956 $sublevelCount[$level] = 0;
1957 $toc .= $sk->tocIndent( $level - $prevlevel );
1958 $toclevel +
= $level - $prevlevel;
1960 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1961 # reset when we step back a level
1962 $sublevelCount[$level+
1]=0;
1963 $toc .= $sk->tocUnindent( $prevlevel - $level );
1964 $toclevel -= $prevlevel - $level;
1966 # count number of headlines for each level
1967 @$sublevelCount[$level]++
;
1968 if( $doNumberHeadings ||
$doShowToc ) {
1970 for( $i = 1; $i <= $level; $i++
) {
1971 if( !empty( $sublevelCount[$i] ) ) {
1975 $numbering .= $wgLang->formatNum( $sublevelCount[$i] );
1981 # The canonized header is a version of the header text safe to use for links
1982 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1983 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
1984 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
1986 # Remove link placeholders by the link text.
1987 # <!--LINK namespace page_title link text with suffix-->
1989 # link text with suffix
1990 $canonized_headline = preg_replace( '/<!--LINK [0-9]* [^ ]* *(.*?)-->/','$1', $canonized_headline );
1992 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
1993 $tocline = trim( $canonized_headline );
1994 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
1995 $replacearray = array(
1999 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2000 $refer[$headlineCount] = $canonized_headline;
2002 # count how many in assoc. array so we can track dupes in anchors
2003 @$refers[$canonized_headline]++
;
2004 $refcount[$headlineCount]=$refers[$canonized_headline];
2006 # Prepend the number to the heading text
2008 if( $doNumberHeadings ||
$doShowToc ) {
2009 $tocline = $numbering . ' ' . $tocline;
2011 # Don't number the heading if it is the only one (looks silly)
2012 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2013 # the two are different if the line contains a link
2014 $headline=$numbering . ' ' . $headline;
2018 # Create the anchor for linking from the TOC to the section
2019 $anchor = $canonized_headline;
2020 if($refcount[$headlineCount] > 1 ) {
2021 $anchor .= '_' . $refcount[$headlineCount];
2023 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2024 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2026 if( $showEditLink ) {
2027 if ( empty( $head[$headlineCount] ) ) {
2028 $head[$headlineCount] = '';
2030 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
2033 # Add the edit section span
2034 if( $rightClickHack ) {
2035 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
2038 # give headline the correct <h#> tag
2039 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2045 $toclines = $headlineCount;
2046 $toc .= $sk->tocUnindent( $toclevel );
2047 $toc = $sk->tocTable( $toc );
2050 # split up and insert constructed headlines
2052 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2055 foreach( $blocks as $block ) {
2056 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2057 # This is the [edit] link that appears for the top block of text when
2058 # section editing is enabled
2060 # Disabled because it broke block formatting
2061 # For example, a bullet point in the top line
2062 # $full .= $sk->editSectionLink(0);
2065 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2066 # Top anchor now in skin
2070 if( !empty( $head[$i] ) ) {
2076 $mw =& MagicWord
::get( MAG_TOC
);
2077 return $mw->replace( $toc, $full );
2083 # Return an HTML link for the "ISBN 123456" text
2084 /* private */ function magicISBN( $text ) {
2086 $fname = 'Parser::magicISBN';
2087 wfProfileIn( $fname );
2089 $a = split( 'ISBN ', ' '.$text );
2090 if ( count ( $a ) < 2 ) {
2091 wfProfileOut( $fname );
2094 $text = substr( array_shift( $a ), 1);
2095 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2097 foreach ( $a as $x ) {
2098 $isbn = $blank = '' ;
2099 while ( ' ' == $x{0} ) {
2101 $x = substr( $x, 1 );
2103 if ( $x == '' ) { # blank isbn
2104 $text .= "ISBN $blank";
2107 while ( strstr( $valid, $x{0} ) != false ) {
2109 $x = substr( $x, 1 );
2111 $num = str_replace( '-', '', $isbn );
2112 $num = str_replace( ' ', '', $num );
2115 $text .= "ISBN $blank$x";
2117 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2118 $text .= '<a href="' .
2119 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2120 "\" class=\"internal\">ISBN $isbn</a>";
2124 wfProfileOut( $fname );
2128 # Return an HTML link for the "GEO ..." text
2129 /* private */ function magicGEO( $text ) {
2130 global $wgLang, $wgUseGeoMode;
2131 $fname = 'Parser::magicGEO';
2132 wfProfileIn( $fname );
2134 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2135 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2136 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2137 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2138 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2139 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2141 $a = split( 'GEO ', ' '.$text );
2142 if ( count ( $a ) < 2 ) {
2143 wfProfileOut( $fname );
2146 $text = substr( array_shift( $a ), 1);
2147 $valid = '0123456789.+-:';
2149 foreach ( $a as $x ) {
2150 $geo = $blank = '' ;
2151 while ( ' ' == $x{0} ) {
2153 $x = substr( $x, 1 );
2155 while ( strstr( $valid, $x{0} ) != false ) {
2157 $x = substr( $x, 1 );
2159 $num = str_replace( '+', '', $geo );
2160 $num = str_replace( ' ', '', $num );
2162 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2163 $text .= "GEO $blank$x";
2165 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2166 $text .= '<a href="' .
2167 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2168 "\" class=\"internal\">GEO $geo</a>";
2172 wfProfileOut( $fname );
2176 # Return an HTML link for the "RFC 1234" text
2177 /* private */ function magicRFC( $text ) {
2180 $a = split( 'RFC ', ' '.$text );
2181 if ( count ( $a ) < 2 ) return $text;
2182 $text = substr( array_shift( $a ), 1);
2183 $valid = '0123456789';
2185 foreach ( $a as $x ) {
2186 $rfc = $blank = '' ;
2187 while ( ' ' == $x{0} ) {
2189 $x = substr( $x, 1 );
2191 while ( strstr( $valid, $x{0} ) != false ) {
2193 $x = substr( $x, 1 );
2197 $text .= "RFC $blank$x";
2199 $url = wfmsg( 'rfcurl' );
2200 $url = str_replace( '$1', $rfc, $url);
2201 $sk =& $this->mOptions
->getSkin();
2202 $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
2203 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2209 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2210 $this->mOptions
= $options;
2211 $this->mTitle
=& $title;
2212 $this->mOutputType
= OT_WIKI
;
2214 if ( $clearState ) {
2215 $this->clearState();
2218 $stripState = false;
2222 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2226 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2227 "/<br *?>/i" => "<br />",
2229 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2231 $text = $this->strip( $text, $stripState, false );
2232 $text = $this->pstPass2( $text, $user );
2233 $text = $this->unstrip( $text, $stripState );
2234 $text = $this->unstripNoWiki( $text, $stripState );
2238 /* private */ function pstPass2( $text, &$user ) {
2239 global $wgLang, $wgLocaltimezone, $wgCurParser;
2241 # Variable replacement
2242 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2243 $text = $this->replaceVariables( $text );
2247 $n = $user->getName();
2248 $k = $user->getOption( 'nickname' );
2249 if ( '' == $k ) { $k = $n; }
2250 if(isset($wgLocaltimezone)) {
2251 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2253 /* Note: this is an ugly timezone hack for the European wikis */
2254 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2255 ' (' . date( 'T' ) . ')';
2256 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2258 $text = preg_replace( '/~~~~~/', $d, $text );
2259 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2260 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2262 # Context links: [[|name]] and [[name (context)|]]
2264 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2265 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2266 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2267 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2269 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2270 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2271 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2272 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2274 $t = $this->mTitle
->getText();
2275 if ( preg_match( $conpat, $t, $m ) ) {
2278 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2279 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2280 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2282 if ( '' == $context ) {
2283 $text = preg_replace( $p2, '[[\\1]]', $text );
2285 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2289 $mw =& MagicWord::get( MAG_SUBST );
2290 $wgCurParser = $this->fork();
2291 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2292 $this->merge( $wgCurParser );
2295 # Trim trailing whitespace
2296 # MAG_END (__END__) tag allows for trailing
2297 # whitespace to be deliberately included
2298 $text = rtrim( $text );
2299 $mw =& MagicWord
::get( MAG_END
);
2300 $mw->matchAndRemove( $text );
2305 # Set up some variables which are usually set up in parse()
2306 # so that an external function can call some class members with confidence
2307 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2308 $this->mTitle
=& $title;
2309 $this->mOptions
= $options;
2310 $this->mOutputType
= $outputType;
2311 if ( $clearState ) {
2312 $this->clearState();
2316 function transformMsg( $text, $options ) {
2318 static $executing = false;
2320 # Guard against infinite recursion
2326 $this->mTitle
= $wgTitle;
2327 $this->mOptions
= $options;
2328 $this->mOutputType
= OT_MSG
;
2329 $this->clearState();
2330 $text = $this->replaceVariables( $text );
2336 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2337 # Callback will be called with the text within
2338 # Transform and return the text within
2339 function setHook( $tag, $callback ) {
2340 $oldVal = @$this->mTagHooks
[$tag];
2341 $this->mTagHooks
[$tag] = $callback;
2348 * @package MediaWiki
2352 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2353 var $mCacheTime; # Used in ParserCache
2355 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2356 $containsOldMagic = false )
2358 $this->mText
= $text;
2359 $this->mLanguageLinks
= $languageLinks;
2360 $this->mCategoryLinks
= $categoryLinks;
2361 $this->mContainsOldMagic
= $containsOldMagic;
2362 $this->mCacheTime
= '';
2365 function getText() { return $this->mText
; }
2366 function getLanguageLinks() { return $this->mLanguageLinks
; }
2367 function getCategoryLinks() { return $this->mCategoryLinks
; }
2368 function getCacheTime() { return $this->mCacheTime
; }
2369 function containsOldMagic() { return $this->mContainsOldMagic
; }
2370 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2371 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2372 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2373 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2374 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2376 function merge( $other ) {
2377 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2378 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2379 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2385 * Set options of the Parser
2387 * @package MediaWiki
2391 # All variables are private
2392 var $mUseTeX; # Use texvc to expand <math> tags
2393 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2394 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2395 var $mAllowExternalImages; # Allow external images inline
2396 var $mSkin; # Reference to the preferred skin
2397 var $mDateFormat; # Date format index
2398 var $mEditSection; # Create "edit section" links
2399 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2400 var $mNumberHeadings; # Automatically number headings
2401 var $mShowToc; # Show table of contents
2403 function getUseTeX() { return $this->mUseTeX
; }
2404 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2405 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2406 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2407 function getSkin() { return $this->mSkin
; }
2408 function getDateFormat() { return $this->mDateFormat
; }
2409 function getEditSection() { return $this->mEditSection
; }
2410 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2411 function getNumberHeadings() { return $this->mNumberHeadings
; }
2412 function getShowToc() { return $this->mShowToc
; }
2414 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2415 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2416 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2417 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2418 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2419 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2420 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2421 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2422 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2424 function setSkin( &$x ) { $this->mSkin
=& $x; }
2426 # Get parser options
2427 /* static */ function newFromUser( &$user ) {
2428 $popts = new ParserOptions
;
2429 $popts->initialiseFromUser( $user );
2434 function initialiseFromUser( &$userInput ) {
2435 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2437 $fname = 'ParserOptions::initialiseFromUser';
2438 wfProfileIn( $fname );
2439 if ( !$userInput ) {
2441 $user->setLoaded( true );
2443 $user =& $userInput;
2446 $this->mUseTeX
= $wgUseTeX;
2447 $this->mUseDynamicDates
= $wgUseDynamicDates;
2448 $this->mInterwikiMagic
= $wgInterwikiMagic;
2449 $this->mAllowExternalImages
= $wgAllowExternalImages;
2450 wfProfileIn( $fname.'-skin' );
2451 $this->mSkin
=& $user->getSkin();
2452 wfProfileOut( $fname.'-skin' );
2453 $this->mDateFormat
= $user->getOption( 'date' );
2454 $this->mEditSection
= $user->getOption( 'editsection' );
2455 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2456 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2457 $this->mShowToc
= $user->getOption( 'showtoc' );
2458 wfProfileOut( $fname );
2464 # Regex callbacks, used in Parser::replaceVariables
2465 function wfBraceSubstitution( $matches ) {
2466 global $wgCurParser;
2467 return $wgCurParser->braceSubstitution( $matches );
2470 function wfArgSubstitution( $matches ) {
2471 global $wgCurParser;
2472 return $wgCurParser->argSubstitution( $matches );
2475 function wfVariableSubstitution( $matches ) {
2476 global $wgCurParser;
2477 return $wgCurParser->variableSubstitution( $matches );
2481 * Return the total number of articles
2483 function wfNumberOfArticles() {
2484 global $wgNumberOfArticles;
2487 return $wgNumberOfArticles;
2491 * Get various statistics from the database
2494 function wfLoadSiteStats() {
2495 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2496 $fname = 'wfLoadSiteStats';
2498 if ( -1 != $wgNumberOfArticles ) return;
2499 $dbr =& wfGetDB( DB_SLAVE
);
2500 $s = $dbr->getArray( 'site_stats',
2501 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2502 array( 'ss_row_id' => 1 ), $fname
2505 if ( $s === false ) {
2508 $wgTotalViews = $s->ss_total_views
;
2509 $wgTotalEdits = $s->ss_total_edits
;
2510 $wgNumberOfArticles = $s->ss_good_articles
;
2514 function wfEscapeHTMLTagsOnly( $in ) {
2516 array( '"', '>', '<' ),
2517 array( '"', '>', '<' ),