c25acecadc73e764e303f3c5c0f9889beefd2103
3 // require_once('Tokenizer.php');
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.
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*,
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 );
34 define( "MAX_INCLUDE_SIZE", 1000000 ); // 1 Million
36 # Allowed values for $mOutputType
37 define( "OT_HTML", 1 );
38 define( "OT_WIKI", 2 );
39 define( "OT_MSG", 3 );
41 # string parameter for extractTags which will cause it
42 # to strip HTML comments in addition to regular
43 # <XML>-style tags. This should not be anything we
44 # may want to use in wikisyntax
45 define( "STRIP_COMMENTS", "HTMLCommentStrip" );
47 # prefix for escaping, used in two functions at least
48 define( "UNIQ_PREFIX", "NaodW29");
55 # Cleared with clearState():
56 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
57 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
60 var $mOptions, $mTitle, $mOutputType,
61 $mTemplates, // cache of already loaded templates, avoids
62 // multiple SQL queries for the same string
63 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
64 // in this path. Used for loop detection.
67 $this->mTemplates
= array();
68 $this->mTemplatePath
= array();
69 $this->mTagHooks
= array();
73 function clearState() {
74 $this->mOutput
= new ParserOutput
;
75 $this->mAutonumber
= 0;
76 $this->mLastSection
= "";
77 $this->mDTopen
= false;
78 $this->mVariables
= false;
79 $this->mIncludeCount
= array();
80 $this->mStripState
= array();
81 $this->mArgStack
= array();
82 $this->mInPre
= false;
85 # First pass--just handle <nowiki> sections, pass the rest off
86 # to internalParse() which does all the real work.
88 # Returns a ParserOutput
90 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
92 $fname = "Parser::parse";
93 wfProfileIn( $fname );
99 $this->mOptions
= $options;
100 $this->mTitle
=& $title;
101 $this->mOutputType
= OT_HTML
;
104 $text = $this->strip( $text, $this->mStripState
);
105 $text = $this->internalParse( $text, $linestart );
106 $text = $this->unstrip( $text, $this->mStripState
);
107 # Clean up special characters, only run once, next-to-last before doBlockLevels
110 # french spaces, last one Guillemet-left
111 # only if there is something before the space
112 '/(.) (\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
113 # french spaces, Guillemet-right
114 "/(\\302\\253) /i"=>"\\1 ",
115 '/<hr *>/i' => '<hr />',
116 '/<br *>/i' => '<br />',
117 '/<center *>/i' => '<div class="center">',
118 '/<\\/center *>/i' => '</div>',
119 # Clean up spare ampersands; note that we probably ought to be
120 # more careful about named entities.
121 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
123 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
126 # french spaces, last one Guillemet-left
127 '/ (\\?|:|!|\\302\\273)/i' => ' \\1',
128 # french spaces, Guillemet-right
129 '/(\\302\\253) /i' => '\\1 ',
130 '/([^> ]+(0(1|3|9);)[^< ]*)/i' => '<span class="diacrit">\\1</span>',
131 '/<center *>/i' => '<div class="center">',
132 '/<\\/center *>/i' => '</div>'
134 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
137 $text = $this->doBlockLevels( $text, $linestart );
138 $text = $this->unstripNoWiki( $text, $this->mStripState
);
140 $text = $this->tidy($text);
142 $this->mOutput
->setText( $text );
143 wfProfileOut( $fname );
144 return $this->mOutput
;
147 /* static */ function getRandomString() {
148 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
151 # Replaces all occurrences of <$tag>content</$tag> in the text
152 # with a random marker and returns the new text. the output parameter
153 # $content will be an associative array filled with data on the form
154 # $unique_marker => content.
156 # If $content is already set, the additional entries will be appended
158 # If $tag is set to STRIP_COMMENTS, the function will extract
159 # <!-- HTML comments -->
161 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
162 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
169 while ( '' != $text ) {
170 if($tag==STRIP_COMMENTS
) {
171 $p = preg_split( '/<!--/i', $text, 2 );
173 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
176 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
179 if($tag==STRIP_COMMENTS
) {
180 $q = preg_split( '/-->/i', $p[1], 2 );
182 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
184 $marker = $rnd . sprintf('%08X', $n++
);
185 $content[$marker] = $q[0];
186 $stripped .= $marker;
193 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
194 # If $render is set, performs necessary rendering operations on plugins
195 # Returns the text, and fills an array with data needed in unstrip()
196 # If the $state is already a valid strip state, it adds to the state
198 # When $stripcomments is set, HTML comments <!-- like this -->
199 # will be stripped in addition to other tags. This is important
200 # for section editing, where these comments cause confusion when
201 # counting the sections in the wikisource
202 function strip( $text, &$state, $stripcomments = false ) {
203 $render = ($this->mOutputType
== OT_HTML
);
204 $html_content = array();
205 $nowiki_content = array();
206 $math_content = array();
207 $pre_content = array();
208 $comment_content = array();
209 $ext_content = array();
211 # Replace any instances of the placeholders
212 $uniq_prefix = UNIQ_PREFIX
;
213 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
218 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
219 foreach( $html_content as $marker => $content ) {
221 # Raw and unchecked for validity.
222 $html_content[$marker] = $content;
224 $html_content[$marker] = "<html>$content</html>";
230 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
231 foreach( $nowiki_content as $marker => $content ) {
233 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
235 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
240 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
241 foreach( $math_content as $marker => $content ){
243 if( $this->mOptions
->getUseTeX() ) {
244 $math_content[$marker] = renderMath( $content );
246 $math_content[$marker] = "<math>$content<math>";
249 $math_content[$marker] = "<math>$content</math>";
254 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
255 foreach( $pre_content as $marker => $content ){
257 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
259 $pre_content[$marker] = "<pre>$content</pre>";
265 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
266 foreach( $comment_content as $marker => $content ){
267 $comment_content[$marker] = "<!--$content-->";
272 foreach ( $this->mTagHooks
as $tag => $callback ) {
273 $ext_contents[$tag] = array();
274 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
275 foreach( $ext_content[$tag] as $marker => $content ) {
277 $ext_content[$tag][$marker] = $callback( $content );
279 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
284 # Merge state with the pre-existing state, if there is one
286 $state['html'] = $state['html'] +
$html_content;
287 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
288 $state['math'] = $state['math'] +
$math_content;
289 $state['pre'] = $state['pre'] +
$pre_content;
290 $state['comment'] = $state['comment'] +
$comment_content;
292 foreach( $ext_content as $tag => $array ) {
293 if ( array_key_exists( $tag, $state ) ) {
294 $state[$tag] = $state[$tag] +
$array;
299 'html' => $html_content,
300 'nowiki' => $nowiki_content,
301 'math' => $math_content,
302 'pre' => $pre_content,
303 'comment' => $comment_content,
309 # always call unstripNoWiki() after this one
310 function unstrip( $text, &$state ) {
311 # Must expand in reverse order, otherwise nested tags will be corrupted
312 $contentDict = end( $state );
313 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
314 if( key($state) != 'nowiki' && key($state) != 'html') {
315 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
316 $text = str_replace( key( $contentDict ), $content, $text );
323 # always call this after unstrip() to preserve the order
324 function unstripNoWiki( $text, &$state ) {
325 # Must expand in reverse order, otherwise nested tags will be corrupted
326 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
327 $text = str_replace( key( $state['nowiki'] ), $content, $text );
332 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
333 $text = str_replace( key( $state['html'] ), $content, $text );
340 # Add an item to the strip state
341 # Returns the unique tag which must be inserted into the stripped text
342 # The tag will be replaced with the original text in unstrip()
344 function insertStripItem( $text, &$state ) {
345 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
354 $state['item'][$rnd] = $text;
359 # generate a list of subcategories and pages for a category
360 # depending on wfMsg("usenewcategorypage") it either calls the new
361 # or the old code. The new code will not work properly for some
362 # languages due to sorting issues, so they might want to turn it
364 function categoryMagic() {
365 $msg = wfMsg('usenewcategorypage');
366 if ( '0' == @$msg[0] )
368 return $this->oldCategoryMagic();
370 return $this->newCategoryMagic();
374 # This method generates the list of subcategories and pages for a category
375 function oldCategoryMagic () {
376 global $wgLang , $wgUser ;
377 $fname = 'Parser::oldCategoryMagic';
379 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
381 $cns = Namespace::getCategory() ;
382 if ( $this->mTitle
->getNamespace() != $cns ) return "" ; # This ain't a category page
384 $r = "<br style=\"clear:both;\"/>\n";
387 $sk =& $wgUser->getSkin() ;
389 $articles = array() ;
390 $children = array() ;
392 $id = $this->mTitle
->getArticleID() ;
395 $dbr =& wfGetDB( DB_SLAVE
);
396 $cur = $dbr->tableName( 'cur' );
397 $categorylinks = $dbr->tableName( 'categorylinks' );
399 $t = $dbr->strencode( $this->mTitle
->getDBKey() );
400 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM $cur,$categorylinks " .
401 "WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
402 $res = $dbr->query( $sql, $fname ) ;
403 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
405 # For all pages that link to this category
406 foreach ( $data AS $x )
408 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
409 if ( $t != "" ) $t .= ":" ;
410 $t .= $x->cur_title
;
412 if ( $x->cur_namespace
== $cns ) {
413 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
415 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
418 $dbr->freeResult ( $res ) ;
420 # Showing subcategories
421 if ( count ( $children ) > 0 ) {
422 $r .= '<h2>'.wfMsg('subcategories')."</h2>\n" ;
423 $r .= implode ( ', ' , $children ) ;
426 # Showing pages in this category
427 if ( count ( $articles ) > 0 ) {
428 $ti = $this->mTitle
->getText() ;
429 $h = wfMsg( 'category_header', $ti );
430 $r .= "<h2>{$h}</h2>\n" ;
431 $r .= implode ( ', ' , $articles ) ;
439 function newCategoryMagic () {
440 global $wgLang , $wgUser ;
441 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
443 $cns = Namespace::getCategory() ;
444 if ( $this->mTitle
->getNamespace() != $cns ) return '' ; # This ain't a category page
446 $r = "<br style=\"clear:both;\"/>\n";
449 $sk =& $wgUser->getSkin() ;
451 $articles = array() ;
452 $articles_start_char = array();
453 $children = array() ;
454 $children_start_char = array();
456 $id = $this->mTitle
->getArticleID() ;
459 $dbr =& wfGetDB( DB_SLAVE
);
460 $cur = $dbr->tableName( 'cur' );
461 $categorylinks = $dbr->tableName( 'categorylinks' );
463 $t = $dbr->strencode( $this->mTitle
->getDBKey() );
464 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM " .
465 "$cur,$categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
466 $res = $dbr->query ( $sql ) ;
467 while ( $x = $dbr->fetchObject ( $res ) )
469 $t = $ns = $wgLang->getNsText ( $x->cur_namespace
) ;
470 if ( $t != '' ) $t .= ':' ;
471 $t .= $x->cur_title
;
473 if ( $x->cur_namespace
== $cns ) {
474 $ctitle = str_replace( '_',' ',$x->cur_title
);
475 array_push ( $children, $sk->makeKnownLink ( $t, $ctitle ) ) ; # Subcategory
477 // If there's a link from Category:A to Category:B, the sortkey of the resulting
478 // entry in the categorylinks table is Category:A, not A, which it SHOULD be.
479 // Workaround: If sortkey == "Category:".$title, than use $title for sorting,
480 // else use sortkey...
481 if ( ($ns.":".$ctitle) == $x->cl_sortkey
) {
482 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title
) );
484 array_push ( $children_start_char, $wgLang->firstChar( $x->cl_sortkey
) ) ;
487 array_push ( $articles , $sk->makeKnownLink ( $t ) ) ; # Page in this category
488 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey
) ) ;
491 $dbr->freeResult ( $res ) ;
493 $ti = $this->mTitle
->getText() ;
495 # Don't show subcategories section if there are none.
496 if ( count ( $children ) > 0 )
498 # Showing subcategories
499 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n"
500 . wfMsg( 'subcategorycount', count( $children ) );
501 if ( count ( $children ) > 6 ) {
503 // divide list into three equal chunks
504 $chunk = (int) (count ( $children ) / 3);
506 // get and display header
507 $r .= '<table width="100%"><tr valign="top">';
512 // loop through the chunks
513 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
515 $chunkIndex++
, $startChunk = $endChunk, $endChunk +
= $chunk +
1)
519 // output all subcategories to category
520 for ($index = $startChunk ;
521 $index < $endChunk && $index < count($children);
524 // check for change of starting letter or begging of chunk
525 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
526 ||
($index == $startChunk) )
528 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
531 $r .= "<li>{$children[$index]}</li>";
537 $r .= '</tr></table>';
539 // for short lists of subcategories to category.
541 $r .= "<h3>{$children_start_char[0]}</h3>\n";
542 $r .= '<ul><li>'.$children[0].'</li>';
543 for ($index = 1; $index < count($children); $index++
)
545 if ($children_start_char[$index] != $children_start_char[$index - 1])
547 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
550 $r .= "<li>{$children[$index]}</li>";
554 } # END of if ( count($children) > 0 )
556 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n" .
557 wfMsg( 'categoryarticlecount', count( $articles ) );
559 # Showing articles in this category
560 if ( count ( $articles ) > 6) {
561 $ti = $this->mTitle
->getText() ;
563 // divide list into three equal chunks
564 $chunk = (int) (count ( $articles ) / 3);
566 // get and display header
567 $r .= '<table width="100%"><tr valign="top">';
569 // loop through the chunks
570 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
572 $chunkIndex++
, $startChunk = $endChunk, $endChunk +
= $chunk +
1)
577 // output all articles in category
578 for ($index = $startChunk ;
579 $index < $endChunk && $index < count($articles);
582 // check for change of starting letter or begging of chunk
583 if ( ($articles_start_char[$index] != $articles_start_char[$index - 1])
584 ||
($index == $startChunk) )
586 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
589 $r .= "<li>{$articles[$index]}</li>";
595 $r .= '</tr></table>';
596 } elseif ( count ( $articles ) > 0) {
597 // for short lists of articles in categories.
598 $ti = $this->mTitle
->getText() ;
600 $r .= '<h3>'.$articles_start_char[0]."</h3>\n";
601 $r .= '<ul><li>'.$articles[0].'</li>';
602 for ($index = 1; $index < count($articles); $index++
)
604 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
606 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
609 $r .= "<li>{$articles[$index]}</li>";
618 # Return allowed HTML attributes
619 function getHTMLattrs () {
620 $htmlattrs = array( # Allowed attributes--no scripting, etc.
621 'title', 'align', 'lang', 'dir', 'width', 'height',
622 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
623 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
624 /* FONT */ 'type', 'start', 'value', 'compact',
625 /* For various lists, mostly deprecated but safe */
626 'summary', 'width', 'border', 'frame', 'rules',
627 'cellspacing', 'cellpadding', 'valign', 'char',
628 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
629 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
630 'id', 'class', 'name', 'style' /* For CSS */
635 # Remove non approved attributes and javascript in css
636 function fixTagAttributes ( $t ) {
637 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
638 $htmlattrs = $this->getHTMLattrs() ;
640 # Strip non-approved attributes from the tag
642 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
643 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
645 # Strip javascript "expression" from stylesheets. Brute force approach:
646 # If anythin offensive is found, all attributes of the HTML tag are dropped
649 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
650 wfMungeToUtf8( $t ) ) )
658 # interface with html tidy, used if $wgUseTidy = true
659 function tidy ( $text ) {
660 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
661 global $wgInputEncoding, $wgOutputEncoding;
662 $fname = 'Parser::tidy';
663 wfProfileIn( $fname );
666 switch(strtoupper($wgOutputEncoding)) {
668 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
671 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
674 $wgTidyOpts .= ' -raw';
677 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
678 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
679 '<head><title>test</title></head><body>'.$text.'</body></html>';
680 $descriptorspec = array(
681 0 => array('pipe', 'r'),
682 1 => array('pipe', 'w'),
683 2 => array('file', '/dev/null', 'a')
685 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
686 if (is_resource($process)) {
687 fwrite($pipes[0], $wrappedtext);
689 while (!feof($pipes[1])) {
690 $cleansource .= fgets($pipes[1], 1024);
693 $return_value = proc_close($process);
696 wfProfileOut( $fname );
698 if( $cleansource == '' && $text != '') {
699 wfDebug( "Tidy error detected!\n" );
700 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
706 # parse the wiki syntax used to render tables
707 function doTableStuff ( $t ) {
708 $fname = 'Parser::doTableStuff';
709 wfProfileIn( $fname );
711 $t = explode ( "\n" , $t ) ;
712 $td = array () ; # Is currently a td tag open?
713 $ltd = array () ; # Was it TD or TH?
714 $tr = array () ; # Is currently a tr tag open?
715 $ltr = array () ; # tr attributes
716 $indent_level = 0; # indent level of the table
717 foreach ( $t AS $k => $x )
720 $fc = substr ( $x , 0 , 1 ) ;
721 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) )
723 $indent_level = strlen( $matches[1] );
725 str_repeat( "<dl><dd>", $indent_level ) .
726 "<table " . $this->fixTagAttributes ( $matches[2] ) . '>' ;
727 array_push ( $td , false ) ;
728 array_push ( $ltd , '' ) ;
729 array_push ( $tr , false ) ;
730 array_push ( $ltr , '' ) ;
732 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
733 else if ( '|}' == substr ( $x , 0 , 2 ) )
736 $l = array_pop ( $ltd ) ;
737 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
738 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
740 $t[$k] = $z . str_repeat( "</dd></dl>", $indent_level );
742 else if ( '|-' == substr ( $x , 0 , 2 ) ) # Allows for |---------------
744 $x = substr ( $x , 1 ) ;
745 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
747 $l = array_pop ( $ltd ) ;
748 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
749 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
752 array_push ( $tr , false ) ;
753 array_push ( $td , false ) ;
754 array_push ( $ltd , '' ) ;
755 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
757 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) # Caption
759 if ( '|+' == substr ( $x , 0 , 2 ) )
762 $x = substr ( $x , 1 ) ;
764 $after = substr ( $x , 1 ) ;
765 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
766 $after = explode ( '||' , $after ) ;
768 foreach ( $after AS $theline )
773 $tra = array_pop ( $ltr ) ;
774 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
775 array_push ( $tr , true ) ;
776 array_push ( $ltr , '' ) ;
779 $l = array_pop ( $ltd ) ;
780 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
781 if ( $fc == '|' ) $l = 'td' ;
782 else if ( $fc == '!' ) $l = 'th' ;
783 else if ( $fc == '+' ) $l = 'caption' ;
785 array_push ( $ltd , $l ) ;
786 $y = explode ( '|' , $theline , 2 ) ;
787 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
788 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
790 array_push ( $td , true ) ;
795 # Closing open td, tr && table
796 while ( count ( $td ) > 0 )
798 if ( array_pop ( $td ) ) $t[] = '</td>' ;
799 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
803 $t = implode ( "\n" , $t ) ;
804 # $t = $this->removeHTMLtags( $t );
805 wfProfileOut( $fname );
809 # Parses the text and adds the result to the strip state
810 # Returns the strip tag
811 function stripParse( $text, $newline, $args )
813 $text = $this->strip( $text, $this->mStripState
);
814 $text = $this->internalParse( $text, (bool)$newline, $args, false );
815 return $newline.$this->insertStripItem( $text, $this->mStripState
);
818 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
819 $fname = 'Parser::internalParse';
820 wfProfileIn( $fname );
822 $text = $this->removeHTMLtags( $text );
823 $text = $this->replaceVariables( $text, $args );
826 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
828 $text = $this->doHeadings( $text );
829 if($this->mOptions
->getUseDynamicDates()) {
830 global $wgDateFormatter;
831 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
833 $text = $this->doAllQuotes( $text );
834 // $text = $this->doExponent( $text );
835 $text = $this->replaceExternalLinks( $text );
836 $text = $this->doMagicLinks( $text );
837 $text = $this->replaceInternalLinks ( $text );
838 $text = $this->replaceInternalLinks ( $text );
839 //$text = $this->doTokenizedParser ( $text );
840 $text = $this->doTableStuff( $text );
841 $text = $this->formatHeadings( $text, $isMain );
842 $sk =& $this->mOptions
->getSkin();
843 $text = $sk->transformContent( $text );
845 if ( $isMain && !isset ( $this->categoryMagicDone
) ) {
846 $text .= $this->categoryMagic () ;
847 $this->categoryMagicDone
= true ;
850 wfProfileOut( $fname );
854 /* private */ function &doMagicLinks( &$text ) {
855 $text = $this->magicISBN( $text );
856 $text = $this->magicGEO( $text );
857 $text = $this->magicRFC( $text );
861 # Parse ^^ tokens and return html
862 /* private */ function doExponent ( $text )
864 $fname = 'Parser::doExponent';
865 wfProfileIn( $fname);
866 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
867 wfProfileOut( $fname);
871 # Parse headers and return html
872 /* private */ function doHeadings( $text ) {
873 $fname = 'Parser::doHeadings';
874 wfProfileIn( $fname );
875 for ( $i = 6; $i >= 1; --$i ) {
876 $h = substr( '======', 0, $i );
877 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
878 "<h{$i}>\\1</h{$i}>\\2", $text );
880 wfProfileOut( $fname );
884 /* private */ function doAllQuotes( $text ) {
885 $fname = 'Parser::doAllQuotes';
886 wfProfileIn( $fname );
888 $lines = explode( "\n", $text );
889 foreach ( $lines as $line ) {
890 $outtext .= $this->doQuotes ( '', $line, '' ) . "\n";
892 $outtext = substr($outtext, 0,-1);
893 wfProfileOut( $fname );
897 /* private */ function doQuotes( $pre, $text, $mode ) {
898 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
899 $m1_strong = ($m[1] == "") ?
"" : "<strong>{$m[1]}</strong>";
900 $m1_em = ($m[1] == "") ?
"" : "<em>{$m[1]}</em>";
901 if ( substr ($m[2], 0, 1) == '\'' ) {
902 $m[2] = substr ($m[2], 1);
904 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ?
'both' : 'emstrong' );
905 } else if ($mode == 'strong') {
906 return $m1_strong . $this->doQuotes ( '', $m[2], '' );
907 } else if (($mode == 'emstrong') ||
($mode == 'both')) {
908 return $this->doQuotes ( '', $pre.$m1_strong.$m[2], 'em' );
909 } else if ($mode == 'strongem') {
910 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( '', $m[2], 'em' );
912 return $m[1] . $this->doQuotes ( '', $m[2], 'strong' );
915 if ($mode == 'strong') {
916 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ?
'both' : 'strongem' );
917 } else if ($mode == 'em') {
918 return $m1_em . $this->doQuotes ( '', $m[2], '' );
919 } else if ($mode == 'emstrong') {
920 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( '', $m[2], 'strong' );
921 } else if (($mode == 'strongem') ||
($mode == 'both')) {
922 return $this->doQuotes ( '', $pre.$m1_em.$m[2], 'strong' );
924 return $m[1] . $this->doQuotes ( '', $m[2], 'em' );
928 $text_strong = ($text == '') ?
'' : "<strong>{$text}</strong>";
929 $text_em = ($text == '') ?
'' : "<em>{$text}</em>";
932 } else if ($mode == 'em') {
933 return $pre . $text_em;
934 } else if ($mode == 'strong') {
935 return $pre . $text_strong;
936 } else if ($mode == 'strongem') {
937 return (($pre == '') && ($text == '')) ?
'' : "<strong>{$pre}{$text_em}</strong>";
939 return (($pre == '') && ($text == '')) ?
'' : "<em>{$pre}{$text_strong}</em>";
944 # Note: we have to do external links before the internal ones,
945 # and otherwise take great care in the order of things here, so
946 # that we don't end up interpreting some URLs twice.
948 /* private */ function replaceExternalLinks( $text ) {
949 $fname = 'Parser::replaceExternalLinks';
950 wfProfileIn( $fname );
951 $text = $this->subReplaceExternalLinks( $text, 'http', true );
952 $text = $this->subReplaceExternalLinks( $text, 'https', true );
953 $text = $this->subReplaceExternalLinks( $text, 'ftp', false );
954 $text = $this->subReplaceExternalLinks( $text, 'irc', false );
955 $text = $this->subReplaceExternalLinks( $text, 'gopher', false );
956 $text = $this->subReplaceExternalLinks( $text, 'news', false );
957 $text = $this->subReplaceExternalLinks( $text, 'mailto', false );
958 wfProfileOut( $fname );
962 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber ) {
963 $unique = '4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3';
964 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
966 # this is the list of separators that should be ignored if they
967 # are the last character of an URL but that should be included
968 # if they occur within the URL, e.g. "go to www.foo.com, where .."
969 # in this case, the last comma should not become part of the URL,
970 # but in "www.foo.com/123,2342,32.htm" it should.
972 $fnc = 'A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF';
973 $images = 'gif|png|jpg|jpeg';
975 # PLEASE NOTE: The curly braces { } are not part of the regex,
976 # they are interpreted as part of the string (used to tell PHP
977 # that the content of the string should be inserted there).
978 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
979 "((?i){$images})([^{$uc}]|$)/";
981 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
982 $sk =& $this->mOptions
->getSkin();
984 if ( $autonumber and $this->mOptions
->getAllowExternalImages() ) { # Use img tags only for HTTP urls
985 $s = preg_replace( $e1, '\\1' . $sk->makeImage( "{$unique}:\\3" .
986 '/\\4.\\5', '\\4.\\5' ) . '\\6', $s );
988 $s = preg_replace( $e2, '\\1' . "<a href=\"{$unique}:\\3\"" .
989 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
990 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
992 $s = str_replace( $unique, $protocol, $s );
994 $a = explode( "[{$protocol}:", " " . $s );
995 $s = array_shift( $a );
996 $s = substr( $s, 1 );
998 # Regexp for URL in square brackets
999 $e1 = "/^([{$uc}{$sep}]+)\\](.*)\$/sD";
1000 # Regexp for URL with link text in square brackets
1001 $e2 = "/^([{$uc}{$sep}]+)\\s+([^\\]]+)\\](.*)\$/sD";
1003 foreach ( $a as $line ) {
1005 # CASE 1: Link in square brackets, e.g.
1006 # some text [http://domain.tld/some.link] more text
1007 if ( preg_match( $e1, $line, $m ) ) {
1008 $link = "{$protocol}:{$m[1]}";
1010 if ( $autonumber ) { $text = "[" . ++
$this->mAutonumber
. "]"; }
1011 else { $text = wfEscapeHTML( $link ); }
1014 # CASE 2: Link with link text and text directly following it, e.g.
1015 # This is a collection of [http://domain.tld/some.link link]s
1016 else if ( preg_match( $e2, $line, $m ) ) {
1017 $link = "{$protocol}:{$m[1]}";
1021 if ( preg_match( wfMsg ('linktrail'), $trail, $m2 ) ) {
1027 # CASE 3: Nothing matches, just output the source text
1029 $s .= "[{$protocol}:" . $line;
1033 if( $link == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
1036 # Expand the URL for printable version
1037 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
1039 $la = $sk->getExternalLinkAttributes( $link, $text );
1040 $s .= "<a href='{$link}'{$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
1047 /* private */ function replaceInternalLinks( $s ) {
1048 global $wgLang, $wgLinkCache;
1049 global $wgNamespacesWithSubpages, $wgLanguageCode;
1050 static $fname = 'Parser::replaceInternalLinks' ;
1051 wfProfileIn( $fname );
1053 wfProfileIn( $fname.'-setup' );
1055 # the % is needed to support urlencoded titles as well
1056 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1057 $sk =& $this->mOptions
->getSkin();
1059 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1060 $isRedirect = $redirect->matchStart ( strtoupper ( substr ( $s , 0 , 10 ) ) ) ;
1062 $a = explode( '[[', ' ' . $s );
1063 $s = array_shift( $a );
1064 $s = substr( $s, 1 );
1066 # Match a link having the form [[namespace:link|alternate]]trail
1068 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1069 # Match the end of a line for a word that's not followed by whitespace,
1070 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1071 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1073 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1074 # Special and Media are pseudo-namespaces; no pages actually exist in them
1075 static $image = FALSE;
1076 static $special = FALSE;
1077 static $media = FALSE;
1078 static $category = FALSE;
1079 if ( !$image ) { $image = Namespace::getImage(); }
1080 if ( !$special ) { $special = Namespace::getSpecial(); }
1081 if ( !$media ) { $media = Namespace::getMedia(); }
1082 if ( !$category ) { $category = Namespace::getCategory(); }
1084 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1086 if ( $useLinkPrefixExtension ) {
1087 if ( preg_match( $e2, $s, $m ) ) {
1088 $first_prefix = $m[2];
1091 $first_prefix = false;
1097 wfProfileOut( $fname.'-setup' );
1099 foreach ( $a as $line ) {
1100 wfProfileIn( $fname.'-prefixhandling' );
1101 if ( $useLinkPrefixExtension ) {
1102 if ( preg_match( $e2, $s, $m ) ) {
1110 $prefix = $first_prefix;
1111 $first_prefix = false;
1114 wfProfileOut( $fname.'-prefixhandling' );
1116 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1118 # fix up urlencoded title texts
1119 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1121 } else { # Invalid form; output directly
1122 $s .= $prefix . '[[' . $line ;
1126 /* Valid link forms:
1128 :Foobar -- override special treatment of prefix (images, language links)
1129 /Foobar -- convert to CurrentPage/Foobar
1130 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1132 $c = substr($m[1],0,1);
1133 $noforce = ($c != ':');
1134 if( $c == '/' ) { # subpage
1135 if(substr($m[1],-1,1)=='/') { # / at end means we don't want the slash to be shown
1136 $m[1]=substr($m[1],1,strlen($m[1])-2);
1139 $noslash=substr($m[1],1);
1141 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) { # subpages allowed here
1142 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1145 } # this might be changed for ugliness reasons
1147 $link = $noslash; # no subpage allowed, use standard link
1149 } elseif( $noforce ) { # no subpage
1152 $link = substr( $m[1], 1 );
1154 $wasblank = ( '' == $text );
1158 $nt = Title
::newFromText( $link );
1160 $s .= $prefix . '[[' . $line;
1163 $ns = $nt->getNamespace();
1164 $iw = $nt->getInterWiki();
1166 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1167 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1168 $tmp = $prefix . $trail ;
1169 $s .= (trim($tmp) == '')?
'': $tmp;
1172 if ( $ns == $image ) {
1173 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1174 $wgLinkCache->addImageLinkObj( $nt );
1177 if ( $ns == $category && !$isRedirect ) {
1178 $t = $nt->getText() ;
1179 $nnt = Title
::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1181 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1182 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1183 $wgLinkCache->resume();
1185 $sortkey = $wasblank ?
$this->mTitle
->getPrefixedText() : $text;
1186 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1187 $this->mOutput
->mCategoryLinks
[] = $t ;
1188 $s .= $prefix . $trail ;
1192 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
1193 ( strpos( $link, '#' ) == FALSE ) ) {
1194 # Self-links are handled specially; generally de-link and change to bold.
1195 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1199 if( $ns == $media ) {
1200 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1201 $wgLinkCache->addImageLinkObj( $nt );
1203 } elseif( $ns == $special ) {
1204 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1207 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1209 wfProfileOut( $fname );
1213 # Some functions here used by doBlockLevels()
1215 /* private */ function closeParagraph() {
1217 if ( '' != $this->mLastSection
) {
1218 $result = '</' . $this->mLastSection
. ">\n";
1220 $this->mInPre
= false;
1221 $this->mLastSection
= '';
1224 # getCommon() returns the length of the longest common substring
1225 # of both arguments, starting at the beginning of both.
1227 /* private */ function getCommon( $st1, $st2 ) {
1228 $fl = strlen( $st1 );
1229 $shorter = strlen( $st2 );
1230 if ( $fl < $shorter ) { $shorter = $fl; }
1232 for ( $i = 0; $i < $shorter; ++
$i ) {
1233 if ( $st1{$i} != $st2{$i} ) { break; }
1237 # These next three functions open, continue, and close the list
1238 # element appropriate to the prefix character passed into them.
1240 /* private */ function openList( $char )
1242 $result = $this->closeParagraph();
1244 if ( '*' == $char ) { $result .= '<ul><li>'; }
1245 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1246 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1247 else if ( ';' == $char ) {
1248 $result .= '<dl><dt>';
1249 $this->mDTopen
= true;
1251 else { $result = '<!-- ERR 1 -->'; }
1256 /* private */ function nextItem( $char ) {
1257 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1258 else if ( ':' == $char ||
';' == $char ) {
1260 if ( $this->mDTopen
) { $close = '</dt>'; }
1261 if ( ';' == $char ) {
1262 $this->mDTopen
= true;
1263 return $close . '<dt>';
1265 $this->mDTopen
= false;
1266 return $close . '<dd>';
1269 return '<!-- ERR 2 -->';
1272 /* private */function closeList( $char ) {
1273 if ( '*' == $char ) { $text = '</li></ul>'; }
1274 else if ( '#' == $char ) { $text = '</li></ol>'; }
1275 else if ( ':' == $char ) {
1276 if ( $this->mDTopen
) {
1277 $this->mDTopen
= false;
1278 $text = '</dt></dl>';
1280 $text = '</dd></dl>';
1283 else { return '<!-- ERR 3 -->'; }
1287 /* private */ function doBlockLevels( $text, $linestart ) {
1288 $fname = 'Parser::doBlockLevels';
1289 wfProfileIn( $fname );
1291 # Parsing through the text line by line. The main thing
1292 # happening here is handling of block-level elements p, pre,
1293 # and making lists from lines starting with * # : etc.
1295 $textLines = explode( "\n", $text );
1297 $lastPrefix = $output = $lastLine = '';
1298 $this->mDTopen
= $inBlockElem = false;
1300 $paragraphStack = false;
1302 if ( !$linestart ) {
1303 $output .= array_shift( $textLines );
1305 foreach ( $textLines as $oLine ) {
1306 $lastPrefixLength = strlen( $lastPrefix );
1307 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1308 $preOpenMatch = preg_match("/<pre/i", $oLine );
1309 if ( !$this->mInPre
) {
1310 # Multiple prefixes may abut each other for nested lists.
1311 $prefixLength = strspn( $oLine, '*#:;' );
1312 $pref = substr( $oLine, 0, $prefixLength );
1315 $pref2 = str_replace( ';', ':', $pref );
1316 $t = substr( $oLine, $prefixLength );
1317 $this->mInPre
= !empty($preOpenMatch);
1319 # Don't interpret any other prefixes in preformatted text
1321 $pref = $pref2 = '';
1326 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1327 # Same as the last item, so no need to deal with nesting or opening stuff
1328 $output .= $this->nextItem( substr( $pref, -1 ) );
1329 $paragraphStack = false;
1331 if ( ";" == substr( $pref, -1 ) ) {
1332 # The one nasty exception: definition lists work like this:
1333 # ; title : definition text
1334 # So we check for : in the remainder text to split up the
1335 # title and definition, without b0rking links.
1336 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1337 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1339 $output .= $term . $this->nextItem( ':' );
1343 } elseif( $prefixLength ||
$lastPrefixLength ) {
1344 # Either open or close a level...
1345 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1346 $paragraphStack = false;
1348 while( $commonPrefixLength < $lastPrefixLength ) {
1349 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1350 --$lastPrefixLength;
1352 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1353 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1355 while ( $prefixLength > $commonPrefixLength ) {
1356 $char = substr( $pref, $commonPrefixLength, 1 );
1357 $output .= $this->openList( $char );
1359 if ( ';' == $char ) {
1360 # FIXME: This is dupe of code above
1361 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1363 $output .= $term . $this->nextItem( ":" );
1367 ++
$commonPrefixLength;
1369 $lastPrefix = $pref2;
1371 if( 0 == $prefixLength ) {
1372 # No prefix (not in list)--go to paragraph mode
1373 $uniq_prefix = UNIQ_PREFIX
;
1374 // XXX: use a stack for nestable elements like span, table and div
1375 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1376 $closematch = preg_match(
1377 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1378 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1379 if ( $openmatch or $closematch ) {
1380 $paragraphStack = false;
1381 $output .= $this->closeParagraph();
1382 if($preOpenMatch and !$preCloseMatch) {
1383 $this->mInPre
= true;
1385 if ( $closematch ) {
1386 $inBlockElem = false;
1388 $inBlockElem = true;
1390 } else if ( !$inBlockElem && !$this->mInPre
) {
1391 if ( " " == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1393 if ($this->mLastSection
!= 'pre') {
1394 $paragraphStack = false;
1395 $output .= $this->closeParagraph().'<pre>';
1396 $this->mLastSection
= 'pre';
1400 if ( '' == trim($t) ) {
1401 if ( $paragraphStack ) {
1402 $output .= $paragraphStack.'<br />';
1403 $paragraphStack = false;
1404 $this->mLastSection
= 'p';
1406 if ($this->mLastSection
!= 'p' ) {
1407 $output .= $this->closeParagraph();
1408 $this->mLastSection
= '';
1409 $paragraphStack = '<p>';
1411 $paragraphStack = '</p><p>';
1415 if ( $paragraphStack ) {
1416 $output .= $paragraphStack;
1417 $paragraphStack = false;
1418 $this->mLastSection
= 'p';
1419 } else if ($this->mLastSection
!= 'p') {
1420 $output .= $this->closeParagraph().'<p>';
1421 $this->mLastSection
= 'p';
1427 if ($paragraphStack === false) {
1431 while ( $prefixLength ) {
1432 $output .= $this->closeList( $pref2{$prefixLength-1} );
1435 if ( '' != $this->mLastSection
) {
1436 $output .= '</' . $this->mLastSection
. '>';
1437 $this->mLastSection
= '';
1440 wfProfileOut( $fname );
1444 # Return value of a magic variable (like PAGENAME)
1445 function getVariableValue( $index ) {
1446 global $wgLang, $wgSitename, $wgServer;
1449 case MAG_CURRENTMONTH
:
1450 return $wgLang->formatNum( date( 'm' ) );
1451 case MAG_CURRENTMONTHNAME
:
1452 return $wgLang->getMonthName( date('n') );
1453 case MAG_CURRENTMONTHNAMEGEN
:
1454 return $wgLang->getMonthNameGen( date('n') );
1455 case MAG_CURRENTDAY
:
1456 return $wgLang->formatNum( date('j') );
1458 return $this->mTitle
->getText();
1460 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1461 return $wgLang->getNsText($this->mTitle
->getNamespace()); // Patch by Dori
1462 case MAG_CURRENTDAYNAME
:
1463 return $wgLang->getWeekdayName( date('w')+
1 );
1464 case MAG_CURRENTYEAR
:
1465 return $wgLang->formatNum( date( 'Y' ) );
1466 case MAG_CURRENTTIME
:
1467 return $wgLang->time( wfTimestampNow(), false );
1468 case MAG_NUMBEROFARTICLES
:
1469 return $wgLang->formatNum( wfNumberOfArticles() );
1479 # initialise the magic variables (like CURRENTMONTHNAME)
1480 function initialiseVariables() {
1481 global $wgVariableIDs;
1482 $this->mVariables
= array();
1483 foreach ( $wgVariableIDs as $id ) {
1484 $mw =& MagicWord
::get( $id );
1485 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1489 /* private */ function replaceVariables( $text, $args = array() ) {
1490 global $wgLang, $wgScript, $wgArticlePath;
1492 # Prevent too big inclusions
1493 if(strlen($text)> MAX_INCLUDE_SIZE
)
1496 $fname = 'Parser::replaceVariables';
1497 wfProfileIn( $fname );
1500 $titleChars = Title
::legalChars();
1501 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1503 # This function is called recursively. To keep track of arguments we need a stack:
1504 array_push( $this->mArgStack
, $args );
1506 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1507 $GLOBALS['wgCurParser'] =& $this;
1510 if ( $this->mOutputType
== OT_HTML
) {
1511 # Variable substitution
1512 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1514 # Argument substitution
1515 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1517 # Template substitution
1518 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1519 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1521 array_pop( $this->mArgStack
);
1523 wfProfileOut( $fname );
1527 function variableSubstitution( $matches ) {
1528 if ( !$this->mVariables
) {
1529 $this->initialiseVariables();
1531 if ( array_key_exists( $matches[1], $this->mVariables
) ) {
1532 $text = $this->mVariables
[$matches[1]];
1533 $this->mOutput
->mContainsOldMagic
= true;
1535 $text = $matches[0];
1540 # Split template arguments
1541 function getTemplateArgs( $argsString ) {
1542 if ( $argsString === '' ) {
1546 $args = explode( '|', substr( $argsString, 1 ) );
1548 # If any of the arguments contains a '[[' but no ']]', it needs to be
1549 # merged with the next arg because the '|' character between belongs
1550 # to the link syntax and not the template parameter syntax.
1551 $argc = count($args);
1553 for ( $i = 0; $i < $argc-1; $i++
) {
1554 if ( substr_count ( $args[$i], "[[" ) != substr_count ( $args[$i], "]]" ) ) {
1555 $args[$i] .= "|".$args[$i+
1];
1556 array_splice($args, $i+
1, 1);
1565 function braceSubstitution( $matches ) {
1566 global $wgLinkCache, $wgLang;
1567 $fname = 'Parser::braceSubstitution';
1574 # $newline is an optional newline character before the braces
1575 # $part1 is the bit before the first |, and must contain only title characters
1576 # $args is a list of arguments, starting from index 0, not including $part1
1578 $newline = $matches[1];
1579 $part1 = $matches[2];
1580 # If the third subpattern matched anything, it will start with |
1582 $args = $this->getTemplateArgs($matches[3]);
1583 $argc = count( $args );
1586 if ( strpos( $matches[0], '{{{' ) !== false ) {
1587 $text = $matches[0];
1594 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1595 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1596 if ( $this->mOutputType
!= OT_WIKI
) {
1597 # Invalid SUBST not replaced at PST time
1598 # Return without further processing
1599 $text = $matches[0];
1603 } elseif ( $this->mOutputType
== OT_WIKI
) {
1604 # SUBST not found in PST pass, do nothing
1605 $text = $matches[0];
1610 # MSG, MSGNW and INT
1613 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1614 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1617 # Remove obsolete MSG:
1618 $mwMsg =& MagicWord
::get( MAG_MSG
);
1619 $mwMsg->matchStartAndRemove( $part1 );
1622 # Check if it is an internal message
1623 $mwInt =& MagicWord
::get( MAG_INT
);
1624 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1625 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1626 $text = wfMsgReal( $part1, $args, true );
1634 # Check for NS: (namespace expansion)
1635 $mwNs = MagicWord
::get( MAG_NS
);
1636 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1637 if ( intval( $part1 ) ) {
1638 $text = $wgLang->getNsText( intval( $part1 ) );
1641 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1642 if ( !is_null( $index ) ) {
1643 $text = $wgLang->getNsText( $index );
1650 # LOCALURL and LOCALURLE
1652 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1653 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1655 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1656 $func = 'getLocalURL';
1657 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1658 $func = 'escapeLocalURL';
1663 if ( $func !== '' ) {
1664 $title = Title
::newFromText( $part1 );
1665 if ( !is_null( $title ) ) {
1667 $text = $title->$func( $args[0] );
1669 $text = $title->$func();
1676 # Internal variables
1677 if ( !$this->mVariables
) {
1678 $this->initialiseVariables();
1680 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1681 $text = $this->mVariables
[$part1];
1683 $this->mOutput
->mContainsOldMagic
= true;
1686 # Template table test
1688 # Did we encounter this template already? If yes, it is in the cache
1689 # and we need to check for loops.
1690 if ( isset( $this->mTemplates
[$part1] ) ) {
1691 # Infinite loop test
1692 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1696 # set $text to cached message.
1697 $text = $this->mTemplates
[$part1];
1701 # Load from database
1703 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1704 if ( !is_null( $title ) && !$title->isExternal() ) {
1705 # Check for excessive inclusion
1706 $dbk = $title->getPrefixedDBkey();
1707 if ( $this->incrementIncludeCount( $dbk ) ) {
1708 # This should never be reached.
1709 $article = new Article( $title );
1710 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1711 if ( $articleContent !== false ) {
1713 $text = $articleContent;
1718 # If the title is valid but undisplayable, make a link to it
1719 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1720 $text = '[[' . $title->getPrefixedText() . ']]';
1724 # Template cache array insertion
1725 $this->mTemplates
[$part1] = $text;
1729 # Recursive parsing, escaping and link table handling
1730 # Only for HTML output
1731 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1732 $text = wfEscapeWikiText( $text );
1733 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1734 # Clean up argument array
1735 $assocArgs = array();
1737 foreach( $args as $arg ) {
1738 $eqpos = strpos( $arg, '=' );
1739 if ( $eqpos === false ) {
1740 $assocArgs[$index++
] = $arg;
1742 $name = trim( substr( $arg, 0, $eqpos ) );
1743 $value = trim( substr( $arg, $eqpos+
1 ) );
1744 if ( $value === false ) {
1747 if ( $name !== false ) {
1748 $assocArgs[$name] = $value;
1753 # Do not enter included links in link table
1754 if ( !is_null( $title ) ) {
1755 $wgLinkCache->suspend();
1758 # Add a new element to the templace recursion path
1759 $this->mTemplatePath
[$part1] = 1;
1761 # Run full parser on the included text
1762 $text = $this->internalParse( $text, $newline, $assocArgs );
1763 # I replaced the line below with the line above, as it former seems to cause several bugs
1764 #$text = $this->stripParse( $text, $newline, $assocArgs );
1766 # Resume the link cache and register the inclusion as a link
1767 if ( !is_null( $title ) ) {
1768 $wgLinkCache->resume();
1769 $wgLinkCache->addLinkObj( $title );
1772 # Empties the template path
1773 $this->mTemplatePath
= array();
1782 # Triple brace replacement -- used for template arguments
1783 function argSubstitution( $matches ) {
1784 $newline = $matches[1];
1785 $arg = trim( $matches[2] );
1786 $text = $matches[0];
1787 $inputArgs = end( $this->mArgStack
);
1789 if ( array_key_exists( $arg, $inputArgs ) ) {
1790 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1796 # Returns true if the function is allowed to include this entity
1797 function incrementIncludeCount( $dbk ) {
1798 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1799 $this->mIncludeCount
[$dbk] = 0;
1801 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1809 # Cleans up HTML, removes dangerous tags and attributes
1810 /* private */ function removeHTMLtags( $text ) {
1811 global $wgUseTidy, $wgUserHtml;
1812 $fname = 'Parser::removeHTMLtags';
1813 wfProfileIn( $fname );
1816 $htmlpairs = array( # Tags that must be closed
1817 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1818 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1819 'strike', 'strong', 'tt', 'var', 'div', 'center',
1820 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1821 'ruby', 'rt' , 'rb' , 'rp', 'p'
1823 $htmlsingle = array(
1824 'br', 'hr', 'li', 'dt', 'dd'
1826 $htmlnest = array( # Tags that can be nested--??
1827 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1828 'dl', 'font', 'big', 'small', 'sub', 'sup'
1830 $tabletags = array( # Can only appear inside table
1834 $htmlpairs = array();
1835 $htmlsingle = array();
1836 $htmlnest = array();
1837 $tabletags = array();
1840 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1841 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1843 $htmlattrs = $this->getHTMLattrs () ;
1845 # Remove HTML comments
1846 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1848 $bits = explode( '<', $text );
1849 $text = array_shift( $bits );
1851 $tagstack = array(); $tablestack = array();
1852 foreach ( $bits as $x ) {
1853 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1854 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1856 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1857 error_reporting( $prev );
1860 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1864 if ( ! in_array( $t, $htmlsingle ) &&
1865 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
1866 @array_push
( $tagstack, $ot );
1869 if ( $t == 'table' ) {
1870 $tagstack = array_pop( $tablestack );
1875 # Keep track for later
1876 if ( in_array( $t, $tabletags ) &&
1877 ! in_array( 'table', $tagstack ) ) {
1879 } else if ( in_array( $t, $tagstack ) &&
1880 ! in_array ( $t , $htmlnest ) ) {
1882 } else if ( ! in_array( $t, $htmlsingle ) ) {
1883 if ( $t == 'table' ) {
1884 array_push( $tablestack, $tagstack );
1885 $tagstack = array();
1887 array_push( $tagstack, $t );
1889 # Strip non-approved attributes from the tag
1890 $newparams = $this->fixTagAttributes($params);
1894 $rest = str_replace( '>', '>', $rest );
1895 $text .= "<$slash$t $newparams$brace$rest";
1899 $text .= '<' . str_replace( '>', '>', $x);
1901 # Close off any remaining tags
1902 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1904 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1907 # this might be possible using tidy itself
1908 foreach ( $bits as $x ) {
1909 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1911 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1912 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1913 $newparams = $this->fixTagAttributes($params);
1914 $rest = str_replace( '>', '>', $rest );
1915 $text .= "<$slash$t $newparams$brace$rest";
1917 $text .= '<' . str_replace( '>', '>', $x);
1921 wfProfileOut( $fname );
1928 * This function accomplishes several tasks:
1929 * 1) Auto-number headings if that option is enabled
1930 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1931 * 3) Add a Table of contents on the top for users who have enabled the option
1932 * 4) Auto-anchor headings
1934 * It loops through all headlines, collects the necessary data, then splits up the
1935 * string and re-inserts the newly formatted headlines.
1939 /* private */ function formatHeadings( $text, $isMain=true ) {
1940 global $wgInputEncoding, $wgMaxTocLevel;
1942 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1943 $doShowToc = $this->mOptions
->getShowToc();
1944 $forceTocHere = false;
1945 if( !$this->mTitle
->userCanEdit() ) {
1947 $rightClickHack = 0;
1949 $showEditLink = $this->mOptions
->getEditSection();
1950 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1953 # Inhibit editsection links if requested in the page
1954 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1955 if( $esw->matchAndRemove( $text ) ) {
1958 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1960 $mw =& MagicWord
::get( MAG_NOTOC
);
1961 if( $mw->matchAndRemove( $text ) ) {
1965 # never add the TOC to the Main Page. This is an entry page that should not
1966 # be more than 1-2 screens large anyway
1967 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
1971 # Get all headlines for numbering them and adding funky stuff like [edit]
1972 # links - this is for later, but we need the number of headlines right now
1973 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1975 # if there are fewer than 4 headlines in the article, do not show TOC
1976 if( $numMatches < 4 ) {
1980 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
1981 # override above conditions and always show TOC at that place
1982 $mw =& MagicWord
::get( MAG_TOC
);
1983 if ($mw->match( $text ) ) {
1985 $forceTocHere = true;
1987 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1988 # override above conditions and always show TOC above first header
1989 $mw =& MagicWord
::get( MAG_FORCETOC
);
1990 if ($mw->matchAndRemove( $text ) ) {
1997 # We need this to perform operations on the HTML
1998 $sk =& $this->mOptions
->getSkin();
2003 # Ugh .. the TOC should have neat indentation levels which can be
2004 # passed to the skin functions. These are determined here
2009 $sublevelCount = array();
2012 foreach( $matches[3] as $headline ) {
2015 $prevlevel = $level;
2017 $level = $matches[1][$headlineCount];
2018 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2019 # reset when we enter a new level
2020 $sublevelCount[$level] = 0;
2021 $toc .= $sk->tocIndent( $level - $prevlevel );
2022 $toclevel +
= $level - $prevlevel;
2024 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2025 # reset when we step back a level
2026 $sublevelCount[$level+
1]=0;
2027 $toc .= $sk->tocUnindent( $prevlevel - $level );
2028 $toclevel -= $prevlevel - $level;
2030 # count number of headlines for each level
2031 @$sublevelCount[$level]++
;
2032 if( $doNumberHeadings ||
$doShowToc ) {
2034 for( $i = 1; $i <= $level; $i++
) {
2035 if( !empty( $sublevelCount[$i] ) ) {
2039 $numbering .= $sublevelCount[$i];
2045 # The canonized header is a version of the header text safe to use for links
2046 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2047 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2048 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2051 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2052 $tocline = trim( $canonized_headline );
2053 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2054 $replacearray = array(
2058 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2059 $refer[$headlineCount] = $canonized_headline;
2061 # count how many in assoc. array so we can track dupes in anchors
2062 @$refers[$canonized_headline]++
;
2063 $refcount[$headlineCount]=$refers[$canonized_headline];
2065 # Prepend the number to the heading text
2067 if( $doNumberHeadings ||
$doShowToc ) {
2068 $tocline = $numbering . ' ' . $tocline;
2070 # Don't number the heading if it is the only one (looks silly)
2071 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2072 # the two are different if the line contains a link
2073 $headline=$numbering . ' ' . $headline;
2077 # Create the anchor for linking from the TOC to the section
2078 $anchor = $canonized_headline;
2079 if($refcount[$headlineCount] > 1 ) {
2080 $anchor .= '_' . $refcount[$headlineCount];
2082 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2083 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2085 if( $showEditLink ) {
2086 if ( empty( $head[$headlineCount] ) ) {
2087 $head[$headlineCount] = '';
2089 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
2092 # Add the edit section span
2093 if( $rightClickHack ) {
2094 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
2097 # give headline the correct <h#> tag
2098 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
2104 $toclines = $headlineCount;
2105 $toc .= $sk->tocUnindent( $toclevel );
2106 $toc = $sk->tocTable( $toc );
2109 # split up and insert constructed headlines
2111 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2114 foreach( $blocks as $block ) {
2115 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2116 # This is the [edit] link that appears for the top block of text when
2117 # section editing is enabled
2119 # Disabled because it broke block formatting
2120 # For example, a bullet point in the top line
2121 # $full .= $sk->editSectionLink(0);
2124 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2125 # Top anchor now in skin
2129 if( !empty( $head[$i] ) ) {
2135 $mw =& MagicWord
::get( MAG_TOC
);
2136 return $mw->replace( $toc, $full );
2142 # Return an HTML link for the "ISBN 123456" text
2143 /* private */ function magicISBN( $text ) {
2145 $fname = 'Parser::magicISBN';
2146 wfProfileIn( $fname );
2148 $a = split( 'ISBN ', " $text" );
2149 if ( count ( $a ) < 2 ) {
2150 wfProfileOut( $fname );
2153 $text = substr( array_shift( $a ), 1);
2154 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2156 foreach ( $a as $x ) {
2157 $isbn = $blank = '' ;
2158 while ( ' ' == $x{0} ) {
2160 $x = substr( $x, 1 );
2162 while ( strstr( $valid, $x{0} ) != false ) {
2164 $x = substr( $x, 1 );
2166 $num = str_replace( '-', '', $isbn );
2167 $num = str_replace( ' ', '', $num );
2170 $text .= "ISBN $blank$x";
2172 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2173 $text .= '<a href="' .
2174 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2175 "\" class=\"internal\">ISBN $isbn</a>";
2179 wfProfileOut( $fname );
2183 # Return an HTML link for the "GEO ..." text
2184 /* private */ function magicGEO( $text ) {
2185 global $wgLang, $wgUseGeoMode;
2186 if ( !isset ( $wgUseGeoMode ) ||
!$wgUseGeoMode ) return $text ;
2187 $fname = 'Parser::magicGEO';
2188 wfProfileIn( $fname );
2190 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2191 $directions = array ( "N" => "North" , "S" => "South" , "E" => "East" , "W" => "West" ) ;
2192 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2193 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2194 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2195 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2197 $a = split( 'GEO ', " $text" );
2198 if ( count ( $a ) < 2 ) {
2199 wfProfileOut( $fname );
2202 $text = substr( array_shift( $a ), 1);
2203 $valid = '0123456789.+-:';
2205 foreach ( $a as $x ) {
2206 $geo = $blank = '' ;
2207 while ( ' ' == $x{0} ) {
2209 $x = substr( $x, 1 );
2211 while ( strstr( $valid, $x{0} ) != false ) {
2213 $x = substr( $x, 1 );
2215 $num = str_replace( '+', '', $geo );
2216 $num = str_replace( ' ', '', $num );
2218 if ( '' == $num ||
count ( explode ( ":" , $num , 3 ) ) < 2 ) {
2219 $text .= "GEO $blank$x";
2221 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2222 $text .= '<a href="' .
2223 $titleObj->escapeLocalUrl( "coordinates={$num}" ) .
2224 "\" class=\"internal\">GEO $geo</a>";
2228 wfProfileOut( $fname );
2232 # Return an HTML link for the "RFC 1234" text
2233 /* private */ function magicRFC( $text ) {
2236 $a = split( 'RFC ', ' '.$text );
2237 if ( count ( $a ) < 2 ) return $text;
2238 $text = substr( array_shift( $a ), 1);
2239 $valid = '0123456789';
2241 foreach ( $a as $x ) {
2242 $rfc = $blank = '' ;
2243 while ( ' ' == $x{0} ) {
2245 $x = substr( $x, 1 );
2247 while ( strstr( $valid, $x{0} ) != false ) {
2249 $x = substr( $x, 1 );
2253 $text .= "RFC $blank$x";
2255 $url = wfmsg( 'rfcurl' );
2256 $url = str_replace( '$1', $rfc, $url);
2257 $sk =& $this->mOptions
->getSkin();
2258 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2259 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2265 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2266 $this->mOptions
= $options;
2267 $this->mTitle
=& $title;
2268 $this->mOutputType
= OT_WIKI
;
2270 if ( $clearState ) {
2271 $this->clearState();
2274 $stripState = false;
2278 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2282 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2283 "/<br *?>/i" => "<br />",
2285 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2287 $text = $this->strip( $text, $stripState, false );
2288 $text = $this->pstPass2( $text, $user );
2289 $text = $this->unstrip( $text, $stripState );
2290 $text = $this->unstripNoWiki( $text, $stripState );
2294 /* private */ function pstPass2( $text, &$user ) {
2295 global $wgLang, $wgLocaltimezone, $wgCurParser;
2297 # Variable replacement
2298 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2299 $text = $this->replaceVariables( $text );
2303 $n = $user->getName();
2304 $k = $user->getOption( 'nickname' );
2305 if ( '' == $k ) { $k = $n; }
2306 if(isset($wgLocaltimezone)) {
2307 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2309 /* Note: this is an ugly timezone hack for the European wikis */
2310 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2311 ' (' . date( 'T' ) . ')';
2312 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2314 $text = preg_replace( '/~~~~~/', $d, $text );
2315 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText(
2316 Namespace::getUser() ) . ":$n|$k]] $d", $text );
2317 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText(
2318 Namespace::getUser() ) . ":$n|$k]]", $text );
2320 # Context links: [[|name]] and [[name (context)|]]
2322 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2323 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2324 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2325 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2327 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2328 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2329 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2330 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2331 # [[ns:page (cont)|]]
2333 $t = $this->mTitle
->getText();
2334 if ( preg_match( $conpat, $t, $m ) ) {
2337 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2338 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2339 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2341 if ( '' == $context ) {
2342 $text = preg_replace( $p2, '[[\\1]]', $text );
2344 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2348 $mw =& MagicWord::get( MAG_SUBST );
2349 $wgCurParser = $this->fork();
2350 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2351 $this->merge( $wgCurParser );
2354 # Trim trailing whitespace
2355 # MAG_END (__END__) tag allows for trailing
2356 # whitespace to be deliberately included
2357 $text = rtrim( $text );
2358 $mw =& MagicWord
::get( MAG_END
);
2359 $mw->matchAndRemove( $text );
2364 # Set up some variables which are usually set up in parse()
2365 # so that an external function can call some class members with confidence
2366 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2367 $this->mTitle
=& $title;
2368 $this->mOptions
= $options;
2369 $this->mOutputType
= $outputType;
2370 if ( $clearState ) {
2371 $this->clearState();
2375 function transformMsg( $text, $options ) {
2377 static $executing = false;
2379 # Guard against infinite recursion
2385 $this->mTitle
= $wgTitle;
2386 $this->mOptions
= $options;
2387 $this->mOutputType
= OT_MSG
;
2388 $this->clearState();
2389 $text = $this->replaceVariables( $text );
2395 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2396 # Callback will be called with the text within
2397 # Transform and return the text within
2398 function setHook( $tag, $callback ) {
2399 $oldVal = @$this->mTagHooks
[$tag];
2400 $this->mTagHooks
[$tag] = $callback;
2407 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2408 var $mCacheTime; # Used in ParserCache
2410 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2411 $containsOldMagic = false )
2413 $this->mText
= $text;
2414 $this->mLanguageLinks
= $languageLinks;
2415 $this->mCategoryLinks
= $categoryLinks;
2416 $this->mContainsOldMagic
= $containsOldMagic;
2417 $this->mCacheTime
= "";
2420 function getText() { return $this->mText
; }
2421 function getLanguageLinks() { return $this->mLanguageLinks
; }
2422 function getCategoryLinks() { return $this->mCategoryLinks
; }
2423 function getCacheTime() { return $this->mCacheTime
; }
2424 function containsOldMagic() { return $this->mContainsOldMagic
; }
2425 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2426 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2427 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2428 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2429 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2431 function merge( $other ) {
2432 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2433 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2434 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2441 # All variables are private
2442 var $mUseTeX; # Use texvc to expand <math> tags
2443 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2444 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2445 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2446 var $mAllowExternalImages; # Allow external images inline
2447 var $mSkin; # Reference to the preferred skin
2448 var $mDateFormat; # Date format index
2449 var $mEditSection; # Create "edit section" links
2450 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2451 var $mNumberHeadings; # Automatically number headings
2452 var $mShowToc; # Show table of contents
2454 function getUseTeX() { return $this->mUseTeX
; }
2455 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
2456 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2457 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2458 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2459 function getSkin() { return $this->mSkin
; }
2460 function getDateFormat() { return $this->mDateFormat
; }
2461 function getEditSection() { return $this->mEditSection
; }
2462 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2463 function getNumberHeadings() { return $this->mNumberHeadings
; }
2464 function getShowToc() { return $this->mShowToc
; }
2466 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2467 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
2468 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2469 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2470 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2471 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2472 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2473 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2474 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2475 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2477 function setSkin( &$x ) { $this->mSkin
=& $x; }
2479 /* static */ function newFromUser( &$user ) {
2480 $popts = new ParserOptions
;
2481 $popts->initialiseFromUser( $user );
2485 function initialiseFromUser( &$userInput ) {
2486 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2488 if ( !$userInput ) {
2490 $user->setLoaded( true );
2492 $user =& $userInput;
2495 $this->mUseTeX
= $wgUseTeX;
2496 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2497 $this->mUseDynamicDates
= $wgUseDynamicDates;
2498 $this->mInterwikiMagic
= $wgInterwikiMagic;
2499 $this->mAllowExternalImages
= $wgAllowExternalImages;
2500 $this->mSkin
=& $user->getSkin();
2501 $this->mDateFormat
= $user->getOption( 'date' );
2502 $this->mEditSection
= $user->getOption( 'editsection' );
2503 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2504 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2505 $this->mShowToc
= $user->getOption( 'showtoc' );
2511 # Regex callbacks, used in Parser::replaceVariables
2512 function wfBraceSubstitution( $matches )
2514 global $wgCurParser;
2515 return $wgCurParser->braceSubstitution( $matches );
2518 function wfArgSubstitution( $matches )
2520 global $wgCurParser;
2521 return $wgCurParser->argSubstitution( $matches );
2524 function wfVariableSubstitution( $matches )
2526 global $wgCurParser;
2527 return $wgCurParser->variableSubstitution( $matches );