Don't generate article list if we have no article to show
[mediawiki.git] / includes / Parser.php
blob9437fbf11edc69aad14cc48217af8cabd88590fc
1 <?php
3 // require_once('Tokenizer.php');
5 if( $GLOBALS['wgUseWikiHiero'] ){
6 require_once('extensions/wikihiero/wikihiero.php');
8 if( $GLOBALS['wgUseTimeline'] ){
9 require_once('extensions/timeline/Timeline.php');
12 # PHP Parser
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.
19 # Globals used:
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*,
26 # $wgLocaltimezone
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");
56 class Parser
58 # Cleared with clearState():
59 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
60 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
62 # Temporary:
63 var $mOptions, $mTitle, $mOutputType;
65 function Parser()
67 $this->clearState();
70 function clearState()
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();
80 $this->mInPre = false;
83 # First pass--just handle <nowiki> sections, pass the rest off
84 # to internalParse() which does all the real work.
86 # Returns a ParserOutput
88 function parse( $text, &$title, $options, $linestart = true, $clearState = true )
90 global $wgUseTidy;
91 $fname = "Parser::parse";
92 wfProfileIn( $fname );
94 if ( $clearState ) {
95 $this->clearState();
98 $this->mOptions = $options;
99 $this->mTitle =& $title;
100 $this->mOutputType = OT_HTML;
102 $stripState = NULL;
103 $text = $this->strip( $text, $this->mStripState );
104 $text = $this->internalParse( $text, $linestart );
105 $text = $this->unstrip( $text, $this->mStripState );
106 # Clean up special characters, only run once, next-to-last before doBlockLevels
107 if(!$wgUseTidy) {
108 $fixtags = array(
109 # french spaces, last one Guillemet-left
110 # only if there is something before the space
111 "/(.) (\\?|:|!|\\302\\273)/i"=>"\\1&nbsp;\\2",
112 # french spaces, Guillemet-right
113 "/(\\302\\253) /i"=>"\\1&nbsp;",
114 "/<hr *>/i" => '<hr />',
115 "/<br *>/i" => '<br />',
116 "/<center *>/i"=>'<div class="center">',
117 "/<\\/center *>/i" => '</div>',
118 # Clean up spare ampersands; note that we probably ought to be
119 # more careful about named entities.
120 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&amp;'
122 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
123 } else {
124 $fixtags = array(
125 # french spaces, last one Guillemet-left
126 "/ (\\?|:|!|\\302\\273)/i"=>"&nbsp;\\1",
127 # french spaces, Guillemet-right
128 "/(\\302\\253) /i"=>"\\1&nbsp;",
129 "/<center *>/i"=>'<div class="center">',
130 "/<\\/center *>/i" => '</div>'
132 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
134 # only once and last
135 $text = $this->doBlockLevels( $text, $linestart );
136 $text = $this->unstripNoWiki( $text, $this->mStripState );
137 if($wgUseTidy) {
138 $text = $this->tidy($text);
140 $this->mOutput->setText( $text );
141 wfProfileOut( $fname );
142 return $this->mOutput;
145 /* static */ function getRandomString()
147 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
150 # Replaces all occurrences of <$tag>content</$tag> in the text
151 # with a random marker and returns the new text. the output parameter
152 # $content will be an associative array filled with data on the form
153 # $unique_marker => content.
155 # If $content is already set, the additional entries will be appended
157 # If $tag is set to STRIP_COMMENTS, the function will extract
158 # <!-- HTML comments -->
160 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
161 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
162 if ( !$content ) {
163 $content = array( );
165 $n = 1;
166 $stripped = "";
168 while ( "" != $text ) {
169 if($tag==STRIP_COMMENTS) {
170 $p = preg_split( "/<!--/i", $text, 2 );
171 } else {
172 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
174 $stripped .= $p[0];
175 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) {
176 $text = "";
177 } else {
178 if($tag==STRIP_COMMENTS) {
179 $q = preg_split( "/-->/i", $p[1], 2 );
180 } else {
181 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
183 $marker = $rnd . sprintf("%08X", $n++);
184 $content[$marker] = $q[0];
185 $stripped .= $marker;
186 $text = $q[1];
189 return $stripped;
192 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
193 # If $render is set, performs necessary rendering operations on plugins
194 # Returns the text, and fills an array with data needed in unstrip()
195 # If the $state is already a valid strip state, it adds to the state
197 # When $stripcomments is set, HTML comments <!-- like this -->
198 # will be stripped in addition to other tags. This is important
199 # for section editing, where these comments cause confusion when
200 # counting the sections in the wikisource
201 function strip( $text, &$state, $stripcomments = false )
203 $render = ($this->mOutputType == OT_HTML);
204 $nowiki_content = array();
205 $hiero_content = array();
206 $timeline_content = array();
207 $math_content = array();
208 $pre_content = array();
209 $comment_content = array();
211 # Replace any instances of the placeholders
212 $uniq_prefix = UNIQ_PREFIX;
213 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
215 $text = Parser::extractTags("nowiki", $text, $nowiki_content, $uniq_prefix);
216 foreach( $nowiki_content as $marker => $content ){
217 if( $render ){
218 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
219 } else {
220 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
224 $text = Parser::extractTags("hiero", $text, $hiero_content, $uniq_prefix);
225 foreach( $hiero_content as $marker => $content ){
226 if( $render && $GLOBALS['wgUseWikiHiero']){
227 $hiero_content[$marker] = WikiHiero( $content, WH_MODE_HTML);
228 } else {
229 $hiero_content[$marker] = "<hiero>$content</hiero>";
233 $text = Parser::extractTags("timeline", $text, $timeline_content, $uniq_prefix);
234 foreach( $timeline_content as $marker => $content ){
235 if( $render && $GLOBALS['wgUseTimeline']){
236 $timeline_content[$marker] = renderTimeline( $content );
237 } else {
238 $timeline_content[$marker] = "<timeline>$content</timeline>";
242 $text = Parser::extractTags("math", $text, $math_content, $uniq_prefix);
243 foreach( $math_content as $marker => $content ){
244 if( $render ) {
245 if( $this->mOptions->getUseTeX() ) {
246 $math_content[$marker] = renderMath( $content );
247 } else {
248 $math_content[$marker] = "&lt;math&gt;$content&lt;math&gt;";
250 } else {
251 $math_content[$marker] = "<math>$content</math>";
255 $text = Parser::extractTags("pre", $text, $pre_content, $uniq_prefix);
256 foreach( $pre_content as $marker => $content ){
257 if( $render ){
258 $pre_content[$marker] = "<pre>" . wfEscapeHTMLTagsOnly( $content ) . "</pre>";
259 } else {
260 $pre_content[$marker] = "<pre>$content</pre>";
263 if($stripcomments) {
264 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
265 foreach( $comment_content as $marker => $content ){
266 $comment_content[$marker] = "<!--$content-->";
270 # Merge state with the pre-existing state, if there is one
271 if ( $state ) {
272 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
273 $state['hiero'] = $state['hiero'] + $hiero_content;
274 $state['timeline'] = $state['timeline'] + $timeline_content;
275 $state['math'] = $state['math'] + $math_content;
276 $state['pre'] = $state['pre'] + $pre_content;
277 $state['comment'] = $state['comment'] + $comment_content;
278 } else {
279 $state = array(
280 'nowiki' => $nowiki_content,
281 'hiero' => $hiero_content,
282 'timeline' => $timeline_content,
283 'math' => $math_content,
284 'pre' => $pre_content,
285 'comment' => $comment_content
288 return $text;
291 # always call unstripNoWiki() after this one
292 function unstrip( $text, &$state )
294 # Must expand in reverse order, otherwise nested tags will be corrupted
295 $contentDict = end( $state );
296 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
297 if( key($state) != 'nowiki') {
298 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
299 $text = str_replace( key( $contentDict ), $content, $text );
304 return $text;
306 # always call this after unstrip() to preserve the order
307 function unstripNoWiki( $text, &$state )
309 # Must expand in reverse order, otherwise nested tags will be corrupted
310 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
311 $text = str_replace( key( $state['nowiki'] ), $content, $text );
314 return $text;
317 # Add an item to the strip state
318 # Returns the unique tag which must be inserted into the stripped text
319 # The tag will be replaced with the original text in unstrip()
321 function insertStripItem( $text, &$state )
323 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
324 if ( !$state ) {
325 $state = array(
326 'nowiki' => array(),
327 'hiero' => array(),
328 'math' => array(),
329 'pre' => array()
332 $state['item'][$rnd] = $text;
333 return $rnd;
336 # categoryMagic
337 # generate a list of subcategories and pages for a category
338 # depending on wfMsg("usenewcategorypage") it either calls the new
339 # or the old code. The new code will not work properly for some
340 # languages due to sorting issues, so they might want to turn it
341 # off.
342 function categoryMagic()
344 $msg = wfMsg("usenewcategorypage");
345 if ( "0" == @$msg[0] )
347 return $this->oldCategoryMagic();
348 } else {
349 return $this->newCategoryMagic();
353 # This method generates the list of subcategories and pages for a category
354 function oldCategoryMagic ()
356 global $wgLang , $wgUser ;
357 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
359 $cns = Namespace::getCategory() ;
360 if ( $this->mTitle->getNamespace() != $cns ) return "" ; # This ain't a category page
362 $r = "<br style=\"clear:both;\"/>\n";
365 $sk =& $wgUser->getSkin() ;
367 $articles = array() ;
368 $children = array() ;
369 $data = array () ;
370 $id = $this->mTitle->getArticleID() ;
372 # FIXME: add limits
373 $t = wfStrencode( $this->mTitle->getDBKey() );
374 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM cur,categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
375 $res = wfQuery ( $sql, DB_READ ) ;
376 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
378 # For all pages that link to this category
379 foreach ( $data AS $x )
381 $t = $wgLang->getNsText ( $x->cur_namespace ) ;
382 if ( $t != "" ) $t .= ":" ;
383 $t .= $x->cur_title ;
385 if ( $x->cur_namespace == $cns ) {
386 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
387 } else {
388 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
391 wfFreeResult ( $res ) ;
393 # Showing subcategories
394 if ( count ( $children ) > 0 ) {
395 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
396 $r .= implode ( ", " , $children ) ;
399 # Showing pages in this category
400 if ( count ( $articles ) > 0 ) {
401 $ti = $this->mTitle->getText() ;
402 $h = wfMsg( "category_header", $ti );
403 $r .= "<h2>{$h}</h2>\n" ;
404 $r .= implode ( ", " , $articles ) ;
408 return $r ;
413 function newCategoryMagic ()
415 global $wgLang , $wgUser ;
416 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
418 $cns = Namespace::getCategory() ;
419 if ( $this->mTitle->getNamespace() != $cns ) return "" ; # This ain't a category page
421 $r = "<br style=\"clear:both;\"/>\n";
424 $sk =& $wgUser->getSkin() ;
426 $articles = array() ;
427 $articles_start_char = array();
428 $children = array() ;
429 $children_start_char = array();
430 $data = array () ;
431 $id = $this->mTitle->getArticleID() ;
433 # FIXME: add limits
434 $t = wfStrencode( $this->mTitle->getDBKey() );
435 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM
436 cur,categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY
437 cl_sortkey" ;
438 $res = wfQuery ( $sql, DB_READ ) ;
439 while ( $x = wfFetchObject ( $res ) )
441 $data[] = $x ;
444 # For all pages that link to this category
445 foreach ( $data as $x )
447 $t = $wgLang->getNsText ( $x->cur_namespace ) ;
448 if ( $t != "" ) $t .= ":" ;
449 $t .= $x->cur_title ;
451 if ( $x->cur_namespace == $cns ) {
452 array_push ( $children, $sk->makeKnownLink ( $t, $x->cur_title) ) ; # Subcategory
453 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title ) ) ;
454 } else {
455 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
456 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
459 wfFreeResult ( $res ) ;
461 $ti = $this->mTitle->getText() ;
463 # Don't show subcategories section if there are none.
464 if ( count ( $children ) > 0 )
466 # Showing subcategories
467 $r .= "<h2>" . wfMsg( "subcategories" ) . "</h2>\n"
468 . wfMsg( "subcategorycount", count( $children ) );
469 if ( count ( $children ) > 20) {
471 // divide list into three equal chunks
472 $chunk = (int) (count ( $children ) / 3);
474 // get and display header
475 $r .= "<table width=\"100%\"><tr valign=\"top\">";
477 $startChunk = 0;
478 $endChunk = $chunk;
480 // loop through the chunks
481 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
482 $chunkIndex < 3;
483 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
486 $r .= "<td><ul>";
487 // output all subcategories to category
488 for ($index = $startChunk ;
489 $index < $endChunk && $index < count($children);
490 $index++ )
492 // check for change of starting letter or begging of chunk
493 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
494 || ($index == $startChunk) )
496 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
499 $r .= "<li>{$children[$index]}</li>";
501 $r .= "</ul></td>";
505 $r .= "</tr></table>";
506 } else {
507 // for short lists of subcategories to category.
509 $r .= "<h3>{$children_start_char[0]}</h3>\n";
510 $r .= "<ul><li>".$children[0]."</li>";
511 for ($index = 1; $index < count($children); $index++ )
513 if ($children_start_char[$index] != $children_start_char[$index - 1])
515 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
518 $r .= "<li>{$children[$index]}</li>";
520 $r .= "</ul>";
522 } # END of if ( count($children) > 0 )
524 $r .= "<h2>" . wfMsg( "category_header", $ti ) . "</h2>\n" .
525 wfMsg( "categoryarticlecount", count( $articles ) );
527 # Showing articles in this category
528 if ( count ( $articles ) > 6) {
529 $ti = $this->mTitle->getText() ;
531 // divide list into three equal chunks
532 $chunk = (int) (count ( $articles ) / 3);
534 // get and display header
535 $r .= "<table width=\"100%\"><tr valign=\"top\">";
537 // loop through the chunks
538 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
539 $chunkIndex < 3;
540 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
543 $r .= "<td><ul>";
545 // output all articles in category
546 for ($index = $startChunk ;
547 $index < $endChunk && $index < count($articles);
548 $index++ )
550 // check for change of starting letter or begging of chunk
551 if ( ($articles_start_char[$index] != $articles_start_char[$index - 1])
552 || ($index == $startChunk) )
554 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
557 $r .= "<li>{$articles[$index]}</li>";
559 $r .= "</ul></td>";
563 $r .= "</tr></table>";
564 } elseif ( count ( $articles ) > 0) {
565 // for short lists of articles in categories.
566 $ti = $this->mTitle->getText() ;
568 $r .= "<h3>".$articles_start_char[0]."</h3>\n";
569 $r .= "<ul><li>".$articles[0]."</li>";
570 for ($index = 1; $index < count($articles); $index++ )
572 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
574 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
577 $r .= "<li>{$articles[$index]}</li>";
579 $r .= "</ul>";
583 return $r ;
586 # Return allowed HTML attributes
587 function getHTMLattrs ()
589 $htmlattrs = array( # Allowed attributes--no scripting, etc.
590 "title", "align", "lang", "dir", "width", "height",
591 "bgcolor", "clear", /* BR */ "noshade", /* HR */
592 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
593 /* FONT */ "type", "start", "value", "compact",
594 /* For various lists, mostly deprecated but safe */
595 "summary", "width", "border", "frame", "rules",
596 "cellspacing", "cellpadding", "valign", "char",
597 "charoff", "colgroup", "col", "span", "abbr", "axis",
598 "headers", "scope", "rowspan", "colspan", /* Tables */
599 "id", "class", "name", "style" /* For CSS */
601 return $htmlattrs ;
604 # Remove non approved attributes and javascript in css
605 function fixTagAttributes ( $t )
607 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
608 $htmlattrs = $this->getHTMLattrs() ;
610 # Strip non-approved attributes from the tag
611 $t = preg_replace(
612 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
613 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
614 $t);
615 # Strip javascript "expression" from stylesheets. Brute force approach:
616 # If anythin offensive is found, all attributes of the HTML tag are dropped
618 if( preg_match(
619 "/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is",
620 wfMungeToUtf8( $t ) ) )
622 $t="";
625 return trim ( $t ) ;
628 # interface with html tidy, used if $wgUseTidy = true
629 function tidy ( $text ) {
630 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
631 global $wgInputEncoding, $wgOutputEncoding;
632 $fname = "Parser::tidy";
633 wfProfileIn( $fname );
635 $cleansource = '';
636 switch(strtoupper($wgOutputEncoding)) {
637 case 'ISO-8859-1':
638 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
639 break;
640 case 'UTF-8':
641 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
642 break;
643 default:
644 $wgTidyOpts .= ' -raw';
647 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
648 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
649 '<head><title>test</title></head><body>'.$text.'</body></html>';
650 $descriptorspec = array(
651 0 => array("pipe", "r"),
652 1 => array("pipe", "w"),
653 2 => array("file", "/dev/null", "a")
655 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
656 if (is_resource($process)) {
657 fwrite($pipes[0], $wrappedtext);
658 fclose($pipes[0]);
659 while (!feof($pipes[1])) {
660 $cleansource .= fgets($pipes[1], 1024);
662 fclose($pipes[1]);
663 $return_value = proc_close($process);
666 wfProfileOut( $fname );
668 if( $cleansource == '' && $text != '') {
669 wfDebug( "Tidy error detected!\n" );
670 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
671 } else {
672 return $cleansource;
676 # parse the wiki syntax used to render tables
677 function doTableStuff ( $t )
679 $t = explode ( "\n" , $t ) ;
680 $td = array () ; # Is currently a td tag open?
681 $ltd = array () ; # Was it TD or TH?
682 $tr = array () ; # Is currently a tr tag open?
683 $ltr = array () ; # tr attributes
684 foreach ( $t AS $k => $x )
686 $x = trim ( $x ) ;
687 $fc = substr ( $x , 0 , 1 ) ;
688 if ( "{|" == substr ( $x , 0 , 2 ) )
690 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
691 array_push ( $td , false ) ;
692 array_push ( $ltd , "" ) ;
693 array_push ( $tr , false ) ;
694 array_push ( $ltr , "" ) ;
696 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
697 else if ( "|}" == substr ( $x , 0 , 2 ) )
699 $z = "</table>\n" ;
700 $l = array_pop ( $ltd ) ;
701 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
702 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
703 array_pop ( $ltr ) ;
704 $t[$k] = $z ;
706 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
708 $z = trim ( substr ( $x , 2 ) ) ;
709 $t[$k] = "<caption>{$z}</caption>\n" ;
711 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
713 $x = substr ( $x , 1 ) ;
714 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
715 $z = "" ;
716 $l = array_pop ( $ltd ) ;
717 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
718 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
719 array_pop ( $ltr ) ;
720 $t[$k] = $z ;
721 array_push ( $tr , false ) ;
722 array_push ( $td , false ) ;
723 array_push ( $ltd , "" ) ;
724 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
726 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
728 if ( "|+" == substr ( $x , 0 , 2 ) )
730 $fc = "+" ;
731 $x = substr ( $x , 1 ) ;
733 $after = substr ( $x , 1 ) ;
734 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
735 $after = explode ( "||" , $after ) ;
736 $t[$k] = "" ;
737 foreach ( $after AS $theline )
739 $z = "" ;
740 if ( $fc != "+" )
742 $tra = array_pop ( $ltr ) ;
743 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
744 array_push ( $tr , true ) ;
745 array_push ( $ltr , "" ) ;
748 $l = array_pop ( $ltd ) ;
749 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
750 if ( $fc == "|" ) $l = "td" ;
751 else if ( $fc == "!" ) $l = "th" ;
752 else if ( $fc == "+" ) $l = "caption" ;
753 else $l = "" ;
754 array_push ( $ltd , $l ) ;
755 $y = explode ( "|" , $theline , 2 ) ;
756 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
757 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
758 $t[$k] .= $y ;
759 array_push ( $td , true ) ;
764 # Closing open td, tr && table
765 while ( count ( $td ) > 0 )
767 if ( array_pop ( $td ) ) $t[] = "</td>" ;
768 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
769 $t[] = "</table>" ;
772 $t = implode ( "\n" , $t ) ;
773 # $t = $this->removeHTMLtags( $t );
774 return $t ;
777 # Parses the text and adds the result to the strip state
778 # Returns the strip tag
779 function stripParse( $text, $newline, $args )
781 $text = $this->strip( $text, $this->mStripState );
782 $text = $this->internalParse( $text, (bool)$newline, $args, false );
783 return $newline.$this->insertStripItem( $text, $this->mStripState );
786 function internalParse( $text, $linestart, $args = array(), $isMain=true )
788 $fname = "Parser::internalParse";
789 wfProfileIn( $fname );
791 $text = $this->removeHTMLtags( $text );
792 $text = $this->replaceVariables( $text, $args );
794 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr />", $text );
796 $text = $this->doHeadings( $text );
797 if($this->mOptions->getUseDynamicDates()) {
798 global $wgDateFormatter;
799 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
801 $text = $this->doAllQuotes( $text );
802 $text = $this->replaceExternalLinks( $text );
803 $text = $this->replaceInternalLinks ( $text );
804 $text = $this->replaceInternalLinks ( $text );
805 //$text = $this->doTokenizedParser ( $text );
806 $text = $this->doTableStuff ( $text ) ;
807 $text = $this->magicISBN( $text );
808 $text = $this->magicRFC( $text );
809 $text = $this->formatHeadings( $text, $isMain );
810 $sk =& $this->mOptions->getSkin();
811 $text = $sk->transformContent( $text );
813 if ( !isset ( $this->categoryMagicDone ) ) {
814 $text .= $this->categoryMagic () ;
815 $this->categoryMagicDone = true ;
818 wfProfileOut( $fname );
819 return $text;
822 # Parse headers and return html
823 /* private */ function doHeadings( $text )
825 $fname = "Parser::doHeadings";
826 wfProfileIn( $fname );
827 for ( $i = 6; $i >= 1; --$i ) {
828 $h = substr( "======", 0, $i );
829 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
830 "<h{$i}>\\1</h{$i}>\\2", $text );
832 wfProfileOut( $fname );
833 return $text;
836 /* private */ function doAllQuotes( $text )
838 $fname = "Parser::doAllQuotes";
839 wfProfileIn( $fname );
840 $outtext = "";
841 $lines = explode( "\n", $text );
842 foreach ( $lines as $line ) {
843 $outtext .= $this->doQuotes ( "", $line, "" ) . "\n";
845 $outtext = substr($outtext, 0,-1);
846 wfProfileOut( $fname );
847 return $outtext;
850 /* private */ function doQuotes( $pre, $text, $mode )
852 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
853 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
854 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
855 if ( substr ($m[2], 0, 1) == "'" ) {
856 $m[2] = substr ($m[2], 1);
857 if ($mode == "em") {
858 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
859 } else if ($mode == "strong") {
860 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
861 } else if (($mode == "emstrong") || ($mode == "both")) {
862 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
863 } else if ($mode == "strongem") {
864 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
865 } else {
866 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
868 } else {
869 if ($mode == "strong") {
870 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
871 } else if ($mode == "em") {
872 return $m1_em . $this->doQuotes ( "", $m[2], "" );
873 } else if ($mode == "emstrong") {
874 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
875 } else if (($mode == "strongem") || ($mode == "both")) {
876 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
877 } else {
878 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
881 } else {
882 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
883 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
884 if ($mode == "") {
885 return $pre . $text;
886 } else if ($mode == "em") {
887 return $pre . $text_em;
888 } else if ($mode == "strong") {
889 return $pre . $text_strong;
890 } else if ($mode == "strongem") {
891 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
892 } else {
893 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
898 # Note: we have to do external links before the internal ones,
899 # and otherwise take great care in the order of things here, so
900 # that we don't end up interpreting some URLs twice.
902 /* private */ function replaceExternalLinks( $text )
904 $fname = "Parser::replaceExternalLinks";
905 wfProfileIn( $fname );
906 $text = $this->subReplaceExternalLinks( $text, "http", true );
907 $text = $this->subReplaceExternalLinks( $text, "https", true );
908 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
909 $text = $this->subReplaceExternalLinks( $text, "irc", false );
910 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
911 $text = $this->subReplaceExternalLinks( $text, "news", false );
912 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
913 wfProfileOut( $fname );
914 return $text;
917 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
919 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
920 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
922 # this is the list of separators that should be ignored if they
923 # are the last character of an URL but that should be included
924 # if they occur within the URL, e.g. "go to www.foo.com, where .."
925 # in this case, the last comma should not become part of the URL,
926 # but in "www.foo.com/123,2342,32.htm" it should.
927 $sep = ",;\.:";
928 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
929 $images = "gif|png|jpg|jpeg";
931 # PLEASE NOTE: The curly braces { } are not part of the regex,
932 # they are interpreted as part of the string (used to tell PHP
933 # that the content of the string should be inserted there).
934 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
935 "((?i){$images})([^{$uc}]|$)/";
937 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
938 $sk =& $this->mOptions->getSkin();
940 if ( $autonumber and $this->mOptions->getAllowExternalImages() ) { # Use img tags only for HTTP urls
941 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
942 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
944 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
945 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
946 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
947 "</a>\\5", $s );
948 $s = str_replace( $unique, $protocol, $s );
950 $a = explode( "[{$protocol}:", " " . $s );
951 $s = array_shift( $a );
952 $s = substr( $s, 1 );
954 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
955 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
957 foreach ( $a as $line ) {
958 if ( preg_match( $e1, $line, $m ) ) {
959 $link = "{$protocol}:{$m[1]}";
960 $trail = $m[2];
961 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
962 else { $text = wfEscapeHTML( $link ); }
963 } else if ( preg_match( $e2, $line, $m ) ) {
964 $link = "{$protocol}:{$m[1]}";
965 $text = $m[2];
966 $trail = $m[3];
967 } else {
968 $s .= "[{$protocol}:" . $line;
969 continue;
971 if( $link == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
972 $paren = "";
973 } else {
974 # Expand the URL for printable version
975 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
977 $la = $sk->getExternalLinkAttributes( $link, $text );
978 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
981 return $s;
985 /* private */ function replaceInternalLinks( $s )
987 global $wgLang, $wgLinkCache;
988 global $wgNamespacesWithSubpages, $wgLanguageCode;
989 static $fname = "Parser::replaceInternalLinks" ;
990 wfProfileIn( $fname );
992 wfProfileIn( "$fname-setup" );
993 static $tc = FALSE;
994 # the % is needed to support urlencoded titles as well
995 if ( !$tc ) { $tc = Title::legalChars() . "#%"; }
996 $sk =& $this->mOptions->getSkin();
998 $a = explode( "[[", " " . $s );
999 $s = array_shift( $a );
1000 $s = substr( $s, 1 );
1002 # Match a link having the form [[namespace:link|alternate]]trail
1003 static $e1 = FALSE;
1004 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1005 # Match the end of a line for a word that's not followed by whitespace,
1006 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1007 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1009 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1010 # Special and Media are pseudo-namespaces; no pages actually exist in them
1011 static $image = FALSE;
1012 static $special = FALSE;
1013 static $media = FALSE;
1014 static $category = FALSE;
1015 if ( !$image ) { $image = Namespace::getImage(); }
1016 if ( !$special ) { $special = Namespace::getSpecial(); }
1017 if ( !$media ) { $media = Namespace::getMedia(); }
1018 if ( !$category ) { $category = Namespace::getCategory(); }
1020 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1022 if ( $useLinkPrefixExtension ) {
1023 if ( preg_match( $e2, $s, $m ) ) {
1024 $first_prefix = $m[2];
1025 $s = $m[1];
1026 } else {
1027 $first_prefix = false;
1029 } else {
1030 $prefix = '';
1033 wfProfileOut( "$fname-setup" );
1035 foreach ( $a as $line ) {
1036 wfProfileIn( "$fname-prefixhandling" );
1037 if ( $useLinkPrefixExtension ) {
1038 if ( preg_match( $e2, $s, $m ) ) {
1039 $prefix = $m[2];
1040 $s = $m[1];
1041 } else {
1042 $prefix='';
1044 # first link
1045 if($first_prefix) {
1046 $prefix = $first_prefix;
1047 $first_prefix = false;
1050 wfProfileOut( "$fname-prefixhandling" );
1052 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1053 $text = $m[2];
1054 # fix up urlencoded title texts
1055 if(preg_match("/%/", $m[1] )) $m[1] = urldecode($m[1]);
1056 $trail = $m[3];
1057 } else { # Invalid form; output directly
1058 $s .= $prefix . "[[" . $line ;
1059 continue;
1062 /* Valid link forms:
1063 Foobar -- normal
1064 :Foobar -- override special treatment of prefix (images, language links)
1065 /Foobar -- convert to CurrentPage/Foobar
1066 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1068 $c = substr($m[1],0,1);
1069 $noforce = ($c != ":");
1070 if( $c == "/" ) { # subpage
1071 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
1072 $m[1]=substr($m[1],1,strlen($m[1])-2);
1073 $noslash=$m[1];
1074 } else {
1075 $noslash=substr($m[1],1);
1077 if(!empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()])) { # subpages allowed here
1078 $link = $this->mTitle->getPrefixedText(). "/" . trim($noslash);
1079 if( "" == $text ) {
1080 $text= $m[1];
1081 } # this might be changed for ugliness reasons
1082 } else {
1083 $link = $noslash; # no subpage allowed, use standard link
1085 } elseif( $noforce ) { # no subpage
1086 $link = $m[1];
1087 } else {
1088 $link = substr( $m[1], 1 );
1090 $wasblank = ( "" == $text );
1091 if( $wasblank )
1092 $text = $link;
1094 $nt = Title::newFromText( $link );
1095 if( !$nt ) {
1096 $s .= $prefix . "[[" . $line;
1097 continue;
1099 $ns = $nt->getNamespace();
1100 $iw = $nt->getInterWiki();
1101 if( $noforce ) {
1102 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1103 array_push( $this->mOutput->mLanguageLinks, $nt->getPrefixedText() );
1104 $tmp = $prefix . $trail ;
1105 $s .= (trim($tmp) == '')? '': $tmp;
1106 continue;
1108 if ( $ns == $image ) {
1109 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1110 $wgLinkCache->addImageLinkObj( $nt );
1111 continue;
1113 if ( $ns == $category ) {
1114 $t = $nt->getText() ;
1115 $nnt = Title::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1117 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1118 $t = $sk->makeLinkObj( $nnt, $t, "", "" , $prefix );
1119 $wgLinkCache->resume();
1121 $sortkey = $wasblank ? $this->mTitle->getPrefixedText() : $text;
1122 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1123 $this->mOutput->mCategoryLinks[] = $t ;
1124 $s .= $prefix . $trail ;
1125 continue;
1128 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
1129 ( strpos( $link, "#" ) == FALSE ) ) {
1130 # Self-links are handled specially; generally de-link and change to bold.
1131 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, "", $trail );
1132 continue;
1135 if( $ns == $media ) {
1136 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1137 $wgLinkCache->addImageLinkObj( $nt );
1138 continue;
1139 } elseif( $ns == $special ) {
1140 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1141 continue;
1143 $s .= $sk->makeLinkObj( $nt, $text, "", $trail, $prefix );
1145 wfProfileOut( $fname );
1146 return $s;
1149 # Some functions here used by doBlockLevels()
1151 /* private */ function closeParagraph()
1153 $result = "";
1154 if ( '' != $this->mLastSection ) {
1155 $result = "</" . $this->mLastSection . ">\n";
1157 $this->mInPre = false;
1158 $this->mLastSection = "";
1159 return $result;
1161 # getCommon() returns the length of the longest common substring
1162 # of both arguments, starting at the beginning of both.
1164 /* private */ function getCommon( $st1, $st2 )
1166 $fl = strlen( $st1 );
1167 $shorter = strlen( $st2 );
1168 if ( $fl < $shorter ) { $shorter = $fl; }
1170 for ( $i = 0; $i < $shorter; ++$i ) {
1171 if ( $st1{$i} != $st2{$i} ) { break; }
1173 return $i;
1175 # These next three functions open, continue, and close the list
1176 # element appropriate to the prefix character passed into them.
1178 /* private */ function openList( $char )
1180 $result = $this->closeParagraph();
1182 if ( "*" == $char ) { $result .= "<ul><li>"; }
1183 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1184 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1185 else if ( ";" == $char ) {
1186 $result .= "<dl><dt>";
1187 $this->mDTopen = true;
1189 else { $result = "<!-- ERR 1 -->"; }
1191 return $result;
1194 /* private */ function nextItem( $char )
1196 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1197 else if ( ":" == $char || ";" == $char ) {
1198 $close = "</dd>";
1199 if ( $this->mDTopen ) { $close = "</dt>"; }
1200 if ( ";" == $char ) {
1201 $this->mDTopen = true;
1202 return $close . "<dt>";
1203 } else {
1204 $this->mDTopen = false;
1205 return $close . "<dd>";
1208 return "<!-- ERR 2 -->";
1211 /* private */function closeList( $char )
1213 if ( "*" == $char ) { $text = "</li></ul>"; }
1214 else if ( "#" == $char ) { $text = "</li></ol>"; }
1215 else if ( ":" == $char ) {
1216 if ( $this->mDTopen ) {
1217 $this->mDTopen = false;
1218 $text = "</dt></dl>";
1219 } else {
1220 $text = "</dd></dl>";
1223 else { return "<!-- ERR 3 -->"; }
1224 return $text."\n";
1227 /* private */ function doBlockLevels( $text, $linestart ) {
1228 $fname = "Parser::doBlockLevels";
1229 wfProfileIn( $fname );
1231 # Parsing through the text line by line. The main thing
1232 # happening here is handling of block-level elements p, pre,
1233 # and making lists from lines starting with * # : etc.
1235 $textLines = explode( "\n", $text );
1237 $lastPrefix = $output = $lastLine = '';
1238 $this->mDTopen = $inBlockElem = false;
1239 $prefixLength = 0;
1240 $paragraphStack = false;
1242 if ( !$linestart ) {
1243 $output .= array_shift( $textLines );
1245 foreach ( $textLines as $oLine ) {
1246 $lastPrefixLength = strlen( $lastPrefix );
1247 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1248 $preOpenMatch = preg_match("/<pre/i", $oLine );
1249 if (!$this->mInPre) {
1250 $this->mInPre = !empty($preOpenMatch);
1252 if ( !$this->mInPre ) {
1253 # Multiple prefixes may abut each other for nested lists.
1254 $prefixLength = strspn( $oLine, "*#:;" );
1255 $pref = substr( $oLine, 0, $prefixLength );
1257 # eh?
1258 $pref2 = str_replace( ";", ":", $pref );
1259 $t = substr( $oLine, $prefixLength );
1260 } else {
1261 # Don't interpret any other prefixes in preformatted text
1262 $prefixLength = 0;
1263 $pref = $pref2 = '';
1264 $t = $oLine;
1267 # List generation
1268 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1269 # Same as the last item, so no need to deal with nesting or opening stuff
1270 $output .= $this->nextItem( substr( $pref, -1 ) );
1271 $paragraphStack = false;
1273 if ( ";" == substr( $pref, -1 ) ) {
1274 # The one nasty exception: definition lists work like this:
1275 # ; title : definition text
1276 # So we check for : in the remainder text to split up the
1277 # title and definition, without b0rking links.
1278 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1279 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1280 $term = $match[1];
1281 $output .= $term . $this->nextItem( ":" );
1282 $t = $match[2];
1285 } elseif( $prefixLength || $lastPrefixLength ) {
1286 # Either open or close a level...
1287 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1288 $paragraphStack = false;
1290 while( $commonPrefixLength < $lastPrefixLength ) {
1291 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1292 --$lastPrefixLength;
1294 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1295 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1297 while ( $prefixLength > $commonPrefixLength ) {
1298 $char = substr( $pref, $commonPrefixLength, 1 );
1299 $output .= $this->openList( $char );
1301 if ( ";" == $char ) {
1302 # FIXME: This is dupe of code above
1303 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1304 $term = $match[1];
1305 $output .= $term . $this->nextItem( ":" );
1306 $t = $match[2];
1309 ++$commonPrefixLength;
1311 $lastPrefix = $pref2;
1313 if( 0 == $prefixLength ) {
1314 # No prefix (not in list)--go to paragraph mode
1315 $uniq_prefix = UNIQ_PREFIX;
1316 // XXX: use a stack for nestable elements like span, table and div
1317 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i", $t );
1318 $closematch = preg_match(
1319 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1320 "<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|".$uniq_prefix."-pre|<\\/li|<\\/ul)/i", $t );
1321 if ( $openmatch or $closematch ) {
1322 $paragraphStack = false;
1323 $output .= $this->closeParagraph();
1324 if($preOpenMatch and !$preCloseMatch) {
1325 $this->mInPre = true;
1327 if ( $closematch ) {
1328 $inBlockElem = false;
1329 } else {
1330 $inBlockElem = true;
1332 } else if ( !$inBlockElem && !$this->mInPre ) {
1333 if ( " " == $t{0} and trim($t) != '' ) {
1334 // pre
1335 if ($this->mLastSection != 'pre') {
1336 $paragraphStack = false;
1337 $output .= $this->closeParagraph().'<pre>';
1338 $this->mLastSection = 'pre';
1340 } else {
1341 // paragraph
1342 if ( '' == trim($t) ) {
1343 if ( $paragraphStack ) {
1344 $output .= $paragraphStack.'<br />';
1345 $paragraphStack = false;
1346 $this->mLastSection = 'p';
1347 } else {
1348 if ($this->mLastSection != 'p' ) {
1349 $output .= $this->closeParagraph();
1350 $this->mLastSection = '';
1351 $paragraphStack = "<p>";
1352 } else {
1353 $paragraphStack = '</p><p>';
1356 } else {
1357 if ( $paragraphStack ) {
1358 $output .= $paragraphStack;
1359 $paragraphStack = false;
1360 $this->mLastSection = 'p';
1361 } else if ($this->mLastSection != 'p') {
1362 $output .= $this->closeParagraph().'<p>';
1363 $this->mLastSection = 'p';
1369 if ($paragraphStack === false) {
1370 $output .= $t."\n";
1373 while ( $prefixLength ) {
1374 $output .= $this->closeList( $pref2{$prefixLength-1} );
1375 --$prefixLength;
1377 if ( "" != $this->mLastSection ) {
1378 $output .= "</" . $this->mLastSection . ">";
1379 $this->mLastSection = "";
1382 wfProfileOut( $fname );
1383 return $output;
1386 # Return value of a magic variable (like PAGENAME)
1387 function getVariableValue( $index ) {
1388 global $wgLang, $wgSitename, $wgServer;
1390 switch ( $index ) {
1391 case MAG_CURRENTMONTH:
1392 return date( "m" );
1393 case MAG_CURRENTMONTHNAME:
1394 return $wgLang->getMonthName( date("n") );
1395 case MAG_CURRENTMONTHNAMEGEN:
1396 return $wgLang->getMonthNameGen( date("n") );
1397 case MAG_CURRENTDAY:
1398 return date("j");
1399 case MAG_PAGENAME:
1400 return $this->mTitle->getText();
1401 case MAG_NAMESPACE:
1402 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1403 return $wgLang->getNsText($this->mTitle->getNamespace()); // Patch by Dori
1404 case MAG_CURRENTDAYNAME:
1405 return $wgLang->getWeekdayName( date("w")+1 );
1406 case MAG_CURRENTYEAR:
1407 return date( "Y" );
1408 case MAG_CURRENTTIME:
1409 return $wgLang->time( wfTimestampNow(), false );
1410 case MAG_NUMBEROFARTICLES:
1411 return wfNumberOfArticles();
1412 case MAG_SITENAME:
1413 return $wgSitename;
1414 case MAG_SERVER:
1415 return $wgServer;
1416 default:
1417 return NULL;
1421 # initialise the magic variables (like CURRENTMONTHNAME)
1422 function initialiseVariables()
1424 global $wgVariableIDs;
1425 $this->mVariables = array();
1426 foreach ( $wgVariableIDs as $id ) {
1427 $mw =& MagicWord::get( $id );
1428 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1432 /* private */ function replaceVariables( $text, $args = array() )
1434 global $wgLang, $wgScript, $wgArticlePath;
1436 $fname = "Parser::replaceVariables";
1437 wfProfileIn( $fname );
1439 $bail = false;
1440 if ( !$this->mVariables ) {
1441 $this->initialiseVariables();
1443 $titleChars = Title::legalChars();
1444 $nonBraceChars = str_replace( array( "{", "}" ), array( "", "" ), $titleChars );
1446 # This function is called recursively. To keep track of arguments we need a stack:
1447 array_push( $this->mArgStack, $args );
1449 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1450 $GLOBALS['wgCurParser'] =& $this;
1453 if ( $this->mOutputType == OT_HTML ) {
1454 # Variable substitution
1455 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", "wfVariableSubstitution", $text );
1457 # Argument substitution
1458 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", "wfArgSubstitution", $text );
1460 # Template substitution
1461 $regex = "/(\\n?){{([$nonBraceChars]*)(\\|.*?|)}}/s";
1462 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1464 array_pop( $this->mArgStack );
1466 wfProfileOut( $fname );
1467 return $text;
1470 function variableSubstitution( $matches )
1472 if ( array_key_exists( $matches[1], $this->mVariables ) ) {
1473 $text = $this->mVariables[$matches[1]];
1474 $this->mOutput->mContainsOldMagic = true;
1475 } else {
1476 $text = $matches[0];
1478 return $text;
1481 function braceSubstitution( $matches )
1483 global $wgLinkCache, $wgLang;
1484 $fname = "Parser::braceSubstitution";
1485 $found = false;
1486 $nowiki = false;
1487 $noparse = false;
1489 $title = NULL;
1491 # $newline is an optional newline character before the braces
1492 # $part1 is the bit before the first |, and must contain only title characters
1493 # $args is a list of arguments, starting from index 0, not including $part1
1495 $newline = $matches[1];
1496 $part1 = $matches[2];
1497 # If the third subpattern matched anything, it will start with |
1498 if ( $matches[3] !== "" ) {
1499 $args = explode( "|", substr( $matches[3], 1 ) );
1500 } else {
1501 $args = array();
1503 $argc = count( $args );
1505 # {{{}}}
1506 if ( strpos( $matches[0], "{{{" ) !== false ) {
1507 $text = $matches[0];
1508 $found = true;
1509 $noparse = true;
1512 # SUBST
1513 if ( !$found ) {
1514 $mwSubst =& MagicWord::get( MAG_SUBST );
1515 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1516 if ( $this->mOutputType != OT_WIKI ) {
1517 # Invalid SUBST not replaced at PST time
1518 # Return without further processing
1519 $text = $matches[0];
1520 $found = true;
1521 $noparse= true;
1523 } elseif ( $this->mOutputType == OT_WIKI ) {
1524 # SUBST not found in PST pass, do nothing
1525 $text = $matches[0];
1526 $found = true;
1530 # MSG, MSGNW and INT
1531 if ( !$found ) {
1532 # Check for MSGNW:
1533 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1534 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1535 $nowiki = true;
1536 } else {
1537 # Remove obsolete MSG:
1538 $mwMsg =& MagicWord::get( MAG_MSG );
1539 $mwMsg->matchStartAndRemove( $part1 );
1542 # Check if it is an internal message
1543 $mwInt =& MagicWord::get( MAG_INT );
1544 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1545 if ( $this->incrementIncludeCount( "int:$part1" ) ) {
1546 $text = wfMsgReal( $part1, $args, true );
1547 $found = true;
1552 # NS
1553 if ( !$found ) {
1554 # Check for NS: (namespace expansion)
1555 $mwNs = MagicWord::get( MAG_NS );
1556 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1557 if ( intval( $part1 ) ) {
1558 $text = $wgLang->getNsText( intval( $part1 ) );
1559 $found = true;
1560 } else {
1561 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1562 if ( !is_null( $index ) ) {
1563 $text = $wgLang->getNsText( $index );
1564 $found = true;
1570 # LOCALURL and LOCALURLE
1571 if ( !$found ) {
1572 $mwLocal = MagicWord::get( MAG_LOCALURL );
1573 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1575 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1576 $func = 'getLocalURL';
1577 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1578 $func = 'escapeLocalURL';
1579 } else {
1580 $func = '';
1583 if ( $func !== '' ) {
1584 $title = Title::newFromText( $part1 );
1585 if ( !is_null( $title ) ) {
1586 if ( $argc > 0 ) {
1587 $text = $title->$func( $args[0] );
1588 } else {
1589 $text = $title->$func();
1591 $found = true;
1596 # Internal variables
1597 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1598 $text = $this->mVariables[$part1];
1599 $found = true;
1600 $this->mOutput->mContainsOldMagic = true;
1603 # Arguments input from the caller
1604 $inputArgs = end( $this->mArgStack );
1605 if ( !$found && array_key_exists( $part1, $inputArgs ) ) {
1606 $text = $inputArgs[$part1];
1607 $found = true;
1610 # Load from database
1611 if ( !$found ) {
1612 $title = Title::newFromText( $part1, NS_TEMPLATE );
1613 if ( !is_null( $title ) && !$title->isExternal() ) {
1614 # Check for excessive inclusion
1615 $dbk = $title->getPrefixedDBkey();
1616 if ( $this->incrementIncludeCount( $dbk ) ) {
1617 $article = new Article( $title );
1618 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1619 if ( $articleContent !== false ) {
1620 $found = true;
1621 $text = $articleContent;
1626 # If the title is valid but undisplayable, make a link to it
1627 if ( $this->mOutputType == OT_HTML && !$found ) {
1628 $text = "[[" . $title->getPrefixedText() . "]]";
1629 $found = true;
1634 # Recursive parsing, escaping and link table handling
1635 # Only for HTML output
1636 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1637 $text = wfEscapeWikiText( $text );
1638 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1639 # Clean up argument array
1640 $assocArgs = array();
1641 $index = 1;
1642 foreach( $args as $arg ) {
1643 $eqpos = strpos( $arg, "=" );
1644 if ( $eqpos === false ) {
1645 $assocArgs[$index++] = $arg;
1646 } else {
1647 $name = trim( substr( $arg, 0, $eqpos ) );
1648 $value = trim( substr( $arg, $eqpos+1 ) );
1649 if ( $value === false ) {
1650 $value = "";
1652 if ( $name !== false ) {
1653 $assocArgs[$name] = $value;
1658 # Do not enter included links in link table
1659 if ( !is_null( $title ) ) {
1660 $wgLinkCache->suspend();
1663 # Run full parser on the included text
1664 $text = $this->stripParse( $text, $newline, $assocArgs );
1666 # Resume the link cache and register the inclusion as a link
1667 if ( !is_null( $title ) ) {
1668 $wgLinkCache->resume();
1669 $wgLinkCache->addLinkObj( $title );
1673 if ( !$found ) {
1674 return $matches[0];
1675 } else {
1676 return $text;
1680 # Triple brace replacement -- used for template arguments
1681 function argSubstitution( $matches )
1683 $newline = $matches[1];
1684 $arg = trim( $matches[2] );
1685 $text = $matches[0];
1686 $inputArgs = end( $this->mArgStack );
1688 if ( array_key_exists( $arg, $inputArgs ) ) {
1689 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1692 return $text;
1695 # Returns true if the function is allowed to include this entity
1696 function incrementIncludeCount( $dbk )
1698 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1699 $this->mIncludeCount[$dbk] = 0;
1701 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1702 return true;
1703 } else {
1704 return false;
1709 # Cleans up HTML, removes dangerous tags and attributes
1710 /* private */ function removeHTMLtags( $text )
1712 global $wgUseTidy, $wgUserHtml;
1713 $fname = "Parser::removeHTMLtags";
1714 wfProfileIn( $fname );
1716 if( $wgUserHtml ) {
1717 $htmlpairs = array( # Tags that must be closed
1718 "b", "del", "i", "ins", "u", "font", "big", "small", "sub", "sup", "h1",
1719 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1720 "strike", "strong", "tt", "var", "div", "center",
1721 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1722 "ruby", "rt" , "rb" , "rp", "p"
1724 $htmlsingle = array(
1725 "br", "hr", "li", "dt", "dd"
1727 $htmlnest = array( # Tags that can be nested--??
1728 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1729 "dl", "font", "big", "small", "sub", "sup"
1731 $tabletags = array( # Can only appear inside table
1732 "td", "th", "tr"
1734 } else {
1735 $htmlpairs = array();
1736 $htmlsingle = array();
1737 $htmlnest = array();
1738 $tabletags = array();
1741 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1742 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1744 $htmlattrs = $this->getHTMLattrs () ;
1746 # Remove HTML comments
1747 $text = preg_replace( "/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU", "$2", $text );
1749 $bits = explode( "<", $text );
1750 $text = array_shift( $bits );
1751 if(!$wgUseTidy) {
1752 $tagstack = array(); $tablestack = array();
1753 foreach ( $bits as $x ) {
1754 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1755 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1756 $x, $regs );
1757 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1758 error_reporting( $prev );
1760 $badtag = 0 ;
1761 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1762 # Check our stack
1763 if ( $slash ) {
1764 # Closing a tag...
1765 if ( ! in_array( $t, $htmlsingle ) &&
1766 ( $ot = @array_pop( $tagstack ) ) != $t ) {
1767 @array_push( $tagstack, $ot );
1768 $badtag = 1;
1769 } else {
1770 if ( $t == "table" ) {
1771 $tagstack = array_pop( $tablestack );
1773 $newparams = "";
1775 } else {
1776 # Keep track for later
1777 if ( in_array( $t, $tabletags ) &&
1778 ! in_array( "table", $tagstack ) ) {
1779 $badtag = 1;
1780 } else if ( in_array( $t, $tagstack ) &&
1781 ! in_array ( $t , $htmlnest ) ) {
1782 $badtag = 1 ;
1783 } else if ( ! in_array( $t, $htmlsingle ) ) {
1784 if ( $t == "table" ) {
1785 array_push( $tablestack, $tagstack );
1786 $tagstack = array();
1788 array_push( $tagstack, $t );
1790 # Strip non-approved attributes from the tag
1791 $newparams = $this->fixTagAttributes($params);
1794 if ( ! $badtag ) {
1795 $rest = str_replace( ">", "&gt;", $rest );
1796 $text .= "<$slash$t $newparams$brace$rest";
1797 continue;
1800 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1802 # Close off any remaining tags
1803 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1804 $text .= "</$t>\n";
1805 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1807 } else {
1808 # this might be possible using tidy itself
1809 foreach ( $bits as $x ) {
1810 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1811 $x, $regs );
1812 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1813 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1814 $newparams = $this->fixTagAttributes($params);
1815 $rest = str_replace( ">", "&gt;", $rest );
1816 $text .= "<$slash$t $newparams$brace$rest";
1817 } else {
1818 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1822 wfProfileOut( $fname );
1823 return $text;
1829 * This function accomplishes several tasks:
1830 * 1) Auto-number headings if that option is enabled
1831 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1832 * 3) Add a Table of contents on the top for users who have enabled the option
1833 * 4) Auto-anchor headings
1835 * It loops through all headlines, collects the necessary data, then splits up the
1836 * string and re-inserts the newly formatted headlines.
1840 /* private */ function formatHeadings( $text, $isMain=true )
1842 global $wgInputEncoding;
1844 $doNumberHeadings = $this->mOptions->getNumberHeadings();
1845 $doShowToc = $this->mOptions->getShowToc();
1846 if( !$this->mTitle->userCanEdit() ) {
1847 $showEditLink = 0;
1848 $rightClickHack = 0;
1849 } else {
1850 $showEditLink = $this->mOptions->getEditSection();
1851 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
1854 # Inhibit editsection links if requested in the page
1855 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1856 if( $esw->matchAndRemove( $text ) ) {
1857 $showEditLink = 0;
1859 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1860 # do not add TOC
1861 $mw =& MagicWord::get( MAG_NOTOC );
1862 if( $mw->matchAndRemove( $text ) ) {
1863 $doShowToc = 0;
1866 # never add the TOC to the Main Page. This is an entry page that should not
1867 # be more than 1-2 screens large anyway
1868 if( $this->mTitle->getPrefixedText() == wfMsg("mainpage") ) {
1869 $doShowToc = 0;
1872 # Get all headlines for numbering them and adding funky stuff like [edit]
1873 # links - this is for later, but we need the number of headlines right now
1874 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1876 # if there are fewer than 4 headlines in the article, do not show TOC
1877 if( $numMatches < 4 ) {
1878 $doShowToc = 0;
1881 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1882 # override above conditions and always show TOC
1883 $mw =& MagicWord::get( MAG_FORCETOC );
1884 if ($mw->matchAndRemove( $text ) ) {
1885 $doShowToc = 1;
1889 # We need this to perform operations on the HTML
1890 $sk =& $this->mOptions->getSkin();
1892 # headline counter
1893 $headlineCount = 0;
1895 # Ugh .. the TOC should have neat indentation levels which can be
1896 # passed to the skin functions. These are determined here
1897 $toclevel = 0;
1898 $toc = "";
1899 $full = "";
1900 $head = array();
1901 $sublevelCount = array();
1902 $level = 0;
1903 $prevlevel = 0;
1904 foreach( $matches[3] as $headline ) {
1905 $numbering = "";
1906 if( $level ) {
1907 $prevlevel = $level;
1909 $level = $matches[1][$headlineCount];
1910 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
1911 # reset when we enter a new level
1912 $sublevelCount[$level] = 0;
1913 $toc .= $sk->tocIndent( $level - $prevlevel );
1914 $toclevel += $level - $prevlevel;
1916 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
1917 # reset when we step back a level
1918 $sublevelCount[$level+1]=0;
1919 $toc .= $sk->tocUnindent( $prevlevel - $level );
1920 $toclevel -= $prevlevel - $level;
1922 # count number of headlines for each level
1923 @$sublevelCount[$level]++;
1924 if( $doNumberHeadings || $doShowToc ) {
1925 $dot = 0;
1926 for( $i = 1; $i <= $level; $i++ ) {
1927 if( !empty( $sublevelCount[$i] ) ) {
1928 if( $dot ) {
1929 $numbering .= ".";
1931 $numbering .= $sublevelCount[$i];
1932 $dot = 1;
1937 # The canonized header is a version of the header text safe to use for links
1938 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1939 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
1940 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
1942 # strip out HTML
1943 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1944 $tocline = trim( $canonized_headline );
1945 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
1946 $replacearray = array(
1947 '%3A' => ':',
1948 '%' => '.'
1950 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
1951 $refer[$headlineCount] = $canonized_headline;
1953 # count how many in assoc. array so we can track dupes in anchors
1954 @$refers[$canonized_headline]++;
1955 $refcount[$headlineCount]=$refers[$canonized_headline];
1957 # Prepend the number to the heading text
1959 if( $doNumberHeadings || $doShowToc ) {
1960 $tocline = $numbering . " " . $tocline;
1962 # Don't number the heading if it is the only one (looks silly)
1963 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1964 # the two are different if the line contains a link
1965 $headline=$numbering . " " . $headline;
1969 # Create the anchor for linking from the TOC to the section
1970 $anchor = $canonized_headline;
1971 if($refcount[$headlineCount] > 1 ) {
1972 $anchor .= "_" . $refcount[$headlineCount];
1974 if( $doShowToc ) {
1975 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1977 if( $showEditLink ) {
1978 if ( empty( $head[$headlineCount] ) ) {
1979 $head[$headlineCount] = "";
1981 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
1984 # Add the edit section span
1985 if( $rightClickHack ) {
1986 $headline = $sk->editSectionScript($headlineCount+1,$headline);
1989 # give headline the correct <h#> tag
1990 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1992 $headlineCount++;
1995 if( $doShowToc ) {
1996 $toclines = $headlineCount;
1997 $toc .= $sk->tocUnindent( $toclevel );
1998 $toc = $sk->tocTable( $toc );
2001 # split up and insert constructed headlines
2003 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
2004 $i = 0;
2006 foreach( $blocks as $block ) {
2007 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2008 # This is the [edit] link that appears for the top block of text when
2009 # section editing is enabled
2011 # Disabled because it broke block formatting
2012 # For example, a bullet point in the top line
2013 # $full .= $sk->editSectionLink(0);
2015 $full .= $block;
2016 if( $doShowToc && !$i && $isMain) {
2017 # Top anchor now in skin
2018 $full = $full.$toc;
2021 if( !empty( $head[$i] ) ) {
2022 $full .= $head[$i];
2024 $i++;
2027 return $full;
2030 # Return an HTML link for the "ISBN 123456" text
2031 /* private */ function magicISBN( $text )
2033 global $wgLang;
2035 $a = split( "ISBN ", " $text" );
2036 if ( count ( $a ) < 2 ) return $text;
2037 $text = substr( array_shift( $a ), 1);
2038 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2040 foreach ( $a as $x ) {
2041 $isbn = $blank = "" ;
2042 while ( " " == $x{0} ) {
2043 $blank .= " ";
2044 $x = substr( $x, 1 );
2046 while ( strstr( $valid, $x{0} ) != false ) {
2047 $isbn .= $x{0};
2048 $x = substr( $x, 1 );
2050 $num = str_replace( "-", "", $isbn );
2051 $num = str_replace( " ", "", $num );
2053 if ( "" == $num ) {
2054 $text .= "ISBN $blank$x";
2055 } else {
2056 $titleObj = Title::makeTitle( NS_SPECIAL, "Booksources" );
2057 $text .= "<a href=\"" .
2058 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2059 "\" class=\"internal\">ISBN $isbn</a>";
2060 $text .= $x;
2063 return $text;
2066 # Return an HTML link for the "RFC 1234" text
2067 /* private */ function magicRFC( $text )
2069 global $wgLang;
2071 $a = split( "RFC ", " $text" );
2072 if ( count ( $a ) < 2 ) return $text;
2073 $text = substr( array_shift( $a ), 1);
2074 $valid = "0123456789";
2076 foreach ( $a as $x ) {
2077 $rfc = $blank = "" ;
2078 while ( " " == $x{0} ) {
2079 $blank .= " ";
2080 $x = substr( $x, 1 );
2082 while ( strstr( $valid, $x{0} ) != false ) {
2083 $rfc .= $x{0};
2084 $x = substr( $x, 1 );
2087 if ( "" == $rfc ) {
2088 $text .= "RFC $blank$x";
2089 } else {
2090 $url = wfmsg( "rfcurl" );
2091 $url = str_replace( "$1", $rfc, $url);
2092 $sk =& $this->mOptions->getSkin();
2093 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2094 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2097 return $text;
2100 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
2102 $this->mOptions = $options;
2103 $this->mTitle =& $title;
2104 $this->mOutputType = OT_WIKI;
2106 if ( $clearState ) {
2107 $this->clearState();
2110 $stripState = false;
2111 $pairs = array(
2112 "\r\n" => "\n",
2114 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2115 // now with regexes
2117 $pairs = array(
2118 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2119 "/<br *?>/i" => "<br />",
2121 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2123 $text = $this->strip( $text, $stripState, false );
2124 $text = $this->pstPass2( $text, $user );
2125 $text = $this->unstrip( $text, $stripState );
2126 $text = $this->unstripNoWiki( $text, $stripState );
2127 return $text;
2130 /* private */ function pstPass2( $text, &$user )
2132 global $wgLang, $wgLocaltimezone, $wgCurParser;
2134 # Variable replacement
2135 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2136 $text = $this->replaceVariables( $text );
2138 # Signatures
2140 $n = $user->getName();
2141 $k = $user->getOption( "nickname" );
2142 if ( "" == $k ) { $k = $n; }
2143 if(isset($wgLocaltimezone)) {
2144 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
2146 /* Note: this is an ugly timezone hack for the European wikis */
2147 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
2148 " (" . date( "T" ) . ")";
2149 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
2151 $text = preg_replace( "/~~~~~/", $d, $text );
2152 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
2153 Namespace::getUser() ) . ":$n|$k]] $d", $text );
2154 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
2155 Namespace::getUser() ) . ":$n|$k]]", $text );
2157 # Context links: [[|name]] and [[name (context)|]]
2159 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2160 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2161 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2162 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2164 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2165 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2166 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2167 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2168 # [[ns:page (cont)|]]
2169 $context = "";
2170 $t = $this->mTitle->getText();
2171 if ( preg_match( $conpat, $t, $m ) ) {
2172 $context = $m[2];
2174 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
2175 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
2176 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
2178 if ( "" == $context ) {
2179 $text = preg_replace( $p2, "[[\\1]]", $text );
2180 } else {
2181 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2185 $mw =& MagicWord::get( MAG_SUBST );
2186 $wgCurParser = $this->fork();
2187 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2188 $this->merge( $wgCurParser );
2191 # Trim trailing whitespace
2192 # MAG_END (__END__) tag allows for trailing
2193 # whitespace to be deliberately included
2194 $text = rtrim( $text );
2195 $mw =& MagicWord::get( MAG_END );
2196 $mw->matchAndRemove( $text );
2198 return $text;
2201 # Set up some variables which are usually set up in parse()
2202 # so that an external function can call some class members with confidence
2203 function startExternalParse( &$title, $options, $outputType, $clearState = true )
2205 $this->mTitle =& $title;
2206 $this->mOptions = $options;
2207 $this->mOutputType = $outputType;
2208 if ( $clearState ) {
2209 $this->clearState();
2213 function transformMsg( $text, $options ) {
2214 global $wgTitle;
2215 static $executing = false;
2217 # Guard against infinite recursion
2218 if ( $executing ) {
2219 return $text;
2221 $executing = true;
2223 $this->mTitle = $wgTitle;
2224 $this->mOptions = $options;
2225 $this->mOutputType = OT_MSG;
2226 $this->clearState();
2227 $text = $this->replaceVariables( $text );
2229 $executing = false;
2230 return $text;
2234 class ParserOutput
2236 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2237 var $mCacheTime; # Used in ParserCache
2239 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2240 $containsOldMagic = false )
2242 $this->mText = $text;
2243 $this->mLanguageLinks = $languageLinks;
2244 $this->mCategoryLinks = $categoryLinks;
2245 $this->mContainsOldMagic = $containsOldMagic;
2246 $this->mCacheTime = "";
2249 function getText() { return $this->mText; }
2250 function getLanguageLinks() { return $this->mLanguageLinks; }
2251 function getCategoryLinks() { return $this->mCategoryLinks; }
2252 function getCacheTime() { return $this->mCacheTime; }
2253 function containsOldMagic() { return $this->mContainsOldMagic; }
2254 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2255 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2256 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2257 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2258 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2260 function merge( $other ) {
2261 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2262 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2263 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2268 class ParserOptions
2270 # All variables are private
2271 var $mUseTeX; # Use texvc to expand <math> tags
2272 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2273 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2274 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2275 var $mAllowExternalImages; # Allow external images inline
2276 var $mSkin; # Reference to the preferred skin
2277 var $mDateFormat; # Date format index
2278 var $mEditSection; # Create "edit section" links
2279 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2280 var $mNumberHeadings; # Automatically number headings
2281 var $mShowToc; # Show table of contents
2283 function getUseTeX() { return $this->mUseTeX; }
2284 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
2285 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2286 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2287 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2288 function getSkin() { return $this->mSkin; }
2289 function getDateFormat() { return $this->mDateFormat; }
2290 function getEditSection() { return $this->mEditSection; }
2291 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2292 function getNumberHeadings() { return $this->mNumberHeadings; }
2293 function getShowToc() { return $this->mShowToc; }
2295 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2296 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
2297 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2298 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2299 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2300 function setSkin( $x ) { return wfSetRef( $this->mSkin, $x ); }
2301 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2302 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2303 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2304 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2305 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2307 /* static */ function newFromUser( &$user )
2309 $popts = new ParserOptions;
2310 $popts->initialiseFromUser( $user );
2311 return $popts;
2314 function initialiseFromUser( &$userInput )
2316 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2318 if ( !$userInput ) {
2319 $user = new User;
2320 $user->setLoaded( true );
2321 } else {
2322 $user =& $userInput;
2325 $this->mUseTeX = $wgUseTeX;
2326 $this->mUseCategoryMagic = $wgUseCategoryMagic;
2327 $this->mUseDynamicDates = $wgUseDynamicDates;
2328 $this->mInterwikiMagic = $wgInterwikiMagic;
2329 $this->mAllowExternalImages = $wgAllowExternalImages;
2330 $this->mSkin =& $user->getSkin();
2331 $this->mDateFormat = $user->getOption( "date" );
2332 $this->mEditSection = $user->getOption( "editsection" );
2333 $this->mEditSectionOnRightClick = $user->getOption( "editsectiononrightclick" );
2334 $this->mNumberHeadings = $user->getOption( "numberheadings" );
2335 $this->mShowToc = $user->getOption( "showtoc" );
2341 # Regex callbacks, used in Parser::replaceVariables
2342 function wfBraceSubstitution( $matches )
2344 global $wgCurParser;
2345 return $wgCurParser->braceSubstitution( $matches );
2348 function wfArgSubstitution( $matches )
2350 global $wgCurParser;
2351 return $wgCurParser->argSubstitution( $matches );
2354 function wfVariableSubstitution( $matches )
2356 global $wgCurParser;
2357 return $wgCurParser->variableSubstitution( $matches );