A few language files from some of the larger Wikipedias, extracted from the MediaWiki...
[mediawiki.git] / includes / Parser.php
blob5d6a7c7bcc94e6aecc81a4c6004b244fafba8e1d
1 <?php
3 // require_once('Tokenizer.php');
5 # PHP Parser
7 # Processes wiki markup
9 # There are two main entry points into the Parser class: parse() and preSaveTransform().
10 # The parse() function produces HTML output, preSaveTransform() produces altered wiki markup.
12 # Globals used:
13 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
15 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
17 # settings: $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
18 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
19 # $wgLocaltimezone
21 # * only within ParserOptions
24 #----------------------------------------
25 # Variable substitution O(N^2) attack
26 #-----------------------------------------
27 # Without countermeasures, it would be possible to attack the parser by saving a page
28 # filled with a large number of inclusions of large pages. The size of the generated
29 # page would be proportional to the square of the input size. Hence, we limit the number
30 # of inclusions of any given page, thus bringing any attack back to O(N).
33 define( "MAX_INCLUDE_REPEAT", 5 );
35 # Allowed values for $mOutputType
36 define( "OT_HTML", 1 );
37 define( "OT_WIKI", 2 );
38 define( "OT_MSG", 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( "STRIP_COMMENTS", "HTMLCommentStrip" );
46 # prefix for escaping, used in two functions at least
47 define( "UNIQ_PREFIX", "NaodW29");
49 class Parser
51 # Persistent:
52 var $mTagHooks;
54 # Cleared with clearState():
55 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
56 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
58 # Temporary:
59 var $mOptions, $mTitle, $mOutputType;
61 function Parser() {
62 $this->mTagHooks = array();
63 $this->clearState();
66 function clearState() {
67 $this->mOutput = new ParserOutput;
68 $this->mAutonumber = 0;
69 $this->mLastSection = "";
70 $this->mDTopen = false;
71 $this->mVariables = false;
72 $this->mIncludeCount = array();
73 $this->mStripState = array();
74 $this->mArgStack = array();
75 $this->mInPre = false;
78 # First pass--just handle <nowiki> sections, pass the rest off
79 # to internalParse() which does all the real work.
81 # Returns a ParserOutput
83 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
84 global $wgUseTidy;
85 $fname = "Parser::parse";
86 wfProfileIn( $fname );
88 if ( $clearState ) {
89 $this->clearState();
92 $this->mOptions = $options;
93 $this->mTitle =& $title;
94 $this->mOutputType = OT_HTML;
96 $stripState = NULL;
97 $text = $this->strip( $text, $this->mStripState );
98 $text = $this->internalParse( $text, $linestart );
99 $text = $this->unstrip( $text, $this->mStripState );
100 # Clean up special characters, only run once, next-to-last before doBlockLevels
101 if(!$wgUseTidy) {
102 $fixtags = array(
103 # french spaces, last one Guillemet-left
104 # only if there is something before the space
105 '/(.) (\\?|:|!|\\302\\273)/i' => '\\1&nbsp;\\2',
106 # french spaces, Guillemet-right
107 "/(\\302\\253) /i"=>"\\1&nbsp;",
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]+;)/' => '&amp;'
116 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
117 } else {
118 $fixtags = array(
119 # french spaces, last one Guillemet-left
120 '/ (\\?|:|!|\\302\\273)/i' => '&nbsp;\\1',
121 # french spaces, Guillemet-right
122 '/(\\302\\253) /i' => '\\1&nbsp;',
123 '/<center *>/i' => '<div class="center">',
124 '/<\\/center *>/i' => '</div>'
126 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
128 # only once and last
129 $text = $this->doBlockLevels( $text, $linestart );
130 $text = $this->unstripNoWiki( $text, $this->mStripState );
131 if($wgUseTidy) {
132 $text = $this->tidy($text);
134 $this->mOutput->setText( $text );
135 wfProfileOut( $fname );
136 return $this->mOutput;
139 /* static */ function getRandomString() {
140 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
143 # Replaces all occurrences of <$tag>content</$tag> in the text
144 # with a random marker and returns the new text. the output parameter
145 # $content will be an associative array filled with data on the form
146 # $unique_marker => content.
148 # If $content is already set, the additional entries will be appended
150 # If $tag is set to STRIP_COMMENTS, the function will extract
151 # <!-- HTML comments -->
153 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
154 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
155 if ( !$content ) {
156 $content = array( );
158 $n = 1;
159 $stripped = '';
161 while ( '' != $text ) {
162 if($tag==STRIP_COMMENTS) {
163 $p = preg_split( '/<!--/i', $text, 2 );
164 } else {
165 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
167 $stripped .= $p[0];
168 if ( ( count( $p ) < 2 ) || ( '' == $p[1] ) ) {
169 $text = '';
170 } else {
171 if($tag==STRIP_COMMENTS) {
172 $q = preg_split( '/-->/i', $p[1], 2 );
173 } else {
174 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
176 $marker = $rnd . sprintf('%08X', $n++);
177 $content[$marker] = $q[0];
178 $stripped .= $marker;
179 $text = $q[1];
182 return $stripped;
185 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
186 # If $render is set, performs necessary rendering operations on plugins
187 # Returns the text, and fills an array with data needed in unstrip()
188 # If the $state is already a valid strip state, it adds to the state
190 # When $stripcomments is set, HTML comments <!-- like this -->
191 # will be stripped in addition to other tags. This is important
192 # for section editing, where these comments cause confusion when
193 # counting the sections in the wikisource
194 function strip( $text, &$state, $stripcomments = false ) {
195 $render = ($this->mOutputType == OT_HTML);
196 $nowiki_content = array();
197 $math_content = array();
198 $pre_content = array();
199 $comment_content = array();
200 $ext_content = array();
202 # Replace any instances of the placeholders
203 $uniq_prefix = UNIQ_PREFIX;
204 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
207 # nowiki
208 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
209 foreach( $nowiki_content as $marker => $content ){
210 if( $render ){
211 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
212 } else {
213 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
217 # math
218 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
219 foreach( $math_content as $marker => $content ){
220 if( $render ) {
221 if( $this->mOptions->getUseTeX() ) {
222 $math_content[$marker] = renderMath( $content );
223 } else {
224 $math_content[$marker] = "&lt;math&gt;$content&lt;math&gt;";
226 } else {
227 $math_content[$marker] = "<math>$content</math>";
231 # pre
232 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
233 foreach( $pre_content as $marker => $content ){
234 if( $render ){
235 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
236 } else {
237 $pre_content[$marker] = "<pre>$content</pre>";
241 # Comments
242 if($stripcomments) {
243 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
244 foreach( $comment_content as $marker => $content ){
245 $comment_content[$marker] = "<!--$content-->";
249 # Extensions
250 foreach ( $this->mTagHooks as $tag => $callback ) {
251 $ext_contents[$tag] = array();
252 $text = Parser::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
253 foreach( $ext_content[$tag] as $marker => $content ) {
254 if ( $render ) {
255 $ext_content[$tag][$marker] = $callback( $content );
256 } else {
257 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
262 # Merge state with the pre-existing state, if there is one
263 if ( $state ) {
264 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
265 $state['math'] = $state['math'] + $math_content;
266 $state['pre'] = $state['pre'] + $pre_content;
267 $state['comment'] = $state['comment'] + $comment_content;
269 foreach( $ext_content as $tag => $array ) {
270 if ( array_key_exists( $tag, $state ) ) {
271 $state[$tag] = $state[$tag] + $array;
274 } else {
275 $state = array(
276 'nowiki' => $nowiki_content,
277 'math' => $math_content,
278 'pre' => $pre_content,
279 'comment' => $comment_content,
280 ) + $ext_content;
282 return $text;
285 # always call unstripNoWiki() after this one
286 function unstrip( $text, &$state ) {
287 # Must expand in reverse order, otherwise nested tags will be corrupted
288 $contentDict = end( $state );
289 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
290 if( key($state) != 'nowiki') {
291 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
292 $text = str_replace( key( $contentDict ), $content, $text );
297 return $text;
299 # always call this after unstrip() to preserve the order
300 function unstripNoWiki( $text, &$state ) {
301 # Must expand in reverse order, otherwise nested tags will be corrupted
302 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
303 $text = str_replace( key( $state['nowiki'] ), $content, $text );
306 return $text;
309 # Add an item to the strip state
310 # Returns the unique tag which must be inserted into the stripped text
311 # The tag will be replaced with the original text in unstrip()
313 function insertStripItem( $text, &$state ) {
314 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
315 if ( !$state ) {
316 $state = array(
317 'nowiki' => array(),
318 'math' => array(),
319 'pre' => array()
322 $state['item'][$rnd] = $text;
323 return $rnd;
326 # categoryMagic
327 # generate a list of subcategories and pages for a category
328 # depending on wfMsg("usenewcategorypage") it either calls the new
329 # or the old code. The new code will not work properly for some
330 # languages due to sorting issues, so they might want to turn it
331 # off.
332 function categoryMagic() {
333 $msg = wfMsg('usenewcategorypage');
334 if ( '0' == @$msg[0] )
336 return $this->oldCategoryMagic();
337 } else {
338 return $this->newCategoryMagic();
342 # This method generates the list of subcategories and pages for a category
343 function oldCategoryMagic () {
344 global $wgLang , $wgUser ;
345 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
347 $cns = Namespace::getCategory() ;
348 if ( $this->mTitle->getNamespace() != $cns ) return "" ; # This ain't a category page
350 $r = "<br style=\"clear:both;\"/>\n";
353 $sk =& $wgUser->getSkin() ;
355 $articles = array() ;
356 $children = array() ;
357 $data = array () ;
358 $id = $this->mTitle->getArticleID() ;
360 # FIXME: add limits
361 $t = wfStrencode( $this->mTitle->getDBKey() );
362 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM cur,categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
363 $res = wfQuery ( $sql, DB_READ ) ;
364 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
366 # For all pages that link to this category
367 foreach ( $data AS $x )
369 $t = $wgLang->getNsText ( $x->cur_namespace ) ;
370 if ( $t != "" ) $t .= ":" ;
371 $t .= $x->cur_title ;
373 if ( $x->cur_namespace == $cns ) {
374 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
375 } else {
376 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
379 wfFreeResult ( $res ) ;
381 # Showing subcategories
382 if ( count ( $children ) > 0 ) {
383 $r .= '<h2>'.wfMsg('subcategories')."</h2>\n" ;
384 $r .= implode ( ', ' , $children ) ;
387 # Showing pages in this category
388 if ( count ( $articles ) > 0 ) {
389 $ti = $this->mTitle->getText() ;
390 $h = wfMsg( 'category_header', $ti );
391 $r .= "<h2>{$h}</h2>\n" ;
392 $r .= implode ( ', ' , $articles ) ;
396 return $r ;
401 function newCategoryMagic () {
402 global $wgLang , $wgUser ;
403 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
405 $cns = Namespace::getCategory() ;
406 if ( $this->mTitle->getNamespace() != $cns ) return '' ; # This ain't a category page
408 $r = "<br style=\"clear:both;\"/>\n";
411 $sk =& $wgUser->getSkin() ;
413 $articles = array() ;
414 $articles_start_char = array();
415 $children = array() ;
416 $children_start_char = array();
417 $data = array () ;
418 $id = $this->mTitle->getArticleID() ;
420 # FIXME: add limits
421 $t = wfStrencode( $this->mTitle->getDBKey() );
422 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM
423 cur,categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY
424 cl_sortkey" ;
425 $res = wfQuery ( $sql, DB_READ ) ;
426 while ( $x = wfFetchObject ( $res ) )
428 $t = $ns = $wgLang->getNsText ( $x->cur_namespace ) ;
429 if ( $t != '' ) $t .= ':' ;
430 $t .= $x->cur_title ;
432 if ( $x->cur_namespace == $cns ) {
433 $ctitle = str_replace( '_',' ',$x->cur_title );
434 array_push ( $children, $sk->makeKnownLink ( $t, $ctitle ) ) ; # Subcategory
436 // If there's a link from Category:A to Category:B, the sortkey of the resulting
437 // entry in the categorylinks table is Category:A, not A, which it SHOULD be.
438 // Workaround: If sortkey == "Category:".$title, than use $title for sorting,
439 // else use sortkey...
440 if ( ($ns.":".$ctitle) == $x->cl_sortkey ) {
441 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title ) );
442 } else {
443 array_push ( $children_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
445 } else {
446 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
447 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
450 wfFreeResult ( $res ) ;
452 $ti = $this->mTitle->getText() ;
454 # Don't show subcategories section if there are none.
455 if ( count ( $children ) > 0 )
457 # Showing subcategories
458 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n"
459 . wfMsg( 'subcategorycount', count( $children ) );
460 if ( count ( $children ) > 6 ) {
462 // divide list into three equal chunks
463 $chunk = (int) (count ( $children ) / 3);
465 // get and display header
466 $r .= '<table width="100%"><tr valign="top">';
468 $startChunk = 0;
469 $endChunk = $chunk;
471 // loop through the chunks
472 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
473 $chunkIndex < 3;
474 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
477 $r .= '<td><ul>';
478 // output all subcategories to category
479 for ($index = $startChunk ;
480 $index < $endChunk && $index < count($children);
481 $index++ )
483 // check for change of starting letter or begging of chunk
484 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
485 || ($index == $startChunk) )
487 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
490 $r .= "<li>{$children[$index]}</li>";
492 $r .= '</ul></td>';
496 $r .= '</tr></table>';
497 } else {
498 // for short lists of subcategories to category.
500 $r .= "<h3>{$children_start_char[0]}</h3>\n";
501 $r .= '<ul><li>'.$children[0].'</li>';
502 for ($index = 1; $index < count($children); $index++ )
504 if ($children_start_char[$index] != $children_start_char[$index - 1])
506 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
509 $r .= "<li>{$children[$index]}</li>";
511 $r .= '</ul>';
513 } # END of if ( count($children) > 0 )
515 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n" .
516 wfMsg( 'categoryarticlecount', count( $articles ) );
518 # Showing articles in this category
519 if ( count ( $articles ) > 6) {
520 $ti = $this->mTitle->getText() ;
522 // divide list into three equal chunks
523 $chunk = (int) (count ( $articles ) / 3);
525 // get and display header
526 $r .= '<table width="100%"><tr valign="top">';
528 // loop through the chunks
529 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
530 $chunkIndex < 3;
531 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
534 $r .= '<td><ul>';
536 // output all articles in category
537 for ($index = $startChunk ;
538 $index < $endChunk && $index < count($articles);
539 $index++ )
541 // check for change of starting letter or begging of chunk
542 if ( ($articles_start_char[$index] != $articles_start_char[$index - 1])
543 || ($index == $startChunk) )
545 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
548 $r .= "<li>{$articles[$index]}</li>";
550 $r .= '</ul></td>';
554 $r .= '</tr></table>';
555 } elseif ( count ( $articles ) > 0) {
556 // for short lists of articles in categories.
557 $ti = $this->mTitle->getText() ;
559 $r .= '<h3>'.$articles_start_char[0]."</h3>\n";
560 $r .= '<ul><li>'.$articles[0].'</li>';
561 for ($index = 1; $index < count($articles); $index++ )
563 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
565 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
568 $r .= "<li>{$articles[$index]}</li>";
570 $r .= '</ul>';
574 return $r ;
577 # Return allowed HTML attributes
578 function getHTMLattrs () {
579 $htmlattrs = array( # Allowed attributes--no scripting, etc.
580 'title', 'align', 'lang', 'dir', 'width', 'height',
581 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
582 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
583 /* FONT */ 'type', 'start', 'value', 'compact',
584 /* For various lists, mostly deprecated but safe */
585 'summary', 'width', 'border', 'frame', 'rules',
586 'cellspacing', 'cellpadding', 'valign', 'char',
587 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
588 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
589 'id', 'class', 'name', 'style' /* For CSS */
591 return $htmlattrs ;
594 # Remove non approved attributes and javascript in css
595 function fixTagAttributes ( $t ) {
596 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
597 $htmlattrs = $this->getHTMLattrs() ;
599 # Strip non-approved attributes from the tag
600 $t = preg_replace(
601 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
602 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
603 $t);
604 # Strip javascript "expression" from stylesheets. Brute force approach:
605 # If anythin offensive is found, all attributes of the HTML tag are dropped
607 if( preg_match(
608 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
609 wfMungeToUtf8( $t ) ) )
611 $t='';
614 return trim ( $t ) ;
617 # interface with html tidy, used if $wgUseTidy = true
618 function tidy ( $text ) {
619 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
620 global $wgInputEncoding, $wgOutputEncoding;
621 $fname = 'Parser::tidy';
622 wfProfileIn( $fname );
624 $cleansource = '';
625 switch(strtoupper($wgOutputEncoding)) {
626 case 'ISO-8859-1':
627 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
628 break;
629 case 'UTF-8':
630 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
631 break;
632 default:
633 $wgTidyOpts .= ' -raw';
636 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
637 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
638 '<head><title>test</title></head><body>'.$text.'</body></html>';
639 $descriptorspec = array(
640 0 => array('pipe', 'r'),
641 1 => array('pipe', 'w'),
642 2 => array('file', '/dev/null', 'a')
644 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
645 if (is_resource($process)) {
646 fwrite($pipes[0], $wrappedtext);
647 fclose($pipes[0]);
648 while (!feof($pipes[1])) {
649 $cleansource .= fgets($pipes[1], 1024);
651 fclose($pipes[1]);
652 $return_value = proc_close($process);
655 wfProfileOut( $fname );
657 if( $cleansource == '' && $text != '') {
658 wfDebug( "Tidy error detected!\n" );
659 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
660 } else {
661 return $cleansource;
665 # parse the wiki syntax used to render tables
666 function doTableStuff ( $t ) {
667 $t = explode ( "\n" , $t ) ;
668 $td = array () ; # Is currently a td tag open?
669 $ltd = array () ; # Was it TD or TH?
670 $tr = array () ; # Is currently a tr tag open?
671 $ltr = array () ; # tr attributes
672 foreach ( $t AS $k => $x )
674 $x = trim ( $x ) ;
675 $fc = substr ( $x , 0 , 1 ) ;
676 if ( '{|' == substr ( $x , 0 , 2 ) )
678 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . '>' ;
679 array_push ( $td , false ) ;
680 array_push ( $ltd , '' ) ;
681 array_push ( $tr , false ) ;
682 array_push ( $ltr , '' ) ;
684 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
685 else if ( '|}' == substr ( $x , 0 , 2 ) )
687 $z = "</table>\n" ;
688 $l = array_pop ( $ltd ) ;
689 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
690 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
691 array_pop ( $ltr ) ;
692 $t[$k] = $z ;
694 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
696 $z = trim ( substr ( $x , 2 ) ) ;
697 $t[$k] = "<caption>{$z}</caption>\n" ;
699 else if ( '|-' == substr ( $x , 0 , 2 ) ) # Allows for |---------------
701 $x = substr ( $x , 1 ) ;
702 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
703 $z = '' ;
704 $l = array_pop ( $ltd ) ;
705 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
706 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
707 array_pop ( $ltr ) ;
708 $t[$k] = $z ;
709 array_push ( $tr , false ) ;
710 array_push ( $td , false ) ;
711 array_push ( $ltd , '' ) ;
712 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
714 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) # Caption
716 if ( '|+' == substr ( $x , 0 , 2 ) )
718 $fc = '+' ;
719 $x = substr ( $x , 1 ) ;
721 $after = substr ( $x , 1 ) ;
722 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
723 $after = explode ( '||' , $after ) ;
724 $t[$k] = '' ;
725 foreach ( $after AS $theline )
727 $z = '' ;
728 if ( $fc != '+' )
730 $tra = array_pop ( $ltr ) ;
731 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
732 array_push ( $tr , true ) ;
733 array_push ( $ltr , '' ) ;
736 $l = array_pop ( $ltd ) ;
737 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
738 if ( $fc == '|' ) $l = 'td' ;
739 else if ( $fc == '!' ) $l = 'th' ;
740 else if ( $fc == '+' ) $l = 'caption' ;
741 else $l = '' ;
742 array_push ( $ltd , $l ) ;
743 $y = explode ( '|' , $theline , 2 ) ;
744 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
745 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
746 $t[$k] .= $y ;
747 array_push ( $td , true ) ;
752 # Closing open td, tr && table
753 while ( count ( $td ) > 0 )
755 if ( array_pop ( $td ) ) $t[] = '</td>' ;
756 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
757 $t[] = '</table>' ;
760 $t = implode ( "\n" , $t ) ;
761 # $t = $this->removeHTMLtags( $t );
762 return $t ;
765 # Parses the text and adds the result to the strip state
766 # Returns the strip tag
767 function stripParse( $text, $newline, $args )
769 $text = $this->strip( $text, $this->mStripState );
770 $text = $this->internalParse( $text, (bool)$newline, $args, false );
771 return $newline.$this->insertStripItem( $text, $this->mStripState );
774 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
775 $fname = 'Parser::internalParse';
776 wfProfileIn( $fname );
778 $text = $this->removeHTMLtags( $text );
779 $text = $this->replaceVariables( $text, $args );
781 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
783 $text = $this->doHeadings( $text );
784 if($this->mOptions->getUseDynamicDates()) {
785 global $wgDateFormatter;
786 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
788 $text = $this->doAllQuotes( $text );
789 $text = $this->replaceExternalLinks( $text );
790 $text = $this->replaceInternalLinks ( $text );
791 $text = $this->replaceInternalLinks ( $text );
792 //$text = $this->doTokenizedParser ( $text );
793 $text = $this->doTableStuff ( $text ) ;
794 $text = $this->magicISBN( $text );
795 $text = $this->magicRFC( $text );
796 $text = $this->formatHeadings( $text, $isMain );
797 $sk =& $this->mOptions->getSkin();
798 $text = $sk->transformContent( $text );
800 if ( !isset ( $this->categoryMagicDone ) ) {
801 $text .= $this->categoryMagic () ;
802 $this->categoryMagicDone = true ;
805 wfProfileOut( $fname );
806 return $text;
809 # Parse headers and return html
810 /* private */ function doHeadings( $text ) {
811 $fname = 'Parser::doHeadings';
812 wfProfileIn( $fname );
813 for ( $i = 6; $i >= 1; --$i ) {
814 $h = substr( '======', 0, $i );
815 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
816 "<h{$i}>\\1</h{$i}>\\2", $text );
818 wfProfileOut( $fname );
819 return $text;
822 /* private */ function doAllQuotes( $text ) {
823 $fname = 'Parser::doAllQuotes';
824 wfProfileIn( $fname );
825 $outtext = '';
826 $lines = explode( "\n", $text );
827 foreach ( $lines as $line ) {
828 $outtext .= $this->doQuotes ( '', $line, '' ) . "\n";
830 $outtext = substr($outtext, 0,-1);
831 wfProfileOut( $fname );
832 return $outtext;
835 /* private */ function doQuotes( $pre, $text, $mode ) {
836 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
837 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
838 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
839 if ( substr ($m[2], 0, 1) == '\'' ) {
840 $m[2] = substr ($m[2], 1);
841 if ($mode == 'em') {
842 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ? 'both' : 'emstrong' );
843 } else if ($mode == 'strong') {
844 return $m1_strong . $this->doQuotes ( '', $m[2], '' );
845 } else if (($mode == 'emstrong') || ($mode == 'both')) {
846 return $this->doQuotes ( '', $pre.$m1_strong.$m[2], 'em' );
847 } else if ($mode == 'strongem') {
848 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( '', $m[2], 'em' );
849 } else {
850 return $m[1] . $this->doQuotes ( '', $m[2], 'strong' );
852 } else {
853 if ($mode == 'strong') {
854 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ? 'both' : 'strongem' );
855 } else if ($mode == 'em') {
856 return $m1_em . $this->doQuotes ( '', $m[2], '' );
857 } else if ($mode == 'emstrong') {
858 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( '', $m[2], 'strong' );
859 } else if (($mode == 'strongem') || ($mode == 'both')) {
860 return $this->doQuotes ( '', $pre.$m1_em.$m[2], 'strong' );
861 } else {
862 return $m[1] . $this->doQuotes ( '', $m[2], 'em' );
865 } else {
866 $text_strong = ($text == '') ? '' : "<strong>{$text}</strong>";
867 $text_em = ($text == '') ? '' : "<em>{$text}</em>";
868 if ($mode == '') {
869 return $pre . $text;
870 } else if ($mode == 'em') {
871 return $pre . $text_em;
872 } else if ($mode == 'strong') {
873 return $pre . $text_strong;
874 } else if ($mode == 'strongem') {
875 return (($pre == '') && ($text == '')) ? '' : "<strong>{$pre}{$text_em}</strong>";
876 } else {
877 return (($pre == '') && ($text == '')) ? '' : "<em>{$pre}{$text_strong}</em>";
882 # Note: we have to do external links before the internal ones,
883 # and otherwise take great care in the order of things here, so
884 # that we don't end up interpreting some URLs twice.
886 /* private */ function replaceExternalLinks( $text ) {
887 $fname = 'Parser::replaceExternalLinks';
888 wfProfileIn( $fname );
889 $text = $this->subReplaceExternalLinks( $text, 'http', true );
890 $text = $this->subReplaceExternalLinks( $text, 'https', true );
891 $text = $this->subReplaceExternalLinks( $text, 'ftp', false );
892 $text = $this->subReplaceExternalLinks( $text, 'irc', false );
893 $text = $this->subReplaceExternalLinks( $text, 'gopher', false );
894 $text = $this->subReplaceExternalLinks( $text, 'news', false );
895 $text = $this->subReplaceExternalLinks( $text, 'mailto', false );
896 wfProfileOut( $fname );
897 return $text;
900 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber ) {
901 $unique = '4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3';
902 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
904 # this is the list of separators that should be ignored if they
905 # are the last character of an URL but that should be included
906 # if they occur within the URL, e.g. "go to www.foo.com, where .."
907 # in this case, the last comma should not become part of the URL,
908 # but in "www.foo.com/123,2342,32.htm" it should.
909 $sep = ",;\.:";
910 $fnc = 'A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF';
911 $images = 'gif|png|jpg|jpeg';
913 # PLEASE NOTE: The curly braces { } are not part of the regex,
914 # they are interpreted as part of the string (used to tell PHP
915 # that the content of the string should be inserted there).
916 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
917 "((?i){$images})([^{$uc}]|$)/";
919 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
920 $sk =& $this->mOptions->getSkin();
922 if ( $autonumber and $this->mOptions->getAllowExternalImages() ) { # Use img tags only for HTTP urls
923 $s = preg_replace( $e1, '\\1' . $sk->makeImage( "{$unique}:\\3" .
924 '/\\4.\\5', '\\4.\\5' ) . '\\6', $s );
926 $s = preg_replace( $e2, '\\1' . "<a href=\"{$unique}:\\3\"" .
927 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
928 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
929 '</a>\\5', $s );
930 $s = str_replace( $unique, $protocol, $s );
932 $a = explode( "[{$protocol}:", " " . $s );
933 $s = array_shift( $a );
934 $s = substr( $s, 1 );
936 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
937 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
939 foreach ( $a as $line ) {
940 if ( preg_match( $e1, $line, $m ) ) {
941 $link = "{$protocol}:{$m[1]}";
942 $trail = $m[2];
943 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
944 else { $text = wfEscapeHTML( $link ); }
945 } else if ( preg_match( $e2, $line, $m ) ) {
946 $link = "{$protocol}:{$m[1]}";
947 $text = $m[2];
948 $trail = $m[3];
949 } else {
950 $s .= "[{$protocol}:" . $line;
951 continue;
953 if( $link == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
954 $paren = '';
955 } else {
956 # Expand the URL for printable version
957 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
959 $la = $sk->getExternalLinkAttributes( $link, $text );
960 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
963 return $s;
967 /* private */ function replaceInternalLinks( $s ) {
968 global $wgLang, $wgLinkCache;
969 global $wgNamespacesWithSubpages, $wgLanguageCode;
970 static $fname = 'Parser::replaceInternalLinks' ;
971 wfProfileIn( $fname );
973 wfProfileIn( $fname.'-setup' );
974 static $tc = FALSE;
975 # the % is needed to support urlencoded titles as well
976 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
977 $sk =& $this->mOptions->getSkin();
979 $a = explode( '[[', ' ' . $s );
980 $s = array_shift( $a );
981 $s = substr( $s, 1 );
983 # Match a link having the form [[namespace:link|alternate]]trail
984 static $e1 = FALSE;
985 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
986 # Match the end of a line for a word that's not followed by whitespace,
987 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
988 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
990 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
991 # Special and Media are pseudo-namespaces; no pages actually exist in them
992 static $image = FALSE;
993 static $special = FALSE;
994 static $media = FALSE;
995 static $category = FALSE;
996 if ( !$image ) { $image = Namespace::getImage(); }
997 if ( !$special ) { $special = Namespace::getSpecial(); }
998 if ( !$media ) { $media = Namespace::getMedia(); }
999 if ( !$category ) { $category = Namespace::getCategory(); }
1001 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1003 if ( $useLinkPrefixExtension ) {
1004 if ( preg_match( $e2, $s, $m ) ) {
1005 $first_prefix = $m[2];
1006 $s = $m[1];
1007 } else {
1008 $first_prefix = false;
1010 } else {
1011 $prefix = '';
1014 wfProfileOut( $fname.'-setup' );
1016 foreach ( $a as $line ) {
1017 wfProfileIn( $fname.'-prefixhandling' );
1018 if ( $useLinkPrefixExtension ) {
1019 if ( preg_match( $e2, $s, $m ) ) {
1020 $prefix = $m[2];
1021 $s = $m[1];
1022 } else {
1023 $prefix='';
1025 # first link
1026 if($first_prefix) {
1027 $prefix = $first_prefix;
1028 $first_prefix = false;
1031 wfProfileOut( $fname.'-prefixhandling' );
1033 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1034 $text = $m[2];
1035 # fix up urlencoded title texts
1036 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1037 $trail = $m[3];
1038 } else { # Invalid form; output directly
1039 $s .= $prefix . '[[' . $line ;
1040 continue;
1043 /* Valid link forms:
1044 Foobar -- normal
1045 :Foobar -- override special treatment of prefix (images, language links)
1046 /Foobar -- convert to CurrentPage/Foobar
1047 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1049 $c = substr($m[1],0,1);
1050 $noforce = ($c != ':');
1051 if( $c == '/' ) { # subpage
1052 if(substr($m[1],-1,1)=='/') { # / at end means we don't want the slash to be shown
1053 $m[1]=substr($m[1],1,strlen($m[1])-2);
1054 $noslash=$m[1];
1055 } else {
1056 $noslash=substr($m[1],1);
1058 if(!empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()])) { # subpages allowed here
1059 $link = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1060 if( '' == $text ) {
1061 $text= $m[1];
1062 } # this might be changed for ugliness reasons
1063 } else {
1064 $link = $noslash; # no subpage allowed, use standard link
1066 } elseif( $noforce ) { # no subpage
1067 $link = $m[1];
1068 } else {
1069 $link = substr( $m[1], 1 );
1071 $wasblank = ( '' == $text );
1072 if( $wasblank )
1073 $text = $link;
1075 $nt = Title::newFromText( $link );
1076 if( !$nt ) {
1077 $s .= $prefix . '[[' . $line;
1078 continue;
1080 $ns = $nt->getNamespace();
1081 $iw = $nt->getInterWiki();
1082 if( $noforce ) {
1083 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1084 array_push( $this->mOutput->mLanguageLinks, $nt->getPrefixedText() );
1085 $tmp = $prefix . $trail ;
1086 $s .= (trim($tmp) == '')? '': $tmp;
1087 continue;
1089 if ( $ns == $image ) {
1090 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1091 $wgLinkCache->addImageLinkObj( $nt );
1092 continue;
1094 if ( $ns == $category ) {
1095 $t = $nt->getText() ;
1096 $nnt = Title::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1098 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1099 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1100 $wgLinkCache->resume();
1102 $sortkey = $wasblank ? $this->mTitle->getPrefixedText() : $text;
1103 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1104 $this->mOutput->mCategoryLinks[] = $t ;
1105 $s .= $prefix . $trail ;
1106 continue;
1109 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
1110 ( strpos( $link, '#' ) == FALSE ) ) {
1111 # Self-links are handled specially; generally de-link and change to bold.
1112 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1113 continue;
1116 if( $ns == $media ) {
1117 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1118 $wgLinkCache->addImageLinkObj( $nt );
1119 continue;
1120 } elseif( $ns == $special ) {
1121 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1122 continue;
1124 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1126 wfProfileOut( $fname );
1127 return $s;
1130 # Some functions here used by doBlockLevels()
1132 /* private */ function closeParagraph() {
1133 $result = '';
1134 if ( '' != $this->mLastSection ) {
1135 $result = '</' . $this->mLastSection . ">\n";
1137 $this->mInPre = false;
1138 $this->mLastSection = '';
1139 return $result;
1141 # getCommon() returns the length of the longest common substring
1142 # of both arguments, starting at the beginning of both.
1144 /* private */ function getCommon( $st1, $st2 ) {
1145 $fl = strlen( $st1 );
1146 $shorter = strlen( $st2 );
1147 if ( $fl < $shorter ) { $shorter = $fl; }
1149 for ( $i = 0; $i < $shorter; ++$i ) {
1150 if ( $st1{$i} != $st2{$i} ) { break; }
1152 return $i;
1154 # These next three functions open, continue, and close the list
1155 # element appropriate to the prefix character passed into them.
1157 /* private */ function openList( $char )
1159 $result = $this->closeParagraph();
1161 if ( '*' == $char ) { $result .= '<ul><li>'; }
1162 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1163 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1164 else if ( ';' == $char ) {
1165 $result .= '<dl><dt>';
1166 $this->mDTopen = true;
1168 else { $result = '<!-- ERR 1 -->'; }
1170 return $result;
1173 /* private */ function nextItem( $char ) {
1174 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1175 else if ( ':' == $char || ';' == $char ) {
1176 $close = "</dd>";
1177 if ( $this->mDTopen ) { $close = '</dt>'; }
1178 if ( ';' == $char ) {
1179 $this->mDTopen = true;
1180 return $close . '<dt>';
1181 } else {
1182 $this->mDTopen = false;
1183 return $close . '<dd>';
1186 return '<!-- ERR 2 -->';
1189 /* private */function closeList( $char ) {
1190 if ( '*' == $char ) { $text = '</li></ul>'; }
1191 else if ( '#' == $char ) { $text = '</li></ol>'; }
1192 else if ( ':' == $char ) {
1193 if ( $this->mDTopen ) {
1194 $this->mDTopen = false;
1195 $text = '</dt></dl>';
1196 } else {
1197 $text = '</dd></dl>';
1200 else { return '<!-- ERR 3 -->'; }
1201 return $text."\n";
1204 /* private */ function doBlockLevels( $text, $linestart ) {
1205 $fname = 'Parser::doBlockLevels';
1206 wfProfileIn( $fname );
1208 # Parsing through the text line by line. The main thing
1209 # happening here is handling of block-level elements p, pre,
1210 # and making lists from lines starting with * # : etc.
1212 $textLines = explode( "\n", $text );
1214 $lastPrefix = $output = $lastLine = '';
1215 $this->mDTopen = $inBlockElem = false;
1216 $prefixLength = 0;
1217 $paragraphStack = false;
1219 if ( !$linestart ) {
1220 $output .= array_shift( $textLines );
1222 foreach ( $textLines as $oLine ) {
1223 $lastPrefixLength = strlen( $lastPrefix );
1224 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1225 $preOpenMatch = preg_match("/<pre/i", $oLine );
1226 if (!$this->mInPre) {
1227 $this->mInPre = !empty($preOpenMatch);
1229 if ( !$this->mInPre ) {
1230 # Multiple prefixes may abut each other for nested lists.
1231 $prefixLength = strspn( $oLine, '*#:;' );
1232 $pref = substr( $oLine, 0, $prefixLength );
1234 # eh?
1235 $pref2 = str_replace( ';', ':', $pref );
1236 $t = substr( $oLine, $prefixLength );
1237 } else {
1238 # Don't interpret any other prefixes in preformatted text
1239 $prefixLength = 0;
1240 $pref = $pref2 = '';
1241 $t = $oLine;
1244 # List generation
1245 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1246 # Same as the last item, so no need to deal with nesting or opening stuff
1247 $output .= $this->nextItem( substr( $pref, -1 ) );
1248 $paragraphStack = false;
1250 if ( ";" == substr( $pref, -1 ) ) {
1251 # The one nasty exception: definition lists work like this:
1252 # ; title : definition text
1253 # So we check for : in the remainder text to split up the
1254 # title and definition, without b0rking links.
1255 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1256 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1257 $term = $match[1];
1258 $output .= $term . $this->nextItem( ':' );
1259 $t = $match[2];
1262 } elseif( $prefixLength || $lastPrefixLength ) {
1263 # Either open or close a level...
1264 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1265 $paragraphStack = false;
1267 while( $commonPrefixLength < $lastPrefixLength ) {
1268 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1269 --$lastPrefixLength;
1271 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1272 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1274 while ( $prefixLength > $commonPrefixLength ) {
1275 $char = substr( $pref, $commonPrefixLength, 1 );
1276 $output .= $this->openList( $char );
1278 if ( ';' == $char ) {
1279 # FIXME: This is dupe of code above
1280 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1281 $term = $match[1];
1282 $output .= $term . $this->nextItem( ":" );
1283 $t = $match[2];
1286 ++$commonPrefixLength;
1288 $lastPrefix = $pref2;
1290 if( 0 == $prefixLength ) {
1291 # No prefix (not in list)--go to paragraph mode
1292 $uniq_prefix = UNIQ_PREFIX;
1293 // XXX: use a stack for nestable elements like span, table and div
1294 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1295 $closematch = preg_match(
1296 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1297 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1298 if ( $openmatch or $closematch ) {
1299 $paragraphStack = false;
1300 $output .= $this->closeParagraph();
1301 if($preOpenMatch and !$preCloseMatch) {
1302 $this->mInPre = true;
1304 if ( $closematch ) {
1305 $inBlockElem = false;
1306 } else {
1307 $inBlockElem = true;
1309 } else if ( !$inBlockElem && !$this->mInPre ) {
1310 if ( " " == $t{0} and trim($t) != '' ) {
1311 // pre
1312 if ($this->mLastSection != 'pre') {
1313 $paragraphStack = false;
1314 $output .= $this->closeParagraph().'<pre>';
1315 $this->mLastSection = 'pre';
1317 } else {
1318 // paragraph
1319 if ( '' == trim($t) ) {
1320 if ( $paragraphStack ) {
1321 $output .= $paragraphStack.'<br />';
1322 $paragraphStack = false;
1323 $this->mLastSection = 'p';
1324 } else {
1325 if ($this->mLastSection != 'p' ) {
1326 $output .= $this->closeParagraph();
1327 $this->mLastSection = '';
1328 $paragraphStack = '<p>';
1329 } else {
1330 $paragraphStack = '</p><p>';
1333 } else {
1334 if ( $paragraphStack ) {
1335 $output .= $paragraphStack;
1336 $paragraphStack = false;
1337 $this->mLastSection = 'p';
1338 } else if ($this->mLastSection != 'p') {
1339 $output .= $this->closeParagraph().'<p>';
1340 $this->mLastSection = 'p';
1346 if ($paragraphStack === false) {
1347 $output .= $t."\n";
1350 while ( $prefixLength ) {
1351 $output .= $this->closeList( $pref2{$prefixLength-1} );
1352 --$prefixLength;
1354 if ( '' != $this->mLastSection ) {
1355 $output .= '</' . $this->mLastSection . '>';
1356 $this->mLastSection = '';
1359 wfProfileOut( $fname );
1360 return $output;
1363 # Return value of a magic variable (like PAGENAME)
1364 function getVariableValue( $index ) {
1365 global $wgLang, $wgSitename, $wgServer;
1367 switch ( $index ) {
1368 case MAG_CURRENTMONTH:
1369 return date( 'm' );
1370 case MAG_CURRENTMONTHNAME:
1371 return $wgLang->getMonthName( date('n') );
1372 case MAG_CURRENTMONTHNAMEGEN:
1373 return $wgLang->getMonthNameGen( date('n') );
1374 case MAG_CURRENTDAY:
1375 return date('j');
1376 case MAG_PAGENAME:
1377 return $this->mTitle->getText();
1378 case MAG_NAMESPACE:
1379 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1380 return $wgLang->getNsText($this->mTitle->getNamespace()); // Patch by Dori
1381 case MAG_CURRENTDAYNAME:
1382 return $wgLang->getWeekdayName( date('w')+1 );
1383 case MAG_CURRENTYEAR:
1384 return date( 'Y' );
1385 case MAG_CURRENTTIME:
1386 return $wgLang->time( wfTimestampNow(), false );
1387 case MAG_NUMBEROFARTICLES:
1388 return wfNumberOfArticles();
1389 case MAG_SITENAME:
1390 return $wgSitename;
1391 case MAG_SERVER:
1392 return $wgServer;
1393 default:
1394 return NULL;
1398 # initialise the magic variables (like CURRENTMONTHNAME)
1399 function initialiseVariables() {
1400 global $wgVariableIDs;
1401 $this->mVariables = array();
1402 foreach ( $wgVariableIDs as $id ) {
1403 $mw =& MagicWord::get( $id );
1404 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1408 /* private */ function replaceVariables( $text, $args = array() ) {
1409 global $wgLang, $wgScript, $wgArticlePath;
1411 $fname = 'Parser::replaceVariables';
1412 wfProfileIn( $fname );
1414 $bail = false;
1415 if ( !$this->mVariables ) {
1416 $this->initialiseVariables();
1418 $titleChars = Title::legalChars();
1419 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1421 # This function is called recursively. To keep track of arguments we need a stack:
1422 array_push( $this->mArgStack, $args );
1424 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1425 $GLOBALS['wgCurParser'] =& $this;
1428 if ( $this->mOutputType == OT_HTML ) {
1429 # Variable substitution
1430 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1432 # Argument substitution
1433 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1435 # Template substitution
1436 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1437 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1439 array_pop( $this->mArgStack );
1441 wfProfileOut( $fname );
1442 return $text;
1445 function variableSubstitution( $matches ) {
1446 if ( array_key_exists( $matches[1], $this->mVariables ) ) {
1447 $text = $this->mVariables[$matches[1]];
1448 $this->mOutput->mContainsOldMagic = true;
1449 } else {
1450 $text = $matches[0];
1452 return $text;
1455 function braceSubstitution( $matches ) {
1456 global $wgLinkCache, $wgLang;
1457 $fname = 'Parser::braceSubstitution';
1458 $found = false;
1459 $nowiki = false;
1460 $noparse = false;
1462 $title = NULL;
1464 # $newline is an optional newline character before the braces
1465 # $part1 is the bit before the first |, and must contain only title characters
1466 # $args is a list of arguments, starting from index 0, not including $part1
1468 $newline = $matches[1];
1469 $part1 = $matches[2];
1470 # If the third subpattern matched anything, it will start with |
1471 if ( $matches[3] !== '' ) {
1472 $args = explode( '|', substr( $matches[3], 1 ) );
1473 } else {
1474 $args = array();
1476 $argc = count( $args );
1478 # {{{}}}
1479 if ( strpos( $matches[0], '{{{' ) !== false ) {
1480 $text = $matches[0];
1481 $found = true;
1482 $noparse = true;
1485 # SUBST
1486 if ( !$found ) {
1487 $mwSubst =& MagicWord::get( MAG_SUBST );
1488 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1489 if ( $this->mOutputType != OT_WIKI ) {
1490 # Invalid SUBST not replaced at PST time
1491 # Return without further processing
1492 $text = $matches[0];
1493 $found = true;
1494 $noparse= true;
1496 } elseif ( $this->mOutputType == OT_WIKI ) {
1497 # SUBST not found in PST pass, do nothing
1498 $text = $matches[0];
1499 $found = true;
1503 # MSG, MSGNW and INT
1504 if ( !$found ) {
1505 # Check for MSGNW:
1506 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1507 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1508 $nowiki = true;
1509 } else {
1510 # Remove obsolete MSG:
1511 $mwMsg =& MagicWord::get( MAG_MSG );
1512 $mwMsg->matchStartAndRemove( $part1 );
1515 # Check if it is an internal message
1516 $mwInt =& MagicWord::get( MAG_INT );
1517 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1518 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1519 $text = wfMsgReal( $part1, $args, true );
1520 $found = true;
1525 # NS
1526 if ( !$found ) {
1527 # Check for NS: (namespace expansion)
1528 $mwNs = MagicWord::get( MAG_NS );
1529 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1530 if ( intval( $part1 ) ) {
1531 $text = $wgLang->getNsText( intval( $part1 ) );
1532 $found = true;
1533 } else {
1534 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1535 if ( !is_null( $index ) ) {
1536 $text = $wgLang->getNsText( $index );
1537 $found = true;
1543 # LOCALURL and LOCALURLE
1544 if ( !$found ) {
1545 $mwLocal = MagicWord::get( MAG_LOCALURL );
1546 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1548 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1549 $func = 'getLocalURL';
1550 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1551 $func = 'escapeLocalURL';
1552 } else {
1553 $func = '';
1556 if ( $func !== '' ) {
1557 $title = Title::newFromText( $part1 );
1558 if ( !is_null( $title ) ) {
1559 if ( $argc > 0 ) {
1560 $text = $title->$func( $args[0] );
1561 } else {
1562 $text = $title->$func();
1564 $found = true;
1569 # Internal variables
1570 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1571 $text = $this->mVariables[$part1];
1572 $found = true;
1573 $this->mOutput->mContainsOldMagic = true;
1576 # Arguments input from the caller
1577 $inputArgs = end( $this->mArgStack );
1578 if ( !$found && array_key_exists( $part1, $inputArgs ) ) {
1579 $text = $inputArgs[$part1];
1580 $found = true;
1583 # Load from database
1584 if ( !$found ) {
1585 $title = Title::newFromText( $part1, NS_TEMPLATE );
1586 if ( !is_null( $title ) && !$title->isExternal() ) {
1587 # Check for excessive inclusion
1588 $dbk = $title->getPrefixedDBkey();
1589 if ( $this->incrementIncludeCount( $dbk ) ) {
1590 $article = new Article( $title );
1591 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1592 if ( $articleContent !== false ) {
1593 $found = true;
1594 $text = $articleContent;
1599 # If the title is valid but undisplayable, make a link to it
1600 if ( $this->mOutputType == OT_HTML && !$found ) {
1601 $text = '[[' . $title->getPrefixedText() . ']]';
1602 $found = true;
1607 # Recursive parsing, escaping and link table handling
1608 # Only for HTML output
1609 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1610 $text = wfEscapeWikiText( $text );
1611 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1612 # Clean up argument array
1613 $assocArgs = array();
1614 $index = 1;
1615 foreach( $args as $arg ) {
1616 $eqpos = strpos( $arg, '=' );
1617 if ( $eqpos === false ) {
1618 $assocArgs[$index++] = $arg;
1619 } else {
1620 $name = trim( substr( $arg, 0, $eqpos ) );
1621 $value = trim( substr( $arg, $eqpos+1 ) );
1622 if ( $value === false ) {
1623 $value = '';
1625 if ( $name !== false ) {
1626 $assocArgs[$name] = $value;
1631 # Do not enter included links in link table
1632 if ( !is_null( $title ) ) {
1633 $wgLinkCache->suspend();
1636 # Run full parser on the included text
1637 $text = $this->stripParse( $text, $newline, $assocArgs );
1639 # Resume the link cache and register the inclusion as a link
1640 if ( !is_null( $title ) ) {
1641 $wgLinkCache->resume();
1642 $wgLinkCache->addLinkObj( $title );
1646 if ( !$found ) {
1647 return $matches[0];
1648 } else {
1649 return $text;
1653 # Triple brace replacement -- used for template arguments
1654 function argSubstitution( $matches ) {
1655 $newline = $matches[1];
1656 $arg = trim( $matches[2] );
1657 $text = $matches[0];
1658 $inputArgs = end( $this->mArgStack );
1660 if ( array_key_exists( $arg, $inputArgs ) ) {
1661 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1664 return $text;
1667 # Returns true if the function is allowed to include this entity
1668 function incrementIncludeCount( $dbk ) {
1669 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1670 $this->mIncludeCount[$dbk] = 0;
1672 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1673 return true;
1674 } else {
1675 return false;
1680 # Cleans up HTML, removes dangerous tags and attributes
1681 /* private */ function removeHTMLtags( $text ) {
1682 global $wgUseTidy, $wgUserHtml;
1683 $fname = 'Parser::removeHTMLtags';
1684 wfProfileIn( $fname );
1686 if( $wgUserHtml ) {
1687 $htmlpairs = array( # Tags that must be closed
1688 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1689 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1690 'strike', 'strong', 'tt', 'var', 'div', 'center',
1691 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1692 'ruby', 'rt' , 'rb' , 'rp', 'p'
1694 $htmlsingle = array(
1695 'br', 'hr', 'li', 'dt', 'dd'
1697 $htmlnest = array( # Tags that can be nested--??
1698 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1699 'dl', 'font', 'big', 'small', 'sub', 'sup'
1701 $tabletags = array( # Can only appear inside table
1702 'td', 'th', 'tr'
1704 } else {
1705 $htmlpairs = array();
1706 $htmlsingle = array();
1707 $htmlnest = array();
1708 $tabletags = array();
1711 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1712 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1714 $htmlattrs = $this->getHTMLattrs () ;
1716 # Remove HTML comments
1717 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1719 $bits = explode( '<', $text );
1720 $text = array_shift( $bits );
1721 if(!$wgUseTidy) {
1722 $tagstack = array(); $tablestack = array();
1723 foreach ( $bits as $x ) {
1724 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1725 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1726 $x, $regs );
1727 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1728 error_reporting( $prev );
1730 $badtag = 0 ;
1731 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1732 # Check our stack
1733 if ( $slash ) {
1734 # Closing a tag...
1735 if ( ! in_array( $t, $htmlsingle ) &&
1736 ( $ot = @array_pop( $tagstack ) ) != $t ) {
1737 @array_push( $tagstack, $ot );
1738 $badtag = 1;
1739 } else {
1740 if ( $t == 'table' ) {
1741 $tagstack = array_pop( $tablestack );
1743 $newparams = '';
1745 } else {
1746 # Keep track for later
1747 if ( in_array( $t, $tabletags ) &&
1748 ! in_array( 'table', $tagstack ) ) {
1749 $badtag = 1;
1750 } else if ( in_array( $t, $tagstack ) &&
1751 ! in_array ( $t , $htmlnest ) ) {
1752 $badtag = 1 ;
1753 } else if ( ! in_array( $t, $htmlsingle ) ) {
1754 if ( $t == 'table' ) {
1755 array_push( $tablestack, $tagstack );
1756 $tagstack = array();
1758 array_push( $tagstack, $t );
1760 # Strip non-approved attributes from the tag
1761 $newparams = $this->fixTagAttributes($params);
1764 if ( ! $badtag ) {
1765 $rest = str_replace( '>', '&gt;', $rest );
1766 $text .= "<$slash$t $newparams$brace$rest";
1767 continue;
1770 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
1772 # Close off any remaining tags
1773 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1774 $text .= "</$t>\n";
1775 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1777 } else {
1778 # this might be possible using tidy itself
1779 foreach ( $bits as $x ) {
1780 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1781 $x, $regs );
1782 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1783 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1784 $newparams = $this->fixTagAttributes($params);
1785 $rest = str_replace( '>', '&gt;', $rest );
1786 $text .= "<$slash$t $newparams$brace$rest";
1787 } else {
1788 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
1792 wfProfileOut( $fname );
1793 return $text;
1799 * This function accomplishes several tasks:
1800 * 1) Auto-number headings if that option is enabled
1801 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1802 * 3) Add a Table of contents on the top for users who have enabled the option
1803 * 4) Auto-anchor headings
1805 * It loops through all headlines, collects the necessary data, then splits up the
1806 * string and re-inserts the newly formatted headlines.
1810 /* private */ function formatHeadings( $text, $isMain=true ) {
1811 global $wgInputEncoding;
1813 $doNumberHeadings = $this->mOptions->getNumberHeadings();
1814 $doShowToc = $this->mOptions->getShowToc();
1815 if( !$this->mTitle->userCanEdit() ) {
1816 $showEditLink = 0;
1817 $rightClickHack = 0;
1818 } else {
1819 $showEditLink = $this->mOptions->getEditSection();
1820 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
1823 # Inhibit editsection links if requested in the page
1824 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1825 if( $esw->matchAndRemove( $text ) ) {
1826 $showEditLink = 0;
1828 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1829 # do not add TOC
1830 $mw =& MagicWord::get( MAG_NOTOC );
1831 if( $mw->matchAndRemove( $text ) ) {
1832 $doShowToc = 0;
1835 # never add the TOC to the Main Page. This is an entry page that should not
1836 # be more than 1-2 screens large anyway
1837 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
1838 $doShowToc = 0;
1841 # Get all headlines for numbering them and adding funky stuff like [edit]
1842 # links - this is for later, but we need the number of headlines right now
1843 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1845 # if there are fewer than 4 headlines in the article, do not show TOC
1846 if( $numMatches < 4 ) {
1847 $doShowToc = 0;
1850 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1851 # override above conditions and always show TOC
1852 $mw =& MagicWord::get( MAG_FORCETOC );
1853 if ($mw->matchAndRemove( $text ) ) {
1854 $doShowToc = 1;
1858 # We need this to perform operations on the HTML
1859 $sk =& $this->mOptions->getSkin();
1861 # headline counter
1862 $headlineCount = 0;
1864 # Ugh .. the TOC should have neat indentation levels which can be
1865 # passed to the skin functions. These are determined here
1866 $toclevel = 0;
1867 $toc = '';
1868 $full = '';
1869 $head = array();
1870 $sublevelCount = array();
1871 $level = 0;
1872 $prevlevel = 0;
1873 foreach( $matches[3] as $headline ) {
1874 $numbering = '';
1875 if( $level ) {
1876 $prevlevel = $level;
1878 $level = $matches[1][$headlineCount];
1879 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
1880 # reset when we enter a new level
1881 $sublevelCount[$level] = 0;
1882 $toc .= $sk->tocIndent( $level - $prevlevel );
1883 $toclevel += $level - $prevlevel;
1885 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
1886 # reset when we step back a level
1887 $sublevelCount[$level+1]=0;
1888 $toc .= $sk->tocUnindent( $prevlevel - $level );
1889 $toclevel -= $prevlevel - $level;
1891 # count number of headlines for each level
1892 @$sublevelCount[$level]++;
1893 if( $doNumberHeadings || $doShowToc ) {
1894 $dot = 0;
1895 for( $i = 1; $i <= $level; $i++ ) {
1896 if( !empty( $sublevelCount[$i] ) ) {
1897 if( $dot ) {
1898 $numbering .= '.';
1900 $numbering .= $sublevelCount[$i];
1901 $dot = 1;
1906 # The canonized header is a version of the header text safe to use for links
1907 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1908 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
1909 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
1911 # strip out HTML
1912 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
1913 $tocline = trim( $canonized_headline );
1914 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
1915 $replacearray = array(
1916 '%3A' => ':',
1917 '%' => '.'
1919 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
1920 $refer[$headlineCount] = $canonized_headline;
1922 # count how many in assoc. array so we can track dupes in anchors
1923 @$refers[$canonized_headline]++;
1924 $refcount[$headlineCount]=$refers[$canonized_headline];
1926 # Prepend the number to the heading text
1928 if( $doNumberHeadings || $doShowToc ) {
1929 $tocline = $numbering . ' ' . $tocline;
1931 # Don't number the heading if it is the only one (looks silly)
1932 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1933 # the two are different if the line contains a link
1934 $headline=$numbering . ' ' . $headline;
1938 # Create the anchor for linking from the TOC to the section
1939 $anchor = $canonized_headline;
1940 if($refcount[$headlineCount] > 1 ) {
1941 $anchor .= '_' . $refcount[$headlineCount];
1943 if( $doShowToc ) {
1944 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1946 if( $showEditLink ) {
1947 if ( empty( $head[$headlineCount] ) ) {
1948 $head[$headlineCount] = '';
1950 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
1953 # Add the edit section span
1954 if( $rightClickHack ) {
1955 $headline = $sk->editSectionScript($headlineCount+1,$headline);
1958 # give headline the correct <h#> tag
1959 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1961 $headlineCount++;
1964 if( $doShowToc ) {
1965 $toclines = $headlineCount;
1966 $toc .= $sk->tocUnindent( $toclevel );
1967 $toc = $sk->tocTable( $toc );
1970 # split up and insert constructed headlines
1972 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
1973 $i = 0;
1975 foreach( $blocks as $block ) {
1976 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1977 # This is the [edit] link that appears for the top block of text when
1978 # section editing is enabled
1980 # Disabled because it broke block formatting
1981 # For example, a bullet point in the top line
1982 # $full .= $sk->editSectionLink(0);
1984 $full .= $block;
1985 if( $doShowToc && !$i && $isMain) {
1986 # Top anchor now in skin
1987 $full = $full.$toc;
1990 if( !empty( $head[$i] ) ) {
1991 $full .= $head[$i];
1993 $i++;
1996 return $full;
1999 # Return an HTML link for the "ISBN 123456" text
2000 /* private */ function magicISBN( $text ) {
2001 global $wgLang;
2003 $a = split( 'ISBN ', " $text" );
2004 if ( count ( $a ) < 2 ) return $text;
2005 $text = substr( array_shift( $a ), 1);
2006 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2008 foreach ( $a as $x ) {
2009 $isbn = $blank = '' ;
2010 while ( ' ' == $x{0} ) {
2011 $blank .= ' ';
2012 $x = substr( $x, 1 );
2014 while ( strstr( $valid, $x{0} ) != false ) {
2015 $isbn .= $x{0};
2016 $x = substr( $x, 1 );
2018 $num = str_replace( '-', '', $isbn );
2019 $num = str_replace( ' ', '', $num );
2021 if ( '' == $num ) {
2022 $text .= "ISBN $blank$x";
2023 } else {
2024 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2025 $text .= '<a href="' .
2026 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2027 "\" class=\"internal\">ISBN $isbn</a>";
2028 $text .= $x;
2031 return $text;
2034 # Return an HTML link for the "RFC 1234" text
2035 /* private */ function magicRFC( $text ) {
2036 global $wgLang;
2038 $a = split( 'RFC ', ' '.$text );
2039 if ( count ( $a ) < 2 ) return $text;
2040 $text = substr( array_shift( $a ), 1);
2041 $valid = '0123456789';
2043 foreach ( $a as $x ) {
2044 $rfc = $blank = '' ;
2045 while ( ' ' == $x{0} ) {
2046 $blank .= ' ';
2047 $x = substr( $x, 1 );
2049 while ( strstr( $valid, $x{0} ) != false ) {
2050 $rfc .= $x{0};
2051 $x = substr( $x, 1 );
2054 if ( '' == $rfc ) {
2055 $text .= "RFC $blank$x";
2056 } else {
2057 $url = wfmsg( 'rfcurl' );
2058 $url = str_replace( '$1', $rfc, $url);
2059 $sk =& $this->mOptions->getSkin();
2060 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2061 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2064 return $text;
2067 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2068 $this->mOptions = $options;
2069 $this->mTitle =& $title;
2070 $this->mOutputType = OT_WIKI;
2072 if ( $clearState ) {
2073 $this->clearState();
2076 $stripState = false;
2077 $pairs = array(
2078 "\r\n" => "\n",
2080 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2081 // now with regexes
2083 $pairs = array(
2084 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2085 "/<br *?>/i" => "<br />",
2087 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2089 $text = $this->strip( $text, $stripState, false );
2090 $text = $this->pstPass2( $text, $user );
2091 $text = $this->unstrip( $text, $stripState );
2092 $text = $this->unstripNoWiki( $text, $stripState );
2093 return $text;
2096 /* private */ function pstPass2( $text, &$user ) {
2097 global $wgLang, $wgLocaltimezone, $wgCurParser;
2099 # Variable replacement
2100 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2101 $text = $this->replaceVariables( $text );
2103 # Signatures
2105 $n = $user->getName();
2106 $k = $user->getOption( 'nickname' );
2107 if ( '' == $k ) { $k = $n; }
2108 if(isset($wgLocaltimezone)) {
2109 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2111 /* Note: this is an ugly timezone hack for the European wikis */
2112 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2113 ' (' . date( 'T' ) . ')';
2114 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2116 $text = preg_replace( '/~~~~~/', $d, $text );
2117 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText(
2118 Namespace::getUser() ) . ":$n|$k]] $d", $text );
2119 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText(
2120 Namespace::getUser() ) . ":$n|$k]]", $text );
2122 # Context links: [[|name]] and [[name (context)|]]
2124 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2125 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2126 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2127 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2129 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2130 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2131 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2132 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2133 # [[ns:page (cont)|]]
2134 $context = "";
2135 $t = $this->mTitle->getText();
2136 if ( preg_match( $conpat, $t, $m ) ) {
2137 $context = $m[2];
2139 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2140 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2141 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2143 if ( '' == $context ) {
2144 $text = preg_replace( $p2, '[[\\1]]', $text );
2145 } else {
2146 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2150 $mw =& MagicWord::get( MAG_SUBST );
2151 $wgCurParser = $this->fork();
2152 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2153 $this->merge( $wgCurParser );
2156 # Trim trailing whitespace
2157 # MAG_END (__END__) tag allows for trailing
2158 # whitespace to be deliberately included
2159 $text = rtrim( $text );
2160 $mw =& MagicWord::get( MAG_END );
2161 $mw->matchAndRemove( $text );
2163 return $text;
2166 # Set up some variables which are usually set up in parse()
2167 # so that an external function can call some class members with confidence
2168 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2169 $this->mTitle =& $title;
2170 $this->mOptions = $options;
2171 $this->mOutputType = $outputType;
2172 if ( $clearState ) {
2173 $this->clearState();
2177 function transformMsg( $text, $options ) {
2178 global $wgTitle;
2179 static $executing = false;
2181 # Guard against infinite recursion
2182 if ( $executing ) {
2183 return $text;
2185 $executing = true;
2187 $this->mTitle = $wgTitle;
2188 $this->mOptions = $options;
2189 $this->mOutputType = OT_MSG;
2190 $this->clearState();
2191 $text = $this->replaceVariables( $text );
2193 $executing = false;
2194 return $text;
2197 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2198 # Callback will be called with the text within
2199 # Transform and return the text within
2200 function setHook( $tag, $callback ) {
2201 $oldVal = @$this->mTagHooks[$tag];
2202 $this->mTagHooks[$tag] = $callback;
2203 return $oldVal;
2207 class ParserOutput
2209 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2210 var $mCacheTime; # Used in ParserCache
2212 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2213 $containsOldMagic = false )
2215 $this->mText = $text;
2216 $this->mLanguageLinks = $languageLinks;
2217 $this->mCategoryLinks = $categoryLinks;
2218 $this->mContainsOldMagic = $containsOldMagic;
2219 $this->mCacheTime = "";
2222 function getText() { return $this->mText; }
2223 function getLanguageLinks() { return $this->mLanguageLinks; }
2224 function getCategoryLinks() { return $this->mCategoryLinks; }
2225 function getCacheTime() { return $this->mCacheTime; }
2226 function containsOldMagic() { return $this->mContainsOldMagic; }
2227 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2228 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2229 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2230 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2231 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2233 function merge( $other ) {
2234 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2235 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2236 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2241 class ParserOptions
2243 # All variables are private
2244 var $mUseTeX; # Use texvc to expand <math> tags
2245 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2246 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2247 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2248 var $mAllowExternalImages; # Allow external images inline
2249 var $mSkin; # Reference to the preferred skin
2250 var $mDateFormat; # Date format index
2251 var $mEditSection; # Create "edit section" links
2252 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2253 var $mNumberHeadings; # Automatically number headings
2254 var $mShowToc; # Show table of contents
2256 function getUseTeX() { return $this->mUseTeX; }
2257 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
2258 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2259 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2260 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2261 function getSkin() { return $this->mSkin; }
2262 function getDateFormat() { return $this->mDateFormat; }
2263 function getEditSection() { return $this->mEditSection; }
2264 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2265 function getNumberHeadings() { return $this->mNumberHeadings; }
2266 function getShowToc() { return $this->mShowToc; }
2268 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2269 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
2270 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2271 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2272 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2273 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2274 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2275 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2276 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2277 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2279 function setSkin( &$x ) { $this->mSkin =& $x; }
2281 /* static */ function newFromUser( &$user ) {
2282 $popts = new ParserOptions;
2283 $popts->initialiseFromUser( $user );
2284 return $popts;
2287 function initialiseFromUser( &$userInput ) {
2288 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2290 if ( !$userInput ) {
2291 $user = new User;
2292 $user->setLoaded( true );
2293 } else {
2294 $user =& $userInput;
2297 $this->mUseTeX = $wgUseTeX;
2298 $this->mUseCategoryMagic = $wgUseCategoryMagic;
2299 $this->mUseDynamicDates = $wgUseDynamicDates;
2300 $this->mInterwikiMagic = $wgInterwikiMagic;
2301 $this->mAllowExternalImages = $wgAllowExternalImages;
2302 $this->mSkin =& $user->getSkin();
2303 $this->mDateFormat = $user->getOption( 'date' );
2304 $this->mEditSection = $user->getOption( 'editsection' );
2305 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
2306 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
2307 $this->mShowToc = $user->getOption( 'showtoc' );
2313 # Regex callbacks, used in Parser::replaceVariables
2314 function wfBraceSubstitution( $matches )
2316 global $wgCurParser;
2317 return $wgCurParser->braceSubstitution( $matches );
2320 function wfArgSubstitution( $matches )
2322 global $wgCurParser;
2323 return $wgCurParser->argSubstitution( $matches );
2326 function wfVariableSubstitution( $matches )
2328 global $wgCurParser;
2329 return $wgCurParser->variableSubstitution( $matches );