3 // require_once('Tokenizer.php');
5 if( $GLOBALS['wgUseWikiHiero'] ){
6 require_once('extensions/wikihiero/wikihiero.php');
8 if( $GLOBALS['wgUseTimeline'] ){
9 require_once('extensions/timeline/Timeline.php');
14 # Processes wiki markup
16 # There are two main entry points into the Parser class: parse() and preSaveTransform().
17 # The parse() function produces HTML output, preSaveTransform() produces altered wiki markup.
20 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
22 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
24 # settings: $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
25 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
28 # * only within ParserOptions
31 #----------------------------------------
32 # Variable substitution O(N^2) attack
33 #-----------------------------------------
34 # Without countermeasures, it would be possible to attack the parser by saving a page
35 # filled with a large number of inclusions of large pages. The size of the generated
36 # page would be proportional to the square of the input size. Hence, we limit the number
37 # of inclusions of any given page, thus bringing any attack back to O(N).
40 define( "MAX_INCLUDE_REPEAT", 5 );
42 # Allowed values for $mOutputType
43 define( "OT_HTML", 1 );
44 define( "OT_WIKI", 2 );
45 define( "OT_MSG", 3 );
47 # string parameter for extractTags which will cause it
48 # to strip HTML comments in addition to regular
49 # <XML>-style tags. This should not be anything we
50 # may want to use in wikisyntax
51 define( "STRIP_COMMENTS", "HTMLCommentStrip" );
53 # prefix for escaping, used in two functions at least
54 define( "UNIQ_PREFIX", "NaodW29");
58 # Cleared with clearState():
59 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
60 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
63 var $mOptions, $mTitle, $mOutputType;
72 $this->mOutput
= new ParserOutput
;
73 $this->mAutonumber
= 0;
74 $this->mLastSection
= "";
75 $this->mDTopen
= false;
76 $this->mVariables
= false;
77 $this->mIncludeCount
= array();
78 $this->mStripState
= array();
79 $this->mArgStack
= array();
82 # First pass--just handle <nowiki> sections, pass the rest off
83 # to internalParse() which does all the real work.
85 # Returns a ParserOutput
87 function parse( $text, &$title, $options, $linestart = true, $clearState = true )
90 $fname = "Parser::parse";
91 wfProfileIn( $fname );
97 $this->mOptions
= $options;
98 $this->mTitle
=& $title;
99 $this->mOutputType
= OT_HTML
;
102 $text = $this->strip( $text, $this->mStripState
);
103 $text = $this->internalParse( $text, $linestart );
104 $text = $this->unstrip( $text, $this->mStripState
);
105 # Clean up special characters, only run once, next-to-last before doBlockLevels
108 # french spaces, last one Guillemet-left
109 "/ (\\?|:|!|\\302\\273)/i"=>" \\1",
110 # french spaces, Guillemet-right
111 "/(\\302\\253) /i"=>"\\1 ",
112 "/<hr *>/i" => '<hr/>',
113 "/<br *>/i" => '<br/>',
114 "/<center *>/i"=>'<div class="center">',
115 "/<\\/center *>/i" => '</div>',
116 # Clean up spare ampersands; note that we probably ought to be
117 # more careful about named entities.
118 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
120 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
123 # french spaces, last one Guillemet-left
124 "/ (\\?|:|!|\\302\\273)/i"=>" \\1",
125 # french spaces, Guillemet-right
126 "/(\\302\\253) /i"=>"\\1 ",
127 "/<center *>/i"=>'<div class="center">',
128 "/<\\/center *>/i" => '</div>'
130 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
133 $text = $this->doBlockLevels( $text, $linestart );
135 $text = $this->tidy($text);
137 $this->mOutput
->setText( $text );
138 wfProfileOut( $fname );
139 return $this->mOutput
;
142 /* static */ function getRandomString()
144 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
147 # Replaces all occurrences of <$tag>content</$tag> in the text
148 # with a random marker and returns the new text. the output parameter
149 # $content will be an associative array filled with data on the form
150 # $unique_marker => content.
152 # If $content is already set, the additional entries will be appended
154 # If $tag is set to STRIP_COMMENTS, the function will extract
155 # <!-- HTML comments -->
157 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
158 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
165 while ( "" != $text ) {
166 if($tag==STRIP_COMMENTS
) {
167 $p = preg_split( "/<!--/i", $text, 2 );
169 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
172 if ( ( count( $p ) < 2 ) ||
( "" == $p[1] ) ) {
175 if($tag==STRIP_COMMENTS
) {
176 $q = preg_split( "/-->/i", $p[1], 2 );
178 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
180 $marker = $rnd . sprintf("%08X", $n++
);
181 $content[$marker] = $q[0];
182 $stripped .= $marker;
189 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
190 # If $render is set, performs necessary rendering operations on plugins
191 # Returns the text, and fills an array with data needed in unstrip()
192 # If the $state is already a valid strip state, it adds to the state
194 # When $stripcomments is set, HTML comments <!-- like this -->
195 # will be stripped in addition to other tags. This is important
196 # for section editing, where these comments cause confusion when
197 # counting the sections in the wikisource
198 function strip( $text, &$state, $stripcomments = false )
200 $render = ($this->mOutputType
== OT_HTML
);
201 $nowiki_content = array();
202 $hiero_content = array();
203 $timeline_content = array();
204 $math_content = array();
205 $pre_content = array();
206 $comment_content = array();
208 # Replace any instances of the placeholders
209 $uniq_prefix = UNIQ_PREFIX
;
210 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
212 $text = Parser
::extractTags("nowiki", $text, $nowiki_content, $uniq_prefix);
213 foreach( $nowiki_content as $marker => $content ){
215 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
217 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
221 $text = Parser
::extractTags("hiero", $text, $hiero_content, $uniq_prefix);
222 foreach( $hiero_content as $marker => $content ){
223 if( $render && $GLOBALS['wgUseWikiHiero']){
224 $hiero_content[$marker] = WikiHiero( $content, WH_MODE_HTML
);
226 $hiero_content[$marker] = "<hiero>$content</hiero>";
230 $text = Parser
::extractTags("timeline", $text, $timeline_content, $uniq_prefix);
231 foreach( $timeline_content as $marker => $content ){
232 if( $render && $GLOBALS['wgUseTimeline']){
233 $timeline_content[$marker] = renderTimeline( $content );
235 $timeline_content[$marker] = "<timeline>$content</timeline>";
239 $text = Parser
::extractTags("math", $text, $math_content, $uniq_prefix);
240 foreach( $math_content as $marker => $content ){
242 if( $this->mOptions
->getUseTeX() ) {
243 $math_content[$marker] = renderMath( $content );
245 $math_content[$marker] = "<math>$content<math>";
248 $math_content[$marker] = "<math>$content</math>";
252 $text = Parser
::extractTags("pre", $text, $pre_content, $uniq_prefix);
253 foreach( $pre_content as $marker => $content ){
255 $pre_content[$marker] = "<pre>" . wfEscapeHTMLTagsOnly( $content ) . "</pre>";
257 $pre_content[$marker] = "<pre>$content</pre>";
261 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
262 foreach( $comment_content as $marker => $content ){
263 $comment_content[$marker] = "<!--$content-->";
267 # Merge state with the pre-existing state, if there is one
269 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
270 $state['hiero'] = $state['hiero'] +
$hiero_content;
271 $state['timeline'] = $state['timeline'] +
$timeline_content;
272 $state['math'] = $state['math'] +
$math_content;
273 $state['pre'] = $state['pre'] +
$pre_content;
274 $state['comment'] = $state['comment'] +
$comment_content;
277 'nowiki' => $nowiki_content,
278 'hiero' => $hiero_content,
279 'timeline' => $timeline_content,
280 'math' => $math_content,
281 'pre' => $pre_content,
282 'comment' => $comment_content
288 function unstrip( $text, &$state )
290 # Must expand in reverse order, otherwise nested tags will be corrupted
291 $contentDict = end( $state );
292 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
293 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
294 $text = str_replace( key( $contentDict ), $content, $text );
301 # Add an item to the strip state
302 # Returns the unique tag which must be inserted into the stripped text
303 # The tag will be replaced with the original text in unstrip()
305 function insertStripItem( $text, &$state )
307 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
316 $state['item'][$rnd] = $text;
320 # This method generates the list of subcategories and pages for a category
321 function categoryMagic ()
323 global $wgLang , $wgUser ;
324 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
326 $cns = Namespace::getCategory() ;
327 if ( $this->mTitle
->getNamespace() != $cns ) return "" ; # This ain't a category page
329 $r = "<br style=\"clear:both;\"/>\n";
332 $sk =& $wgUser->getSkin() ;
334 $articles = array() ;
335 $children = array() ;
337 $id = $this->mTitle
->getArticleID() ;
340 $t = wfStrencode( $this->mTitle
->getDBKey() );
341 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM cur,categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
342 $res = wfQuery ( $sql, DB_READ
) ;
343 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
345 # For all pages that link to this category
346 foreach ( $data AS $x )
348 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
349 if ( $t != "" ) $t .= ":" ;
350 $t .= $x->cur_title
;
352 if ( $x->cur_namespace
== $cns ) {
353 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
355 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
358 wfFreeResult ( $res ) ;
360 # Showing subcategories
361 if ( count ( $children ) > 0 ) {
362 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
363 $r .= implode ( ", " , $children ) ;
366 # Showing pages in this category
367 if ( count ( $articles ) > 0 ) {
368 $ti = $this->mTitle
->getText() ;
369 $h = wfMsg( "category_header", $ti );
370 $r .= "<h2>{$h}</h2>\n" ;
371 $r .= implode ( ", " , $articles ) ;
378 function getHTMLattrs ()
380 $htmlattrs = array( # Allowed attributes--no scripting, etc.
381 "title", "align", "lang", "dir", "width", "height",
382 "bgcolor", "clear", /* BR */ "noshade", /* HR */
383 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
384 /* FONT */ "type", "start", "value", "compact",
385 /* For various lists, mostly deprecated but safe */
386 "summary", "width", "border", "frame", "rules",
387 "cellspacing", "cellpadding", "valign", "char",
388 "charoff", "colgroup", "col", "span", "abbr", "axis",
389 "headers", "scope", "rowspan", "colspan", /* Tables */
390 "id", "class", "name", "style" /* For CSS */
395 function fixTagAttributes ( $t )
397 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
398 $htmlattrs = $this->getHTMLattrs() ;
400 # Strip non-approved attributes from the tag
402 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
403 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
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;
423 switch(strtoupper($wgOutputEncoding)) {
425 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
428 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
431 $wgTidyOpts .= ' -raw';
434 $text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
435 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
436 '<head><title>test</title></head><body>'.$text.'</body></html>';
437 $descriptorspec = array(
438 0 => array("pipe", "r"),
439 1 => array("pipe", "w"),
440 2 => array("file", "/dev/null", "a")
442 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
443 if (is_resource($process)) {
444 fwrite($pipes[0], $text);
446 while (!feof($pipes[1])) {
447 $cleansource .= fgets($pipes[1], 1024);
450 $return_value = proc_close($process);
452 if( $cleansource == '' && $text != '') {
453 return '<h2>'.wfMsg('seriousxhtmlerrors').'</h2><pre>'.htmlspecialchars($text).'</pre>';
459 function doTableStuff ( $t )
461 $t = explode ( "\n" , $t ) ;
462 $td = array () ; # Is currently a td tag open?
463 $ltd = array () ; # Was it TD or TH?
464 $tr = array () ; # Is currently a tr tag open?
465 $ltr = array () ; # tr attributes
466 foreach ( $t AS $k => $x )
469 $fc = substr ( $x , 0 , 1 ) ;
470 if ( "{|" == substr ( $x , 0 , 2 ) )
472 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
473 array_push ( $td , false ) ;
474 array_push ( $ltd , "" ) ;
475 array_push ( $tr , false ) ;
476 array_push ( $ltr , "" ) ;
478 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
479 else if ( "|}" == substr ( $x , 0 , 2 ) )
482 $l = array_pop ( $ltd ) ;
483 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
484 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
488 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
490 $z = trim ( substr ( $x , 2 ) ) ;
491 $t[$k] = "<caption>{$z}</caption>\n" ;
493 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
495 $x = substr ( $x , 1 ) ;
496 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
498 $l = array_pop ( $ltd ) ;
499 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
500 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
503 array_push ( $tr , false ) ;
504 array_push ( $td , false ) ;
505 array_push ( $ltd , "" ) ;
506 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
508 else if ( "|" == $fc ||
"!" == $fc ||
"|+" == substr ( $x , 0 , 2 ) ) # Caption
510 if ( "|+" == substr ( $x , 0 , 2 ) )
513 $x = substr ( $x , 1 ) ;
515 $after = substr ( $x , 1 ) ;
516 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
517 $after = explode ( "||" , $after ) ;
519 foreach ( $after AS $theline )
524 $tra = array_pop ( $ltr ) ;
525 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
526 array_push ( $tr , true ) ;
527 array_push ( $ltr , "" ) ;
530 $l = array_pop ( $ltd ) ;
531 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
532 if ( $fc == "|" ) $l = "td" ;
533 else if ( $fc == "!" ) $l = "th" ;
534 else if ( $fc == "+" ) $l = "caption" ;
536 array_push ( $ltd , $l ) ;
537 $y = explode ( "|" , $theline , 2 ) ;
538 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
539 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
541 array_push ( $td , true ) ;
546 # Closing open td, tr && table
547 while ( count ( $td ) > 0 )
549 if ( array_pop ( $td ) ) $t[] = "</td>" ;
550 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
554 $t = implode ( "\n" , $t ) ;
555 # $t = $this->removeHTMLtags( $t );
559 # Parses the text and adds the result to the strip state
560 # Returns the strip tag
561 function stripParse( $text, $linestart, $args )
563 $text = $this->strip( $text, $this->mStripState
);
564 $text = $this->internalParse( $text, $linestart, $args, false );
566 $text = "\n" . $text;
568 return $this->insertStripItem( $text, $this->mStripState
);
571 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->replaceInternalLinks ( $text );
589 //$text = $this->doTokenizedParser ( $text );
590 $text = $this->doTableStuff ( $text ) ;
591 $text = $this->magicISBN( $text );
592 $text = $this->magicRFC( $text );
593 $text = $this->formatHeadings( $text, $isMain );
594 $sk =& $this->mOptions
->getSkin();
595 $text = $sk->transformContent( $text );
597 if ( !isset ( $this->categoryMagicDone
) ) {
598 $text .= $this->categoryMagic () ;
599 $this->categoryMagicDone
= true ;
602 wfProfileOut( $fname );
607 /* private */ function doHeadings( $text )
609 for ( $i = 6; $i >= 1; --$i ) {
610 $h = substr( "======", 0, $i );
611 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
612 "<h{$i}>\\1</h{$i}>\\2", $text );
617 /* private */ function doAllQuotes( $text )
620 $lines = explode( "\r\n", $text );
621 foreach ( $lines as $line ) {
622 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
627 /* private */ function doQuotes( $pre, $text, $mode )
629 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
630 $m1_strong = ($m[1] == "") ?
"" : "<strong>{$m[1]}</strong>";
631 $m1_em = ($m[1] == "") ?
"" : "<em>{$m[1]}</em>";
632 if ( substr ($m[2], 0, 1) == "'" ) {
633 $m[2] = substr ($m[2], 1);
635 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ?
"both" : "emstrong" );
636 } else if ($mode == "strong") {
637 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
638 } else if (($mode == "emstrong") ||
($mode == "both")) {
639 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
640 } else if ($mode == "strongem") {
641 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
643 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
646 if ($mode == "strong") {
647 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ?
"both" : "strongem" );
648 } else if ($mode == "em") {
649 return $m1_em . $this->doQuotes ( "", $m[2], "" );
650 } else if ($mode == "emstrong") {
651 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
652 } else if (($mode == "strongem") ||
($mode == "both")) {
653 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
655 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
659 $text_strong = ($text == "") ?
"" : "<strong>{$text}</strong>";
660 $text_em = ($text == "") ?
"" : "<em>{$text}</em>";
663 } else if ($mode == "em") {
664 return $pre . $text_em;
665 } else if ($mode == "strong") {
666 return $pre . $text_strong;
667 } else if ($mode == "strongem") {
668 return (($pre == "") && ($text == "")) ?
"" : "<strong>{$pre}{$text_em}</strong>";
670 return (($pre == "") && ($text == "")) ?
"" : "<em>{$pre}{$text_strong}</em>";
675 # Note: we have to do external links before the internal ones,
676 # and otherwise take great care in the order of things here, so
677 # that we don't end up interpreting some URLs twice.
679 /* private */ function replaceExternalLinks( $text )
681 $fname = "Parser::replaceExternalLinks";
682 wfProfileIn( $fname );
683 $text = $this->subReplaceExternalLinks( $text, "http", true );
684 $text = $this->subReplaceExternalLinks( $text, "https", true );
685 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
686 $text = $this->subReplaceExternalLinks( $text, "irc", false );
687 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
688 $text = $this->subReplaceExternalLinks( $text, "news", false );
689 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
690 wfProfileOut( $fname );
694 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
696 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
697 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
699 # this is the list of separators that should be ignored if they
700 # are the last character of an URL but that should be included
701 # if they occur within the URL, e.g. "go to www.foo.com, where .."
702 # in this case, the last comma should not become part of the URL,
703 # but in "www.foo.com/123,2342,32.htm" it should.
705 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
706 $images = "gif|png|jpg|jpeg";
708 # PLEASE NOTE: The curly braces { } are not part of the regex,
709 # they are interpreted as part of the string (used to tell PHP
710 # that the content of the string should be inserted there).
711 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
712 "((?i){$images})([^{$uc}]|$)/";
714 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
715 $sk =& $this->mOptions
->getSkin();
717 if ( $autonumber and $this->mOptions
->getAllowExternalImages() ) { # Use img tags only for HTTP urls
718 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
719 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
721 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
722 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
723 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
725 $s = str_replace( $unique, $protocol, $s );
727 $a = explode( "[{$protocol}:", " " . $s );
728 $s = array_shift( $a );
729 $s = substr( $s, 1 );
731 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
732 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
734 foreach ( $a as $line ) {
735 if ( preg_match( $e1, $line, $m ) ) {
736 $link = "{$protocol}:{$m[1]}";
738 if ( $autonumber ) { $text = "[" . ++
$this->mAutonumber
. "]"; }
739 else { $text = wfEscapeHTML( $link ); }
740 } else if ( preg_match( $e2, $line, $m ) ) {
741 $link = "{$protocol}:{$m[1]}";
745 $s .= "[{$protocol}:" . $line;
748 if( $link == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
751 # Expand the URL for printable version
752 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
754 $la = $sk->getExternalLinkAttributes( $link, $text );
755 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
762 /* private */ function replaceInternalLinks( $s )
764 global $wgLang, $wgLinkCache;
765 global $wgNamespacesWithSubpages, $wgLanguageCode;
766 static $fname = "Parser::replaceInternalLink" ;
767 wfProfileIn( $fname );
769 wfProfileIn( "$fname-setup" );
771 # the % is needed to support urlencoded titles as well
772 if ( !$tc ) { $tc = Title
::legalChars() . "#%"; }
773 $sk =& $this->mOptions
->getSkin();
775 $a = explode( "[[", " " . $s );
776 $s = array_shift( $a );
777 $s = substr( $s, 1 );
779 # Match a link having the form [[namespace:link|alternate]]trail
781 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
782 # Match the end of a line for a word that's not followed by whitespace,
783 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
784 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
785 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
786 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
789 # Special and Media are pseudo-namespaces; no pages actually exist in them
790 static $image = FALSE;
791 static $special = FALSE;
792 static $media = FALSE;
793 static $category = FALSE;
794 if ( !$image ) { $image = Namespace::getImage(); }
795 if ( !$special ) { $special = Namespace::getSpecial(); }
796 if ( !$media ) { $media = Namespace::getMedia(); }
797 if ( !$category ) { $category = Namespace::getCategory(); }
799 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
801 if ( $wgLang->linkPrefixExtension() && preg_match( $e2, $s, $m ) ) {
808 wfProfileOut( "$fname-setup" );
810 foreach ( $a as $line ) {
811 $prefix = $new_prefix;
813 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
815 # fix up urlencoded title texts
816 if(preg_match("/%/", $m[1] )) $m[1] = urldecode($m[1]);
818 } else { # Invalid form; output directly
819 $s .= $prefix . "[[" . $line ;
820 wfProfileOut( $fname );
826 :Foobar -- override special treatment of prefix (images, language links)
827 /Foobar -- convert to CurrentPage/Foobar
828 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
830 $c = substr($m[1],0,1);
831 $noforce = ($c != ":");
832 if( $c == "/" ) { # subpage
833 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
834 $m[1]=substr($m[1],1,strlen($m[1])-2);
837 $noslash=substr($m[1],1);
839 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) { # subpages allowed here
840 $link = $this->mTitle
->getPrefixedText(). "/" . trim($noslash);
843 } # this might be changed for ugliness reasons
845 $link = $noslash; # no subpage allowed, use standard link
847 } elseif( $noforce ) { # no subpage
850 $link = substr( $m[1], 1 );
852 $wasblank = ( "" == $text );
856 $nt = Title
::newFromText( $link );
858 $s .= $prefix . "[[" . $line;
859 wfProfileOut( $fname );
862 $ns = $nt->getNamespace();
863 $iw = $nt->getInterWiki();
865 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
866 array_push( $this->mOutput
->mLanguageLinks
, $nt->getPrefixedText() );
867 $s .= $prefix . $trail ;
868 wfProfileOut( $fname );
869 return (trim($s) == '')?
'': $s;
872 if ( $ns == $image ) {
873 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
874 $wgLinkCache->addImageLinkObj( $nt );
875 wfProfileOut( $fname );
877 } else if ( $ns == $category ) {
878 $t = $nt->getText() ;
879 $nnt = Title
::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
881 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
882 $t = $sk->makeLinkObj( $nnt, $t, "", "" , $prefix );
883 $wgLinkCache->resume();
885 $sortkey = $wasblank ?
$this->mTitle
->getPrefixedText() : $text;
886 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
887 $this->mOutput
->mCategoryLinks
[] = $t ;
888 $s .= $prefix . $trail ;
889 wfProfileOut( $fname );
893 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
894 ( strpos( $link, "#" ) == FALSE ) ) {
895 # Self-links are handled specially; generally de-link and change to bold.
896 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, "", $trail );
897 wfProfileOut( $fname );
901 if( $ns == $media ) {
902 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
903 $wgLinkCache->addImageLinkObj( $nt );
904 wfProfileOut( $fname );
906 } elseif( $ns == $special ) {
907 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
908 wfProfileOut( $fname );
911 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
913 wfProfileOut( $fname );
917 # Some functions here used by doBlockLevels()
919 /* private */ function closeParagraph()
922 if ( '' != $this->mLastSection
) {
923 $result = "</" . $this->mLastSection
. ">\n";
925 $this->mInPre
= false;
926 $this->mLastSection
= "";
929 # getCommon() returns the length of the longest common substring
930 # of both arguments, starting at the beginning of both.
932 /* private */ function getCommon( $st1, $st2 )
934 $fl = strlen( $st1 );
935 $shorter = strlen( $st2 );
936 if ( $fl < $shorter ) { $shorter = $fl; }
938 for ( $i = 0; $i < $shorter; ++
$i ) {
939 if ( $st1{$i} != $st2{$i} ) { break; }
943 # These next three functions open, continue, and close the list
944 # element appropriate to the prefix character passed into them.
946 /* private */ function openList( $char )
948 $result = $this->closeParagraph();
950 if ( "*" == $char ) { $result .= "<ul><li>"; }
951 else if ( "#" == $char ) { $result .= "<ol><li>"; }
952 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
953 else if ( ";" == $char ) {
954 $result .= "<dl><dt>";
955 $this->mDTopen
= true;
957 else { $result = "<!-- ERR 1 -->"; }
962 /* private */ function nextItem( $char )
964 if ( "*" == $char ||
"#" == $char ) { return "</li><li>"; }
965 else if ( ":" == $char ||
";" == $char ) {
967 if ( $this->mDTopen
) { $close = "</dt>"; }
968 if ( ";" == $char ) {
969 $this->mDTopen
= true;
970 return $close . "<dt>";
972 $this->mDTopen
= false;
973 return $close . "<dd>";
976 return "<!-- ERR 2 -->";
979 /* private */function closeList( $char )
981 if ( "*" == $char ) { $text = "</li></ul>"; }
982 else if ( "#" == $char ) { $text = "</li></ol>"; }
983 else if ( ":" == $char ) {
984 if ( $this->mDTopen
) {
985 $this->mDTopen
= false;
986 $text = "</dt></dl>";
988 $text = "</dd></dl>";
991 else { return "<!-- ERR 3 -->"; }
995 /* private */ function doBlockLevels( $text, $linestart ) {
996 $fname = "Parser::doBlockLevels";
997 wfProfileIn( $fname );
999 # Parsing through the text line by line. The main thing
1000 # happening here is handling of block-level elements p, pre,
1001 # and making lists from lines starting with * # : etc.
1003 $textLines = explode( "\n", $text );
1005 $lastPrefix = $output = $lastLine = '';
1006 $this->mDTopen
= $inBlockElem = false;
1008 $paragraphStack = false;
1010 if ( !$linestart ) {
1011 $output .= array_shift( $textLines );
1013 foreach ( $textLines as $oLine ) {
1014 $lastPrefixLength = strlen( $lastPrefix );
1015 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1016 $preOpenMatch = preg_match("/<pre/i", $oLine );
1017 if (!$this->mInPre
) {
1018 $this->mInPre
= !empty($preOpenMatch);
1020 if ( !$this->mInPre
) {
1021 # Multiple prefixes may abut each other for nested lists.
1022 $prefixLength = strspn( $oLine, "*#:;" );
1023 $pref = substr( $oLine, 0, $prefixLength );
1026 $pref2 = str_replace( ";", ":", $pref );
1027 $t = substr( $oLine, $prefixLength );
1029 # Don't interpret any other prefixes in preformatted text
1031 $pref = $pref2 = '';
1036 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1037 # Same as the last item, so no need to deal with nesting or opening stuff
1038 $output .= $this->nextItem( substr( $pref, -1 ) );
1039 $paragraphStack = false;
1041 if ( ";" == substr( $pref, -1 ) ) {
1042 # The one nasty exception: definition lists work like this:
1043 # ; title : definition text
1044 # So we check for : in the remainder text to split up the
1045 # title and definition, without b0rking links.
1046 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1047 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1049 $output .= $term . $this->nextItem( ":" );
1053 } elseif( $prefixLength ||
$lastPrefixLength ) {
1054 # Either open or close a level...
1055 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1056 $paragraphStack = false;
1058 while( $commonPrefixLength < $lastPrefixLength ) {
1059 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1060 --$lastPrefixLength;
1062 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1063 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1065 while ( $prefixLength > $commonPrefixLength ) {
1066 $char = substr( $pref, $commonPrefixLength, 1 );
1067 $output .= $this->openList( $char );
1069 if ( ";" == $char ) {
1070 # FIXME: This is dupe of code above
1071 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1073 $output .= $term . $this->nextItem( ":" );
1077 ++
$commonPrefixLength;
1079 $lastPrefix = $pref2;
1081 if( 0 == $prefixLength ) {
1082 # No prefix (not in list)--go to paragraph mode
1083 $uniq_prefix = UNIQ_PREFIX
;
1084 // XXX: use a stack for nestable elements like span, table and div
1085 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<td|<p|<ul|<li)/i", $t );
1086 $closematch = preg_match(
1087 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1088 "<div|<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre|<\\/li|<\\/ul)/i", $t );
1089 if ( $openmatch or $closematch ) {
1090 $paragraphStack = false;
1091 $output .= $this->closeParagraph();
1092 if($preOpenMatch and !$preCloseMatch) {
1093 $this->mInPre
= true;
1095 if ( $closematch ) {
1096 $inBlockElem = false;
1098 $inBlockElem = true;
1100 } else if ( !$inBlockElem && !$this->mInPre
) {
1101 if ( " " == $t{0} and trim($t) != '' ) {
1103 if ($this->mLastSection
!= 'pre') {
1104 $paragraphStack = false;
1105 $output .= $this->closeParagraph().'<pre>';
1106 $this->mLastSection
= 'pre';
1110 if ( '' == trim($t) ) {
1111 if ( $paragraphStack ) {
1112 $output .= $paragraphStack.'<br/>';
1113 $paragraphStack = false;
1114 $this->mLastSection
= 'p';
1116 if ($this->mLastSection
!= 'p' ) {
1117 $output .= $this->closeParagraph();
1118 $this->mLastSection
= '';
1119 $paragraphStack = "<p>";
1121 $paragraphStack = '</p><p>';
1125 if ( $paragraphStack ) {
1126 $output .= $paragraphStack;
1127 $paragraphStack = false;
1128 $this->mLastSection
= 'p';
1129 } else if ($this->mLastSection
!= 'p') {
1130 $output .= $this->closeParagraph().'<p>';
1131 $this->mLastSection
= 'p';
1137 if ($paragraphStack === false) {
1141 while ( $prefixLength ) {
1142 $output .= $this->closeList( $pref2{$prefixLength-1} );
1145 if ( "" != $this->mLastSection
) {
1146 $output .= "</" . $this->mLastSection
. ">";
1147 $this->mLastSection
= "";
1150 wfProfileOut( $fname );
1154 function getVariableValue( $index ) {
1155 global $wgLang, $wgSitename, $wgServer;
1158 case MAG_CURRENTMONTH
:
1160 case MAG_CURRENTMONTHNAME
:
1161 return $wgLang->getMonthName( date("n") );
1162 case MAG_CURRENTMONTHNAMEGEN
:
1163 return $wgLang->getMonthNameGen( date("n") );
1164 case MAG_CURRENTDAY
:
1167 return $this->mTitle
->getText();
1169 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1170 return $wgLang->getNsText($this->mTitle
->getNamespace()); // Patch by Dori
1171 case MAG_CURRENTDAYNAME
:
1172 return $wgLang->getWeekdayName( date("w")+
1 );
1173 case MAG_CURRENTYEAR
:
1175 case MAG_CURRENTTIME
:
1176 return $wgLang->time( wfTimestampNow(), false );
1177 case MAG_NUMBEROFARTICLES
:
1178 return wfNumberOfArticles();
1188 function initialiseVariables()
1190 global $wgVariableIDs;
1191 $this->mVariables
= array();
1192 foreach ( $wgVariableIDs as $id ) {
1193 $mw =& MagicWord
::get( $id );
1194 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1198 /* private */ function replaceVariables( $text, $args = array() )
1200 global $wgLang, $wgScript, $wgArticlePath;
1202 $fname = "Parser::replaceVariables";
1203 wfProfileIn( $fname );
1206 if ( !$this->mVariables
) {
1207 $this->initialiseVariables();
1209 $titleChars = Title
::legalChars();
1211 # This function is called recursively. To keep track of arguments we need a stack:
1212 array_push( $this->mArgStack
, $args );
1214 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1215 $GLOBALS['wgCurParser'] =& $this;
1217 # Argument substitution
1218 if ( $this->mOutputType
== OT_HTML
) {
1219 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", "wfArgSubstitution", $text );
1222 # Double brace substitution
1223 $regex = "/(\\n?){{([$titleChars{}_]*)(\\|.*?|)}}/s";
1224 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1226 array_pop( $this->mArgStack
);
1228 wfProfileOut( $fname );
1232 function braceSubstitution( $matches )
1234 global $wgLinkCache, $wgLang;
1235 $fname = "Parser::braceSubstitution";
1242 # $newline is an optional newline character before the braces
1243 # $part1 is the bit before the first |, and must contain only title characters
1244 # $args is a list of arguments, starting from index 0, not including $part1
1246 $newline = $matches[1];
1247 $part1 = $matches[2];
1248 # If the third subpattern matched anything, it will start with |
1249 if ( $matches[3] !== "" ) {
1250 $args = explode( "|", substr( $matches[3], 1 ) );
1254 $argc = count( $args );
1257 if ( strpos( $matches[0], "{{{" ) !== false ) {
1258 $text = $matches[0];
1265 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1266 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1267 if ( $this->mOutputType
!= OT_WIKI
) {
1268 # Invalid SUBST not replaced at PST time
1269 # Return without further processing
1270 $text = $matches[0];
1274 } elseif ( $this->mOutputType
== OT_WIKI
) {
1275 # SUBST not found in PST pass, do nothing
1276 $text = $matches[0];
1281 # MSG, MSGNW and INT
1284 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1285 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1288 # Remove obsolete MSG:
1289 $mwMsg =& MagicWord
::get( MAG_MSG
);
1290 $mwMsg->matchStartAndRemove( $part1 );
1293 # Check if it is an internal message
1294 $mwInt =& MagicWord
::get( MAG_INT
);
1295 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1296 if ( $this->incrementIncludeCount( "int:$part1" ) ) {
1297 $text = wfMsgReal( $part1, $args, true );
1305 # Check for NS: (namespace expansion)
1306 $mwNs = MagicWord
::get( MAG_NS
);
1307 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1308 if ( intval( $part1 ) ) {
1309 $text = $wgLang->getNsText( intval( $part1 ) );
1312 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1313 if ( !is_null( $index ) ) {
1314 $text = $wgLang->getNsText( $index );
1321 # LOCALURL and LOCALURLE
1323 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1324 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1326 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1327 $func = 'getLocalURL';
1328 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1329 $func = 'escapeLocalURL';
1334 if ( $func !== '' ) {
1335 $title = Title
::newFromText( $part1 );
1336 if ( !is_null( $title ) ) {
1338 $text = $title->$func( $args[0] );
1340 $text = $title->$func();
1347 # Internal variables
1348 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1349 $text = $this->mVariables
[$part1];
1351 $this->mOutput
->mContainsOldMagic
= true;
1354 # Arguments input from the caller
1355 $inputArgs = end( $this->mArgStack );
1356 if ( !$found && array_key_exists( $part1, $inputArgs ) ) {
1357 $text = $inputArgs[$part1];
1361 # Load from database
1363 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1364 if ( !is_null( $title ) && !$title->isExternal() ) {
1365 # Check for excessive inclusion
1366 $dbk = $title->getPrefixedDBkey();
1367 if ( $this->incrementIncludeCount( $dbk ) ) {
1368 $article = new Article( $title );
1369 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1370 if ( $articleContent !== false ) {
1372 $text = $articleContent;
1377 # If the title is valid but undisplayable, make a link to it
1378 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1379 $text = "[[" . $title->getPrefixedText() . "]]";
1385 # Recursive parsing, escaping and link table handling
1386 # Only for HTML output
1387 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1388 $text = wfEscapeWikiText( $text );
1389 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1390 # Clean up argument array
1391 $assocArgs = array();
1393 foreach( $args as $arg ) {
1394 $eqpos = strpos( $arg, "=" );
1395 if ( $eqpos === false ) {
1396 $assocArgs[$index++
] = $arg;
1398 $name = trim( substr( $arg, 0, $eqpos ) );
1399 $value = trim( substr( $arg, $eqpos+
1 ) );
1400 if ( $value === false ) {
1403 if ( $name !== false ) {
1404 $assocArgs[$name] = $value;
1409 # Do not enter included links in link table
1410 if ( !is_null( $title ) ) {
1411 $wgLinkCache->suspend();
1414 # Run full parser on the included text
1415 $text = $this->stripParse( $text, (bool)$newline, $assocArgs );
1417 # Resume the link cache and register the inclusion as a link
1418 if ( !is_null( $title ) ) {
1419 $wgLinkCache->resume();
1420 $wgLinkCache->addLinkObj( $title );
1431 # Triple brace replacement -- used for template arguments
1432 function argSubstitution( $matches )
1434 $newline = $matches[1];
1435 $arg = trim( $matches[2] );
1436 $text = $matches[0];
1437 $inputArgs = end( $this->mArgStack
);
1439 if ( array_key_exists( $arg, $inputArgs ) ) {
1440 $text = $this->stripParse( $inputArgs[$arg], (bool)$newline, array() );
1446 # Returns true if the function is allowed to include this entity
1447 function incrementIncludeCount( $dbk )
1449 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1450 $this->mIncludeCount
[$dbk] = 0;
1452 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1460 # Cleans up HTML, removes dangerous tags and attributes
1461 /* private */ function removeHTMLtags( $text )
1463 global $wgUseTidy, $wgUserHtml;
1464 $fname = "Parser::removeHTMLtags";
1465 wfProfileIn( $fname );
1468 $htmlpairs = array( # Tags that must be closed
1469 "b", "del", "i", "ins", "u", "font", "big", "small", "sub", "sup", "h1",
1470 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1471 "strike", "strong", "tt", "var", "div", "center",
1472 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1473 "ruby", "rt" , "rb" , "rp", "p"
1475 $htmlsingle = array(
1476 "br", "hr", "li", "dt", "dd"
1478 $htmlnest = array( # Tags that can be nested--??
1479 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1480 "dl", "font", "big", "small", "sub", "sup"
1482 $tabletags = array( # Can only appear inside table
1486 $htmlpairs = array();
1487 $htmlsingle = array();
1488 $htmlnest = array();
1489 $tabletags = array();
1492 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1493 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1495 $htmlattrs = $this->getHTMLattrs () ;
1497 # Remove HTML comments
1498 $text = preg_replace( "/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU", "$2", $text );
1500 $bits = explode( "<", $text );
1501 $text = array_shift( $bits );
1503 $tagstack = array(); $tablestack = array();
1504 foreach ( $bits as $x ) {
1505 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1506 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1508 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1509 error_reporting( $prev );
1512 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1516 if ( ! in_array( $t, $htmlsingle ) &&
1517 ( count($tagstack) && $ot = array_pop( $tagstack ) ) != $t ) {
1518 if(!empty($ot)) array_push( $tagstack, $ot );
1521 if ( $t == "table" ) {
1522 $tagstack = array_pop( $tablestack );
1527 # Keep track for later
1528 if ( in_array( $t, $tabletags ) &&
1529 ! in_array( "table", $tagstack ) ) {
1531 } else if ( in_array( $t, $tagstack ) &&
1532 ! in_array ( $t , $htmlnest ) ) {
1534 } else if ( ! in_array( $t, $htmlsingle ) ) {
1535 if ( $t == "table" ) {
1536 array_push( $tablestack, $tagstack );
1537 $tagstack = array();
1539 array_push( $tagstack, $t );
1541 # Strip non-approved attributes from the tag
1542 $newparams = $this->fixTagAttributes($params);
1546 $rest = str_replace( ">", ">", $rest );
1547 $text .= "<$slash$t $newparams$brace$rest";
1551 $text .= "<" . str_replace( ">", ">", $x);
1553 # Close off any remaining tags
1554 while ( $t = array_pop( $tagstack ) ) {
1556 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1559 # this might be possible using tidy itself
1560 foreach ( $bits as $x ) {
1561 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1563 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1564 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1565 $newparams = $this->fixTagAttributes($params);
1566 $rest = str_replace( ">", ">", $rest );
1567 $text .= "<$slash$t $newparams$brace$rest";
1569 $text .= "<" . str_replace( ">", ">", $x);
1573 wfProfileOut( $fname );
1580 * This function accomplishes several tasks:
1581 * 1) Auto-number headings if that option is enabled
1582 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1583 * 3) Add a Table of contents on the top for users who have enabled the option
1584 * 4) Auto-anchor headings
1586 * It loops through all headlines, collects the necessary data, then splits up the
1587 * string and re-inserts the newly formatted headlines.
1591 /* private */ function formatHeadings( $text, $isMain=true )
1593 global $wgInputEncoding;
1595 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1596 $doShowToc = $this->mOptions
->getShowToc();
1597 if( !$this->mTitle
->userCanEdit() ) {
1599 $rightClickHack = 0;
1601 $showEditLink = $this->mOptions
->getEditSection();
1602 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1605 # Inhibit editsection links if requested in the page
1606 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1607 if( $esw->matchAndRemove( $text ) ) {
1610 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1612 $mw =& MagicWord
::get( MAG_NOTOC
);
1613 if( $mw->matchAndRemove( $text ) ) {
1617 # never add the TOC to the Main Page. This is an entry page that should not
1618 # be more than 1-2 screens large anyway
1619 if( $this->mTitle
->getPrefixedText() == wfMsg("mainpage") ) {
1623 # Get all headlines for numbering them and adding funky stuff like [edit]
1624 # links - this is for later, but we need the number of headlines right now
1625 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1627 # if there are fewer than 4 headlines in the article, do not show TOC
1628 if( $numMatches < 4 ) {
1632 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1633 # override above conditions and always show TOC
1634 $mw =& MagicWord
::get( MAG_FORCETOC
);
1635 if ($mw->matchAndRemove( $text ) ) {
1640 # We need this to perform operations on the HTML
1641 $sk =& $this->mOptions
->getSkin();
1646 # Ugh .. the TOC should have neat indentation levels which can be
1647 # passed to the skin functions. These are determined here
1652 $sublevelCount = array();
1655 foreach( $matches[3] as $headline ) {
1658 $prevlevel = $level;
1660 $level = $matches[1][$headlineCount];
1661 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1662 # reset when we enter a new level
1663 $sublevelCount[$level] = 0;
1664 $toc .= $sk->tocIndent( $level - $prevlevel );
1665 $toclevel +
= $level - $prevlevel;
1667 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1668 # reset when we step back a level
1669 $sublevelCount[$level+
1]=0;
1670 $toc .= $sk->tocUnindent( $prevlevel - $level );
1671 $toclevel -= $prevlevel - $level;
1673 # count number of headlines for each level
1674 @$sublevelCount[$level]++
;
1675 if( $doNumberHeadings ||
$doShowToc ) {
1677 for( $i = 1; $i <= $level; $i++
) {
1678 if( !empty( $sublevelCount[$i] ) ) {
1682 $numbering .= $sublevelCount[$i];
1688 # The canonized header is a version of the header text safe to use for links
1689 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1690 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
1693 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1694 $tocline = trim( $canonized_headline );
1695 $canonized_headline = preg_replace("/[ \\?&\\/<>\\(\\)\\[\\]=,+']+/", '_', urlencode( do_html_entity_decode( $tocline, ENT_COMPAT
, $wgInputEncoding ) ) );
1696 # strip out urlencoded (inserted for french spaces, e.g. first space in 'something : something')
1697 $canonized_headline = str_replace('%C2%A0','_', $canonized_headline);
1698 $refer[$headlineCount] = $canonized_headline;
1700 # count how many in assoc. array so we can track dupes in anchors
1701 @$refers[$canonized_headline]++
;
1702 $refcount[$headlineCount]=$refers[$canonized_headline];
1704 # Prepend the number to the heading text
1706 if( $doNumberHeadings ||
$doShowToc ) {
1707 $tocline = $numbering . " " . $tocline;
1709 # Don't number the heading if it is the only one (looks silly)
1710 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1711 # the two are different if the line contains a link
1712 $headline=$numbering . " " . $headline;
1716 # Create the anchor for linking from the TOC to the section
1717 $anchor = $canonized_headline;
1718 if($refcount[$headlineCount] > 1 ) {
1719 $anchor .= "_" . $refcount[$headlineCount];
1722 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1724 if( $showEditLink ) {
1725 if ( empty( $head[$headlineCount] ) ) {
1726 $head[$headlineCount] = "";
1728 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
1731 # Add the edit section span
1732 if( $rightClickHack ) {
1733 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
1736 # give headline the correct <h#> tag
1737 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1743 $toclines = $headlineCount;
1744 $toc .= $sk->tocUnindent( $toclevel );
1745 $toc = $sk->tocTable( $toc );
1748 # split up and insert constructed headlines
1750 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1753 foreach( $blocks as $block ) {
1754 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1755 # This is the [edit] link that appears for the top block of text when
1756 # section editing is enabled
1758 # Disabled because it broke block formatting
1759 # For example, a bullet point in the top line
1760 # $full .= $sk->editSectionLink(0);
1763 if( $doShowToc && !$i && $isMain) {
1764 # Top anchor now in skin
1768 if( !empty( $head[$i] ) ) {
1777 /* private */ function magicISBN( $text )
1781 $a = split( "ISBN ", " $text" );
1782 if ( count ( $a ) < 2 ) return $text;
1783 $text = substr( array_shift( $a ), 1);
1784 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1786 foreach ( $a as $x ) {
1787 $isbn = $blank = "" ;
1788 while ( " " == $x{0} ) {
1790 $x = substr( $x, 1 );
1792 while ( strstr( $valid, $x{0} ) != false ) {
1794 $x = substr( $x, 1 );
1796 $num = str_replace( "-", "", $isbn );
1797 $num = str_replace( " ", "", $num );
1800 $text .= "ISBN $blank$x";
1802 $titleObj = Title
::makeTitle( NS_SPECIAL
, "Booksources" );
1803 $text .= "<a href=\"" .
1804 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1805 "\" class=\"internal\">ISBN $isbn</a>";
1811 /* private */ function magicRFC( $text )
1815 $a = split( "ISBN ", " $text" );
1816 if ( count ( $a ) < 2 ) return $text;
1817 $text = substr( array_shift( $a ), 1);
1818 $valid = "0123456789";
1820 foreach ( $a as $x ) {
1821 $rfc = $blank = "" ;
1822 while ( " " == $x{0} ) {
1824 $x = substr( $x, 1 );
1826 while ( strstr( $valid, $x{0} ) != false ) {
1828 $x = substr( $x, 1 );
1832 $text .= "RFC $blank$x";
1834 $url = wfmsg( "rfcurl" );
1835 $url = str_replace( "$1", $rfc, $url);
1836 $sk =& $this->mOptions
->getSkin();
1837 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
1838 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
1844 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
1846 $this->mOptions
= $options;
1847 $this->mTitle
=& $title;
1848 $this->mOutputType
= OT_WIKI
;
1850 if ( $clearState ) {
1851 $this->clearState();
1854 $stripState = false;
1858 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
1861 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
1862 "/<br *?>/i" => "<br/>",
1864 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
1865 $text = $this->strip( $text, $stripState, false );
1866 $text = $this->pstPass2( $text, $user );
1867 $text = $this->unstrip( $text, $stripState );
1871 /* private */ function pstPass2( $text, &$user )
1873 global $wgLang, $wgLocaltimezone, $wgCurParser;
1875 # Variable replacement
1876 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
1877 $text = $this->replaceVariables( $text );
1881 $n = $user->getName();
1882 $k = $user->getOption( "nickname" );
1883 if ( "" == $k ) { $k = $n; }
1884 if(isset($wgLocaltimezone)) {
1885 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1887 /* Note: this is an ugly timezone hack for the European wikis */
1888 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1889 " (" . date( "T" ) . ")";
1890 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1892 $text = preg_replace( "/~~~~~/", $d, $text );
1893 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1894 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1895 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1896 Namespace::getUser() ) . ":$n|$k]]", $text );
1898 # Context links: [[|name]] and [[name (context)|]]
1900 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1901 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1902 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1903 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1905 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1906 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1907 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1908 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1909 # [[ns:page (cont)|]]
1911 $t = $this->mTitle
->getText();
1912 if ( preg_match( $conpat, $t, $m ) ) {
1915 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1916 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1917 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1919 if ( "" == $context ) {
1920 $text = preg_replace( $p2, "[[\\1]]", $text );
1922 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1926 $mw =& MagicWord::get( MAG_SUBST );
1927 $wgCurParser = $this->fork();
1928 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
1929 $this->merge( $wgCurParser );
1932 # Trim trailing whitespace
1933 # MAG_END (__END__) tag allows for trailing
1934 # whitespace to be deliberately included
1935 $text = rtrim( $text );
1936 $mw =& MagicWord
::get( MAG_END
);
1937 $mw->matchAndRemove( $text );
1942 # Set up some variables which are usually set up in parse()
1943 # so that an external function can call some class members with confidence
1944 function startExternalParse( &$title, $options, $outputType, $clearState = true )
1946 $this->mTitle
=& $title;
1947 $this->mOptions
= $options;
1948 $this->mOutputType
= $outputType;
1949 if ( $clearState ) {
1950 $this->clearState();
1954 function transformMsg( $text, $options ) {
1956 static $executing = false;
1958 # Guard against infinite recursion
1964 $this->mTitle
= $wgTitle;
1965 $this->mOptions
= $options;
1966 $this->mOutputType
= OT_MSG
;
1967 $this->clearState();
1968 $text = $this->replaceVariables( $text );
1977 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
1979 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
1980 $containsOldMagic = false )
1982 $this->mText
= $text;
1983 $this->mLanguageLinks
= $languageLinks;
1984 $this->mCategoryLinks
= $categoryLinks;
1985 $this->mContainsOldMagic
= $containsOldMagic;
1988 function getText() { return $this->mText
; }
1989 function getLanguageLinks() { return $this->mLanguageLinks
; }
1990 function getCategoryLinks() { return $this->mCategoryLinks
; }
1991 function containsOldMagic() { return $this->mContainsOldMagic
; }
1992 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
1993 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
1994 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
1995 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
1997 function merge( $other ) {
1998 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
1999 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2000 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2007 # All variables are private
2008 var $mUseTeX; # Use texvc to expand <math> tags
2009 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2010 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2011 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2012 var $mAllowExternalImages; # Allow external images inline
2013 var $mSkin; # Reference to the preferred skin
2014 var $mDateFormat; # Date format index
2015 var $mEditSection; # Create "edit section" links
2016 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2017 var $mNumberHeadings; # Automatically number headings
2018 var $mShowToc; # Show table of contents
2020 function getUseTeX() { return $this->mUseTeX
; }
2021 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
2022 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2023 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2024 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2025 function getSkin() { return $this->mSkin
; }
2026 function getDateFormat() { return $this->mDateFormat
; }
2027 function getEditSection() { return $this->mEditSection
; }
2028 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2029 function getNumberHeadings() { return $this->mNumberHeadings
; }
2030 function getShowToc() { return $this->mShowToc
; }
2032 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2033 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
2034 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2035 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2036 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2037 function setSkin( $x ) { return wfSetRef( $this->mSkin
, $x ); }
2038 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2039 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2040 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2041 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2042 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2044 /* static */ function newFromUser( &$user )
2046 $popts = new ParserOptions
;
2047 $popts->initialiseFromUser( $user );
2051 function initialiseFromUser( &$userInput )
2053 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2055 if ( !$userInput ) {
2057 $user->setLoaded( true );
2059 $user =& $userInput;
2062 $this->mUseTeX
= $wgUseTeX;
2063 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2064 $this->mUseDynamicDates
= $wgUseDynamicDates;
2065 $this->mInterwikiMagic
= $wgInterwikiMagic;
2066 $this->mAllowExternalImages
= $wgAllowExternalImages;
2067 $this->mSkin
=& $user->getSkin();
2068 $this->mDateFormat
= $user->getOption( "date" );
2069 $this->mEditSection
= $user->getOption( "editsection" );
2070 $this->mEditSectionOnRightClick
= $user->getOption( "editsectiononrightclick" );
2071 $this->mNumberHeadings
= $user->getOption( "numberheadings" );
2072 $this->mShowToc
= $user->getOption( "showtoc" );
2078 # Regex callbacks, used in Parser::replaceVariables
2079 function wfBraceSubstitution( $matches )
2081 global $wgCurParser;
2082 $titleChars = Title
::legalChars();
2083 # Double brace substitution, expand bar in {{foo{{bar}}}}
2085 while(preg_match("/{{([$titleChars]*?)}}/", $matches[2], $internalmatches) and $i < 30) {
2086 $text = wfInternalBraceSubstitution( $internalmatches );
2087 $matches[0] = str_replace($internalmatches[0], $text , $matches[0]);
2088 $matches[2] = str_replace($internalmatches[0], $text , $matches[2]);
2092 return $wgCurParser->braceSubstitution( $matches );
2095 function wfArgSubstitution( $matches )
2097 global $wgCurParser;
2098 return $wgCurParser->argSubstitution( $matches );
2101 # XXX: i don't think this is the most elegant way to do it..
2102 function wfInternalBraceSubstitution( $matches ) {
2103 global $wgLinkCache, $wgLang, $wgCurParser;
2104 $fname = "wfInternalBraceSubstitution";
2111 # $newline is an optional newline character before the braces
2112 # $part1 is the bit before the first |, and must contain only title characters
2113 # $args is a list of arguments, starting from index 0, not including $part1
2115 $part1 = $matches[1];
2118 if ( strpos( $matches[0], "{{{" ) !== false ) {
2119 $text = $matches[0];
2126 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2127 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
2128 if ( $wgCurParser->mOutputType
!= OT_WIKI
) {
2129 # Invalid SUBST not replaced at PST time
2130 # Return without further processing
2131 $text = $matches[0];
2135 } elseif ( $wgCurParser->mOutputType
== OT_WIKI
) {
2136 # SUBST not found in PST pass, do nothing
2137 $text = $matches[0];
2142 # MSG, MSGNW and INT
2145 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2146 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2149 # Remove obsolete MSG:
2150 $mwMsg =& MagicWord
::get( MAG_MSG
);
2151 $mwMsg->matchStartAndRemove( $part1 );
2154 # Check if it is an internal message
2155 $mwInt =& MagicWord
::get( MAG_INT
);
2156 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2157 if ( $wgCurParser->incrementIncludeCount( "int:$part1" ) ) {
2158 $text = wfMsgReal( $part1, array(), true );
2166 # Check for NS: (namespace expansion)
2167 $mwNs = MagicWord
::get( MAG_NS
);
2168 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2169 if ( intval( $part1 ) ) {
2170 $text = $wgLang->getNsText( intval( $part1 ) );
2173 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2174 if ( !is_null( $index ) ) {
2175 $text = $wgLang->getNsText( $index );
2182 # LOCALURL and LOCALURLE
2184 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2185 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2187 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2188 $func = 'getLocalURL';
2189 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2190 $func = 'escapeLocalURL';
2195 if ( $func !== '' ) {
2196 $title = Title
::newFromText( $part1 );
2197 if ( !is_null( $title ) ) {
2198 $text = $title->$func();
2204 # Internal variables
2205 if ( !$found && array_key_exists( $part1, $wgCurParser->mVariables
) ) {
2206 $text = $wgCurParser->mVariables
[$part1];
2208 $wgCurParser->mOutput
->mContainsOldMagic
= true;
2211 # Load from database
2213 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
2214 if ( !is_null( $title ) && !$title->isExternal() ) {
2215 # Check for excessive inclusion
2216 $dbk = $title->getPrefixedDBkey();
2217 if ( $wgCurParser->incrementIncludeCount( $dbk ) ) {
2218 $article = new Article( $title );
2219 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2220 if ( $articleContent !== false ) {
2222 $text = $articleContent;
2227 # If the title is valid but undisplayable, make a link to it
2228 if ( $wgCurParser->mOutputType
== OT_HTML
&& !$found ) {
2229 $text = "[[" . $title->getPrefixedText() . "]]";