3 require_once('Tokenizer.php');
5 if( $GLOBALS['wgUseWikiHiero'] ){
6 require_once('wikihiero.php');
8 if( $GLOBALS['wgUseTimeline'] ){
9 require_once('extensions/timeline/Timeline.php');
14 # Processes wiki markup
16 # There are two main entry points into the Parser class: parse() and preSaveTransform().
17 # The parse() function produces HTML output, preSaveTransform() produces altered wiki markup.
20 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
22 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
24 # settings: $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
25 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
28 # * only within ParserOptions
31 #----------------------------------------
32 # Variable substitution O(N^2) attack
33 #-----------------------------------------
34 # Without countermeasures, it would be possible to attack the parser by saving a page
35 # filled with a large number of inclusions of large pages. The size of the generated
36 # page would be proportional to the square of the input size. Hence, we limit the number
37 # of inclusions of any given page, thus bringing any attack back to O(N).
40 define( "MAX_INCLUDE_REPEAT", 5 );
42 # Allowed values for $mOutputType
43 define( "OT_HTML", 1 );
44 define( "OT_WIKI", 2 );
45 define( "OT_MSG", 3 );
47 # string parameter for extractTags which will cause it
48 # to strip HTML comments in addition to regular
49 # <XML>-style tags. This should not be anything we
50 # may want to use in wikisyntax
51 define( "STRIP_COMMENTS", "HTMLCommentStrip" );
53 # prefix for escaping, used in two functions at least
54 define( "UNIQ_PREFIX", "NaodW29");
58 # Cleared with clearState():
59 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
60 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
63 var $mOptions, $mTitle, $mOutputType;
72 $this->mOutput
= new ParserOutput
;
73 $this->mAutonumber
= 0;
74 $this->mLastSection
= "";
75 $this->mDTopen
= false;
76 $this->mVariables
= false;
77 $this->mIncludeCount
= array();
78 $this->mStripState
= array();
79 $this->mArgStack
= array();
82 # First pass--just handle <nowiki> sections, pass the rest off
83 # to internalParse() which does all the real work.
85 # Returns a ParserOutput
87 function parse( $text, &$title, $options, $linestart = true, $clearState = true )
90 $fname = "Parser::parse";
91 wfProfileIn( $fname );
97 $this->mOptions
= $options;
98 $this->mTitle
=& $title;
99 $this->mOutputType
= OT_HTML
;
102 $text = $this->strip( $text, $this->mStripState
);
103 $text = $this->internalParse( $text, $linestart );
104 $text = $this->unstrip( $text, $this->mStripState
);
105 # Clean up special characters, only run once, next-to-last before doBlockLevels
108 "/<hr *>/i" => '<hr/>',
109 "/<br *>/i" => '<br/>',
110 "/<center *>/i"=>'<div class="center">',
111 "/<\\/center *>/i" => '</div>',
112 # Clean up spare ampersands; note that we probably ought to be
113 # more careful about named entities.
114 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
116 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
119 "/<center *>/i"=>'<div class="center">',
120 "/<\\/center *>/i" => '</div>'
122 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
125 $text = $this->doBlockLevels( $text, $linestart );
127 $text = $this->tidy($text);
129 $this->mOutput
->setText( $text );
130 wfProfileOut( $fname );
131 return $this->mOutput
;
134 /* static */ function getRandomString()
136 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
139 # Replaces all occurrences of <$tag>content</$tag> in the text
140 # with a random marker and returns the new text. the output parameter
141 # $content will be an associative array filled with data on the form
142 # $unique_marker => content.
144 # If $content is already set, the additional entries will be appended
146 # If $tag is set to STRIP_COMMENTS, the function will extract
147 # <!-- HTML comments -->
149 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
150 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
157 while ( "" != $text ) {
158 if($tag==STRIP_COMMENTS
) {
159 $p = preg_split( "/<!--/i", $text, 2 );
161 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
164 if ( ( count( $p ) < 2 ) ||
( "" == $p[1] ) ) {
167 if($tag==STRIP_COMMENTS
) {
168 $q = preg_split( "/-->/i", $p[1], 2 );
170 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
172 $marker = $rnd . sprintf("%08X", $n++
);
173 $content[$marker] = $q[0];
174 $stripped .= $marker;
181 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
182 # If $render is set, performs necessary rendering operations on plugins
183 # Returns the text, and fills an array with data needed in unstrip()
184 # If the $state is already a valid strip state, it adds to the state
186 # When $stripcomments is set, HTML comments <!-- like this -->
187 # will be stripped in addition to other tags. This is important
188 # for section editing, where these comments cause confusion when
189 # counting the sections in the wikisource
190 function strip( $text, &$state, $stripcomments = false )
192 $render = ($this->mOutputType
== OT_HTML
);
193 $nowiki_content = array();
194 $hiero_content = array();
195 $math_content = array();
196 $pre_content = array();
197 $comment_content = array();
199 # Replace any instances of the placeholders
200 $uniq_prefix = UNIQ_PREFIX
;
201 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
203 $text = Parser
::extractTags("nowiki", $text, $nowiki_content, $uniq_prefix);
204 foreach( $nowiki_content as $marker => $content ){
206 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
208 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
212 $text = Parser
::extractTags("hiero", $text, $hiero_content, $uniq_prefix);
213 foreach( $hiero_content as $marker => $content ){
214 if( $render && $GLOBALS['wgUseWikiHiero']){
215 $hiero_content[$marker] = WikiHiero( $content, WH_MODE_HTML
);
217 $hiero_content[$marker] = "<hiero>$content</hiero>";
221 $text = Parser
::extractTags("math", $text, $math_content, $uniq_prefix);
222 foreach( $math_content as $marker => $content ){
223 if( $render && $this->mOptions
->getUseTeX() ){
224 $math_content[$marker] = renderMath( $content );
226 $math_content[$marker] = "<math>$content</math>";
230 $text = Parser
::extractTags("pre", $text, $pre_content, $uniq_prefix);
231 foreach( $pre_content as $marker => $content ){
233 $pre_content[$marker] = "<pre>" . wfEscapeHTMLTagsOnly( $content ) . "</pre>";
235 $pre_content[$marker] = "<pre>$content</pre>";
239 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
240 foreach( $comment_content as $marker => $content ){
241 $comment_content[$marker] = "<!--$content-->";
245 # Merge state with the pre-existing state, if there is one
247 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
248 $state['hiero'] = $state['hiero'] +
$hiero_content;
249 $state['math'] = $state['math'] +
$math_content;
250 $state['pre'] = $state['pre'] +
$pre_content;
251 $state['comment'] = $state['comment'] +
$comment_content;
254 'nowiki' => $nowiki_content,
255 'hiero' => $hiero_content,
256 'math' => $math_content,
257 'pre' => $pre_content,
258 'comment' => $comment_content
264 function unstrip( $text, &$state )
266 # Must expand in reverse order, otherwise nested tags will be corrupted
267 $contentDict = end( $state );
268 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
269 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
270 $text = str_replace( key( $contentDict ), $content, $text );
277 # Add an item to the strip state
278 # Returns the unique tag which must be inserted into the stripped text
279 # The tag will be replaced with the original text in unstrip()
281 function insertStripItem( $text, &$state )
283 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
292 $state['item'][$rnd] = $text;
296 # This method generates the list of subcategories and pages for a category
297 function categoryMagic ()
299 global $wgLang , $wgUser ;
300 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
302 $cns = Namespace::getCategory() ;
303 if ( $this->mTitle
->getNamespace() != $cns ) return "" ; # This ain't a category page
305 $r = "<br style=\"clear:both;\"/>\n";
308 $sk =& $wgUser->getSkin() ;
310 $articles = array() ;
311 $children = array() ;
313 $id = $this->mTitle
->getArticleID() ;
315 # For existing categories
317 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM cur,links WHERE l_to={$id} AND l_from=cur_id";
318 $res = wfQuery ( $sql, DB_READ
) ;
319 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
321 # For non-existing categories
322 $t = wfStrencode( $this->mTitle
->getPrefixedDBKey() );
323 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM cur,brokenlinks WHERE bl_to='$t' AND bl_from=cur_id" ;
324 $res = wfQuery ( $sql, DB_READ
) ;
325 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
328 # For all pages that link to this category
329 foreach ( $data AS $x )
331 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
332 if ( $t != "" ) $t .= ":" ;
333 $t .= $x->cur_title
;
335 if ( $x->cur_namespace
== $cns ) {
336 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
338 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
341 wfFreeResult ( $res ) ;
343 # Showing subcategories
344 if ( count ( $children ) > 0 )
346 asort ( $children ) ;
347 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
348 $r .= implode ( ", " , $children ) ;
351 # Showing pages in this category
352 if ( count ( $articles ) > 0 )
354 $ti = $this->mTitle
->getText() ;
355 asort ( $articles ) ;
356 $h = wfMsg( "category_header", $ti );
357 $r .= "<h2>{$h}</h2>\n" ;
358 $r .= implode ( ", " , $articles ) ;
365 function getHTMLattrs ()
367 $htmlattrs = array( # Allowed attributes--no scripting, etc.
368 "title", "align", "lang", "dir", "width", "height",
369 "bgcolor", "clear", /* BR */ "noshade", /* HR */
370 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
371 /* FONT */ "type", "start", "value", "compact",
372 /* For various lists, mostly deprecated but safe */
373 "summary", "width", "border", "frame", "rules",
374 "cellspacing", "cellpadding", "valign", "char",
375 "charoff", "colgroup", "col", "span", "abbr", "axis",
376 "headers", "scope", "rowspan", "colspan", /* Tables */
377 "id", "class", "name", "style" /* For CSS */
382 function fixTagAttributes ( $t )
384 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
385 $htmlattrs = $this->getHTMLattrs() ;
387 # Strip non-approved attributes from the tag
389 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
390 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
392 # Strip javascript "expression" from stylesheets. Brute force approach:
393 # If anythin offensive is found, all attributes of the HTML tag are dropped
396 "/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is",
397 wfMungeToUtf8( $t ) ) )
405 /* interface with html tidy, used if $wgUseTidy = true */
406 function tidy ( $text ) {
407 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
408 global $wgInputEncoding, $wgOutputEncoding;
410 switch(strtoupper($wgOutputEncoding)) {
412 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
415 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
418 $wgTidyOpts .= ' -raw';
421 $text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
422 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
423 '<head><title>test</title></head><body>'.$text.'</body></html>';
424 $descriptorspec = array(
425 0 => array("pipe", "r"),
426 1 => array("pipe", "w"),
427 2 => array("file", "/dev/null", "a")
429 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
430 if (is_resource($process)) {
431 fwrite($pipes[0], $text);
433 while (!feof($pipes[1])) {
434 $cleansource .= fgets($pipes[1], 1024);
437 $return_value = proc_close($process);
439 if( $cleansource == '' && $text != '') {
440 return '<h2>'.wfMsg('seriousxhtmlerrors').'</h2><pre>'.htmlspecialchars($text).'</pre>';
446 function doTableStuff ( $t )
448 $t = explode ( "\n" , $t ) ;
449 $td = array () ; # Is currently a td tag open?
450 $ltd = array () ; # Was it TD or TH?
451 $tr = array () ; # Is currently a tr tag open?
452 $ltr = array () ; # tr attributes
453 foreach ( $t AS $k => $x )
456 $fc = substr ( $x , 0 , 1 ) ;
457 if ( "{|" == substr ( $x , 0 , 2 ) )
459 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
460 array_push ( $td , false ) ;
461 array_push ( $ltd , "" ) ;
462 array_push ( $tr , false ) ;
463 array_push ( $ltr , "" ) ;
465 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
466 else if ( "|}" == substr ( $x , 0 , 2 ) )
469 $l = array_pop ( $ltd ) ;
470 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
471 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
475 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
477 $z = trim ( substr ( $x , 2 ) ) ;
478 $t[$k] = "<caption>{$z}</caption>\n" ;
480 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
482 $x = substr ( $x , 1 ) ;
483 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
485 $l = array_pop ( $ltd ) ;
486 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
487 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
490 array_push ( $tr , false ) ;
491 array_push ( $td , false ) ;
492 array_push ( $ltd , "" ) ;
493 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
495 else if ( "|" == $fc ||
"!" == $fc ||
"|+" == substr ( $x , 0 , 2 ) ) # Caption
497 if ( "|+" == substr ( $x , 0 , 2 ) )
500 $x = substr ( $x , 1 ) ;
502 $after = substr ( $x , 1 ) ;
503 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
504 $after = explode ( "||" , $after ) ;
506 foreach ( $after AS $theline )
511 $tra = array_pop ( $ltr ) ;
512 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
513 array_push ( $tr , true ) ;
514 array_push ( $ltr , "" ) ;
517 $l = array_pop ( $ltd ) ;
518 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
519 if ( $fc == "|" ) $l = "td" ;
520 else if ( $fc == "!" ) $l = "th" ;
521 else if ( $fc == "+" ) $l = "caption" ;
523 array_push ( $ltd , $l ) ;
524 $y = explode ( "|" , $theline , 2 ) ;
525 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
526 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
528 array_push ( $td , true ) ;
533 # Closing open td, tr && table
534 while ( count ( $td ) > 0 )
536 if ( array_pop ( $td ) ) $t[] = "</td>" ;
537 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
541 $t = implode ( "\n" , $t ) ;
542 # $t = $this->removeHTMLtags( $t );
546 function internalParse( $text, $linestart, $args = array() )
548 $fname = "Parser::internalParse";
549 wfProfileIn( $fname );
551 $text = $this->removeHTMLtags( $text );
552 $text = $this->replaceVariables( $text, $args );
554 # $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
556 $text = $this->doHeadings( $text );
557 if($this->mOptions
->getUseDynamicDates()) {
558 global $wgDateFormatter;
559 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
561 $text = $this->replaceExternalLinks( $text );
562 $text = $this->doTokenizedParser ( $text );
563 $text = $this->doTableStuff ( $text ) ;
564 $text = $this->formatHeadings( $text );
565 $sk =& $this->mOptions
->getSkin();
566 $text = $sk->transformContent( $text );
568 if ( !isset ( $this->categoryMagicDone
) ) {
569 $text .= $this->categoryMagic () ;
570 $this->categoryMagicDone
= true ;
573 wfProfileOut( $fname );
578 /* private */ function doHeadings( $text )
580 for ( $i = 6; $i >= 1; --$i ) {
581 $h = substr( "======", 0, $i );
582 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
583 "<h{$i}>\\1</h{$i}>\\2", $text );
588 # Note: we have to do external links before the internal ones,
589 # and otherwise take great care in the order of things here, so
590 # that we don't end up interpreting some URLs twice.
592 /* private */ function replaceExternalLinks( $text )
594 $fname = "Parser::replaceExternalLinks";
595 wfProfileIn( $fname );
596 $text = $this->subReplaceExternalLinks( $text, "http", true );
597 $text = $this->subReplaceExternalLinks( $text, "https", true );
598 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
599 $text = $this->subReplaceExternalLinks( $text, "irc", false );
600 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
601 $text = $this->subReplaceExternalLinks( $text, "news", false );
602 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
603 wfProfileOut( $fname );
607 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
609 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
610 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
612 # this is the list of separators that should be ignored if they
613 # are the last character of an URL but that should be included
614 # if they occur within the URL, e.g. "go to www.foo.com, where .."
615 # in this case, the last comma should not become part of the URL,
616 # but in "www.foo.com/123,2342,32.htm" it should.
618 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
619 $images = "gif|png|jpg|jpeg";
621 # PLEASE NOTE: The curly braces { } are not part of the regex,
622 # they are interpreted as part of the string (used to tell PHP
623 # that the content of the string should be inserted there).
624 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
625 "((?i){$images})([^{$uc}]|$)/";
627 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
628 $sk =& $this->mOptions
->getSkin();
630 if ( $autonumber and $this->mOptions
->getAllowExternalImages() ) { # Use img tags only for HTTP urls
631 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
632 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
634 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
635 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
636 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
638 $s = str_replace( $unique, $protocol, $s );
640 $a = explode( "[{$protocol}:", " " . $s );
641 $s = array_shift( $a );
642 $s = substr( $s, 1 );
644 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
645 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
647 foreach ( $a as $line ) {
648 if ( preg_match( $e1, $line, $m ) ) {
649 $link = "{$protocol}:{$m[1]}";
651 if ( $autonumber ) { $text = "[" . ++
$this->mAutonumber
. "]"; }
652 else { $text = wfEscapeHTML( $link ); }
653 } else if ( preg_match( $e2, $line, $m ) ) {
654 $link = "{$protocol}:{$m[1]}";
658 $s .= "[{$protocol}:" . $line;
661 if( $link == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
664 # Expand the URL for printable version
665 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
667 $la = $sk->getExternalLinkAttributes( $link, $text );
668 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
674 /* private */ function handle3Quotes( &$state, $token )
676 if ( $state["strong"] !== false ) {
677 if ( $state["em"] !== false && $state["em"] > $state["strong"] )
679 # ''' lala ''lala '''
680 $s = "</em></strong><em>";
684 $state["strong"] = FALSE;
687 $state["strong"] = isset($token["pos"]) ?
$token["pos"] : true;
692 /* private */ function handle2Quotes( &$state, $token )
694 if ( $state["em"] !== false ) {
695 if ( $state["strong"] !== false && $state["strong"] > $state["em"] )
697 # ''lala'''lala'' ....'''
698 $s = "</strong></em><strong>";
702 $state["em"] = FALSE;
705 $state["em"] = isset($token["pos"]) ?
$token["pos"] : true;
711 /* private */ function handle5Quotes( &$state, $token )
714 if ( $state["em"] !== false && $state["strong"] !== false ) {
715 if ( $state["em"] < $state["strong"] ) {
716 $s .= "</strong></em>";
718 $s .= "</em></strong>";
720 $state["strong"] = $state["em"] = FALSE;
721 } elseif ( $state["em"] !== false ) {
722 $s .= "</em><strong>";
723 $state["em"] = FALSE;
724 $state["strong"] = $token["pos"];
725 } elseif ( $state["strong"] !== false ) {
726 $s .= "</strong><em>";
727 $state["strong"] = FALSE;
728 $state["em"] = $token["pos"];
729 } else { # not $em and not $strong
730 $s .= "<strong><em>";
731 $state["strong"] = $state["em"] = isset($token["pos"]) ?
$token["pos"] : true;
736 /* private */ function doTokenizedParser( $str )
738 global $wgLang; # for language specific parser hook
739 global $wgUploadDirectory, $wgUseTimeline;
741 $tokenizer=Tokenizer
::newFromString( $str );
742 $tokenStack = array();
745 $state["em"] = FALSE;
746 $state["strong"] = FALSE;
750 # The tokenizer splits the text into tokens and returns them one by one.
751 # Every call to the tokenizer returns a new token.
752 while ( $token = $tokenizer->nextToken() )
754 switch ( $token["type"] )
757 # simple text with no further markup
758 $txt = $token["text"];
761 # Text that contains blanks that have to be converted to
762 # non-breakable spaces for French.
763 # U+202F NARROW NO-BREAK SPACE might be a better choice, but
764 # browser support for Unicode spacing is poor.
765 $txt = str_replace( " ", " ", $token["text"] );
768 # remember the tag opened with 3 [
772 # FIXME : Treat orphaned open tags (stack not empty when text is over)
774 array_push( $tokenStack, $token );
781 # get text from stack, glue it together, and call the code to handle a
784 if ( count( $tokenStack ) == 0 )
786 # stack empty. Found a ]] without an opening [[
790 $lastToken = array_pop( $tokenStack );
791 while ( !(($lastToken["type"] == "[[[") or ($lastToken["type"] == "[[")) )
793 if( !empty( $lastToken["text"] ) ) {
794 $linkText = $lastToken["text"] . $linkText;
796 $lastToken = array_pop( $tokenStack );
799 $txt = $linkText ."]]";
801 if( isset( $lastToken["text"] ) ) {
802 $prefix = $lastToken["text"];
806 $nextToken = $tokenizer->previewToken();
807 if ( $nextToken["type"] == "text" )
809 # Preview just looks at it. Now we have to fetch it.
810 $nextToken = $tokenizer->nextToken();
811 $txt .= $nextToken["text"];
813 $txt = $this->handleInternalLink( $this->unstrip($txt,$this->mStripState
), $prefix );
815 # did the tag start with 3 [ ?
817 # show the first as text
823 $tagIsOpen = (count( $tokenStack ) != 0);
829 # This and the three next ones handle quotes
830 $txt = $this->handle3Quotes( $state, $token );
833 $txt = $this->handle2Quotes( $state, $token );
836 $txt = $this->handle5Quotes( $state, $token );
846 $txt = $this->doMagicRFC( $tokenizer );
853 $txt = $this->doMagicISBN( $tokenizer );
857 if ( $wgUseTimeline &&
858 "" != ( $timelinesrc = $tokenizer->readAllUntil("</timeline>") ) )
860 $txt = renderTimeline( $timelinesrc );
866 # Call language specific Hook.
867 $txt = $wgLang->processToken( $token, $tokenStack );
868 if ( NULL == $txt ) {
869 # An unkown token. Highlight.
870 $txt = "<font color=\"#FF0000\"><b>".$token["type"]."</b></font>";
871 $txt .= "<font color=\"#FFFF00\"><b>".$token["text"]."</b></font>";
875 # If we're parsing the interior of a link, don't append the interior to $s,
876 # but push it to the stack so it can be processed when a ]] token is found.
877 if ( $tagIsOpen && $txt != "" ) {
878 $token["type"] = "text";
879 $token["text"] = $txt;
880 array_push( $tokenStack, $token );
885 if ( count( $tokenStack ) != 0 )
887 # still objects on stack. opened [[ tag without closing ]] tag.
889 while ( $lastToken = array_pop( $tokenStack ) )
891 if ( $lastToken["type"] == "text" )
893 $txt = $lastToken["text"] . $txt;
895 $txt = $lastToken["type"] . $txt;
903 /* private */ function handleInternalLink( $line, $prefix )
905 global $wgLang, $wgLinkCache;
906 global $wgNamespacesWithSubpages, $wgLanguageCode;
907 static $fname = "Parser::handleInternalLink" ;
908 wfProfileIn( $fname );
910 wfProfileIn( "$fname-setup" );
912 if ( !$tc ) { $tc = Title
::legalChars() . "#"; }
913 $sk =& $this->mOptions
->getSkin();
915 # Match a link having the form [[namespace:link|alternate]]trail
917 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
918 # Match the end of a line for a word that's not followed by whitespace,
919 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
920 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
921 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
922 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
925 # Special and Media are pseudo-namespaces; no pages actually exist in them
926 static $image = FALSE;
927 static $special = FALSE;
928 static $media = FALSE;
929 static $category = FALSE;
930 if ( !$image ) { $image = Namespace::getImage(); }
931 if ( !$special ) { $special = Namespace::getSpecial(); }
932 if ( !$media ) { $media = Namespace::getMedia(); }
933 if ( !$category ) { $category = Namespace::getCategory(); }
935 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
937 wfProfileOut( "$fname-setup" );
940 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
943 } else { # Invalid form; output directly
944 $s .= $prefix . "[[" . $line ;
950 :Foobar -- override special treatment of prefix (images, language links)
951 /Foobar -- convert to CurrentPage/Foobar
952 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
954 $c = substr($m[1],0,1);
955 $noforce = ($c != ":");
956 if( $c == "/" ) { # subpage
957 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
958 $m[1]=substr($m[1],1,strlen($m[1])-2);
961 $noslash=substr($m[1],1);
963 if($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]) { # subpages allowed here
964 $link = $this->mTitle
->getPrefixedText(). "/" . trim($noslash);
967 } # this might be changed for ugliness reasons
969 $link = $noslash; # no subpage allowed, use standard link
971 } elseif( $noforce ) { # no subpage
974 $link = substr( $m[1], 1 );
979 $nt = Title
::newFromText( $link );
981 $s .= $prefix . "[[" . $line;
984 $ns = $nt->getNamespace();
985 $iw = $nt->getInterWiki();
987 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
988 array_push( $this->mOutput
->mLanguageLinks
, $nt->getPrefixedText() );
989 $s .= $prefix . $trail ;
990 return (trim($s) == '')?
'': $s;
992 if( $ns == $image ) {
993 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
994 $wgLinkCache->addImageLinkObj( $nt );
997 if ( $ns == $category ) {
998 $t = $nt->getText() ;
999 $nnt = Title
::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1000 $t = $sk->makeLinkObj( $nnt, $t, "", "" , $prefix );
1001 $this->mOutput
->mCategoryLinks
[] = $t ;
1002 $s .= $prefix . $trail ;
1006 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
1007 ( strpos( $link, "#" ) == FALSE ) ) {
1008 # Self-links are handled specially; generally de-link and change to bold.
1009 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, "", $trail );
1013 if( $ns == $media ) {
1014 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1015 $wgLinkCache->addImageLinkObj( $nt );
1017 } elseif( $ns == $special ) {
1018 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1021 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
1023 wfProfileOut( $fname );
1027 # Some functions here used by doBlockLevels()
1029 /* private */ function closeParagraph()
1032 if ( '' != $this->mLastSection
) {
1033 $result = "</" . $this->mLastSection
. ">\n";
1035 $this->mInPre
= false;
1036 $this->mLastSection
= "";
1039 # getCommon() returns the length of the longest common substring
1040 # of both arguments, starting at the beginning of both.
1042 /* private */ function getCommon( $st1, $st2 )
1044 $fl = strlen( $st1 );
1045 $shorter = strlen( $st2 );
1046 if ( $fl < $shorter ) { $shorter = $fl; }
1048 for ( $i = 0; $i < $shorter; ++
$i ) {
1049 if ( $st1{$i} != $st2{$i} ) { break; }
1053 # These next three functions open, continue, and close the list
1054 # element appropriate to the prefix character passed into them.
1056 /* private */ function openList( $char )
1058 $result = $this->closeParagraph();
1060 if ( "*" == $char ) { $result .= "<ul><li>"; }
1061 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1062 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1063 else if ( ";" == $char ) {
1064 $result .= "<dl><dt>";
1065 $this->mDTopen
= true;
1067 else { $result = "<!-- ERR 1 -->"; }
1072 /* private */ function nextItem( $char )
1074 if ( "*" == $char ||
"#" == $char ) { return "</li><li>"; }
1075 else if ( ":" == $char ||
";" == $char ) {
1077 if ( $this->mDTopen
) { $close = "</dt>"; }
1078 if ( ";" == $char ) {
1079 $this->mDTopen
= true;
1080 return $close . "<dt>";
1082 $this->mDTopen
= false;
1083 return $close . "<dd>";
1086 return "<!-- ERR 2 -->";
1089 /* private */function closeList( $char )
1091 if ( "*" == $char ) { $text = "</li></ul>"; }
1092 else if ( "#" == $char ) { $text = "</li></ol>"; }
1093 else if ( ":" == $char ) {
1094 if ( $this->mDTopen
) {
1095 $this->mDTopen
= false;
1096 $text = "</dt></dl>";
1098 $text = "</dd></dl>";
1101 else { return "<!-- ERR 3 -->"; }
1105 /* private */ function doBlockLevels( $text, $linestart ) {
1106 $fname = "Parser::doBlockLevels";
1107 wfProfileIn( $fname );
1109 # Parsing through the text line by line. The main thing
1110 # happening here is handling of block-level elements p, pre,
1111 # and making lists from lines starting with * # : etc.
1113 $textLines = explode( "\n", $text );
1115 $lastPrefix = $output = $lastLine = '';
1116 $this->mDTopen
= $inBlockElem = false;
1118 $paragraphStack = false;
1120 if ( !$linestart ) {
1121 $output .= array_shift( $textLines );
1123 foreach ( $textLines as $oLine ) {
1124 $lastPrefixLength = strlen( $lastPrefix );
1125 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1126 $preOpenMatch = preg_match("/<pre/i", $oLine );
1127 if (!$this->mInPre
) {
1128 $this->mInPre
= !empty($preOpenMatch);
1130 if ( !$this->mInPre
) {
1131 # Multiple prefixes may abut each other for nested lists.
1132 $prefixLength = strspn( $oLine, "*#:;" );
1133 $pref = substr( $oLine, 0, $prefixLength );
1136 $pref2 = str_replace( ";", ":", $pref );
1137 $t = substr( $oLine, $prefixLength );
1139 # Don't interpret any other prefixes in preformatted text
1141 $pref = $pref2 = '';
1146 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1147 # Same as the last item, so no need to deal with nesting or opening stuff
1148 $output .= $this->nextItem( substr( $pref, -1 ) );
1149 $paragraphStack = false;
1151 if ( ";" == substr( $pref, -1 ) ) {
1152 # The one nasty exception: definition lists work like this:
1153 # ; title : definition text
1154 # So we check for : in the remainder text to split up the
1155 # title and definition, without b0rking links.
1156 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1157 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1159 $output .= $term . $this->nextItem( ":" );
1163 } elseif( $prefixLength ||
$lastPrefixLength ) {
1164 # Either open or close a level...
1165 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1166 $paragraphStack = false;
1168 while( $commonPrefixLength < $lastPrefixLength ) {
1169 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1170 --$lastPrefixLength;
1172 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1173 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1175 while ( $prefixLength > $commonPrefixLength ) {
1176 $char = substr( $pref, $commonPrefixLength, 1 );
1177 $output .= $this->openList( $char );
1179 if ( ";" == $char ) {
1180 # FIXME: This is dupe of code above
1181 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1183 $output .= $term . $this->nextItem( ":" );
1187 ++
$commonPrefixLength;
1189 $lastPrefix = $pref2;
1191 if( 0 == $prefixLength ) {
1192 # No prefix (not in list)--go to paragraph mode
1193 $uniq_prefix = UNIQ_PREFIX
;
1194 // XXX: use a stack for nestable elements like span, table and div
1195 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<div|<pre|<tr|<td|<p|<ul|<li)/i", $t );
1196 $closematch = preg_match(
1197 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1198 "<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre|<\\/li|<\\/ul)/i", $t );
1199 if ( $openmatch or $closematch ) {
1200 $paragraphStack = false;
1201 $output .= $this->closeParagraph();
1202 if($preOpenMatch and !$preCloseMatch) {
1203 $this->mInPre
= true;
1205 if ( $closematch ) {
1206 $inBlockElem = false;
1208 $inBlockElem = true;
1210 } else if ( !$inBlockElem ) {
1211 if ( " " == $t{0} ) {
1213 if ($this->mLastSection
!= 'pre') {
1214 $paragraphStack = false;
1215 $output .= $this->closeParagraph().'<pre>';
1216 $this->mLastSection
= 'pre';
1220 if ( '' == trim($t) ) {
1221 if ( $paragraphStack ) {
1222 $output .= $paragraphStack.'<br/>';
1223 $paragraphStack = false;
1224 $this->mLastSection
= 'p';
1226 if ($this->mLastSection
!= 'p' ) {
1227 $output .= $this->closeParagraph();
1228 $this->mLastSection
= '';
1229 $paragraphStack = "<p>";
1231 $paragraphStack = '</p><p>';
1235 if ( $paragraphStack ) {
1236 $output .= $paragraphStack;
1237 $paragraphStack = false;
1238 $this->mLastSection
= 'p';
1239 } else if ($this->mLastSection
!= 'p') {
1240 $output .= $this->closeParagraph().'<p>';
1241 $this->mLastSection
= 'p';
1247 if ($paragraphStack === false) {
1251 while ( $prefixLength ) {
1252 $output .= $this->closeList( $pref2{$prefixLength-1} );
1255 if ( "" != $this->mLastSection
) {
1256 $output .= "</" . $this->mLastSection
. ">";
1257 $this->mLastSection
= "";
1260 wfProfileOut( $fname );
1264 function getVariableValue( $index ) {
1265 global $wgLang, $wgSitename, $wgServer;
1268 case MAG_CURRENTMONTH
:
1270 case MAG_CURRENTMONTHNAME
:
1271 return $wgLang->getMonthName( date("n") );
1272 case MAG_CURRENTMONTHNAMEGEN
:
1273 return $wgLang->getMonthNameGen( date("n") );
1274 case MAG_CURRENTDAY
:
1277 return $this->mTitle
->getText();
1279 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1280 return $wgLang->getNsText($this->mTitle
->getNamespace()); // Patch by Dori
1281 case MAG_CURRENTDAYNAME
:
1282 return $wgLang->getWeekdayName( date("w")+
1 );
1283 case MAG_CURRENTYEAR
:
1285 case MAG_CURRENTTIME
:
1286 return $wgLang->time( wfTimestampNow(), false );
1287 case MAG_NUMBEROFARTICLES
:
1288 return wfNumberOfArticles();
1298 function initialiseVariables()
1300 global $wgVariableIDs;
1301 $this->mVariables
= array();
1302 foreach ( $wgVariableIDs as $id ) {
1303 $mw =& MagicWord
::get( $id );
1304 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1308 /* private */ function replaceVariables( $text, $args = array() )
1310 global $wgLang, $wgScript, $wgArticlePath;
1312 $fname = "Parser::replaceVariables";
1313 wfProfileIn( $fname );
1316 if ( !$this->mVariables
) {
1317 $this->initialiseVariables();
1319 $titleChars = Title
::legalChars();
1320 $regex = "/(\\n?){{([$titleChars]*?)(\\|.*?|)}}/s";
1322 # This function is called recursively. To keep track of arguments we need a stack:
1323 array_push( $this->mArgStack
, $args );
1325 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1326 $GLOBALS['wgCurParser'] =& $this;
1327 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1329 array_pop( $this->mArgStack
);
1334 function braceSubstitution( $matches )
1336 global $wgLinkCache, $wgLang;
1337 $fname = "Parser::braceSubstitution";
1342 # $newline is an optional newline character before the braces
1343 # $part1 is the bit before the first |, and must contain only title characters
1344 # $args is a list of arguments, starting from index 0, not including $part1
1346 $newline = $matches[1];
1347 $part1 = $matches[2];
1348 # If the third subpattern matched anything, it will start with |
1349 if ( $matches[3] !== "" ) {
1350 $args = explode( "|", substr( $matches[3], 1 ) );
1354 $argc = count( $args );
1357 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1358 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1359 if ( $this->mOutputType
!= OT_WIKI
) {
1360 # Invalid SUBST not replaced at PST time
1361 # Return without further processing
1362 $text = $matches[0];
1365 } elseif ( $this->mOutputType
== OT_WIKI
) {
1366 # SUBST not found in PST pass, do nothing
1367 $text = $matches[0];
1371 # MSG, MSGNW and INT
1374 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1375 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1378 # Remove obsolete MSG:
1379 $mwMsg =& MagicWord
::get( MAG_MSG
);
1380 $mwMsg->matchStartAndRemove( $part1 );
1383 # Check if it is an internal message
1384 $mwInt =& MagicWord
::get( MAG_INT
);
1385 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1386 if ( $this->incrementIncludeCount( "int:$part1" ) ) {
1387 $text = wfMsgReal( $part1, $args, true );
1395 # Check for NS: (namespace expansion)
1396 $mwNs = MagicWord
::get( MAG_NS
);
1397 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1398 if ( intval( $part1 ) ) {
1399 $text = $wgLang->getNsText( intval( $part1 ) );
1402 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1403 if ( !is_null( $index ) ) {
1404 $text = $wgLang->getNsText( $index );
1411 # LOCALURL and LOCALURLE
1413 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1414 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1416 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1417 $func = 'getLocalURL';
1418 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1419 $func = 'escapeLocalURL';
1424 if ( $func !== '' ) {
1425 $title = Title
::newFromText( $part1 );
1426 if ( !is_null( $title ) ) {
1428 $text = $title->$func( $args[0] );
1430 $text = $title->$func();
1437 # Internal variables
1438 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1439 $text = $this->mVariables
[$part1];
1441 $this->mOutput
->mContainsOldMagic
= true;
1444 # Arguments input from the caller
1445 $inputArgs = end( $this->mArgStack
);
1446 if ( !$found && array_key_exists( $part1, $inputArgs ) ) {
1447 $text = $inputArgs[$part1];
1451 # Load from database
1453 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1454 if ( !is_null( $title ) && !$title->isExternal() ) {
1455 # Check for excessive inclusion
1456 $dbk = $title->getPrefixedDBkey();
1457 if ( $this->incrementIncludeCount( $dbk ) ) {
1458 $article = new Article( $title );
1459 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1460 if ( $articleContent !== false ) {
1462 $text = $articleContent;
1467 # If the title is valid but undisplayable, make a link to it
1468 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1469 $text = "[[" . $title->getPrefixedText() . "]]";
1475 # Recursive parsing, escaping and link table handling
1476 # Only for HTML output
1477 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1478 $text = wfEscapeWikiText( $text );
1479 } elseif ( $this->mOutputType
== OT_HTML
&& $found ) {
1480 # Clean up argument array
1481 $assocArgs = array();
1483 foreach( $args as $arg ) {
1484 $eqpos = strpos( $arg, "=" );
1485 if ( $eqpos === false ) {
1486 $assocArgs[$index++
] = $arg;
1488 $name = trim( substr( $arg, 0, $eqpos ) );
1489 $value = trim( substr( $arg, $eqpos+
1 ) );
1490 if ( $value === false ) {
1493 if ( $name !== false ) {
1494 $assocArgs[$name] = $value;
1499 # Do not enter included links in link table
1500 if ( !is_null( $title ) ) {
1501 $wgLinkCache->suspend();
1504 # Run full parser on the included text
1505 $text = $this->strip( $text, $this->mStripState
);
1506 $text = $this->internalParse( $text, (bool)$newline, $assocArgs );
1508 # Add the result to the strip state for re-inclusion after
1509 # the rest of the processing
1510 $text = $this->insertStripItem( $text, $this->mStripState
);
1512 # Resume the link cache and register the inclusion as a link
1513 if ( !is_null( $title ) ) {
1514 $wgLinkCache->resume();
1515 $wgLinkCache->addLinkObj( $title );
1526 # Returns true if the function is allowed to include this entity
1527 function incrementIncludeCount( $dbk )
1529 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1530 $this->mIncludeCount
[$dbk] = 0;
1532 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1540 # Cleans up HTML, removes dangerous tags and attributes
1541 /* private */ function removeHTMLtags( $text )
1544 $fname = "Parser::removeHTMLtags";
1545 wfProfileIn( $fname );
1546 $htmlpairs = array( # Tags that must be closed
1547 "b", "del", "i", "ins", "u", "font", "big", "small", "sub", "sup", "h1",
1548 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1549 "strike", "strong", "tt", "var", "div", "center",
1550 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1551 "ruby", "rt" , "rb" , "rp", "p"
1553 $htmlsingle = array(
1554 "br", "hr", "li", "dt", "dd"
1556 $htmlnest = array( # Tags that can be nested--??
1557 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1558 "dl", "font", "big", "small", "sub", "sup"
1560 $tabletags = array( # Can only appear inside table
1564 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1565 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1567 $htmlattrs = $this->getHTMLattrs () ;
1569 # Remove HTML comments
1570 $text = preg_replace( "/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU", "$2", $text );
1572 $bits = explode( "<", $text );
1573 $text = array_shift( $bits );
1575 $tagstack = array(); $tablestack = array();
1576 foreach ( $bits as $x ) {
1577 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1578 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1580 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1581 error_reporting( $prev );
1584 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1588 if ( ! in_array( $t, $htmlsingle ) &&
1589 ( count($tagstack) && $ot = array_pop( $tagstack ) ) != $t ) {
1590 if(!empty($ot)) array_push( $tagstack, $ot );
1593 if ( $t == "table" ) {
1594 $tagstack = array_pop( $tablestack );
1599 # Keep track for later
1600 if ( in_array( $t, $tabletags ) &&
1601 ! in_array( "table", $tagstack ) ) {
1603 } else if ( in_array( $t, $tagstack ) &&
1604 ! in_array ( $t , $htmlnest ) ) {
1606 } else if ( ! in_array( $t, $htmlsingle ) ) {
1607 if ( $t == "table" ) {
1608 array_push( $tablestack, $tagstack );
1609 $tagstack = array();
1611 array_push( $tagstack, $t );
1613 # Strip non-approved attributes from the tag
1614 $newparams = $this->fixTagAttributes($params);
1618 $rest = str_replace( ">", ">", $rest );
1619 $text .= "<$slash$t $newparams$brace$rest";
1623 $text .= "<" . str_replace( ">", ">", $x);
1625 # Close off any remaining tags
1626 while ( $t = array_pop( $tagstack ) ) {
1628 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1631 # this might be possible using tidy itself
1632 foreach ( $bits as $x ) {
1633 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1635 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1636 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1637 $newparams = $this->fixTagAttributes($params);
1638 $rest = str_replace( ">", ">", $rest );
1639 $text .= "<$slash$t $newparams$brace$rest";
1641 $text .= "<" . str_replace( ">", ">", $x);
1645 wfProfileOut( $fname );
1652 * This function accomplishes several tasks:
1653 * 1) Auto-number headings if that option is enabled
1654 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1655 * 3) Add a Table of contents on the top for users who have enabled the option
1656 * 4) Auto-anchor headings
1658 * It loops through all headlines, collects the necessary data, then splits up the
1659 * string and re-inserts the newly formatted headlines.
1663 /* private */ function formatHeadings( $text )
1665 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1666 $doShowToc = $this->mOptions
->getShowToc();
1667 if( !$this->mTitle
->userCanEdit() ) {
1669 $rightClickHack = 0;
1671 $showEditLink = $this->mOptions
->getEditSection();
1672 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1675 # Inhibit editsection links if requested in the page
1676 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1677 if( $esw->matchAndRemove( $text ) ) {
1680 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1682 $mw =& MagicWord
::get( MAG_NOTOC
);
1683 if( $mw->matchAndRemove( $text ) ) {
1687 # never add the TOC to the Main Page. This is an entry page that should not
1688 # be more than 1-2 screens large anyway
1689 if( $this->mTitle
->getPrefixedText() == wfMsg("mainpage") ) {
1693 # Get all headlines for numbering them and adding funky stuff like [edit]
1694 # links - this is for later, but we need the number of headlines right now
1695 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1697 # if there are fewer than 4 headlines in the article, do not show TOC
1698 if( $numMatches < 4 ) {
1702 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1703 # override above conditions and always show TOC
1704 $mw =& MagicWord
::get( MAG_FORCETOC
);
1705 if ($mw->matchAndRemove( $text ) ) {
1710 # We need this to perform operations on the HTML
1711 $sk =& $this->mOptions
->getSkin();
1716 # Ugh .. the TOC should have neat indentation levels which can be
1717 # passed to the skin functions. These are determined here
1722 $sublevelCount = array();
1725 foreach( $matches[3] as $headline ) {
1728 $prevlevel = $level;
1730 $level = $matches[1][$headlineCount];
1731 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1732 # reset when we enter a new level
1733 $sublevelCount[$level] = 0;
1734 $toc .= $sk->tocIndent( $level - $prevlevel );
1735 $toclevel +
= $level - $prevlevel;
1737 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1738 # reset when we step back a level
1739 $sublevelCount[$level+
1]=0;
1740 $toc .= $sk->tocUnindent( $prevlevel - $level );
1741 $toclevel -= $prevlevel - $level;
1743 # count number of headlines for each level
1744 @$sublevelCount[$level]++
;
1745 if( $doNumberHeadings ||
$doShowToc ) {
1747 for( $i = 1; $i <= $level; $i++
) {
1748 if( !empty( $sublevelCount[$i] ) ) {
1752 $numbering .= $sublevelCount[$i];
1758 # The canonized header is a version of the header text safe to use for links
1759 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1760 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
1763 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1764 $tocline = trim( $canonized_headline );
1765 $canonized_headline = preg_replace("/[ \\?&\\/<>\\(\\)\\[\\]=,+']+/", '_', html_entity_decode( $tocline));
1766 $refer[$headlineCount] = $canonized_headline;
1768 # count how many in assoc. array so we can track dupes in anchors
1769 @$refers[$canonized_headline]++
;
1770 $refcount[$headlineCount]=$refers[$canonized_headline];
1772 # Prepend the number to the heading text
1774 if( $doNumberHeadings ||
$doShowToc ) {
1775 $tocline = $numbering . " " . $tocline;
1777 # Don't number the heading if it is the only one (looks silly)
1778 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1779 # the two are different if the line contains a link
1780 $headline=$numbering . " " . $headline;
1784 # Create the anchor for linking from the TOC to the section
1785 $anchor = $canonized_headline;
1786 if($refcount[$headlineCount] > 1 ) {
1787 $anchor .= "_" . $refcount[$headlineCount];
1790 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1792 if( $showEditLink ) {
1793 if ( empty( $head[$headlineCount] ) ) {
1794 $head[$headlineCount] = "";
1796 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
1799 # Add the edit section span
1800 if( $rightClickHack ) {
1801 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
1804 # give headline the correct <h#> tag
1805 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1811 $toclines = $headlineCount;
1812 $toc .= $sk->tocUnindent( $toclevel );
1813 $toc = $sk->tocTable( $toc );
1816 # split up and insert constructed headlines
1818 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1821 foreach( $blocks as $block ) {
1822 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1823 # This is the [edit] link that appears for the top block of text when
1824 # section editing is enabled
1826 # Disabled because it broke block formatting
1827 # For example, a bullet point in the top line
1828 # $full .= $sk->editSectionLink(0);
1831 if( $doShowToc && !$i) {
1832 # Top anchor now in skin
1836 if( !empty( $head[$i] ) ) {
1845 /* private */ function doMagicISBN( &$tokenizer )
1849 # Check whether next token is a text token
1850 # If yes, fetch it and convert the text into a
1851 # Special::BookSources link
1852 $token = $tokenizer->previewToken();
1853 while ( $token["type"] == "" )
1855 $tokenizer->nextToken();
1856 $token = $tokenizer->previewToken();
1858 if ( $token["type"] == "text" )
1860 $token = $tokenizer->nextToken();
1861 $x = $token["text"];
1862 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1864 $isbn = $blank = "" ;
1865 while ( " " == $x{0} ) {
1867 $x = substr( $x, 1 );
1869 while ( strstr( $valid, $x{0} ) != false ) {
1871 $x = substr( $x, 1 );
1873 $num = str_replace( "-", "", $isbn );
1874 $num = str_replace( " ", "", $num );
1877 $text = "ISBN $blank$x";
1879 $titleObj = Title
::makeTitle( NS_SPECIAL
, "Booksources" );
1880 $text = "<a href=\"" .
1881 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1882 "\" class=\"internal\">ISBN $isbn</a>";
1890 /* private */ function doMagicRFC( &$tokenizer )
1894 # Check whether next token is a text token
1895 # If yes, fetch it and convert the text into a
1896 # link to an RFC source
1897 $token = $tokenizer->previewToken();
1898 while ( $token["type"] == "" )
1900 $tokenizer->nextToken();
1901 $token = $tokenizer->previewToken();
1903 if ( $token["type"] == "text" )
1905 $token = $tokenizer->nextToken();
1906 $x = $token["text"];
1907 $valid = "0123456789";
1909 $rfc = $blank = "" ;
1910 while ( " " == $x{0} ) {
1912 $x = substr( $x, 1 );
1914 while ( strstr( $valid, $x{0} ) != false ) {
1916 $x = substr( $x, 1 );
1920 $text .= "RFC $blank$x";
1922 $url = wfmsg( "rfcurl" );
1923 $url = str_replace( "$1", $rfc, $url);
1924 $sk =& $this->mOptions
->getSkin();
1925 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
1926 $text = "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
1934 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
1936 $this->mOptions
= $options;
1937 $this->mTitle
=& $title;
1938 $this->mOutputType
= OT_WIKI
;
1940 if ( $clearState ) {
1941 $this->clearState();
1944 $stripState = false;
1948 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
1951 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
1952 "/<br *?>/i" => "<br/>",
1954 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
1955 $text = $this->strip( $text, $stripState, false );
1956 $text = $this->pstPass2( $text, $user );
1957 $text = $this->unstrip( $text, $stripState );
1961 /* private */ function pstPass2( $text, &$user )
1963 global $wgLang, $wgLocaltimezone, $wgCurParser;
1965 # Variable replacement
1966 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
1967 $text = $this->replaceVariables( $text );
1971 $n = $user->getName();
1972 $k = $user->getOption( "nickname" );
1973 if ( "" == $k ) { $k = $n; }
1974 if(isset($wgLocaltimezone)) {
1975 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1977 /* Note: this is an ugly timezone hack for the European wikis */
1978 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1979 " (" . date( "T" ) . ")";
1980 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1982 $text = preg_replace( "/~~~~~/", $d, $text );
1983 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1984 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1985 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1986 Namespace::getUser() ) . ":$n|$k]]", $text );
1988 # Context links: [[|name]] and [[name (context)|]]
1990 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1991 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1992 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1993 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1995 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1996 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1997 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1998 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1999 # [[ns:page (cont)|]]
2001 $t = $this->mTitle
->getText();
2002 if ( preg_match( $conpat, $t, $m ) ) {
2005 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
2006 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
2007 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
2009 if ( "" == $context ) {
2010 $text = preg_replace( $p2, "[[\\1]]", $text );
2012 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2016 $mw =& MagicWord::get( MAG_SUBST );
2017 $wgCurParser = $this->fork();
2018 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2019 $this->merge( $wgCurParser );
2022 # Trim trailing whitespace
2023 # MAG_END (__END__) tag allows for trailing
2024 # whitespace to be deliberately included
2025 $text = rtrim( $text );
2026 $mw =& MagicWord
::get( MAG_END
);
2027 $mw->matchAndRemove( $text );
2032 # Set up some variables which are usually set up in parse()
2033 # so that an external function can call some class members with confidence
2034 function startExternalParse( &$title, $options, $outputType, $clearState = true )
2036 $this->mTitle
=& $title;
2037 $this->mOptions
= $options;
2038 $this->mOutputType
= $outputType;
2039 if ( $clearState ) {
2040 $this->clearState();
2044 function transformMsg( $text, $options ) {
2046 static $executing = false;
2048 # Guard against infinite recursion
2054 $this->mTitle
= $wgTitle;
2055 $this->mOptions
= $options;
2056 $this->mOutputType
= OT_MSG
;
2057 $this->clearState();
2058 $text = $this->replaceVariables( $text );
2067 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2069 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2070 $containsOldMagic = false )
2072 $this->mText
= $text;
2073 $this->mLanguageLinks
= $languageLinks;
2074 $this->mCategoryLinks
= $categoryLinks;
2075 $this->mContainsOldMagic
= $containsOldMagic;
2078 function getText() { return $this->mText
; }
2079 function getLanguageLinks() { return $this->mLanguageLinks
; }
2080 function getCategoryLinks() { return $this->mCategoryLinks
; }
2081 function containsOldMagic() { return $this->mContainsOldMagic
; }
2082 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2083 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2084 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2085 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2087 function merge( $other ) {
2088 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2089 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2090 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2097 # All variables are private
2098 var $mUseTeX; # Use texvc to expand <math> tags
2099 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2100 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2101 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2102 var $mAllowExternalImages; # Allow external images inline
2103 var $mSkin; # Reference to the preferred skin
2104 var $mDateFormat; # Date format index
2105 var $mEditSection; # Create "edit section" links
2106 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2107 var $mNumberHeadings; # Automatically number headings
2108 var $mShowToc; # Show table of contents
2110 function getUseTeX() { return $this->mUseTeX
; }
2111 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
2112 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2113 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2114 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2115 function getSkin() { return $this->mSkin
; }
2116 function getDateFormat() { return $this->mDateFormat
; }
2117 function getEditSection() { return $this->mEditSection
; }
2118 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2119 function getNumberHeadings() { return $this->mNumberHeadings
; }
2120 function getShowToc() { return $this->mShowToc
; }
2122 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2123 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
2124 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2125 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2126 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2127 function setSkin( $x ) { return wfSetRef( $this->mSkin
, $x ); }
2128 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2129 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2130 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2131 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2132 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2134 /* static */ function newFromUser( &$user )
2136 $popts = new ParserOptions
;
2137 $popts->initialiseFromUser( $user );
2141 function initialiseFromUser( &$userInput )
2143 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2145 if ( !$userInput ) {
2147 $user->setLoaded( true );
2149 $user =& $userInput;
2152 $this->mUseTeX
= $wgUseTeX;
2153 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2154 $this->mUseDynamicDates
= $wgUseDynamicDates;
2155 $this->mInterwikiMagic
= $wgInterwikiMagic;
2156 $this->mAllowExternalImages
= $wgAllowExternalImages;
2157 $this->mSkin
=& $user->getSkin();
2158 $this->mDateFormat
= $user->getOption( "date" );
2159 $this->mEditSection
= $user->getOption( "editsection" );
2160 $this->mEditSectionOnRightClick
= $user->getOption( "editsectiononrightclick" );
2161 $this->mNumberHeadings
= $user->getOption( "numberheadings" );
2162 $this->mShowToc
= $user->getOption( "showtoc" );
2168 # Regex callbacks, used in Parser::replaceVariables
2169 function wfBraceSubstitution( $matches )
2171 global $wgCurParser;
2172 return $wgCurParser->braceSubstitution( $matches );