3 include_once('Tokenizer.php');
5 if( $GLOBALS['wgUseWikiHiero'] ){
6 include_once('wikihiero.php');
11 # Processes wiki markup
13 # There are two main entry points into the Parser class: parse() and preSaveTransform().
14 # The parse() function produces HTML output, preSaveTransform() produces altered wiki markup.
17 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
19 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
21 # settings: $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
22 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
25 # * only within ParserOptions
28 #----------------------------------------
29 # Variable substitution O(N^2) attack
30 #-----------------------------------------
31 # Without countermeasures, it would be possible to attack the parser by saving a page
32 # filled with a large number of inclusions of large pages. The size of the generated
33 # page would be proportional to the square of the input size. Hence, we limit the number
34 # of inclusions of any given page, thus bringing any attack back to O(N).
36 define( "MAX_INCLUDE_REPEAT", 5 );
38 # Recursion depth of variable/inclusion evaluation
39 define( "MAX_INCLUDE_PASSES", 3 );
41 # Allowed values for $mOutputType
42 define( "OT_HTML", 1 );
43 define( "OT_WIKI", 2 );
44 define( "OT_MSG", 3 );
46 # prefix for escaping, used in two functions at least
47 define( "UNIQ_PREFIX", "NaodW29");
51 # Cleared with clearState():
52 var $mOutput, $mAutonumber, $mLastSection, $mDTopen, $mStripState = array();
53 var $mVariables, $mIncludeCount;
56 var $mOptions, $mTitle, $mOutputType;
65 $this->mOutput
= new ParserOutput
;
66 $this->mAutonumber
= 0;
67 $this->mLastSection
= "";
68 $this->mDTopen
= false;
69 $this->mVariables
= false;
70 $this->mIncludeCount
= array();
71 $this->mStripState
= array();
74 # First pass--just handle <nowiki> sections, pass the rest off
75 # to doWikiPass2() which does all the real work.
77 # Returns a ParserOutput
79 function parse( $text, &$title, $options, $linestart = true, $clearState = true )
81 $fname = "Parser::parse";
82 wfProfileIn( $fname );
88 $this->mOptions
= $options;
89 $this->mTitle
=& $title;
90 $this->mOutputType
= OT_HTML
;
93 $text = $this->strip( $text, $this->mStripState
);
94 $text = $this->doWikiPass2( $text, $linestart );
95 $text = $this->unstrip( $text, $this->mStripState
);
96 # Clean up special characters
98 "/<hr *>/i" => '<hr/>',
99 "/<br *>/i" => '<br/>',
100 "/<center *>/i"=>'<span style="text-align:center;">',
101 "/<\\/center *>/i" => '</span>',
102 # Clean up spare ampersands; note that we probably ought to be
103 # more careful about named entities.
104 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
106 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
108 $this->mOutput
->setText( $text );
109 wfProfileOut( $fname );
110 return $this->mOutput
;
113 /* static */ function getRandomString()
115 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
118 # Replaces all occurences of <$tag>content</$tag> in the text
119 # with a random marker and returns the new text. the output parameter
120 # $content will be an associative array filled with data on the form
121 # $unique_marker => content.
123 # If $content is already set, the additional entries will be appended
125 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
126 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
133 while ( "" != $text ) {
134 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
136 if ( ( count( $p ) < 2 ) ||
( "" == $p[1] ) ) {
139 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
140 $marker = $rnd . sprintf("%08X", $n++
);
141 $content[$marker] = $q[0];
142 $stripped .= $marker;
149 # Strips <nowiki>, <pre> and <math>
150 # Returns the text, and fills an array with data needed in unstrip()
151 # If the $state is already a valid strip state, it adds to the state
153 function strip( $text, &$state )
155 $render = ($this->mOutputType
== OT_HTML
);
157 $nowiki_content = $state['nowiki'];
158 $hiero_content = $state['hiero'];
159 $math_content = $state['math'];
160 $pre_content = $state['pre'];
161 $item_content = $state['item'];
163 $nowiki_content = array();
164 $hiero_content = array();
165 $math_content = array();
166 $pre_content = array();
167 $item_content = array();
170 # Replace any instances of the placeholders
171 $uniq_prefix = UNIQ_PREFIX
;
172 $text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
174 $text = Parser
::extractTags("nowiki", $text, $nowiki_content, $uniq_prefix);
175 foreach( $nowiki_content as $marker => $content ){
177 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
179 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
183 if( $GLOBALS['wgUseWikiHiero'] ){
184 $text = Parser
::extractTags("hiero", $text, $hiero_content, $uniq_prefix);
185 foreach( $hiero_content as $marker => $content ){
187 $hiero_content[$marker] = WikiHiero( $content, WH_MODE_HTML
);
189 $hiero_content[$marker] = "<hiero>$content</hiero>";
194 if( $this->mOptions
->getUseTeX() ){
195 $text = Parser
::extractTags("math", $text, $math_content, $uniq_prefix);
196 foreach( $math_content as $marker => $content ){
198 $math_content[$marker] = renderMath( $content );
200 $math_content[$marker] = "<math>$content</math>";
205 $text = Parser
::extractTags("pre", $text, $pre_content, $uniq_prefix);
206 foreach( $pre_content as $marker => $content ){
208 $pre_content[$marker] = "<pre>" . wfEscapeHTMLTagsOnly( $content ) . "</pre>";
210 $pre_content[$marker] = "<pre>$content</pre>";
215 'nowiki' => $nowiki_content,
216 'hiero' => $hiero_content,
217 'math' => $math_content,
218 'pre' => $pre_content,
219 'item' => $item_content
224 function unstrip( $text, &$state )
226 # Must expand in reverse order, otherwise nested tags will be corrupted
228 $dicts = array( 'item', 'pre', 'math', 'hiero', 'nowiki' );
229 foreach ( $dicts as $dictName ) {
230 $content_dict = $state[$dictName];
231 foreach( $content_dict as $marker => $content ){
232 $text = str_replace( $marker, $content, $text );
236 $contentDict = end( $state );
237 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
238 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
239 $text = str_replace( key( $contentDict ), $content, $text );
246 # Add an item to the strip state
247 # Returns the unique tag which must be inserted into the stripped text
248 # The tag will be replaced with the original text in unstrip()
250 function insertStripItem( $text, &$state )
252 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
262 $state['item'][$rnd] = $text;
266 function categoryMagic ()
268 global $wgLang , $wgUser ;
269 if ( !$this->mOptions
->getUseCategoryMagic() ) return ;
270 $id = $this->mTitle
->getArticleID() ;
271 $cat = $wgLang->ucfirst ( wfMsg ( "category" ) ) ;
272 $ti = $this->mTitle
->getText() ;
273 $ti = explode ( ":" , $ti , 2 ) ;
274 if ( $cat != $ti[0] ) return "" ;
275 $r = '<br style="clear:both;"/>\n';
277 $articles = array() ;
278 $parents = array () ;
279 $children = array() ;
282 # $sk =& $this->mGetSkin();
283 $sk =& $wgUser->getSkin() ;
286 $sql1 = "SELECT DISTINCT cur_title,cur_namespace FROM cur,links WHERE l_to={$id} AND l_from=cur_id";
287 $sql2 = "SELECT DISTINCT cur_title,cur_namespace FROM cur,brokenlinks WHERE bl_to={$id} AND bl_from=cur_id" ;
289 $res = wfQuery ( $sql1, DB_READ
) ;
290 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
292 $res = wfQuery ( $sql2, DB_READ
) ;
293 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
296 foreach ( $data AS $x )
298 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
299 if ( $t != "" ) $t .= ":" ;
300 $t .= $x->cur_title
;
302 $y = explode ( ":" , $t , 2 ) ;
303 if ( count ( $y ) == 2 && $y[0] == $cat ) {
304 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
306 array_push ( $articles , $sk->makeLink ( $t ) ) ;
309 wfFreeResult ( $res ) ;
312 if ( count ( $children ) > 0 )
314 asort ( $children ) ;
315 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
316 $r .= implode ( ", " , $children ) ;
320 if ( count ( $articles ) > 0 )
322 asort ( $articles ) ;
323 $h = wfMsg( "category_header", $ti[1] );
324 $r .= "<h2>{$h}</h2>\n" ;
325 $r .= implode ( ", " , $articles ) ;
332 function getHTMLattrs ()
334 $htmlattrs = array( # Allowed attributes--no scripting, etc.
335 "title", "align", "lang", "dir", "width", "height",
336 "bgcolor", "clear", /* BR */ "noshade", /* HR */
337 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
338 /* FONT */ "type", "start", "value", "compact",
339 /* For various lists, mostly deprecated but safe */
340 "summary", "width", "border", "frame", "rules",
341 "cellspacing", "cellpadding", "valign", "char",
342 "charoff", "colgroup", "col", "span", "abbr", "axis",
343 "headers", "scope", "rowspan", "colspan", /* Tables */
344 "id", "class", "name", "style" /* For CSS */
349 function fixTagAttributes ( $t )
351 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
352 $htmlattrs = $this->getHTMLattrs() ;
354 # Strip non-approved attributes from the tag
356 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
357 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
359 # Strip javascript "expression" from stylesheets. Brute force approach:
360 # If anythin offensive is found, all attributes of the HTML tag are dropped
363 "/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is",
364 wfMungeToUtf8( $t ) ) )
372 function doTableStuff ( $t )
374 $t = explode ( "\n" , $t ) ;
375 $td = array () ; # Is currently a td tag open?
376 $ltd = array () ; # Was it TD or TH?
377 $tr = array () ; # Is currently a tr tag open?
378 $ltr = array () ; # tr attributes
379 foreach ( $t AS $k => $x )
382 $fc = substr ( $x , 0 , 1 ) ;
383 if ( "{|" == substr ( $x , 0 , 2 ) )
385 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
386 array_push ( $td , false ) ;
387 array_push ( $ltd , "" ) ;
388 array_push ( $tr , false ) ;
389 array_push ( $ltr , "" ) ;
391 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
392 else if ( "|}" == substr ( $x , 0 , 2 ) )
395 $l = array_pop ( $ltd ) ;
396 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
397 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
401 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
403 $z = trim ( substr ( $x , 2 ) ) ;
404 $t[$k] = "<caption>{$z}</caption>\n" ;
406 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
408 $x = substr ( $x , 1 ) ;
409 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
411 $l = array_pop ( $ltd ) ;
412 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
413 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
416 array_push ( $tr , false ) ;
417 array_push ( $td , false ) ;
418 array_push ( $ltd , "" ) ;
419 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
421 else if ( "|" == $fc ||
"!" == $fc ||
"|+" == substr ( $x , 0 , 2 ) ) # Caption
423 if ( "|+" == substr ( $x , 0 , 2 ) )
426 $x = substr ( $x , 1 ) ;
428 $after = substr ( $x , 1 ) ;
429 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
430 $after = explode ( "||" , $after ) ;
432 foreach ( $after AS $theline )
437 $tra = array_pop ( $ltr ) ;
438 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
439 array_push ( $tr , true ) ;
440 array_push ( $ltr , "" ) ;
443 $l = array_pop ( $ltd ) ;
444 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
445 if ( $fc == "|" ) $l = "td" ;
446 else if ( $fc == "!" ) $l = "th" ;
447 else if ( $fc == "+" ) $l = "caption" ;
449 array_push ( $ltd , $l ) ;
450 $y = explode ( "|" , $theline , 2 ) ;
451 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
452 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
454 array_push ( $td , true ) ;
459 # Closing open td, tr && table
460 while ( count ( $td ) > 0 )
462 if ( array_pop ( $td ) ) $t[] = "</td>" ;
463 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
467 $t = implode ( "\n" , $t ) ;
468 # $t = $this->removeHTMLtags( $t );
472 # Well, OK, it's actually about 14 passes. But since all the
473 # hard lifting is done inside PHP's regex code, it probably
474 # wouldn't speed things up much to add a real parser.
476 function doWikiPass2( $text, $linestart )
478 $fname = "Parser::doWikiPass2";
479 wfProfileIn( $fname );
481 $text = $this->removeHTMLtags( $text );
482 $text = $this->replaceVariables( $text );
484 # $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
486 $text = $this->doHeadings( $text );
488 if($this->mOptions
->getUseDynamicDates()) {
489 global $wgDateFormatter;
490 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
493 $text = $this->replaceExternalLinks( $text );
494 $text = $this->doTokenizedParser ( $text );
496 $text = $this->doTableStuff ( $text ) ;
498 $text = $this->formatHeadings( $text );
500 $sk =& $this->mOptions
->getSkin();
501 $text = $sk->transformContent( $text );
503 $text .= $this->categoryMagic () ;
505 # needs to be called last
506 $text = $this->doBlockLevels( $text, $linestart );
508 wfProfileOut( $fname );
513 /* private */ function doHeadings( $text )
515 for ( $i = 6; $i >= 1; --$i ) {
516 $h = substr( "======", 0, $i );
517 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
518 "<h{$i}>\\1</h{$i}>\\2", $text );
523 # Note: we have to do external links before the internal ones,
524 # and otherwise take great care in the order of things here, so
525 # that we don't end up interpreting some URLs twice.
527 /* private */ function replaceExternalLinks( $text )
529 $fname = "Parser::replaceExternalLinks";
530 wfProfileIn( $fname );
531 $text = $this->subReplaceExternalLinks( $text, "http", true );
532 $text = $this->subReplaceExternalLinks( $text, "https", true );
533 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
534 $text = $this->subReplaceExternalLinks( $text, "irc", false );
535 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
536 $text = $this->subReplaceExternalLinks( $text, "news", false );
537 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
538 wfProfileOut( $fname );
542 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
544 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
545 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
547 # this is the list of separators that should be ignored if they
548 # are the last character of an URL but that should be included
549 # if they occur within the URL, e.g. "go to www.foo.com, where .."
550 # in this case, the last comma should not become part of the URL,
551 # but in "www.foo.com/123,2342,32.htm" it should.
553 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
554 $images = "gif|png|jpg|jpeg";
556 # PLEASE NOTE: The curly braces { } are not part of the regex,
557 # they are interpreted as part of the string (used to tell PHP
558 # that the content of the string should be inserted there).
559 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
560 "((?i){$images})([^{$uc}]|$)/";
562 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
563 $sk =& $this->mOptions
->getSkin();
565 if ( $autonumber and $this->mOptions
->getAllowExternalImages() ) { # Use img tags only for HTTP urls
566 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
567 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
569 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
570 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
571 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
573 $s = str_replace( $unique, $protocol, $s );
575 $a = explode( "[{$protocol}:", " " . $s );
576 $s = array_shift( $a );
577 $s = substr( $s, 1 );
579 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
580 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
582 foreach ( $a as $line ) {
583 if ( preg_match( $e1, $line, $m ) ) {
584 $link = "{$protocol}:{$m[1]}";
586 if ( $autonumber ) { $text = "[" . ++
$this->mAutonumber
. "]"; }
587 else { $text = wfEscapeHTML( $link ); }
588 } else if ( preg_match( $e2, $line, $m ) ) {
589 $link = "{$protocol}:{$m[1]}";
593 $s .= "[{$protocol}:" . $line;
596 if( $link == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
599 # Expand the URL for printable version
600 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
602 $la = $sk->getExternalLinkAttributes( $link, $text );
603 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
609 /* private */ function handle3Quotes( &$state, $token )
611 if ( $state["strong"] !== false ) {
612 if ( $state["em"] !== false && $state["em"] > $state["strong"] )
614 # ''' lala ''lala '''
615 $s = "</em></strong><em>";
619 $state["strong"] = FALSE;
622 $state["strong"] = isset($token["pos"]) ?
$token["pos"] : true;
627 /* private */ function handle2Quotes( &$state, $token )
629 if ( $state["em"] !== false ) {
630 if ( $state["strong"] !== false && $state["strong"] > $state["em"] )
632 # ''lala'''lala'' ....'''
633 $s = "</strong></em><strong>";
637 $state["em"] = FALSE;
640 $state["em"] = isset($token["pos"]) ?
$token["pos"] : true;
646 /* private */ function handle5Quotes( &$state, $token )
649 if ( $state["em"] !== false && $state["strong"] !== false ) {
650 if ( $state["em"] < $state["strong"] ) {
651 $s .= "</strong></em>";
653 $s .= "</em></strong>";
655 $state["strong"] = $state["em"] = FALSE;
656 } elseif ( $state["em"] !== false ) {
657 $s .= "</em><strong>";
658 $state["em"] = FALSE;
659 $state["strong"] = $token["pos"];
660 } elseif ( $state["strong"] !== false ) {
661 $s .= "</strong><em>";
662 $state["strong"] = FALSE;
663 $state["em"] = $token["pos"];
664 } else { # not $em and not $strong
665 $s .= "<strong><em>";
666 $state["strong"] = $state["em"] = isset($token["pos"]) ?
$token["pos"] : true;
671 /* private */ function doTokenizedParser( $str )
673 global $wgLang; # for language specific parser hook
675 $tokenizer=Tokenizer
::newFromString( $str );
676 $tokenStack = array();
679 $state["em"] = FALSE;
680 $state["strong"] = FALSE;
684 # The tokenizer splits the text into tokens and returns them one by one.
685 # Every call to the tokenizer returns a new token.
686 while ( $token = $tokenizer->nextToken() )
688 switch ( $token["type"] )
691 # simple text with no further markup
692 $txt = $token["text"];
695 # remember the tag opened with 3 [
699 # FIXME : Treat orphaned open tags (stack not empty when text is over)
701 array_push( $tokenStack, $token );
708 # get text from stack, glue it together, and call the code to handle a
711 if ( count( $tokenStack ) == 0 )
713 # stack empty. Found a ]] without an opening [[
717 $lastToken = array_pop( $tokenStack );
718 while ( !(($lastToken["type"] == "[[[") or ($lastToken["type"] == "[[")) )
720 if( !empty( $lastToken["text"] ) ) {
721 $linkText = $lastToken["text"] . $linkText;
723 $lastToken = array_pop( $tokenStack );
726 $txt = $linkText ."]]";
728 if( isset( $lastToken["text"] ) ) {
729 $prefix = $lastToken["text"];
733 $nextToken = $tokenizer->previewToken();
734 if ( $nextToken["type"] == "text" )
736 # Preview just looks at it. Now we have to fetch it.
737 $nextToken = $tokenizer->nextToken();
738 $txt .= $nextToken["text"];
740 $fakestate = $this->mStripState
;
741 $txt = $this->handleInternalLink( $this->unstrip($txt,$fakestate), $prefix );
743 # did the tag start with 3 [ ?
745 # show the first as text
751 $tagIsOpen = (count( $tokenStack ) != 0);
757 # This and the three next ones handle quotes
758 $txt = $this->handle3Quotes( $state, $token );
761 $txt = $this->handle2Quotes( $state, $token );
764 $txt = $this->handle5Quotes( $state, $token );
774 $txt = $this->doMagicRFC( $tokenizer );
781 $txt = $this->doMagicISBN( $tokenizer );
785 # Call language specific Hook.
786 $txt = $wgLang->processToken( $token, $tokenStack );
787 if ( NULL == $txt ) {
788 # An unkown token. Highlight.
789 $txt = "<font color=\"#FF0000\"><b>".$token["type"]."</b></font>";
790 $txt .= "<font color=\"#FFFF00\"><b>".$token["text"]."</b></font>";
794 # If we're parsing the interior of a link, don't append the interior to $s,
795 # but push it to the stack so it can be processed when a ]] token is found.
796 if ( $tagIsOpen && $txt != "" ) {
797 $token["type"] = "text";
798 $token["text"] = $txt;
799 array_push( $tokenStack, $token );
804 if ( count( $tokenStack ) != 0 )
806 # still objects on stack. opened [[ tag without closing ]] tag.
808 while ( $lastToken = array_pop( $tokenStack ) )
810 if ( $lastToken["type"] == "text" )
812 $txt = $lastToken["text"] . $txt;
814 $txt = $lastToken["type"] . $txt;
822 /* private */ function handleInternalLink( $line, $prefix )
824 global $wgLang, $wgLinkCache;
825 global $wgNamespacesWithSubpages, $wgLanguageCode;
826 static $fname = "Parser::handleInternalLink" ;
827 wfProfileIn( $fname );
829 wfProfileIn( "$fname-setup" );
831 if ( !$tc ) { $tc = Title
::legalChars() . "#"; }
832 $sk =& $this->mOptions
->getSkin();
834 # Match a link having the form [[namespace:link|alternate]]trail
836 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
837 # Match the end of a line for a word that's not followed by whitespace,
838 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
839 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
840 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
841 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
844 # Special and Media are pseudo-namespaces; no pages actually exist in them
845 static $image = FALSE;
846 static $special = FALSE;
847 static $media = FALSE;
848 static $category = FALSE;
849 if ( !$image ) { $image = Namespace::getImage(); }
850 if ( !$special ) { $special = Namespace::getSpecial(); }
851 if ( !$media ) { $media = Namespace::getMedia(); }
852 if ( !$category ) { $category = wfMsg ( "category" ) ; }
854 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
856 wfProfileOut( "$fname-setup" );
859 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
862 } else { # Invalid form; output directly
863 $s .= $prefix . "[[" . $line ;
869 :Foobar -- override special treatment of prefix (images, language links)
870 /Foobar -- convert to CurrentPage/Foobar
871 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
873 $c = substr($m[1],0,1);
874 $noforce = ($c != ":");
875 if( $c == "/" ) { # subpage
876 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
877 $m[1]=substr($m[1],1,strlen($m[1])-2);
880 $noslash=substr($m[1],1);
882 if($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]) { # subpages allowed here
883 $link = $this->mTitle
->getPrefixedText(). "/" . trim($noslash);
886 } # this might be changed for ugliness reasons
888 $link = $noslash; # no subpage allowed, use standard link
890 } elseif( $noforce ) { # no subpage
893 $link = substr( $m[1], 1 );
898 $nt = Title
::newFromText( $link );
900 $s .= $prefix . "[[" . $line;
903 $ns = $nt->getNamespace();
904 $iw = $nt->getInterWiki();
906 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
907 array_push( $this->mOutput
->mLanguageLinks
, $nt->getPrefixedText() );
908 return (trim($s) == '')?
'': $s;
910 if( $ns == $image ) {
911 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
912 $wgLinkCache->addImageLinkObj( $nt );
916 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
917 ( strpos( $link, "#" ) == FALSE ) ) {
918 $s .= $prefix . "<strong>" . $text . "</strong>" . $trail;
923 $catns = strtoupper ( $nt->getDBkey () ) ;
924 $catns = explode ( ":" , $catns ) ;
925 if ( count ( $catns ) > 1 ) $catns = array_shift ( $catns ) ;
927 if ( $catns == strtoupper($category) && $this->mOptions
->getUseCategoryMagic() ) {
928 $t = explode ( ":" , $nt->getText() ) ;
930 $t = implode ( ":" , $t ) ;
931 $t = $wgLang->ucFirst ( $t ) ;
932 $nnt = Title
::newFromText ( $category.":".$t ) ;
933 $t = $sk->makeLinkObj( $nnt, $t, "", $trail , $prefix );
934 $this->mOutput
->mCategoryLinks
[] = $t ;
935 $s .= $prefix . $trail ;
939 if( $ns == $media ) {
940 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
941 $wgLinkCache->addImageLinkObj( $nt );
943 } elseif( $ns == $special ) {
944 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
947 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
949 wfProfileOut( $fname );
953 # Some functions here used by doBlockLevels()
955 /* private */ function closeParagraph()
958 if ( '' != $this->mLastSection
) {
959 $result = "</" . $this->mLastSection
. ">\n";
961 $this->mLastSection
= "";
964 # getCommon() returns the length of the longest common substring
965 # of both arguments, starting at the beginning of both.
967 /* private */ function getCommon( $st1, $st2 )
969 $fl = strlen( $st1 );
970 $shorter = strlen( $st2 );
971 if ( $fl < $shorter ) { $shorter = $fl; }
973 for ( $i = 0; $i < $shorter; ++
$i ) {
974 if ( $st1{$i} != $st2{$i} ) { break; }
978 # These next three functions open, continue, and close the list
979 # element appropriate to the prefix character passed into them.
981 /* private */ function openList( $char )
983 $result = $this->closeParagraph();
985 if ( "*" == $char ) { $result .= "<ul><li>"; }
986 else if ( "#" == $char ) { $result .= "<ol><li>"; }
987 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
988 else if ( ";" == $char ) {
989 $result .= "<dl><dt>";
990 $this->mDTopen
= true;
992 else { $result = "<!-- ERR 1 -->"; }
997 /* private */ function nextItem( $char )
999 if ( "*" == $char ||
"#" == $char ) { return "</li><li>"; }
1000 else if ( ":" == $char ||
";" == $char ) {
1002 if ( $this->mDTopen
) { $close = "</dt>"; }
1003 if ( ";" == $char ) {
1004 $this->mDTopen
= true;
1005 return $close . "<dt>";
1007 $this->mDTopen
= false;
1008 return $close . "<dd>";
1011 return "<!-- ERR 2 -->";
1014 /* private */function closeList( $char )
1016 if ( "*" == $char ) { $text = "</li></ul>"; }
1017 else if ( "#" == $char ) { $text = "</li></ol>"; }
1018 else if ( ":" == $char ) {
1019 if ( $this->mDTopen
) {
1020 $this->mDTopen
= false;
1021 $text = "</dt></dl>";
1023 $text = "</dd></dl>";
1026 else { return "<!-- ERR 3 -->"; }
1030 /* private */ function doBlockLevels( $text, $linestart )
1032 $fname = "Parser::doBlockLevels";
1033 wfProfileIn( $fname );
1034 # Parsing through the text line by line. The main thing
1035 # happening here is handling of block-level elements p, pre,
1036 # and making lists from lines starting with * # : etc.
1038 $a = explode( "\n", $text );
1039 $lastPref = $text = '';
1040 $this->mDTopen
= $inBlockElem = $pstack = false;
1042 if ( ! $linestart ) { $text .= array_shift( $a ); }
1043 foreach ( $a as $t ) {
1046 $opl = strlen( $lastPref );
1047 $npl = strspn( $t, "*#:;" );
1048 $pref = substr( $t, 0, $npl );
1049 $pref2 = str_replace( ";", ":", $pref );
1050 $t = substr( $t, $npl );
1052 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1053 $text .= $this->nextItem( substr( $pref, -1 ) );
1054 if ( $pstack ) { $pstack = false; }
1056 if ( ";" == substr( $pref, -1 ) ) {
1057 $cpos = strpos( $t, ":" );
1058 if ( ! ( false === $cpos ) ) {
1059 $term = substr( $t, 0, $cpos );
1060 $text .= $term . $this->nextItem( ":" );
1061 $t = substr( $t, $cpos +
1 );
1064 } else if (0 != $npl ||
0 != $opl) {
1065 $cpl = $this->getCommon( $pref, $lastPref );
1066 if ( $pstack ) { $pstack = false; }
1068 while ( $cpl < $opl ) {
1069 $text .= $this->closeList( $lastPref{$opl-1} );
1072 if ( $npl <= $cpl && $cpl > 0 ) {
1073 $text .= $this->nextItem( $pref{$cpl-1} );
1075 while ( $npl > $cpl ) {
1076 $char = substr( $pref, $cpl, 1 );
1077 $text .= $this->openList( $char );
1079 if ( ";" == $char ) {
1080 $cpos = strpos( $t, ":" );
1081 if ( ! ( false === $cpos ) ) {
1082 $term = substr( $t, 0, $cpos );
1083 $text .= $term . $this->nextItem( ":" );
1084 $t = substr( $t, $cpos +
1 );
1091 if ( 0 == $npl ) { # No prefix (not in list)--go to paragraph mode
1092 $uniq_prefix = UNIQ_PREFIX
;
1093 // XXX: use a stack for nestable elements like span, table and div
1094 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<div|<pre|<tr|<td|<p|<ul|<li)/i", $t );
1095 $closematch = preg_match(
1096 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1097 "<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre|<\\/li|<\\/ul)/i", $t );
1098 if ( $openmatch or $closematch ) {
1099 if ( $pstack ) { $pstack = false; }
1100 $text .= $this->closeParagraph();
1101 if ( $closematch ) {
1102 $inBlockElem = false;
1104 $inBlockElem = true;
1106 } else if ( !$inBlockElem ) {
1107 if ( " " == $t{0} ) {
1109 if ($this->mLastSection
!= 'pre') {
1111 $text .= $this->closeParagraph().'<pre>';
1112 $this->mLastSection
= 'pre';
1116 if ( '' == trim($t) ) {
1118 $text .= $pstack.'<br/>';
1120 $this->mLastSection
= 'p';
1122 if ($this->mLastSection
!= 'p' ) {
1123 $text .= $this->closeParagraph();
1124 $this->mLastSection
= '';
1127 $pstack = '</p><p>';
1134 $this->mLastSection
= 'p';
1135 } else if ($this->mLastSection
!= 'p') {
1136 $text .= $this->closeParagraph().'<p>';
1137 $this->mLastSection
= 'p';
1143 if ($pstack === false) {
1148 $text .= $this->closeList( $pref2{$npl-1} );
1151 if ( "" != $this->mLastSection
) {
1152 $text .= "</" . $this->mLastSection
. ">";
1153 $this->mLastSection
= "";
1155 wfProfileOut( $fname );
1159 function getVariableValue( $index ) {
1160 global $wgLang, $wgSitename, $wgServer;
1163 case MAG_CURRENTMONTH
:
1165 case MAG_CURRENTMONTHNAME
:
1166 return $wgLang->getMonthName( date("n") );
1167 case MAG_CURRENTMONTHNAMEGEN
:
1168 return $wgLang->getMonthNameGen( date("n") );
1169 case MAG_CURRENTDAY
:
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 )
1200 global $wgLang, $wgCurParser;
1201 global $wgScript, $wgArticlePath;
1203 $fname = "Parser::replaceVariables";
1204 wfProfileIn( $fname );
1207 if ( !$this->mVariables
) {
1208 $this->initialiseVariables();
1210 $titleChars = Title
::legalChars();
1211 $regex = "/{{([$titleChars\\|]*?)}}/s";
1213 # "Recursive" variable expansion: run it through a couple of passes
1214 for ( $i=0; $i<MAX_INCLUDE_REPEAT
&& !$bail; $i++
) {
1217 # It's impossible to rebind a global in PHP
1218 # Instead, we run the substitution on a copy, then merge the changed fields back in
1219 $wgCurParser = $this->fork();
1221 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1222 if ( $oldText == $text ) {
1225 $this->merge( $wgCurParser );
1231 # Returns a copy of this object except with various variables cleared
1232 # This copy can be re-merged with the parent after operations on the copy
1236 $copy->mOutput
= new ParserOutput
;
1240 # Merges a copy split off with fork()
1241 function merge( &$copy )
1244 $this->mOutput
->merge( $copy->mOutput
);
1246 # Include throttling arrays
1247 foreach( $copy->mIncludeCount
as $dbk => $count ) {
1248 if ( array_key_exists( $dbk, $this->mIncludeCount
) ) {
1249 $this->mIncludeCount
[$dbk] +
= $count;
1251 $this->mIncludeCount
[$dbk] = $count;
1256 foreach( $copy->mStripState
as $dictName => $contentDict ) {
1257 $this->mStripState
[$dictName] +
= $contentDict;
1261 function braceSubstitution( $matches )
1263 global $wgLinkCache, $wgLang;
1264 $fname = "Parser::braceSubstitution";
1268 $text = $matches[1];
1271 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1272 if ( $mwSubst->matchStartAndRemove( $text ) ) {
1273 if ( $this->mOutputType
!= OT_WIKI
) {
1274 # Invalid SUBST not replaced at PST time
1275 # Return without further processing
1276 $text = $matches[0];
1279 } elseif ( $this->mOutputType
== OT_WIKI
) {
1280 # SUBST not found in PST pass, do nothing
1281 $text = $matches[0];
1285 # MSG, MSGNW and INT
1288 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1289 if ( $mwMsgnw->matchStartAndRemove( $text ) ) {
1292 # Remove obsolete MSG:
1293 $mwMsg =& MagicWord
::get( MAG_MSG
);
1294 $mwMsg->matchStartAndRemove( $text );
1297 # Check if it is an internal message
1298 $mwInt =& MagicWord
::get( MAG_INT
);
1299 if ( $mwInt->matchStartAndRemove( $text ) ) {
1300 $text = wfMsg( $text );
1307 # Check for NS: (namespace expansion)
1308 $mwNs = MagicWord
::get( MAG_NS
);
1309 if ( $mwNs->matchStartAndRemove( $text ) ) {
1310 if ( intval( $text ) ) {
1311 $text = $wgLang->getNsText( intval( $text ) );
1314 $index = Namespace::getCanonicalIndex( strtolower( $text ) );
1315 if ( !is_null( $index ) ) {
1316 $text = $wgLang->getNsText( $index );
1323 # LOCALURL and LOCALURLE
1325 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1326 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1328 if ( $mwLocal->matchStartAndRemove( $text ) ) {
1329 $func = 'getLocalURL';
1330 } elseif ( $mwLocalE->matchStartAndRemove( $text ) ) {
1331 $func = 'escapeLocalURL';
1336 if ( $func !== '' ) {
1337 $args = explode( "|", $text );
1338 $n = count( $args );
1340 $title = Title
::newFromText( $args[0] );
1341 if ( !is_null( $title ) ) {
1343 $text = $title->$func( $args[1] );
1345 $text = $title->$func();
1353 # Check for a match against internal variables
1354 if ( !$found && array_key_exists( $text, $this->mVariables
) ) {
1355 $text = $this->mVariables
[$text];
1357 $this->mOutput
->mContainsOldMagic
= true;
1360 # Load from database
1362 $title = Title
::newFromText( $text, NS_TEMPLATE
);
1363 if ( is_object( $title ) && !$title->isExternal() ) {
1364 # Check for excessive inclusion
1365 $dbk = $title->getPrefixedDBkey();
1366 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1367 $this->mIncludeCount
[$dbk] = 0;
1369 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1370 $article = new Article( $title );
1371 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1372 if ( $articleContent !== false ) {
1374 $text = $articleContent;
1376 # Escaping and link table handling
1377 # Not required for preSaveTransform()
1378 if ( $this->mOutputType
== OT_HTML
) {
1380 $text = wfEscapeWikiText( $text );
1382 $text = $this->removeHTMLtags( $text );
1384 # Do not enter included links in link table
1385 $wgLinkCache->suspend();
1387 # Run full parser on the included text
1388 $text = $this->strip( $text, $this->mStripState
);
1389 $text = $this->doWikiPass2( $text, true );
1391 # Add the result to the strip state for re-inclusion after
1392 # the rest of the processing
1393 $text = $this->insertStripItem( $text, $this->mStripState
);
1395 # Resume the link cache and register the inclusion as a link
1396 $wgLinkCache->resume();
1397 $wgLinkCache->addLinkObj( $title );
1403 # If the title is valid but undisplayable, make a link to it
1404 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1405 $text = "[[" . $title->getPrefixedText() . "]]";
1418 # Cleans up HTML, removes dangerous tags and attributes
1419 /* private */ function removeHTMLtags( $text )
1421 $fname = "Parser::removeHTMLtags";
1422 wfProfileIn( $fname );
1423 $htmlpairs = array( # Tags that must be closed
1424 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1425 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1426 "strike", "strong", "tt", "var", "div", "center",
1427 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1428 "ruby", "rt" , "rb" , "rp", "p"
1430 $htmlsingle = array(
1431 "br", "hr", "li", "dt", "dd"
1433 $htmlnest = array( # Tags that can be nested--??
1434 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1435 "dl", "font", "big", "small", "sub", "sup"
1437 $tabletags = array( # Can only appear inside table
1441 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1442 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1444 $htmlattrs = $this->getHTMLattrs () ;
1446 # Remove HTML comments
1447 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1449 $bits = explode( "<", $text );
1450 $text = array_shift( $bits );
1451 $tagstack = array(); $tablestack = array();
1453 foreach ( $bits as $x ) {
1454 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1455 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1457 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1458 error_reporting( $prev );
1461 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1465 if ( ! in_array( $t, $htmlsingle ) &&
1466 ( $ot = array_pop( $tagstack ) ) != $t ) {
1467 array_push( $tagstack, $ot );
1470 if ( $t == "table" ) {
1471 $tagstack = array_pop( $tablestack );
1476 # Keep track for later
1477 if ( in_array( $t, $tabletags ) &&
1478 ! in_array( "table", $tagstack ) ) {
1480 } else if ( in_array( $t, $tagstack ) &&
1481 ! in_array ( $t , $htmlnest ) ) {
1483 } else if ( ! in_array( $t, $htmlsingle ) ) {
1484 if ( $t == "table" ) {
1485 array_push( $tablestack, $tagstack );
1486 $tagstack = array();
1488 array_push( $tagstack, $t );
1490 # Strip non-approved attributes from the tag
1491 $newparams = $this->fixTagAttributes($params);
1495 $rest = str_replace( ">", ">", $rest );
1496 $text .= "<$slash$t $newparams$brace$rest";
1500 $text .= "<" . str_replace( ">", ">", $x);
1502 # Close off any remaining tags
1503 while ( $t = array_pop( $tagstack ) ) {
1505 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1507 wfProfileOut( $fname );
1513 * This function accomplishes several tasks:
1514 * 1) Auto-number headings if that option is enabled
1515 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1516 * 3) Add a Table of contents on the top for users who have enabled the option
1517 * 4) Auto-anchor headings
1519 * It loops through all headlines, collects the necessary data, then splits up the
1520 * string and re-inserts the newly formatted headlines.
1524 /* private */ function formatHeadings( $text )
1526 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1527 $doShowToc = $this->mOptions
->getShowToc();
1528 if( !$this->mTitle
->userCanEdit() ) {
1530 $rightClickHack = 0;
1532 $showEditLink = $this->mOptions
->getEditSection();
1533 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1536 # Inhibit editsection links if requested in the page
1537 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1538 if( $esw->matchAndRemove( $text ) ) {
1541 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1543 $mw =& MagicWord
::get( MAG_NOTOC
);
1544 if( $mw->matchAndRemove( $text ) ) {
1548 # never add the TOC to the Main Page. This is an entry page that should not
1549 # be more than 1-2 screens large anyway
1550 if( $this->mTitle
->getPrefixedText() == wfMsg("mainpage") ) {
1554 # Get all headlines for numbering them and adding funky stuff like [edit]
1555 # links - this is for later, but we need the number of headlines right now
1556 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1558 # if there are fewer than 4 headlines in the article, do not show TOC
1559 if( $numMatches < 4 ) {
1563 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1564 # override above conditions and always show TOC
1565 $mw =& MagicWord
::get( MAG_FORCETOC
);
1566 if ($mw->matchAndRemove( $text ) ) {
1571 # We need this to perform operations on the HTML
1572 $sk =& $this->mOptions
->getSkin();
1577 # Ugh .. the TOC should have neat indentation levels which can be
1578 # passed to the skin functions. These are determined here
1583 $sublevelCount = array();
1586 foreach( $matches[3] as $headline ) {
1589 $prevlevel = $level;
1591 $level = $matches[1][$headlineCount];
1592 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1593 # reset when we enter a new level
1594 $sublevelCount[$level] = 0;
1595 $toc .= $sk->tocIndent( $level - $prevlevel );
1596 $toclevel +
= $level - $prevlevel;
1598 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1599 # reset when we step back a level
1600 $sublevelCount[$level+
1]=0;
1601 $toc .= $sk->tocUnindent( $prevlevel - $level );
1602 $toclevel -= $prevlevel - $level;
1604 # count number of headlines for each level
1605 @$sublevelCount[$level]++
;
1606 if( $doNumberHeadings ||
$doShowToc ) {
1608 for( $i = 1; $i <= $level; $i++
) {
1609 if( !empty( $sublevelCount[$i] ) ) {
1613 $numbering .= $sublevelCount[$i];
1619 # The canonized header is a version of the header text safe to use for links
1620 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1621 $canonized_headline = Parser
::unstrip( $headline, $this->mStripState
);
1624 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1625 $tocline = trim( $canonized_headline );
1626 $canonized_headline = preg_replace("/[ &\\/<>\\(\\)\\[\\]=,+']+/", '_', html_entity_decode( $tocline));
1627 $refer[$headlineCount] = $canonized_headline;
1629 # count how many in assoc. array so we can track dupes in anchors
1630 @$refers[$canonized_headline]++
;
1631 $refcount[$headlineCount]=$refers[$canonized_headline];
1633 # Prepend the number to the heading text
1635 if( $doNumberHeadings ||
$doShowToc ) {
1636 $tocline = $numbering . " " . $tocline;
1638 # Don't number the heading if it is the only one (looks silly)
1639 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1640 # the two are different if the line contains a link
1641 $headline=$numbering . " " . $headline;
1645 # Create the anchor for linking from the TOC to the section
1646 $anchor = $canonized_headline;
1647 if($refcount[$headlineCount] > 1 ) {
1648 $anchor .= "_" . $refcount[$headlineCount];
1651 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1653 if( $showEditLink ) {
1654 if ( empty( $head[$headlineCount] ) ) {
1655 $head[$headlineCount] = "";
1657 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
1660 # Add the edit section span
1661 if( $rightClickHack ) {
1662 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
1665 # give headline the correct <h#> tag
1666 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1672 $toclines = $headlineCount;
1673 $toc .= $sk->tocUnindent( $toclevel );
1674 $toc = $sk->tocTable( $toc );
1677 # split up and insert constructed headlines
1679 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1682 foreach( $blocks as $block ) {
1683 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1684 # This is the [edit] link that appears for the top block of text when
1685 # section editing is enabled
1686 $full .= $sk->editSectionLink(0);
1689 if( $doShowToc && !$i) {
1690 # Top anchor now in skin
1694 if( !empty( $head[$i] ) ) {
1703 /* private */ function doMagicISBN( &$tokenizer )
1707 # Check whether next token is a text token
1708 # If yes, fetch it and convert the text into a
1709 # Special::BookSources link
1710 $token = $tokenizer->previewToken();
1711 while ( $token["type"] == "" )
1713 $tokenizer->nextToken();
1714 $token = $tokenizer->previewToken();
1716 if ( $token["type"] == "text" )
1718 $token = $tokenizer->nextToken();
1719 $x = $token["text"];
1720 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1722 $isbn = $blank = "" ;
1723 while ( " " == $x{0} ) {
1725 $x = substr( $x, 1 );
1727 while ( strstr( $valid, $x{0} ) != false ) {
1729 $x = substr( $x, 1 );
1731 $num = str_replace( "-", "", $isbn );
1732 $num = str_replace( " ", "", $num );
1735 $text = "ISBN $blank$x";
1737 $titleObj = Title
::makeTitle( NS_SPECIAL
, "Booksources" );
1738 $text = "<a href=\"" .
1739 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1740 "\" class=\"internal\">ISBN $isbn</a>";
1748 /* private */ function doMagicRFC( &$tokenizer )
1752 # Check whether next token is a text token
1753 # If yes, fetch it and convert the text into a
1754 # link to an RFC source
1755 $token = $tokenizer->previewToken();
1756 while ( $token["type"] == "" )
1758 $tokenizer->nextToken();
1759 $token = $tokenizer->previewToken();
1761 if ( $token["type"] == "text" )
1763 $token = $tokenizer->nextToken();
1764 $x = $token["text"];
1765 $valid = "0123456789";
1767 $rfc = $blank = "" ;
1768 while ( " " == $x{0} ) {
1770 $x = substr( $x, 1 );
1772 while ( strstr( $valid, $x{0} ) != false ) {
1774 $x = substr( $x, 1 );
1778 $text .= "RFC $blank$x";
1780 $url = wfmsg( "rfcurl" );
1781 $url = str_replace( "$1", $rfc, $url);
1782 $sk =& $this->mOptions
->getSkin();
1783 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
1784 $text = "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
1792 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
1794 $this->mOptions
= $options;
1795 $this->mTitle
=& $title;
1796 $this->mOutputType
= OT_WIKI
;
1798 if ( $clearState ) {
1799 $this->clearState();
1802 $stripState = false;
1806 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
1809 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
1810 "/<br *?>/i" => "<br/>",
1812 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
1813 $text = $this->strip( $text, $stripState, false );
1814 $text = $this->pstPass2( $text, $user );
1815 $text = $this->unstrip( $text, $stripState );
1819 /* private */ function pstPass2( $text, &$user )
1821 global $wgLang, $wgLocaltimezone, $wgCurParser;
1823 # Variable replacement
1824 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
1825 $text = $this->replaceVariables( $text );
1829 $n = $user->getName();
1830 $k = $user->getOption( "nickname" );
1831 if ( "" == $k ) { $k = $n; }
1832 if(isset($wgLocaltimezone)) {
1833 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1835 /* Note: this is an ugly timezone hack for the European wikis */
1836 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1837 " (" . date( "T" ) . ")";
1838 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1840 $text = preg_replace( "/~~~~~/", $d, $text );
1841 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1842 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1843 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1844 Namespace::getUser() ) . ":$n|$k]]", $text );
1846 # Context links: [[|name]] and [[name (context)|]]
1848 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1849 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1850 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1851 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1853 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1854 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1855 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1856 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1857 # [[ns:page (cont)|]]
1859 $t = $this->mTitle
->getText();
1860 if ( preg_match( $conpat, $t, $m ) ) {
1863 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1864 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1865 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1867 if ( "" == $context ) {
1868 $text = preg_replace( $p2, "[[\\1]]", $text );
1870 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1874 $mw =& MagicWord::get( MAG_SUBST );
1875 $wgCurParser = $this->fork();
1876 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
1877 $this->merge( $wgCurParser );
1880 # Trim trailing whitespace
1881 # MAG_END (__END__) tag allows for trailing
1882 # whitespace to be deliberately included
1883 $text = rtrim( $text );
1884 $mw =& MagicWord
::get( MAG_END
);
1885 $mw->matchAndRemove( $text );
1890 # Set up some variables which are usually set up in parse()
1891 # so that an external function can call some class members with confidence
1892 function startExternalParse( &$title, $options, $outputType, $clearState = true )
1894 $this->mTitle
=& $title;
1895 $this->mOptions
= $options;
1896 $this->mOutputType
= $outputType;
1897 if ( $clearState ) {
1898 $this->clearState();
1902 function transformMsg( $text, $options ) {
1904 static $executing = false;
1906 # Guard against infinite recursion
1912 $this->mTitle
= $wgTitle;
1913 $this->mOptions
= $options;
1914 $this->mOutputType
= OT_MSG
;
1915 $this->clearState();
1916 $text = $this->replaceVariables( $text );
1925 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
1927 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
1928 $containsOldMagic = false )
1930 $this->mText
= $text;
1931 $this->mLanguageLinks
= $languageLinks;
1932 $this->mCategoryLinks
= $categoryLinks;
1933 $this->mContainsOldMagic
= $containsOldMagic;
1936 function getText() { return $this->mText
; }
1937 function getLanguageLinks() { return $this->mLanguageLinks
; }
1938 function getCategoryLinks() { return $this->mCategoryLinks
; }
1939 function containsOldMagic() { return $this->mContainsOldMagic
; }
1940 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
1941 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
1942 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
1943 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
1945 function merge( $other ) {
1946 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
1947 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
1948 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
1955 # All variables are private
1956 var $mUseTeX; # Use texvc to expand <math> tags
1957 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
1958 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
1959 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
1960 var $mAllowExternalImages; # Allow external images inline
1961 var $mSkin; # Reference to the preferred skin
1962 var $mDateFormat; # Date format index
1963 var $mEditSection; # Create "edit section" links
1964 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
1965 var $mNumberHeadings; # Automatically number headings
1966 var $mShowToc; # Show table of contents
1968 function getUseTeX() { return $this->mUseTeX
; }
1969 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
1970 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
1971 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
1972 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
1973 function getSkin() { return $this->mSkin
; }
1974 function getDateFormat() { return $this->mDateFormat
; }
1975 function getEditSection() { return $this->mEditSection
; }
1976 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
1977 function getNumberHeadings() { return $this->mNumberHeadings
; }
1978 function getShowToc() { return $this->mShowToc
; }
1980 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
1981 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
1982 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
1983 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
1984 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
1985 function setSkin( $x ) { return wfSetRef( $this->mSkin
, $x ); }
1986 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
1987 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
1988 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
1989 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
1990 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
1992 /* static */ function newFromUser( &$user )
1994 $popts = new ParserOptions
;
1995 $popts->initialiseFromUser( &$user );
1999 function initialiseFromUser( &$userInput )
2001 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2003 if ( !$userInput ) {
2005 $user->setLoaded( true );
2007 $user =& $userInput;
2010 $this->mUseTeX
= $wgUseTeX;
2011 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2012 $this->mUseDynamicDates
= $wgUseDynamicDates;
2013 $this->mInterwikiMagic
= $wgInterwikiMagic;
2014 $this->mAllowExternalImages
= $wgAllowExternalImages;
2015 $this->mSkin
=& $user->getSkin();
2016 $this->mDateFormat
= $user->getOption( "date" );
2017 $this->mEditSection
= $user->getOption( "editsection" );
2018 $this->mEditSectionOnRightClick
= $user->getOption( "editsectiononrightclick" );
2019 $this->mNumberHeadings
= $user->getOption( "numberheadings" );
2020 $this->mShowToc
= $user->getOption( "showtoc" );
2026 # Regex callbacks, used in Parser::replaceVariables
2027 function wfBraceSubstitution( $matches )
2029 global $wgCurParser;
2030 return $wgCurParser->braceSubstitution( $matches );