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
);
97 $this->mOutput
->setText( $text );
98 wfProfileOut( $fname );
99 return $this->mOutput
;
102 /* static */ function getRandomString()
104 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
107 # Replaces all occurences of <$tag>content</$tag> in the text
108 # with a random marker and returns the new text. the output parameter
109 # $content will be an associative array filled with data on the form
110 # $unique_marker => content.
112 # If $content is already set, the additional entries will be appended
114 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
115 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
122 while ( "" != $text ) {
123 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
125 if ( ( count( $p ) < 2 ) ||
( "" == $p[1] ) ) {
128 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
129 $marker = $rnd . sprintf("%08X", $n++
);
130 $content[$marker] = $q[0];
131 $stripped .= $marker;
138 # Strips <nowiki>, <pre> and <math>
139 # Returns the text, and fills an array with data needed in unstrip()
140 # If the $state is already a valid strip state, it adds to the state
142 function strip( $text, &$state )
144 $render = ($this->mOutputType
== OT_HTML
);
146 $nowiki_content = $state['nowiki'];
147 $hiero_content = $state['hiero'];
148 $math_content = $state['math'];
149 $pre_content = $state['pre'];
150 $item_content = $state['item'];
152 $nowiki_content = array();
153 $hiero_content = array();
154 $math_content = array();
155 $pre_content = array();
156 $item_content = array();
159 # Replace any instances of the placeholders
160 $uniq_prefix = UNIQ_PREFIX
;
161 $text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
163 $text = Parser
::extractTags("nowiki", $text, $nowiki_content, $uniq_prefix);
164 foreach( $nowiki_content as $marker => $content ){
166 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
168 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
172 if( $GLOBALS['wgUseWikiHiero'] ){
173 $text = Parser
::extractTags("hiero", $text, $hiero_content, $uniq_prefix);
174 foreach( $hiero_content as $marker => $content ){
176 $hiero_content[$marker] = WikiHiero( $content, WH_MODE_HTML
);
178 $hiero_content[$marker] = "<hiero>$content</hiero>";
183 if( $this->mOptions
->getUseTeX() ){
184 $text = Parser
::extractTags("math", $text, $math_content, $uniq_prefix);
185 foreach( $math_content as $marker => $content ){
187 $math_content[$marker] = renderMath( $content );
189 $math_content[$marker] = "<math>$content</math>";
194 $text = Parser
::extractTags("pre", $text, $pre_content, $uniq_prefix);
195 foreach( $pre_content as $marker => $content ){
197 $pre_content[$marker] = "<pre>" . wfEscapeHTMLTagsOnly( $content ) . "</pre>";
199 $pre_content[$marker] = "<pre>$content</pre>";
204 'nowiki' => $nowiki_content,
205 'hiero' => $hiero_content,
206 'math' => $math_content,
207 'pre' => $pre_content,
208 'item' => $item_content
213 function unstrip( $text, &$state )
215 # Must expand in reverse order, otherwise nested tags will be corrupted
217 $dicts = array( 'item', 'pre', 'math', 'hiero', 'nowiki' );
218 foreach ( $dicts as $dictName ) {
219 $content_dict = $state[$dictName];
220 foreach( $content_dict as $marker => $content ){
221 $text = str_replace( $marker, $content, $text );
225 $contentDict = end( $state );
226 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
227 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
228 $text = str_replace( key( $contentDict ), $content, $text );
235 # Add an item to the strip state
236 # Returns the unique tag which must be inserted into the stripped text
237 # The tag will be replaced with the original text in unstrip()
239 function insertStripItem( $text, &$state )
241 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
251 $state['item'][$rnd] = $text;
255 function categoryMagic ()
257 global $wgLang , $wgUser ;
258 if ( !$this->mOptions
->getUseCategoryMagic() ) return ;
259 $id = $this->mTitle
->getArticleID() ;
260 $cat = $wgLang->ucfirst ( wfMsg ( "category" ) ) ;
261 $ti = $this->mTitle
->getText() ;
262 $ti = explode ( ":" , $ti , 2 ) ;
263 if ( $cat != $ti[0] ) return "" ;
264 $r = '<br style="clear:both;"/>\n';
266 $articles = array() ;
267 $parents = array () ;
268 $children = array() ;
271 # $sk =& $this->mGetSkin();
272 $sk =& $wgUser->getSkin() ;
275 $sql1 = "SELECT DISTINCT cur_title,cur_namespace FROM cur,links WHERE l_to={$id} AND l_from=cur_id";
276 $sql2 = "SELECT DISTINCT cur_title,cur_namespace FROM cur,brokenlinks WHERE bl_to={$id} AND bl_from=cur_id" ;
278 $res = wfQuery ( $sql1, DB_READ
) ;
279 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
281 $res = wfQuery ( $sql2, DB_READ
) ;
282 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
285 foreach ( $data AS $x )
287 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
288 if ( $t != "" ) $t .= ":" ;
289 $t .= $x->cur_title
;
291 $y = explode ( ":" , $t , 2 ) ;
292 if ( count ( $y ) == 2 && $y[0] == $cat ) {
293 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
295 array_push ( $articles , $sk->makeLink ( $t ) ) ;
298 wfFreeResult ( $res ) ;
301 if ( count ( $children ) > 0 )
303 asort ( $children ) ;
304 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
305 $r .= implode ( ", " , $children ) ;
309 if ( count ( $articles ) > 0 )
311 asort ( $articles ) ;
312 $h = wfMsg( "category_header", $ti[1] );
313 $r .= "<h2>{$h}</h2>\n" ;
314 $r .= implode ( ", " , $articles ) ;
321 function getHTMLattrs ()
323 $htmlattrs = array( # Allowed attributes--no scripting, etc.
324 "title", "align", "lang", "dir", "width", "height",
325 "bgcolor", "clear", /* BR */ "noshade", /* HR */
326 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
327 /* FONT */ "type", "start", "value", "compact",
328 /* For various lists, mostly deprecated but safe */
329 "summary", "width", "border", "frame", "rules",
330 "cellspacing", "cellpadding", "valign", "char",
331 "charoff", "colgroup", "col", "span", "abbr", "axis",
332 "headers", "scope", "rowspan", "colspan", /* Tables */
333 "id", "class", "name", "style" /* For CSS */
338 function fixTagAttributes ( $t )
340 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
341 $htmlattrs = $this->getHTMLattrs() ;
343 # Strip non-approved attributes from the tag
345 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
346 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
348 # Strip javascript "expression" from stylesheets. Brute force approach:
349 # If anythin offensive is found, all attributes of the HTML tag are dropped
352 "/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is",
353 wfMungeToUtf8( $t ) ) )
361 function doTableStuff ( $t )
363 $t = explode ( "\n" , $t ) ;
364 $td = array () ; # Is currently a td tag open?
365 $ltd = array () ; # Was it TD or TH?
366 $tr = array () ; # Is currently a tr tag open?
367 $ltr = array () ; # tr attributes
368 foreach ( $t AS $k => $x )
371 $fc = substr ( $x , 0 , 1 ) ;
372 if ( "{|" == substr ( $x , 0 , 2 ) )
374 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
375 array_push ( $td , false ) ;
376 array_push ( $ltd , "" ) ;
377 array_push ( $tr , false ) ;
378 array_push ( $ltr , "" ) ;
380 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
381 else if ( "|}" == substr ( $x , 0 , 2 ) )
384 $l = array_pop ( $ltd ) ;
385 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
386 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
390 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
392 $z = trim ( substr ( $x , 2 ) ) ;
393 $t[$k] = "<caption>{$z}</caption>\n" ;
395 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
397 $x = substr ( $x , 1 ) ;
398 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
400 $l = array_pop ( $ltd ) ;
401 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
402 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
405 array_push ( $tr , false ) ;
406 array_push ( $td , false ) ;
407 array_push ( $ltd , "" ) ;
408 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
410 else if ( "|" == $fc ||
"!" == $fc ||
"|+" == substr ( $x , 0 , 2 ) ) # Caption
412 if ( "|+" == substr ( $x , 0 , 2 ) )
415 $x = substr ( $x , 1 ) ;
417 $after = substr ( $x , 1 ) ;
418 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
419 $after = explode ( "||" , $after ) ;
421 foreach ( $after AS $theline )
426 $tra = array_pop ( $ltr ) ;
427 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
428 array_push ( $tr , true ) ;
429 array_push ( $ltr , "" ) ;
432 $l = array_pop ( $ltd ) ;
433 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
434 if ( $fc == "|" ) $l = "td" ;
435 else if ( $fc == "!" ) $l = "th" ;
436 else if ( $fc == "+" ) $l = "caption" ;
438 array_push ( $ltd , $l ) ;
439 $y = explode ( "|" , $theline , 2 ) ;
440 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
441 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
443 array_push ( $td , true ) ;
448 # Closing open td, tr && table
449 while ( count ( $td ) > 0 )
451 if ( array_pop ( $td ) ) $t[] = "</td>" ;
452 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
456 $t = implode ( "\n" , $t ) ;
457 # $t = $this->removeHTMLtags( $t );
461 # Well, OK, it's actually about 14 passes. But since all the
462 # hard lifting is done inside PHP's regex code, it probably
463 # wouldn't speed things up much to add a real parser.
465 function doWikiPass2( $text, $linestart )
467 $fname = "Parser::doWikiPass2";
468 wfProfileIn( $fname );
470 $text = $this->removeHTMLtags( $text );
471 $text = $this->replaceVariables( $text );
473 # $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
475 $text = $this->doHeadings( $text );
477 if($this->mOptions
->getUseDynamicDates()) {
478 global $wgDateFormatter;
479 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
482 $text = $this->replaceExternalLinks( $text );
483 $text = $this->doTokenizedParser ( $text );
485 $text = $this->doTableStuff ( $text ) ;
487 $text = $this->formatHeadings( $text );
489 $sk =& $this->mOptions
->getSkin();
490 $text = $sk->transformContent( $text );
492 "/<hr *>/i" => '<hr/>',
493 "/<br *>/i" => '<br/>',
494 "/<center *>/i"=>'<span style="text-align:center;">',
495 "/<\\/center *>/i" => '</span>'
497 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
499 # Clean up spare ampersands; note that we probably ought to be
500 # more careful about named entities.
501 $text = preg_replace(
502 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/',
506 $text .= $this->categoryMagic () ;
508 # needs to be called last
509 $text = $this->doBlockLevels( $text, $linestart );
511 wfProfileOut( $fname );
516 /* private */ function doHeadings( $text )
518 for ( $i = 6; $i >= 1; --$i ) {
519 $h = substr( "======", 0, $i );
520 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
521 "<h{$i}>\\1</h{$i}>\\2", $text );
526 # Note: we have to do external links before the internal ones,
527 # and otherwise take great care in the order of things here, so
528 # that we don't end up interpreting some URLs twice.
530 /* private */ function replaceExternalLinks( $text )
532 $fname = "Parser::replaceExternalLinks";
533 wfProfileIn( $fname );
534 $text = $this->subReplaceExternalLinks( $text, "http", true );
535 $text = $this->subReplaceExternalLinks( $text, "https", true );
536 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
537 $text = $this->subReplaceExternalLinks( $text, "irc", false );
538 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
539 $text = $this->subReplaceExternalLinks( $text, "news", false );
540 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
541 wfProfileOut( $fname );
545 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
547 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
548 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
550 # this is the list of separators that should be ignored if they
551 # are the last character of an URL but that should be included
552 # if they occur within the URL, e.g. "go to www.foo.com, where .."
553 # in this case, the last comma should not become part of the URL,
554 # but in "www.foo.com/123,2342,32.htm" it should.
556 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
557 $images = "gif|png|jpg|jpeg";
559 # PLEASE NOTE: The curly braces { } are not part of the regex,
560 # they are interpreted as part of the string (used to tell PHP
561 # that the content of the string should be inserted there).
562 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
563 "((?i){$images})([^{$uc}]|$)/";
565 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
566 $sk =& $this->mOptions
->getSkin();
568 if ( $autonumber and $this->mOptions
->getAllowExternalImages() ) { # Use img tags only for HTTP urls
569 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
570 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
572 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
573 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
574 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
576 $s = str_replace( $unique, $protocol, $s );
578 $a = explode( "[{$protocol}:", " " . $s );
579 $s = array_shift( $a );
580 $s = substr( $s, 1 );
582 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
583 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
585 foreach ( $a as $line ) {
586 if ( preg_match( $e1, $line, $m ) ) {
587 $link = "{$protocol}:{$m[1]}";
589 if ( $autonumber ) { $text = "[" . ++
$this->mAutonumber
. "]"; }
590 else { $text = wfEscapeHTML( $link ); }
591 } else if ( preg_match( $e2, $line, $m ) ) {
592 $link = "{$protocol}:{$m[1]}";
596 $s .= "[{$protocol}:" . $line;
599 if( $link == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
602 # Expand the URL for printable version
603 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
605 $la = $sk->getExternalLinkAttributes( $link, $text );
606 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
612 /* private */ function handle3Quotes( &$state, $token )
614 if ( $state["strong"] !== false ) {
615 if ( $state["em"] !== false && $state["em"] > $state["strong"] )
617 # ''' lala ''lala '''
618 $s = "</em></strong><em>";
622 $state["strong"] = FALSE;
625 $state["strong"] = isset($token["pos"]) ?
$token["pos"] : true;
630 /* private */ function handle2Quotes( &$state, $token )
632 if ( $state["em"] !== false ) {
633 if ( $state["strong"] !== false && $state["strong"] > $state["em"] )
635 # ''lala'''lala'' ....'''
636 $s = "</strong></em><strong>";
640 $state["em"] = FALSE;
643 $state["em"] = isset($token["pos"]) ?
$token["pos"] : true;
649 /* private */ function handle5Quotes( &$state, $token )
652 if ( $state["em"] !== false && $state["strong"] !== false ) {
653 if ( $state["em"] < $state["strong"] ) {
654 $s .= "</strong></em>";
656 $s .= "</em></strong>";
658 $state["strong"] = $state["em"] = FALSE;
659 } elseif ( $state["em"] !== false ) {
660 $s .= "</em><strong>";
661 $state["em"] = FALSE;
662 $state["strong"] = $token["pos"];
663 } elseif ( $state["strong"] !== false ) {
664 $s .= "</strong><em>";
665 $state["strong"] = FALSE;
666 $state["em"] = $token["pos"];
667 } else { # not $em and not $strong
668 $s .= "<strong><em>";
669 $state["strong"] = $state["em"] = $token["pos"];
674 /* private */ function doTokenizedParser( $str )
676 global $wgLang; # for language specific parser hook
678 $tokenizer=Tokenizer
::newFromString( $str );
679 $tokenStack = array();
682 $state["em"] = FALSE;
683 $state["strong"] = FALSE;
687 # The tokenizer splits the text into tokens and returns them one by one.
688 # Every call to the tokenizer returns a new token.
689 while ( $token = $tokenizer->nextToken() )
691 switch ( $token["type"] )
694 # simple text with no further markup
695 $txt = $token["text"];
698 # remember the tag opened with 3 [
702 # FIXME : Treat orphaned open tags (stack not empty when text is over)
704 array_push( $tokenStack, $token );
711 # get text from stack, glue it together, and call the code to handle a
714 if ( count( $tokenStack ) == 0 )
716 # stack empty. Found a ]] without an opening [[
720 $lastToken = array_pop( $tokenStack );
721 while ( !(($lastToken["type"] == "[[[") or ($lastToken["type"] == "[[")) )
723 if( !empty( $lastToken["text"] ) ) {
724 $linkText = $lastToken["text"] . $linkText;
726 $lastToken = array_pop( $tokenStack );
729 $txt = $linkText ."]]";
731 if( isset( $lastToken["text"] ) ) {
732 $prefix = $lastToken["text"];
736 $nextToken = $tokenizer->previewToken();
737 if ( $nextToken["type"] == "text" )
739 # Preview just looks at it. Now we have to fetch it.
740 $nextToken = $tokenizer->nextToken();
741 $txt .= $nextToken["text"];
743 $fakestate = $this->mStripState
;
744 $txt = $this->handleInternalLink( $this->unstrip($txt,$fakestate), $prefix );
746 # did the tag start with 3 [ ?
748 # show the first as text
754 $tagIsOpen = (count( $tokenStack ) != 0);
760 # This and the three next ones handle quotes
761 $txt = $this->handle3Quotes( $state, $token );
764 $txt = $this->handle2Quotes( $state, $token );
767 $txt = $this->handle5Quotes( $state, $token );
777 $txt = $this->doMagicRFC( $tokenizer );
784 $txt = $this->doMagicISBN( $tokenizer );
788 # Call language specific Hook.
789 $txt = $wgLang->processToken( $token, $tokenStack );
790 if ( NULL == $txt ) {
791 # An unkown token. Highlight.
792 $txt = "<font color=\"#FF0000\"><b>".$token["type"]."</b></font>";
793 $txt .= "<font color=\"#FFFF00\"><b>".$token["text"]."</b></font>";
797 # If we're parsing the interior of a link, don't append the interior to $s,
798 # but push it to the stack so it can be processed when a ]] token is found.
799 if ( $tagIsOpen && $txt != "" ) {
800 $token["type"] = "text";
801 $token["text"] = $txt;
802 array_push( $tokenStack, $token );
807 if ( count( $tokenStack ) != 0 )
809 # still objects on stack. opened [[ tag without closing ]] tag.
811 while ( $lastToken = array_pop( $tokenStack ) )
813 if ( $lastToken["type"] == "text" )
815 $txt = $lastToken["text"] . $txt;
817 $txt = $lastToken["type"] . $txt;
825 /* private */ function handleInternalLink( $line, $prefix )
827 global $wgLang, $wgLinkCache;
828 global $wgNamespacesWithSubpages, $wgLanguageCode;
829 static $fname = "Parser::handleInternalLink" ;
830 wfProfileIn( $fname );
832 wfProfileIn( "$fname-setup" );
834 if ( !$tc ) { $tc = Title
::legalChars() . "#"; }
835 $sk =& $this->mOptions
->getSkin();
837 # Match a link having the form [[namespace:link|alternate]]trail
839 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
840 # Match the end of a line for a word that's not followed by whitespace,
841 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
842 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
843 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
844 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
847 # Special and Media are pseudo-namespaces; no pages actually exist in them
848 static $image = FALSE;
849 static $special = FALSE;
850 static $media = FALSE;
851 static $category = FALSE;
852 if ( !$image ) { $image = Namespace::getImage(); }
853 if ( !$special ) { $special = Namespace::getSpecial(); }
854 if ( !$media ) { $media = Namespace::getMedia(); }
855 if ( !$category ) { $category = wfMsg ( "category" ) ; }
857 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
859 wfProfileOut( "$fname-setup" );
862 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
865 } else { # Invalid form; output directly
866 $s .= $prefix . "[[" . $line ;
872 :Foobar -- override special treatment of prefix (images, language links)
873 /Foobar -- convert to CurrentPage/Foobar
874 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
876 $c = substr($m[1],0,1);
877 $noforce = ($c != ":");
878 if( $c == "/" ) { # subpage
879 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
880 $m[1]=substr($m[1],1,strlen($m[1])-2);
883 $noslash=substr($m[1],1);
885 if($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]) { # subpages allowed here
886 $link = $this->mTitle
->getPrefixedText(). "/" . trim($noslash);
889 } # this might be changed for ugliness reasons
891 $link = $noslash; # no subpage allowed, use standard link
893 } elseif( $noforce ) { # no subpage
896 $link = substr( $m[1], 1 );
901 $nt = Title
::newFromText( $link );
903 $s .= $prefix . "[[" . $line;
906 $ns = $nt->getNamespace();
907 $iw = $nt->getInterWiki();
909 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
910 array_push( $this->mOutput
->mLanguageLinks
, $nt->getPrefixedText() );
911 return (trim($s) == '')?
'': $s;
913 if( $ns == $image ) {
914 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
915 $wgLinkCache->addImageLinkObj( $nt );
919 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
920 ( strpos( $link, "#" ) == FALSE ) ) {
921 $s .= $prefix . "<strong>" . $text . "</strong>" . $trail;
926 $catns = strtoupper ( $nt->getDBkey () ) ;
927 $catns = explode ( ":" , $catns ) ;
928 if ( count ( $catns ) > 1 ) $catns = array_shift ( $catns ) ;
930 if ( $catns == strtoupper($category) && $this->mOptions
->getUseCategoryMagic() ) {
931 $t = explode ( ":" , $nt->getText() ) ;
933 $t = implode ( ":" , $t ) ;
934 $t = $wgLang->ucFirst ( $t ) ;
935 $nnt = Title
::newFromText ( $category.":".$t ) ;
936 $t = $sk->makeLinkObj( $nnt, $t, "", $trail , $prefix );
937 $this->mOutput
->mCategoryLinks
[] = $t ;
938 $s .= $prefix . $trail ;
942 if( $ns == $media ) {
943 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
944 $wgLinkCache->addImageLinkObj( $nt );
946 } elseif( $ns == $special ) {
947 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
950 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
952 wfProfileOut( $fname );
956 # Some functions here used by doBlockLevels()
958 /* private */ function closeParagraph()
961 if ( '' != $this->mLastSection
) {
962 $result = "</" . $this->mLastSection
. ">\n";
964 $this->mLastSection
= "";
967 # getCommon() returns the length of the longest common substring
968 # of both arguments, starting at the beginning of both.
970 /* private */ function getCommon( $st1, $st2 )
972 $fl = strlen( $st1 );
973 $shorter = strlen( $st2 );
974 if ( $fl < $shorter ) { $shorter = $fl; }
976 for ( $i = 0; $i < $shorter; ++
$i ) {
977 if ( $st1{$i} != $st2{$i} ) { break; }
981 # These next three functions open, continue, and close the list
982 # element appropriate to the prefix character passed into them.
984 /* private */ function openList( $char )
986 $result = $this->closeParagraph();
988 if ( "*" == $char ) { $result .= "<ul><li>"; }
989 else if ( "#" == $char ) { $result .= "<ol><li>"; }
990 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
991 else if ( ";" == $char ) {
992 $result .= "<dl><dt>";
993 $this->mDTopen
= true;
995 else { $result = "<!-- ERR 1 -->"; }
1000 /* private */ function nextItem( $char )
1002 if ( "*" == $char ||
"#" == $char ) { return "</li><li>"; }
1003 else if ( ":" == $char ||
";" == $char ) {
1005 if ( $this->mDTopen
) { $close = "</dt>"; }
1006 if ( ";" == $char ) {
1007 $this->mDTopen
= true;
1008 return $close . "<dt>";
1010 $this->mDTopen
= false;
1011 return $close . "<dd>";
1014 return "<!-- ERR 2 -->";
1017 /* private */function closeList( $char )
1019 if ( "*" == $char ) { $text = "</li></ul>"; }
1020 else if ( "#" == $char ) { $text = "</li></ol>"; }
1021 else if ( ":" == $char ) {
1022 if ( $this->mDTopen
) {
1023 $this->mDTopen
= false;
1024 $text = "</dt></dl>";
1026 $text = "</dd></dl>";
1029 else { return "<!-- ERR 3 -->"; }
1033 /* private */ function doBlockLevels( $text, $linestart )
1035 $fname = "Parser::doBlockLevels";
1036 wfProfileIn( $fname );
1037 # Parsing through the text line by line. The main thing
1038 # happening here is handling of block-level elements p, pre,
1039 # and making lists from lines starting with * # : etc.
1041 $a = explode( "\n", $text );
1042 $lastPref = $text = $lastLine = '';
1043 $this->mDTopen
= $inBlockElem = false;
1045 if ( ! $linestart ) { $text .= array_shift( $a ); }
1046 foreach ( $a as $t ) {
1047 if ( "" != $text ) { $text .= "\n"; }
1050 $opl = strlen( $lastPref );
1051 $npl = strspn( $t, "*#:;" );
1052 $pref = substr( $t, 0, $npl );
1053 $pref2 = str_replace( ";", ":", $pref );
1054 $t = substr( $t, $npl );
1056 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1057 $text .= $this->nextItem( substr( $pref, -1 ) );
1059 if ( ";" == substr( $pref, -1 ) ) {
1060 $cpos = strpos( $t, ":" );
1061 if ( ! ( false === $cpos ) ) {
1062 $term = substr( $t, 0, $cpos );
1063 $text .= $term . $this->nextItem( ":" );
1064 $t = substr( $t, $cpos +
1 );
1067 } else if (0 != $npl ||
0 != $opl) {
1068 $cpl = $this->getCommon( $pref, $lastPref );
1070 while ( $cpl < $opl ) {
1071 $text .= $this->closeList( $lastPref{$opl-1} );
1074 if ( $npl <= $cpl && $cpl > 0 ) {
1075 $text .= $this->nextItem( $pref{$cpl-1} );
1077 while ( $npl > $cpl ) {
1078 $char = substr( $pref, $cpl, 1 );
1079 $text .= $this->openList( $char );
1081 if ( ";" == $char ) {
1082 $cpos = strpos( $t, ":" );
1083 if ( ! ( false === $cpos ) ) {
1084 $term = substr( $t, 0, $cpos );
1085 $text .= $term . $this->nextItem( ":" );
1086 $t = substr( $t, $cpos +
1 );
1093 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1094 $uniq_prefix = UNIQ_PREFIX
;
1095 // XXX: use a stack for nestable elements like span, table and div
1096 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<div|<pre|<tr|<td|<p)/i", $t );
1097 $closematch = preg_match(
1098 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1099 "<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre)/i", $t );
1100 if ( $openmatch or $closematch ) {
1101 $text .= $this->closeParagraph();
1102 if ( $closematch ) {
1103 $inBlockElem = false;
1105 $inBlockElem = true;
1107 } else if ( !$inBlockElem ) {
1108 if ( " " == $t{0} ) {
1109 $newSection = "pre";
1110 if ($this->mLastSection
!= 'pre') {
1111 $text .= $this->closeParagraph();
1112 $text .= "<" . $newSection . ">";
1113 $this->mLastSection
= $newSection;
1117 if ( ''==trim($t) && ( '' != trim($lastLine) )) {
1118 $text .= $this->closeParagraph();
1119 $text .= "<" . $newSection . ">";
1120 $this->mLastSection
= $newSection;
1130 $text .= $this->closeList( $pref2{$npl-1} );
1133 if ( "" != $this->mLastSection
) {
1134 $text .= "</" . $this->mLastSection
. ">";
1135 $this->mLastSection
= "";
1137 wfProfileOut( $fname );
1141 function getVariableValue( $index ) {
1142 global $wgLang, $wgSitename, $wgServer;
1145 case MAG_CURRENTMONTH
:
1147 case MAG_CURRENTMONTHNAME
:
1148 return $wgLang->getMonthName( date("n") );
1149 case MAG_CURRENTMONTHNAMEGEN
:
1150 return $wgLang->getMonthNameGen( date("n") );
1151 case MAG_CURRENTDAY
:
1153 case MAG_CURRENTDAYNAME
:
1154 return $wgLang->getWeekdayName( date("w")+
1 );
1155 case MAG_CURRENTYEAR
:
1157 case MAG_CURRENTTIME
:
1158 return $wgLang->time( wfTimestampNow(), false );
1159 case MAG_NUMBEROFARTICLES
:
1160 return wfNumberOfArticles();
1170 function initialiseVariables()
1172 global $wgVariableIDs;
1173 $this->mVariables
= array();
1174 foreach ( $wgVariableIDs as $id ) {
1175 $mw =& MagicWord
::get( $id );
1176 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1180 /* private */ function replaceVariables( $text )
1182 global $wgLang, $wgCurParser;
1183 global $wgScript, $wgArticlePath;
1185 $fname = "Parser::replaceVariables";
1186 wfProfileIn( $fname );
1189 if ( !$this->mVariables
) {
1190 $this->initialiseVariables();
1192 $titleChars = Title
::legalChars();
1193 $regex = "/{{([$titleChars\\|]*?)}}/s";
1195 # "Recursive" variable expansion: run it through a couple of passes
1196 for ( $i=0; $i<MAX_INCLUDE_REPEAT
&& !$bail; $i++
) {
1199 # It's impossible to rebind a global in PHP
1200 # Instead, we run the substitution on a copy, then merge the changed fields back in
1201 $wgCurParser = $this->fork();
1203 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1204 if ( $oldText == $text ) {
1207 $this->merge( $wgCurParser );
1213 # Returns a copy of this object except with various variables cleared
1214 # This copy can be re-merged with the parent after operations on the copy
1218 $copy->mOutput
= new ParserOutput
;
1222 # Merges a copy split off with fork()
1223 function merge( &$copy )
1226 $this->mOutput
->merge( $copy->mOutput
);
1228 # Include throttling arrays
1229 foreach( $copy->mIncludeCount
as $dbk => $count ) {
1230 if ( array_key_exists( $dbk, $this->mIncludeCount
) ) {
1231 $this->mIncludeCount
[$dbk] +
= $count;
1233 $this->mIncludeCount
[$dbk] = $count;
1238 foreach( $copy->mStripState
as $dictName => $contentDict ) {
1239 $this->mStripState
[$dictName] +
= $contentDict;
1243 function braceSubstitution( $matches )
1245 global $wgLinkCache, $wgLang;
1246 $fname = "Parser::braceSubstitution";
1250 $text = $matches[1];
1253 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1254 if ( $mwSubst->matchStartAndRemove( $text ) ) {
1255 if ( $this->mOutputType
!= OT_WIKI
) {
1256 # Invalid SUBST not replaced at PST time
1257 # Return without further processing
1258 $text = $matches[0];
1261 } elseif ( $this->mOutputType
== OT_WIKI
) {
1262 # SUBST not found in PST pass, do nothing
1263 $text = $matches[0];
1267 # MSG, MSGNW and INT
1270 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1271 if ( $mwMsgnw->matchStartAndRemove( $text ) ) {
1274 # Remove obsolete MSG:
1275 $mwMsg =& MagicWord
::get( MAG_MSG
);
1276 $mwMsg->matchStartAndRemove( $text );
1279 # Check if it is an internal message
1280 $mwInt =& MagicWord
::get( MAG_INT
);
1281 if ( $mwInt->matchStartAndRemove( $text ) ) {
1282 $text = wfMsg( $text );
1289 # Check for NS: (namespace expansion)
1290 $mwNs = MagicWord
::get( MAG_NS
);
1291 if ( $mwNs->matchStartAndRemove( $text ) ) {
1292 if ( intval( $text ) ) {
1293 $text = $wgLang->getNsText( intval( $text ) );
1296 $index = Namespace::getCanonicalIndex( strtolower( $text ) );
1297 if ( !is_null( $index ) ) {
1298 $text = $wgLang->getNsText( $index );
1305 # LOCALURL and LOCALURLE
1307 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1308 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1310 if ( $mwLocal->matchStartAndRemove( $text ) ) {
1311 $func = 'getLocalURL';
1312 } elseif ( $mwLocalE->matchStartAndRemove( $text ) ) {
1313 $func = 'escapeLocalURL';
1318 if ( $func !== '' ) {
1319 $args = explode( "|", $text );
1320 $n = count( $args );
1322 $title = Title
::newFromText( $args[0] );
1323 if ( !is_null( $title ) ) {
1325 $text = $title->$func( $args[1] );
1327 $text = $title->$func();
1335 # Check for a match against internal variables
1336 if ( !$found && array_key_exists( $text, $this->mVariables
) ) {
1337 $text = $this->mVariables
[$text];
1339 $this->mOutput
->mContainsOldMagic
= true;
1342 # Load from database
1344 $title = Title
::newFromText( $text, NS_TEMPLATE
);
1345 if ( is_object( $title ) && !$title->isExternal() ) {
1346 # Check for excessive inclusion
1347 $dbk = $title->getPrefixedDBkey();
1348 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1349 $this->mIncludeCount
[$dbk] = 0;
1351 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1352 $article = new Article( $title );
1353 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1354 if ( $articleContent !== false ) {
1356 $text = $articleContent;
1358 # Escaping and link table handling
1359 # Not required for preSaveTransform()
1360 if ( $this->mOutputType
== OT_HTML
) {
1362 $text = wfEscapeWikiText( $text );
1364 $text = $this->removeHTMLtags( $text );
1366 # Do not enter included links in link table
1367 $wgLinkCache->suspend();
1369 # Run full parser on the included text
1370 $text = $this->strip( $text, $this->mStripState
);
1371 $text = $this->doWikiPass2( $text, true );
1373 # Add the result to the strip state for re-inclusion after
1374 # the rest of the processing
1375 $text = $this->insertStripItem( $text, $this->mStripState
);
1377 # Resume the link cache and register the inclusion as a link
1378 $wgLinkCache->resume();
1379 $wgLinkCache->addLinkObj( $title );
1385 # If the title is valid but undisplayable, make a link to it
1386 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1387 $text = "[[" . $title->getPrefixedText() . "]]";
1400 # Cleans up HTML, removes dangerous tags and attributes
1401 /* private */ function removeHTMLtags( $text )
1403 $fname = "Parser::removeHTMLtags";
1404 wfProfileIn( $fname );
1405 $htmlpairs = array( # Tags that must be closed
1406 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1407 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1408 "strike", "strong", "tt", "var", "div", "center",
1409 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1410 "ruby", "rt" , "rb" , "rp", "p"
1412 $htmlsingle = array(
1413 "br", "hr", "li", "dt", "dd"
1415 $htmlnest = array( # Tags that can be nested--??
1416 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1417 "dl", "font", "big", "small", "sub", "sup"
1419 $tabletags = array( # Can only appear inside table
1423 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1424 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1426 $htmlattrs = $this->getHTMLattrs () ;
1428 # Remove HTML comments
1429 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1431 $bits = explode( "<", $text );
1432 $text = array_shift( $bits );
1433 $tagstack = array(); $tablestack = array();
1435 foreach ( $bits as $x ) {
1436 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1437 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1439 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1440 error_reporting( $prev );
1443 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1447 if ( ! in_array( $t, $htmlsingle ) &&
1448 ( $ot = array_pop( $tagstack ) ) != $t ) {
1449 array_push( $tagstack, $ot );
1452 if ( $t == "table" ) {
1453 $tagstack = array_pop( $tablestack );
1458 # Keep track for later
1459 if ( in_array( $t, $tabletags ) &&
1460 ! in_array( "table", $tagstack ) ) {
1462 } else if ( in_array( $t, $tagstack ) &&
1463 ! in_array ( $t , $htmlnest ) ) {
1465 } else if ( ! in_array( $t, $htmlsingle ) ) {
1466 if ( $t == "table" ) {
1467 array_push( $tablestack, $tagstack );
1468 $tagstack = array();
1470 array_push( $tagstack, $t );
1472 # Strip non-approved attributes from the tag
1473 $newparams = $this->fixTagAttributes($params);
1477 $rest = str_replace( ">", ">", $rest );
1478 $text .= "<$slash$t $newparams$brace$rest";
1482 $text .= "<" . str_replace( ">", ">", $x);
1484 # Close off any remaining tags
1485 while ( $t = array_pop( $tagstack ) ) {
1487 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1489 wfProfileOut( $fname );
1495 * This function accomplishes several tasks:
1496 * 1) Auto-number headings if that option is enabled
1497 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1498 * 3) Add a Table of contents on the top for users who have enabled the option
1499 * 4) Auto-anchor headings
1501 * It loops through all headlines, collects the necessary data, then splits up the
1502 * string and re-inserts the newly formatted headlines.
1506 /* private */ function formatHeadings( $text )
1508 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1509 $doShowToc = $this->mOptions
->getShowToc();
1510 if( !$this->mTitle
->userCanEdit() ) {
1512 $rightClickHack = 0;
1514 $showEditLink = $this->mOptions
->getEditSection();
1515 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1518 # Inhibit editsection links if requested in the page
1519 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1520 if( $esw->matchAndRemove( $text ) ) {
1523 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1525 $mw =& MagicWord
::get( MAG_NOTOC
);
1526 if( $mw->matchAndRemove( $text ) ) {
1530 # never add the TOC to the Main Page. This is an entry page that should not
1531 # be more than 1-2 screens large anyway
1532 if( $this->mTitle
->getPrefixedText() == wfMsg("mainpage") ) {
1536 # Get all headlines for numbering them and adding funky stuff like [edit]
1537 # links - this is for later, but we need the number of headlines right now
1538 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1540 # if there are fewer than 4 headlines in the article, do not show TOC
1541 if( $numMatches < 4 ) {
1545 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1546 # override above conditions and always show TOC
1547 $mw =& MagicWord
::get( MAG_FORCETOC
);
1548 if ($mw->matchAndRemove( $text ) ) {
1553 # We need this to perform operations on the HTML
1554 $sk =& $this->mOptions
->getSkin();
1559 # Ugh .. the TOC should have neat indentation levels which can be
1560 # passed to the skin functions. These are determined here
1565 $sublevelCount = array();
1568 foreach( $matches[3] as $headline ) {
1571 $prevlevel = $level;
1573 $level = $matches[1][$headlineCount];
1574 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1575 # reset when we enter a new level
1576 $sublevelCount[$level] = 0;
1577 $toc .= $sk->tocIndent( $level - $prevlevel );
1578 $toclevel +
= $level - $prevlevel;
1580 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1581 # reset when we step back a level
1582 $sublevelCount[$level+
1]=0;
1583 $toc .= $sk->tocUnindent( $prevlevel - $level );
1584 $toclevel -= $prevlevel - $level;
1586 # count number of headlines for each level
1587 @$sublevelCount[$level]++
;
1588 if( $doNumberHeadings ||
$doShowToc ) {
1590 for( $i = 1; $i <= $level; $i++
) {
1591 if( !empty( $sublevelCount[$i] ) ) {
1595 $numbering .= $sublevelCount[$i];
1601 # The canonized header is a version of the header text safe to use for links
1602 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1603 $canonized_headline = Parser
::unstrip( $headline, $this->mStripState
);
1606 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1607 $tocline = trim( $canonized_headline );
1608 $canonized_headline = preg_replace("/[ &\\/<>\\(\\)\\[\\]=,+']+/", '_', html_entity_decode( $tocline));
1609 $refer[$headlineCount] = $canonized_headline;
1611 # count how many in assoc. array so we can track dupes in anchors
1612 @$refers[$canonized_headline]++
;
1613 $refcount[$headlineCount]=$refers[$canonized_headline];
1615 # Prepend the number to the heading text
1617 if( $doNumberHeadings ||
$doShowToc ) {
1618 $tocline = $numbering . " " . $tocline;
1620 # Don't number the heading if it is the only one (looks silly)
1621 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1622 # the two are different if the line contains a link
1623 $headline=$numbering . " " . $headline;
1627 # Create the anchor for linking from the TOC to the section
1628 $anchor = $canonized_headline;
1629 if($refcount[$headlineCount] > 1 ) {
1630 $anchor .= "_" . $refcount[$headlineCount];
1633 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1635 if( $showEditLink ) {
1636 if ( empty( $head[$headlineCount] ) ) {
1637 $head[$headlineCount] = "";
1639 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
1642 # Add the edit section span
1643 if( $rightClickHack ) {
1644 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
1647 # give headline the correct <h#> tag
1648 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1654 $toclines = $headlineCount;
1655 $toc .= $sk->tocUnindent( $toclevel );
1656 $toc = $sk->tocTable( $toc );
1659 # split up and insert constructed headlines
1661 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1664 foreach( $blocks as $block ) {
1665 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1666 # This is the [edit] link that appears for the top block of text when
1667 # section editing is enabled
1668 $full .= $sk->editSectionLink(0);
1671 if( $doShowToc && !$i) {
1672 # Top anchor now in skin
1676 if( !empty( $head[$i] ) ) {
1685 /* private */ function doMagicISBN( &$tokenizer )
1689 # Check whether next token is a text token
1690 # If yes, fetch it and convert the text into a
1691 # Special::BookSources link
1692 $token = $tokenizer->previewToken();
1693 while ( $token["type"] == "" )
1695 $tokenizer->nextToken();
1696 $token = $tokenizer->previewToken();
1698 if ( $token["type"] == "text" )
1700 $token = $tokenizer->nextToken();
1701 $x = $token["text"];
1702 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1704 $isbn = $blank = "" ;
1705 while ( " " == $x{0} ) {
1707 $x = substr( $x, 1 );
1709 while ( strstr( $valid, $x{0} ) != false ) {
1711 $x = substr( $x, 1 );
1713 $num = str_replace( "-", "", $isbn );
1714 $num = str_replace( " ", "", $num );
1717 $text = "ISBN $blank$x";
1719 $titleObj = Title
::makeTitle( NS_SPECIAL
, "Booksources" );
1720 $text = "<a href=\"" .
1721 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1722 "\" class=\"internal\">ISBN $isbn</a>";
1730 /* private */ function doMagicRFC( &$tokenizer )
1734 # Check whether next token is a text token
1735 # If yes, fetch it and convert the text into a
1736 # link to an RFC source
1737 $token = $tokenizer->previewToken();
1738 while ( $token["type"] == "" )
1740 $tokenizer->nextToken();
1741 $token = $tokenizer->previewToken();
1743 if ( $token["type"] == "text" )
1745 $token = $tokenizer->nextToken();
1746 $x = $token["text"];
1747 $valid = "0123456789";
1749 $rfc = $blank = "" ;
1750 while ( " " == $x{0} ) {
1752 $x = substr( $x, 1 );
1754 while ( strstr( $valid, $x{0} ) != false ) {
1756 $x = substr( $x, 1 );
1760 $text .= "RFC $blank$x";
1762 $url = wfmsg( "rfcurl" );
1763 $url = str_replace( "$1", $rfc, $url);
1764 $sk =& $this->mOptions
->getSkin();
1765 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
1766 $text = "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
1774 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
1776 $this->mOptions
= $options;
1777 $this->mTitle
=& $title;
1778 $this->mOutputType
= OT_WIKI
;
1780 if ( $clearState ) {
1781 $this->clearState();
1784 $stripState = false;
1788 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
1791 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
1792 "/<br *?>/i" => "<br/>",
1794 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
1795 $text = $this->strip( $text, $stripState, false );
1796 $text = $this->pstPass2( $text, $user );
1797 $text = $this->unstrip( $text, $stripState );
1801 /* private */ function pstPass2( $text, &$user )
1803 global $wgLang, $wgLocaltimezone, $wgCurParser;
1805 # Variable replacement
1806 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
1807 $text = $this->replaceVariables( $text );
1811 $n = $user->getName();
1812 $k = $user->getOption( "nickname" );
1813 if ( "" == $k ) { $k = $n; }
1814 if(isset($wgLocaltimezone)) {
1815 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1817 /* Note: this is an ugly timezone hack for the European wikis */
1818 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1819 " (" . date( "T" ) . ")";
1820 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1822 $text = preg_replace( "/~~~~~/", $d, $text );
1823 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1824 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1825 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1826 Namespace::getUser() ) . ":$n|$k]]", $text );
1828 # Context links: [[|name]] and [[name (context)|]]
1830 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1831 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1832 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1833 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1835 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1836 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1837 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1838 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1839 # [[ns:page (cont)|]]
1841 $t = $this->mTitle
->getText();
1842 if ( preg_match( $conpat, $t, $m ) ) {
1845 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1846 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1847 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1849 if ( "" == $context ) {
1850 $text = preg_replace( $p2, "[[\\1]]", $text );
1852 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1856 $mw =& MagicWord::get( MAG_SUBST );
1857 $wgCurParser = $this->fork();
1858 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
1859 $this->merge( $wgCurParser );
1862 # Trim trailing whitespace
1863 # MAG_END (__END__) tag allows for trailing
1864 # whitespace to be deliberately included
1865 $text = rtrim( $text );
1866 $mw =& MagicWord
::get( MAG_END
);
1867 $mw->matchAndRemove( $text );
1872 # Set up some variables which are usually set up in parse()
1873 # so that an external function can call some class members with confidence
1874 function startExternalParse( &$title, $options, $outputType, $clearState = true )
1876 $this->mTitle
=& $title;
1877 $this->mOptions
= $options;
1878 $this->mOutputType
= $outputType;
1879 if ( $clearState ) {
1880 $this->clearState();
1884 function transformMsg( $text, $options ) {
1886 static $executing = false;
1888 # Guard against infinite recursion
1894 $this->mTitle
= $wgTitle;
1895 $this->mOptions
= $options;
1896 $this->mOutputType
= OT_MSG
;
1897 $this->clearState();
1898 $text = $this->replaceVariables( $text );
1907 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
1909 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
1910 $containsOldMagic = false )
1912 $this->mText
= $text;
1913 $this->mLanguageLinks
= $languageLinks;
1914 $this->mCategoryLinks
= $categoryLinks;
1915 $this->mContainsOldMagic
= $containsOldMagic;
1918 function getText() { return $this->mText
; }
1919 function getLanguageLinks() { return $this->mLanguageLinks
; }
1920 function getCategoryLinks() { return $this->mCategoryLinks
; }
1921 function containsOldMagic() { return $this->mContainsOldMagic
; }
1922 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
1923 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
1924 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
1925 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
1927 function merge( $other ) {
1928 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
1929 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
1930 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
1937 # All variables are private
1938 var $mUseTeX; # Use texvc to expand <math> tags
1939 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
1940 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
1941 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
1942 var $mAllowExternalImages; # Allow external images inline
1943 var $mSkin; # Reference to the preferred skin
1944 var $mDateFormat; # Date format index
1945 var $mEditSection; # Create "edit section" links
1946 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
1947 var $mNumberHeadings; # Automatically number headings
1948 var $mShowToc; # Show table of contents
1950 function getUseTeX() { return $this->mUseTeX
; }
1951 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
1952 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
1953 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
1954 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
1955 function getSkin() { return $this->mSkin
; }
1956 function getDateFormat() { return $this->mDateFormat
; }
1957 function getEditSection() { return $this->mEditSection
; }
1958 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
1959 function getNumberHeadings() { return $this->mNumberHeadings
; }
1960 function getShowToc() { return $this->mShowToc
; }
1962 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
1963 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
1964 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
1965 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
1966 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
1967 function setSkin( $x ) { return wfSetRef( $this->mSkin
, $x ); }
1968 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
1969 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
1970 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
1971 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
1972 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
1974 /* static */ function newFromUser( &$user )
1976 $popts = new ParserOptions
;
1977 $popts->initialiseFromUser( &$user );
1981 function initialiseFromUser( &$userInput )
1983 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
1985 if ( !$userInput ) {
1987 $user->setLoaded( true );
1989 $user =& $userInput;
1992 $this->mUseTeX
= $wgUseTeX;
1993 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
1994 $this->mUseDynamicDates
= $wgUseDynamicDates;
1995 $this->mInterwikiMagic
= $wgInterwikiMagic;
1996 $this->mAllowExternalImages
= $wgAllowExternalImages;
1997 $this->mSkin
=& $user->getSkin();
1998 $this->mDateFormat
= $user->getOption( "date" );
1999 $this->mEditSection
= $user->getOption( "editsection" );
2000 $this->mEditSectionOnRightClick
= $user->getOption( "editsectiononrightclick" );
2001 $this->mNumberHeadings
= $user->getOption( "numberheadings" );
2002 $this->mShowToc
= $user->getOption( "showtoc" );
2008 # Regex callbacks, used in Parser::replaceVariables
2009 function wfBraceSubstitution( $matches )
2011 global $wgCurParser;
2012 return $wgCurParser->braceSubstitution( $matches );