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"] = $token["pos"];
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"] = $token["pos"];
648 /* private */ function handle5Quotes( &$state, $token )
651 if ( $state["em"] !== false && $state["strong"] !== false ) {
652 if ( $state["em"] < $state["strong"] ) {
653 $s .= "</strong></em>";
655 $s .= "</em></strong>";
657 $state["strong"] = $state["em"] = FALSE;
658 } elseif ( $state["em"] !== false ) {
659 $s .= "</em><strong>";
660 $state["em"] = FALSE;
661 $state["strong"] = $token["pos"];
662 } elseif ( $state["strong"] !== false ) {
663 $s .= "</strong><em>";
664 $state["strong"] = FALSE;
665 $state["em"] = $token["pos"];
666 } else { # not $em and not $strong
667 $s .= "<strong><em>";
668 $state["strong"] = $state["em"] = $token["pos"];
673 /* private */ function doTokenizedParser( $str )
675 global $wgLang; # for language specific parser hook
677 $tokenizer=Tokenizer
::newFromString( $str );
678 $tokenStack = array();
681 $state["em"] = FALSE;
682 $state["strong"] = FALSE;
686 # The tokenizer splits the text into tokens and returns them one by one.
687 # Every call to the tokenizer returns a new token.
688 while ( $token = $tokenizer->nextToken() )
690 switch ( $token["type"] )
693 # simple text with no further markup
694 $txt = $token["text"];
697 # remember the tag opened with 3 [
701 # FIXME : Treat orphaned open tags (stack not empty when text is over)
703 array_push( $tokenStack, $token );
710 # get text from stack, glue it together, and call the code to handle a
713 if ( count( $tokenStack ) == 0 )
715 # stack empty. Found a ]] without an opening [[
719 $lastToken = array_pop( $tokenStack );
720 while ( !(($lastToken["type"] == "[[[") or ($lastToken["type"] == "[[")) )
722 if( !empty( $lastToken["text"] ) ) {
723 $linkText = $lastToken["text"] . $linkText;
725 $lastToken = array_pop( $tokenStack );
728 $txt = $linkText ."]]";
730 if( isset( $lastToken["text"] ) ) {
731 $prefix = $lastToken["text"];
735 $nextToken = $tokenizer->previewToken();
736 if ( $nextToken["type"] == "text" )
738 # Preview just looks at it. Now we have to fetch it.
739 $nextToken = $tokenizer->nextToken();
740 $txt .= $nextToken["text"];
742 $fakestate = $this->mStripState
;
743 $txt = $this->handleInternalLink( $this->unstrip($txt,$fakestate), $prefix );
745 # did the tag start with 3 [ ?
747 # show the first as text
753 $tagIsOpen = (count( $tokenStack ) != 0);
759 # This and the three next ones handle quotes
760 $txt = $this->handle3Quotes( $state, $token );
763 $txt = $this->handle2Quotes( $state, $token );
766 $txt = $this->handle5Quotes( $state, $token );
776 $txt = $this->doMagicRFC( $tokenizer );
783 $txt = $this->doMagicISBN( $tokenizer );
787 # Call language specific Hook.
788 $txt = $wgLang->processToken( $token, $tokenStack );
789 if ( NULL == $txt ) {
790 # An unkown token. Highlight.
791 $txt = "<font color=\"#FF0000\"><b>".$token["type"]."</b></font>";
792 $txt .= "<font color=\"#FFFF00\"><b>".$token["text"]."</b></font>";
796 # If we're parsing the interior of a link, don't append the interior to $s,
797 # but push it to the stack so it can be processed when a ]] token is found.
798 if ( $tagIsOpen && $txt != "" ) {
799 $token["type"] = "text";
800 $token["text"] = $txt;
801 array_push( $tokenStack, $token );
806 if ( count( $tokenStack ) != 0 )
808 # still objects on stack. opened [[ tag without closing ]] tag.
810 while ( $lastToken = array_pop( $tokenStack ) )
812 if ( $lastToken["type"] == "text" )
814 $txt = $lastToken["text"] . $txt;
816 $txt = $lastToken["type"] . $txt;
824 /* private */ function handleInternalLink( $line, $prefix )
826 global $wgLang, $wgLinkCache;
827 global $wgNamespacesWithSubpages, $wgLanguageCode;
828 static $fname = "Parser::handleInternalLink" ;
829 wfProfileIn( $fname );
831 wfProfileIn( "$fname-setup" );
833 if ( !$tc ) { $tc = Title
::legalChars() . "#"; }
834 $sk =& $this->mOptions
->getSkin();
836 # Match a link having the form [[namespace:link|alternate]]trail
838 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
839 # Match the end of a line for a word that's not followed by whitespace,
840 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
841 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
842 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
843 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
846 # Special and Media are pseudo-namespaces; no pages actually exist in them
847 static $image = FALSE;
848 static $special = FALSE;
849 static $media = FALSE;
850 static $category = FALSE;
851 if ( !$image ) { $image = Namespace::getImage(); }
852 if ( !$special ) { $special = Namespace::getSpecial(); }
853 if ( !$media ) { $media = Namespace::getMedia(); }
854 if ( !$category ) { $category = wfMsg ( "category" ) ; }
856 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
858 wfProfileOut( "$fname-setup" );
861 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
864 } else { # Invalid form; output directly
865 $s .= $prefix . "[[" . $line ;
871 :Foobar -- override special treatment of prefix (images, language links)
872 /Foobar -- convert to CurrentPage/Foobar
873 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
875 $c = substr($m[1],0,1);
876 $noforce = ($c != ":");
877 if( $c == "/" ) { # subpage
878 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
879 $m[1]=substr($m[1],1,strlen($m[1])-2);
882 $noslash=substr($m[1],1);
884 if($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]) { # subpages allowed here
885 $link = $this->mTitle
->getPrefixedText(). "/" . trim($noslash);
888 } # this might be changed for ugliness reasons
890 $link = $noslash; # no subpage allowed, use standard link
892 } elseif( $noforce ) { # no subpage
895 $link = substr( $m[1], 1 );
900 $nt = Title
::newFromText( $link );
902 $s .= $prefix . "[[" . $line;
905 $ns = $nt->getNamespace();
906 $iw = $nt->getInterWiki();
908 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
909 array_push( $this->mOutput
->mLanguageLinks
, $nt->getPrefixedText() );
910 return (trim($s) == '')?
'': $s;
912 if( $ns == $image ) {
913 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
914 $wgLinkCache->addImageLinkObj( $nt );
918 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
919 ( strpos( $link, "#" ) == FALSE ) ) {
920 $s .= $prefix . "<strong>" . $text . "</strong>" . $trail;
925 $catns = strtoupper ( $nt->getDBkey () ) ;
926 $catns = explode ( ":" , $catns ) ;
927 if ( count ( $catns ) > 1 ) $catns = array_shift ( $catns ) ;
929 if ( $catns == strtoupper($category) && $this->mOptions
->getUseCategoryMagic() ) {
930 $t = explode ( ":" , $nt->getText() ) ;
932 $t = implode ( ":" , $t ) ;
933 $t = $wgLang->ucFirst ( $t ) ;
934 $nnt = Title
::newFromText ( $category.":".$t ) ;
935 $t = $sk->makeLinkObj( $nnt, $t, "", $trail , $prefix );
936 $this->mOutput
->mCategoryLinks
[] = $t ;
937 $s .= $prefix . $trail ;
941 if( $ns == $media ) {
942 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
943 $wgLinkCache->addImageLinkObj( $nt );
945 } elseif( $ns == $special ) {
946 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
949 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
951 wfProfileOut( $fname );
955 # Some functions here used by doBlockLevels()
957 /* private */ function closeParagraph()
960 if ( '' != $this->mLastSection
) {
961 $result = "</" . $this->mLastSection
. ">\n";
963 $this->mLastSection
= "";
966 # getCommon() returns the length of the longest common substring
967 # of both arguments, starting at the beginning of both.
969 /* private */ function getCommon( $st1, $st2 )
971 $fl = strlen( $st1 );
972 $shorter = strlen( $st2 );
973 if ( $fl < $shorter ) { $shorter = $fl; }
975 for ( $i = 0; $i < $shorter; ++
$i ) {
976 if ( $st1{$i} != $st2{$i} ) { break; }
980 # These next three functions open, continue, and close the list
981 # element appropriate to the prefix character passed into them.
983 /* private */ function openList( $char )
985 $result = $this->closeParagraph();
987 if ( "*" == $char ) { $result .= "<ul><li>"; }
988 else if ( "#" == $char ) { $result .= "<ol><li>"; }
989 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
990 else if ( ";" == $char ) {
991 $result .= "<dl><dt>";
992 $this->mDTopen
= true;
994 else { $result = "<!-- ERR 1 -->"; }
999 /* private */ function nextItem( $char )
1001 if ( "*" == $char ||
"#" == $char ) { return "</li><li>"; }
1002 else if ( ":" == $char ||
";" == $char ) {
1004 if ( $this->mDTopen
) { $close = "</dt>"; }
1005 if ( ";" == $char ) {
1006 $this->mDTopen
= true;
1007 return $close . "<dt>";
1009 $this->mDTopen
= false;
1010 return $close . "<dd>";
1013 return "<!-- ERR 2 -->";
1016 /* private */function closeList( $char )
1018 if ( "*" == $char ) { $text = "</li></ul>"; }
1019 else if ( "#" == $char ) { $text = "</li></ol>"; }
1020 else if ( ":" == $char ) {
1021 if ( $this->mDTopen
) {
1022 $this->mDTopen
= false;
1023 $text = "</dt></dl>";
1025 $text = "</dd></dl>";
1028 else { return "<!-- ERR 3 -->"; }
1032 /* private */ function doBlockLevels( $text, $linestart )
1034 $fname = "Parser::doBlockLevels";
1035 wfProfileIn( $fname );
1036 # Parsing through the text line by line. The main thing
1037 # happening here is handling of block-level elements p, pre,
1038 # and making lists from lines starting with * # : etc.
1040 $a = explode( "\n", $text );
1041 $lastPref = $text = $lastLine = '';
1042 $this->mDTopen
= $inBlockElem = false;
1044 if ( ! $linestart ) { $text .= array_shift( $a ); }
1045 foreach ( $a as $t ) {
1046 if ( "" != $text ) { $text .= "\n"; }
1049 $opl = strlen( $lastPref );
1050 $npl = strspn( $t, "*#:;" );
1051 $pref = substr( $t, 0, $npl );
1052 $pref2 = str_replace( ";", ":", $pref );
1053 $t = substr( $t, $npl );
1055 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1056 $text .= $this->nextItem( substr( $pref, -1 ) );
1058 if ( ";" == substr( $pref, -1 ) ) {
1059 $cpos = strpos( $t, ":" );
1060 if ( ! ( false === $cpos ) ) {
1061 $term = substr( $t, 0, $cpos );
1062 $text .= $term . $this->nextItem( ":" );
1063 $t = substr( $t, $cpos +
1 );
1066 } else if (0 != $npl ||
0 != $opl) {
1067 $cpl = $this->getCommon( $pref, $lastPref );
1069 while ( $cpl < $opl ) {
1070 $text .= $this->closeList( $lastPref{$opl-1} );
1073 if ( $npl <= $cpl && $cpl > 0 ) {
1074 $text .= $this->nextItem( $pref{$cpl-1} );
1076 while ( $npl > $cpl ) {
1077 $char = substr( $pref, $cpl, 1 );
1078 $text .= $this->openList( $char );
1080 if ( ";" == $char ) {
1081 $cpos = strpos( $t, ":" );
1082 if ( ! ( false === $cpos ) ) {
1083 $term = substr( $t, 0, $cpos );
1084 $text .= $term . $this->nextItem( ":" );
1085 $t = substr( $t, $cpos +
1 );
1092 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1093 $uniq_prefix = UNIQ_PREFIX
;
1094 // XXX: use a stack for nestable elements like span, table and div
1095 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<div|<pre|<tr|<td|<p)/i", $t );
1096 $closematch = preg_match(
1097 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1098 "<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre)/i", $t );
1099 if ( $openmatch or $closematch ) {
1100 $text .= $this->closeParagraph();
1101 if ( $closematch ) {
1102 $inBlockElem = false;
1104 $inBlockElem = true;
1106 } else if ( !$inBlockElem ) {
1107 if ( " " == $t{0} ) {
1108 $newSection = "pre";
1109 if ($this->mLastSection
!= 'pre') {
1110 $text .= $this->closeParagraph();
1111 $text .= "<" . $newSection . ">";
1112 $this->mLastSection
= $newSection;
1116 if ( '' == trim($t) ) {
1117 if ( '' == trim($lastLine) ) {
1118 $text .= $this->closeParagraph();
1119 $text .= "<" . $newSection . "><br/>";
1120 $this->mLastSection
= $newSection;
1124 } else if ($this->mLastSection
!= $newSection) {
1125 $text .= $this->closeParagraph();
1126 $text .= "<" . $newSection . ">";
1127 $this->mLastSection
= $newSection;
1137 $text .= $this->closeList( $pref2{$npl-1} );
1140 if ( "" != $this->mLastSection
) {
1141 $text .= "</" . $this->mLastSection
. ">";
1142 $this->mLastSection
= "";
1144 wfProfileOut( $fname );
1148 function getVariableValue( $index ) {
1149 global $wgLang, $wgSitename, $wgServer;
1152 case MAG_CURRENTMONTH
:
1154 case MAG_CURRENTMONTHNAME
:
1155 return $wgLang->getMonthName( date("n") );
1156 case MAG_CURRENTMONTHNAMEGEN
:
1157 return $wgLang->getMonthNameGen( date("n") );
1158 case MAG_CURRENTDAY
:
1160 case MAG_CURRENTDAYNAME
:
1161 return $wgLang->getWeekdayName( date("w")+
1 );
1162 case MAG_CURRENTYEAR
:
1164 case MAG_CURRENTTIME
:
1165 return $wgLang->time( wfTimestampNow(), false );
1166 case MAG_NUMBEROFARTICLES
:
1167 return wfNumberOfArticles();
1177 function initialiseVariables()
1179 global $wgVariableIDs;
1180 $this->mVariables
= array();
1181 foreach ( $wgVariableIDs as $id ) {
1182 $mw =& MagicWord
::get( $id );
1183 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1187 /* private */ function replaceVariables( $text )
1189 global $wgLang, $wgCurParser;
1190 global $wgScript, $wgArticlePath;
1192 $fname = "Parser::replaceVariables";
1193 wfProfileIn( $fname );
1196 if ( !$this->mVariables
) {
1197 $this->initialiseVariables();
1199 $titleChars = Title
::legalChars();
1200 $regex = "/{{([$titleChars\\|]*?)}}/s";
1202 # "Recursive" variable expansion: run it through a couple of passes
1203 for ( $i=0; $i<MAX_INCLUDE_REPEAT
&& !$bail; $i++
) {
1206 # It's impossible to rebind a global in PHP
1207 # Instead, we run the substitution on a copy, then merge the changed fields back in
1208 $wgCurParser = $this->fork();
1210 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1211 if ( $oldText == $text ) {
1214 $this->merge( $wgCurParser );
1220 # Returns a copy of this object except with various variables cleared
1221 # This copy can be re-merged with the parent after operations on the copy
1225 $copy->mOutput
= new ParserOutput
;
1229 # Merges a copy split off with fork()
1230 function merge( &$copy )
1233 $this->mOutput
->merge( $copy->mOutput
);
1235 # Include throttling arrays
1236 foreach( $copy->mIncludeCount
as $dbk => $count ) {
1237 if ( array_key_exists( $dbk, $this->mIncludeCount
) ) {
1238 $this->mIncludeCount
[$dbk] +
= $count;
1240 $this->mIncludeCount
[$dbk] = $count;
1245 foreach( $copy->mStripState
as $dictName => $contentDict ) {
1246 $this->mStripState
[$dictName] +
= $contentDict;
1250 function braceSubstitution( $matches )
1252 global $wgLinkCache, $wgLang;
1253 $fname = "Parser::braceSubstitution";
1257 $text = $matches[1];
1260 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1261 if ( $mwSubst->matchStartAndRemove( $text ) ) {
1262 if ( $this->mOutputType
!= OT_WIKI
) {
1263 # Invalid SUBST not replaced at PST time
1264 # Return without further processing
1265 $text = $matches[0];
1268 } elseif ( $this->mOutputType
== OT_WIKI
) {
1269 # SUBST not found in PST pass, do nothing
1270 $text = $matches[0];
1274 # MSG, MSGNW and INT
1277 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1278 if ( $mwMsgnw->matchStartAndRemove( $text ) ) {
1281 # Remove obsolete MSG:
1282 $mwMsg =& MagicWord
::get( MAG_MSG
);
1283 $mwMsg->matchStartAndRemove( $text );
1286 # Check if it is an internal message
1287 $mwInt =& MagicWord
::get( MAG_INT
);
1288 if ( $mwInt->matchStartAndRemove( $text ) ) {
1289 $text = wfMsg( $text );
1296 # Check for NS: (namespace expansion)
1297 $mwNs = MagicWord
::get( MAG_NS
);
1298 if ( $mwNs->matchStartAndRemove( $text ) ) {
1299 if ( intval( $text ) ) {
1300 $text = $wgLang->getNsText( intval( $text ) );
1303 $index = Namespace::getCanonicalIndex( strtolower( $text ) );
1304 if ( !is_null( $index ) ) {
1305 $text = $wgLang->getNsText( $index );
1312 # LOCALURL and LOCALURLE
1314 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1315 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1317 if ( $mwLocal->matchStartAndRemove( $text ) ) {
1318 $func = 'getLocalURL';
1319 } elseif ( $mwLocalE->matchStartAndRemove( $text ) ) {
1320 $func = 'escapeLocalURL';
1325 if ( $func !== '' ) {
1326 $args = explode( "|", $text );
1327 $n = count( $args );
1329 $title = Title
::newFromText( $args[0] );
1330 if ( !is_null( $title ) ) {
1332 $text = $title->$func( $args[1] );
1334 $text = $title->$func();
1342 # Check for a match against internal variables
1343 if ( !$found && array_key_exists( $text, $this->mVariables
) ) {
1344 $text = $this->mVariables
[$text];
1346 $this->mOutput
->mContainsOldMagic
= true;
1349 # Load from database
1351 $title = Title
::newFromText( $text, NS_TEMPLATE
);
1352 if ( is_object( $title ) && !$title->isExternal() ) {
1353 # Check for excessive inclusion
1354 $dbk = $title->getPrefixedDBkey();
1355 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1356 $this->mIncludeCount
[$dbk] = 0;
1358 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1359 $article = new Article( $title );
1360 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1361 if ( $articleContent !== false ) {
1363 $text = $articleContent;
1365 # Escaping and link table handling
1366 # Not required for preSaveTransform()
1367 if ( $this->mOutputType
== OT_HTML
) {
1369 $text = wfEscapeWikiText( $text );
1371 $text = $this->removeHTMLtags( $text );
1373 # Do not enter included links in link table
1374 $wgLinkCache->suspend();
1376 # Run full parser on the included text
1377 $text = $this->strip( $text, $this->mStripState
);
1378 $text = $this->doWikiPass2( $text, true );
1380 # Add the result to the strip state for re-inclusion after
1381 # the rest of the processing
1382 $text = $this->insertStripItem( $text, $this->mStripState
);
1384 # Resume the link cache and register the inclusion as a link
1385 $wgLinkCache->resume();
1386 $wgLinkCache->addLinkObj( $title );
1392 # If the title is valid but undisplayable, make a link to it
1393 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1394 $text = "[[" . $title->getPrefixedText() . "]]";
1407 # Cleans up HTML, removes dangerous tags and attributes
1408 /* private */ function removeHTMLtags( $text )
1410 $fname = "Parser::removeHTMLtags";
1411 wfProfileIn( $fname );
1412 $htmlpairs = array( # Tags that must be closed
1413 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1414 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1415 "strike", "strong", "tt", "var", "div", "center",
1416 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1417 "ruby", "rt" , "rb" , "rp", "p"
1419 $htmlsingle = array(
1420 "br", "hr", "li", "dt", "dd"
1422 $htmlnest = array( # Tags that can be nested--??
1423 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1424 "dl", "font", "big", "small", "sub", "sup"
1426 $tabletags = array( # Can only appear inside table
1430 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1431 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1433 $htmlattrs = $this->getHTMLattrs () ;
1435 # Remove HTML comments
1436 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1438 $bits = explode( "<", $text );
1439 $text = array_shift( $bits );
1440 $tagstack = array(); $tablestack = array();
1442 foreach ( $bits as $x ) {
1443 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1444 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1446 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1447 error_reporting( $prev );
1450 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1454 if ( ! in_array( $t, $htmlsingle ) &&
1455 ( $ot = array_pop( $tagstack ) ) != $t ) {
1456 array_push( $tagstack, $ot );
1459 if ( $t == "table" ) {
1460 $tagstack = array_pop( $tablestack );
1465 # Keep track for later
1466 if ( in_array( $t, $tabletags ) &&
1467 ! in_array( "table", $tagstack ) ) {
1469 } else if ( in_array( $t, $tagstack ) &&
1470 ! in_array ( $t , $htmlnest ) ) {
1472 } else if ( ! in_array( $t, $htmlsingle ) ) {
1473 if ( $t == "table" ) {
1474 array_push( $tablestack, $tagstack );
1475 $tagstack = array();
1477 array_push( $tagstack, $t );
1479 # Strip non-approved attributes from the tag
1480 $newparams = $this->fixTagAttributes($params);
1484 $rest = str_replace( ">", ">", $rest );
1485 $text .= "<$slash$t $newparams$brace$rest";
1489 $text .= "<" . str_replace( ">", ">", $x);
1491 # Close off any remaining tags
1492 while ( $t = array_pop( $tagstack ) ) {
1494 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1496 wfProfileOut( $fname );
1502 * This function accomplishes several tasks:
1503 * 1) Auto-number headings if that option is enabled
1504 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1505 * 3) Add a Table of contents on the top for users who have enabled the option
1506 * 4) Auto-anchor headings
1508 * It loops through all headlines, collects the necessary data, then splits up the
1509 * string and re-inserts the newly formatted headlines.
1513 /* private */ function formatHeadings( $text )
1515 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1516 $doShowToc = $this->mOptions
->getShowToc();
1517 if( !$this->mTitle
->userCanEdit() ) {
1519 $rightClickHack = 0;
1521 $showEditLink = $this->mOptions
->getEditSection();
1522 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1525 # Inhibit editsection links if requested in the page
1526 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1527 if( $esw->matchAndRemove( $text ) ) {
1530 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1532 $mw =& MagicWord
::get( MAG_NOTOC
);
1533 if( $mw->matchAndRemove( $text ) ) {
1537 # never add the TOC to the Main Page. This is an entry page that should not
1538 # be more than 1-2 screens large anyway
1539 if( $this->mTitle
->getPrefixedText() == wfMsg("mainpage") ) {
1543 # Get all headlines for numbering them and adding funky stuff like [edit]
1544 # links - this is for later, but we need the number of headlines right now
1545 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1547 # if there are fewer than 4 headlines in the article, do not show TOC
1548 if( $numMatches < 4 ) {
1552 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1553 # override above conditions and always show TOC
1554 $mw =& MagicWord
::get( MAG_FORCETOC
);
1555 if ($mw->matchAndRemove( $text ) ) {
1560 # We need this to perform operations on the HTML
1561 $sk =& $this->mOptions
->getSkin();
1566 # Ugh .. the TOC should have neat indentation levels which can be
1567 # passed to the skin functions. These are determined here
1572 $sublevelCount = array();
1575 foreach( $matches[3] as $headline ) {
1578 $prevlevel = $level;
1580 $level = $matches[1][$headlineCount];
1581 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1582 # reset when we enter a new level
1583 $sublevelCount[$level] = 0;
1584 $toc .= $sk->tocIndent( $level - $prevlevel );
1585 $toclevel +
= $level - $prevlevel;
1587 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1588 # reset when we step back a level
1589 $sublevelCount[$level+
1]=0;
1590 $toc .= $sk->tocUnindent( $prevlevel - $level );
1591 $toclevel -= $prevlevel - $level;
1593 # count number of headlines for each level
1594 @$sublevelCount[$level]++
;
1595 if( $doNumberHeadings ||
$doShowToc ) {
1597 for( $i = 1; $i <= $level; $i++
) {
1598 if( !empty( $sublevelCount[$i] ) ) {
1602 $numbering .= $sublevelCount[$i];
1608 # The canonized header is a version of the header text safe to use for links
1609 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1610 $canonized_headline = Parser
::unstrip( $headline, $this->mStripState
);
1613 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1614 $tocline = trim( $canonized_headline );
1615 $canonized_headline = preg_replace("/[ &\\/<>\\(\\)\\[\\]=,+']+/", '_', html_entity_decode( $tocline));
1616 $refer[$headlineCount] = $canonized_headline;
1618 # count how many in assoc. array so we can track dupes in anchors
1619 @$refers[$canonized_headline]++
;
1620 $refcount[$headlineCount]=$refers[$canonized_headline];
1622 # Prepend the number to the heading text
1624 if( $doNumberHeadings ||
$doShowToc ) {
1625 $tocline = $numbering . " " . $tocline;
1627 # Don't number the heading if it is the only one (looks silly)
1628 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1629 # the two are different if the line contains a link
1630 $headline=$numbering . " " . $headline;
1634 # Create the anchor for linking from the TOC to the section
1635 $anchor = $canonized_headline;
1636 if($refcount[$headlineCount] > 1 ) {
1637 $anchor .= "_" . $refcount[$headlineCount];
1640 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1642 if( $showEditLink ) {
1643 if ( empty( $head[$headlineCount] ) ) {
1644 $head[$headlineCount] = "";
1646 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
1649 # Add the edit section span
1650 if( $rightClickHack ) {
1651 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
1654 # give headline the correct <h#> tag
1655 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1661 $toclines = $headlineCount;
1662 $toc .= $sk->tocUnindent( $toclevel );
1663 $toc = $sk->tocTable( $toc );
1666 # split up and insert constructed headlines
1668 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1671 foreach( $blocks as $block ) {
1672 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1673 # This is the [edit] link that appears for the top block of text when
1674 # section editing is enabled
1675 $full .= $sk->editSectionLink(0);
1678 if( $doShowToc && !$i) {
1679 # Top anchor now in skin
1683 if( !empty( $head[$i] ) ) {
1692 /* private */ function doMagicISBN( &$tokenizer )
1696 # Check whether next token is a text token
1697 # If yes, fetch it and convert the text into a
1698 # Special::BookSources link
1699 $token = $tokenizer->previewToken();
1700 while ( $token["type"] == "" )
1702 $tokenizer->nextToken();
1703 $token = $tokenizer->previewToken();
1705 if ( $token["type"] == "text" )
1707 $token = $tokenizer->nextToken();
1708 $x = $token["text"];
1709 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1711 $isbn = $blank = "" ;
1712 while ( " " == $x{0} ) {
1714 $x = substr( $x, 1 );
1716 while ( strstr( $valid, $x{0} ) != false ) {
1718 $x = substr( $x, 1 );
1720 $num = str_replace( "-", "", $isbn );
1721 $num = str_replace( " ", "", $num );
1724 $text = "ISBN $blank$x";
1726 $titleObj = Title
::makeTitle( NS_SPECIAL
, "Booksources" );
1727 $text = "<a href=\"" .
1728 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1729 "\" class=\"internal\">ISBN $isbn</a>";
1737 /* private */ function doMagicRFC( &$tokenizer )
1741 # Check whether next token is a text token
1742 # If yes, fetch it and convert the text into a
1743 # link to an RFC source
1744 $token = $tokenizer->previewToken();
1745 while ( $token["type"] == "" )
1747 $tokenizer->nextToken();
1748 $token = $tokenizer->previewToken();
1750 if ( $token["type"] == "text" )
1752 $token = $tokenizer->nextToken();
1753 $x = $token["text"];
1754 $valid = "0123456789";
1756 $rfc = $blank = "" ;
1757 while ( " " == $x{0} ) {
1759 $x = substr( $x, 1 );
1761 while ( strstr( $valid, $x{0} ) != false ) {
1763 $x = substr( $x, 1 );
1767 $text .= "RFC $blank$x";
1769 $url = wfmsg( "rfcurl" );
1770 $url = str_replace( "$1", $rfc, $url);
1771 $sk =& $this->mOptions
->getSkin();
1772 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
1773 $text = "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
1781 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
1783 $this->mOptions
= $options;
1784 $this->mTitle
=& $title;
1785 $this->mOutputType
= OT_WIKI
;
1787 if ( $clearState ) {
1788 $this->clearState();
1791 $stripState = false;
1795 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
1798 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
1799 "/<br *?>/i" => "<br/>",
1801 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
1802 $text = $this->strip( $text, $stripState, false );
1803 $text = $this->pstPass2( $text, $user );
1804 $text = $this->unstrip( $text, $stripState );
1808 /* private */ function pstPass2( $text, &$user )
1810 global $wgLang, $wgLocaltimezone, $wgCurParser;
1812 # Variable replacement
1813 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
1814 $text = $this->replaceVariables( $text );
1818 $n = $user->getName();
1819 $k = $user->getOption( "nickname" );
1820 if ( "" == $k ) { $k = $n; }
1821 if(isset($wgLocaltimezone)) {
1822 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1824 /* Note: this is an ugly timezone hack for the European wikis */
1825 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1826 " (" . date( "T" ) . ")";
1827 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1829 $text = preg_replace( "/~~~~~/", $d, $text );
1830 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1831 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1832 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1833 Namespace::getUser() ) . ":$n|$k]]", $text );
1835 # Context links: [[|name]] and [[name (context)|]]
1837 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1838 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1839 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1840 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1842 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1843 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1844 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1845 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1846 # [[ns:page (cont)|]]
1848 $t = $this->mTitle
->getText();
1849 if ( preg_match( $conpat, $t, $m ) ) {
1852 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1853 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1854 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1856 if ( "" == $context ) {
1857 $text = preg_replace( $p2, "[[\\1]]", $text );
1859 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1863 $mw =& MagicWord::get( MAG_SUBST );
1864 $wgCurParser = $this->fork();
1865 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
1866 $this->merge( $wgCurParser );
1869 # Trim trailing whitespace
1870 # MAG_END (__END__) tag allows for trailing
1871 # whitespace to be deliberately included
1872 $text = rtrim( $text );
1873 $mw =& MagicWord
::get( MAG_END
);
1874 $mw->matchAndRemove( $text );
1879 # Set up some variables which are usually set up in parse()
1880 # so that an external function can call some class members with confidence
1881 function startExternalParse( &$title, $options, $outputType, $clearState = true )
1883 $this->mTitle
=& $title;
1884 $this->mOptions
= $options;
1885 $this->mOutputType
= $outputType;
1886 if ( $clearState ) {
1887 $this->clearState();
1891 function transformMsg( $text, $options ) {
1893 static $executing = false;
1895 # Guard against infinite recursion
1901 $this->mTitle
= $wgTitle;
1902 $this->mOptions
= $options;
1903 $this->mOutputType
= OT_MSG
;
1904 $this->clearState();
1905 $text = $this->replaceVariables( $text );
1914 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
1916 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
1917 $containsOldMagic = false )
1919 $this->mText
= $text;
1920 $this->mLanguageLinks
= $languageLinks;
1921 $this->mCategoryLinks
= $categoryLinks;
1922 $this->mContainsOldMagic
= $containsOldMagic;
1925 function getText() { return $this->mText
; }
1926 function getLanguageLinks() { return $this->mLanguageLinks
; }
1927 function getCategoryLinks() { return $this->mCategoryLinks
; }
1928 function containsOldMagic() { return $this->mContainsOldMagic
; }
1929 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
1930 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
1931 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
1932 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
1934 function merge( $other ) {
1935 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
1936 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
1937 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
1944 # All variables are private
1945 var $mUseTeX; # Use texvc to expand <math> tags
1946 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
1947 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
1948 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
1949 var $mAllowExternalImages; # Allow external images inline
1950 var $mSkin; # Reference to the preferred skin
1951 var $mDateFormat; # Date format index
1952 var $mEditSection; # Create "edit section" links
1953 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
1954 var $mNumberHeadings; # Automatically number headings
1955 var $mShowToc; # Show table of contents
1957 function getUseTeX() { return $this->mUseTeX
; }
1958 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
1959 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
1960 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
1961 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
1962 function getSkin() { return $this->mSkin
; }
1963 function getDateFormat() { return $this->mDateFormat
; }
1964 function getEditSection() { return $this->mEditSection
; }
1965 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
1966 function getNumberHeadings() { return $this->mNumberHeadings
; }
1967 function getShowToc() { return $this->mShowToc
; }
1969 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
1970 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
1971 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
1972 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
1973 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
1974 function setSkin( $x ) { return wfSetRef( $this->mSkin
, $x ); }
1975 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
1976 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
1977 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
1978 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
1979 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
1981 /* static */ function newFromUser( &$user )
1983 $popts = new ParserOptions
;
1984 $popts->initialiseFromUser( &$user );
1988 function initialiseFromUser( &$userInput )
1990 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
1992 if ( !$userInput ) {
1994 $user->setLoaded( true );
1996 $user =& $userInput;
1999 $this->mUseTeX
= $wgUseTeX;
2000 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2001 $this->mUseDynamicDates
= $wgUseDynamicDates;
2002 $this->mInterwikiMagic
= $wgInterwikiMagic;
2003 $this->mAllowExternalImages
= $wgAllowExternalImages;
2004 $this->mSkin
=& $user->getSkin();
2005 $this->mDateFormat
= $user->getOption( "date" );
2006 $this->mEditSection
= $user->getOption( "editsection" );
2007 $this->mEditSectionOnRightClick
= $user->getOption( "editsectiononrightclick" );
2008 $this->mNumberHeadings
= $user->getOption( "numberheadings" );
2009 $this->mShowToc
= $user->getOption( "showtoc" );
2015 # Regex callbacks, used in Parser::replaceVariables
2016 function wfBraceSubstitution( $matches )
2018 global $wgCurParser;
2019 return $wgCurParser->braceSubstitution( $matches );