f4d87e6192903a71ea1fdbf124f3c3f7053d7b16
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 );
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");
54 # Cleared with clearState():
55 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
56 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
59 var $mOptions, $mTitle, $mOutputType;
62 $this->mTagHooks
= array();
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 ) {
85 $fname = "Parser::parse";
86 wfProfileIn( $fname );
92 $this->mOptions
= $options;
93 $this->mTitle
=& $title;
94 $this->mOutputType
= OT_HTML
;
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
103 # french spaces, last one Guillemet-left
104 # only if there is something before the space
105 '/(.) (\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
106 # french spaces, Guillemet-right
107 "/(\\302\\253) /i"=>"\\1 ",
108 '/<hr *>/i' => '<hr />',
109 '/<br *>/i' => '<br />',
110 '/<center *>/i' => '<div class="center">',
111 '/<\\/center *>/i' => '</div>',
112 # Clean up spare ampersands; note that we probably ought to be
113 # more careful about named entities.
114 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
116 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
119 # french spaces, last one Guillemet-left
120 '/ (\\?|:|!|\\302\\273)/i' => ' \\1',
121 # french spaces, Guillemet-right
122 '/(\\302\\253) /i' => '\\1 ',
123 '/([^> ]+(0(1|3|9);)[^< ]*)/i' => '<span class="diacrit">\\1</span>',
124 '/<center *>/i' => '<div class="center">',
125 '/<\\/center *>/i' => '</div>'
127 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
130 $text = $this->doBlockLevels( $text, $linestart );
131 $text = $this->unstripNoWiki( $text, $this->mStripState
);
133 $text = $this->tidy($text);
135 $this->mOutput
->setText( $text );
136 wfProfileOut( $fname );
137 return $this->mOutput
;
140 /* static */ function getRandomString() {
141 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
144 # Replaces all occurrences of <$tag>content</$tag> in the text
145 # with a random marker and returns the new text. the output parameter
146 # $content will be an associative array filled with data on the form
147 # $unique_marker => content.
149 # If $content is already set, the additional entries will be appended
151 # If $tag is set to STRIP_COMMENTS, the function will extract
152 # <!-- HTML comments -->
154 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
155 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
162 while ( '' != $text ) {
163 if($tag==STRIP_COMMENTS
) {
164 $p = preg_split( '/<!--/i', $text, 2 );
166 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
169 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
172 if($tag==STRIP_COMMENTS
) {
173 $q = preg_split( '/-->/i', $p[1], 2 );
175 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
177 $marker = $rnd . sprintf('%08X', $n++
);
178 $content[$marker] = $q[0];
179 $stripped .= $marker;
186 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
187 # If $render is set, performs necessary rendering operations on plugins
188 # Returns the text, and fills an array with data needed in unstrip()
189 # If the $state is already a valid strip state, it adds to the state
191 # When $stripcomments is set, HTML comments <!-- like this -->
192 # will be stripped in addition to other tags. This is important
193 # for section editing, where these comments cause confusion when
194 # counting the sections in the wikisource
195 function strip( $text, &$state, $stripcomments = false ) {
196 $render = ($this->mOutputType
== OT_HTML
);
197 $nowiki_content = array();
198 $math_content = array();
199 $pre_content = array();
200 $comment_content = array();
201 $ext_content = array();
203 # Replace any instances of the placeholders
204 $uniq_prefix = UNIQ_PREFIX
;
205 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
209 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
210 foreach( $nowiki_content as $marker => $content ){
212 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
214 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
219 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
220 foreach( $math_content as $marker => $content ){
222 if( $this->mOptions
->getUseTeX() ) {
223 $math_content[$marker] = renderMath( $content );
225 $math_content[$marker] = "<math>$content<math>";
228 $math_content[$marker] = "<math>$content</math>";
233 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
234 foreach( $pre_content as $marker => $content ){
236 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
238 $pre_content[$marker] = "<pre>$content</pre>";
244 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
245 foreach( $comment_content as $marker => $content ){
246 $comment_content[$marker] = "<!--$content-->";
251 foreach ( $this->mTagHooks
as $tag => $callback ) {
252 $ext_contents[$tag] = array();
253 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
254 foreach( $ext_content[$tag] as $marker => $content ) {
256 $ext_content[$tag][$marker] = $callback( $content );
258 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
263 # Merge state with the pre-existing state, if there is one
265 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
266 $state['math'] = $state['math'] +
$math_content;
267 $state['pre'] = $state['pre'] +
$pre_content;
268 $state['comment'] = $state['comment'] +
$comment_content;
270 foreach( $ext_content as $tag => $array ) {
271 if ( array_key_exists( $tag, $state ) ) {
272 $state[$tag] = $state[$tag] +
$array;
277 'nowiki' => $nowiki_content,
278 'math' => $math_content,
279 'pre' => $pre_content,
280 'comment' => $comment_content,
286 # always call unstripNoWiki() after this one
287 function unstrip( $text, &$state ) {
288 # Must expand in reverse order, otherwise nested tags will be corrupted
289 $contentDict = end( $state );
290 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
291 if( key($state) != 'nowiki') {
292 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
293 $text = str_replace( key( $contentDict ), $content, $text );
300 # always call this after unstrip() to preserve the order
301 function unstripNoWiki( $text, &$state ) {
302 # Must expand in reverse order, otherwise nested tags will be corrupted
303 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
304 $text = str_replace( key( $state['nowiki'] ), $content, $text );
310 # Add an item to the strip state
311 # Returns the unique tag which must be inserted into the stripped text
312 # The tag will be replaced with the original text in unstrip()
314 function insertStripItem( $text, &$state ) {
315 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
323 $state['item'][$rnd] = $text;
328 # generate a list of subcategories and pages for a category
329 # depending on wfMsg("usenewcategorypage") it either calls the new
330 # or the old code. The new code will not work properly for some
331 # languages due to sorting issues, so they might want to turn it
333 function categoryMagic() {
334 $msg = wfMsg('usenewcategorypage');
335 if ( '0' == @$msg[0] )
337 return $this->oldCategoryMagic();
339 return $this->newCategoryMagic();
343 # This method generates the list of subcategories and pages for a category
344 function oldCategoryMagic () {
345 global $wgLang , $wgUser ;
346 $fname = 'Parser::oldCategoryMagic';
348 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
350 $cns = Namespace::getCategory() ;
351 if ( $this->mTitle
->getNamespace() != $cns ) return "" ; # This ain't a category page
353 $r = "<br style=\"clear:both;\"/>\n";
356 $sk =& $wgUser->getSkin() ;
358 $articles = array() ;
359 $children = array() ;
361 $id = $this->mTitle
->getArticleID() ;
364 $dbr =& wfGetDB( DB_READ
);
365 $cur = $dbr->tableName( 'cur' );
366 $categorylinks = $dbr->tableName( 'categorylinks' );
368 $t = $dbr->strencode( $this->mTitle
->getDBKey() );
369 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM $cur,$categorylinks " .
370 "WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
371 $res = $dbr->query( $sql, $fname ) ;
372 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
374 # For all pages that link to this category
375 foreach ( $data AS $x )
377 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
378 if ( $t != "" ) $t .= ":" ;
379 $t .= $x->cur_title
;
381 if ( $x->cur_namespace
== $cns ) {
382 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
384 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
387 $dbr->freeResult ( $res ) ;
389 # Showing subcategories
390 if ( count ( $children ) > 0 ) {
391 $r .= '<h2>'.wfMsg('subcategories')."</h2>\n" ;
392 $r .= implode ( ', ' , $children ) ;
395 # Showing pages in this category
396 if ( count ( $articles ) > 0 ) {
397 $ti = $this->mTitle
->getText() ;
398 $h = wfMsg( 'category_header', $ti );
399 $r .= "<h2>{$h}</h2>\n" ;
400 $r .= implode ( ', ' , $articles ) ;
408 function newCategoryMagic () {
409 global $wgLang , $wgUser ;
410 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
412 $cns = Namespace::getCategory() ;
413 if ( $this->mTitle
->getNamespace() != $cns ) return '' ; # This ain't a category page
415 $r = "<br style=\"clear:both;\"/>\n";
418 $sk =& $wgUser->getSkin() ;
420 $articles = array() ;
421 $articles_start_char = array();
422 $children = array() ;
423 $children_start_char = array();
425 $id = $this->mTitle
->getArticleID() ;
428 $dbr =& wfGetDB( DB_READ
);
429 $cur = $dbr->tableName( 'cur' );
430 $categorylinks = $dbr->tableName( 'categorylinks' );
432 $t = $dbr->strencode( $this->mTitle
->getDBKey() );
433 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM " .
434 "$cur,$categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
435 $res = $dbr->query ( $sql ) ;
436 while ( $x = $dbr->fetchObject ( $res ) )
438 $t = $ns = $wgLang->getNsText ( $x->cur_namespace
) ;
439 if ( $t != '' ) $t .= ':' ;
440 $t .= $x->cur_title
;
442 if ( $x->cur_namespace
== $cns ) {
443 $ctitle = str_replace( '_',' ',$x->cur_title
);
444 array_push ( $children, $sk->makeKnownLink ( $t, $ctitle ) ) ; # Subcategory
446 // If there's a link from Category:A to Category:B, the sortkey of the resulting
447 // entry in the categorylinks table is Category:A, not A, which it SHOULD be.
448 // Workaround: If sortkey == "Category:".$title, than use $title for sorting,
449 // else use sortkey...
450 if ( ($ns.":".$ctitle) == $x->cl_sortkey
) {
451 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title
) );
453 array_push ( $children_start_char, $wgLang->firstChar( $x->cl_sortkey
) ) ;
456 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
457 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey
) ) ;
460 $dbr->freeResult ( $res ) ;
462 $ti = $this->mTitle
->getText() ;
464 # Don't show subcategories section if there are none.
465 if ( count ( $children ) > 0 )
467 # Showing subcategories
468 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n"
469 . wfMsg( 'subcategorycount', count( $children ) );
470 if ( count ( $children ) > 6 ) {
472 // divide list into three equal chunks
473 $chunk = (int) (count ( $children ) / 3);
475 // get and display header
476 $r .= '<table width="100%"><tr valign="top">';
481 // loop through the chunks
482 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
484 $chunkIndex++
, $startChunk = $endChunk, $endChunk +
= $chunk +
1)
488 // output all subcategories to category
489 for ($index = $startChunk ;
490 $index < $endChunk && $index < count($children);
493 // check for change of starting letter or begging of chunk
494 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
495 ||
($index == $startChunk) )
497 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
500 $r .= "<li>{$children[$index]}</li>";
506 $r .= '</tr></table>';
508 // for short lists of subcategories to category.
510 $r .= "<h3>{$children_start_char[0]}</h3>\n";
511 $r .= '<ul><li>'.$children[0].'</li>';
512 for ($index = 1; $index < count($children); $index++
)
514 if ($children_start_char[$index] != $children_start_char[$index - 1])
516 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
519 $r .= "<li>{$children[$index]}</li>";
523 } # END of if ( count($children) > 0 )
525 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n" .
526 wfMsg( 'categoryarticlecount', count( $articles ) );
528 # Showing articles in this category
529 if ( count ( $articles ) > 6) {
530 $ti = $this->mTitle
->getText() ;
532 // divide list into three equal chunks
533 $chunk = (int) (count ( $articles ) / 3);
535 // get and display header
536 $r .= '<table width="100%"><tr valign="top">';
538 // loop through the chunks
539 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
541 $chunkIndex++
, $startChunk = $endChunk, $endChunk +
= $chunk +
1)
546 // output all articles in category
547 for ($index = $startChunk ;
548 $index < $endChunk && $index < count($articles);
551 // check for change of starting letter or begging of chunk
552 if ( ($articles_start_char[$index] != $articles_start_char[$index - 1])
553 ||
($index == $startChunk) )
555 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
558 $r .= "<li>{$articles[$index]}</li>";
564 $r .= '</tr></table>';
565 } elseif ( count ( $articles ) > 0) {
566 // for short lists of articles in categories.
567 $ti = $this->mTitle
->getText() ;
569 $r .= '<h3>'.$articles_start_char[0]."</h3>\n";
570 $r .= '<ul><li>'.$articles[0].'</li>';
571 for ($index = 1; $index < count($articles); $index++
)
573 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
575 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
578 $r .= "<li>{$articles[$index]}</li>";
587 # Return allowed HTML attributes
588 function getHTMLattrs () {
589 $htmlattrs = array( # Allowed attributes--no scripting, etc.
590 'title', 'align', 'lang', 'dir', 'width', 'height',
591 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
592 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
593 /* FONT */ 'type', 'start', 'value', 'compact',
594 /* For various lists, mostly deprecated but safe */
595 'summary', 'width', 'border', 'frame', 'rules',
596 'cellspacing', 'cellpadding', 'valign', 'char',
597 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
598 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
599 'id', 'class', 'name', 'style' /* For CSS */
604 # Remove non approved attributes and javascript in css
605 function fixTagAttributes ( $t ) {
606 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
607 $htmlattrs = $this->getHTMLattrs() ;
609 # Strip non-approved attributes from the tag
611 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
612 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
614 # Strip javascript "expression" from stylesheets. Brute force approach:
615 # If anythin offensive is found, all attributes of the HTML tag are dropped
618 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
619 wfMungeToUtf8( $t ) ) )
627 # interface with html tidy, used if $wgUseTidy = true
628 function tidy ( $text ) {
629 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
630 global $wgInputEncoding, $wgOutputEncoding;
631 $fname = 'Parser::tidy';
632 wfProfileIn( $fname );
635 switch(strtoupper($wgOutputEncoding)) {
637 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
640 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
643 $wgTidyOpts .= ' -raw';
646 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
647 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
648 '<head><title>test</title></head><body>'.$text.'</body></html>';
649 $descriptorspec = array(
650 0 => array('pipe', 'r'),
651 1 => array('pipe', 'w'),
652 2 => array('file', '/dev/null', 'a')
654 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
655 if (is_resource($process)) {
656 fwrite($pipes[0], $wrappedtext);
658 while (!feof($pipes[1])) {
659 $cleansource .= fgets($pipes[1], 1024);
662 $return_value = proc_close($process);
665 wfProfileOut( $fname );
667 if( $cleansource == '' && $text != '') {
668 wfDebug( "Tidy error detected!\n" );
669 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
675 # parse the wiki syntax used to render tables
676 function doTableStuff ( $t ) {
677 $fname = 'Parser::doTableStuff';
678 wfProfileIn( $fname );
680 $t = explode ( "\n" , $t ) ;
681 $td = array () ; # Is currently a td tag open?
682 $ltd = array () ; # Was it TD or TH?
683 $tr = array () ; # Is currently a tr tag open?
684 $ltr = array () ; # tr attributes
685 foreach ( $t AS $k => $x )
688 $fc = substr ( $x , 0 , 1 ) ;
689 if ( '{|' == substr ( $x , 0 , 2 ) )
691 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 2 ) ) . '>' ;
692 array_push ( $td , false ) ;
693 array_push ( $ltd , '' ) ;
694 array_push ( $tr , false ) ;
695 array_push ( $ltr , '' ) ;
697 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
698 else if ( '|}' == substr ( $x , 0 , 2 ) )
701 $l = array_pop ( $ltd ) ;
702 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
703 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
707 else if ( '|-' == substr ( $x , 0 , 2 ) ) # Allows for |---------------
709 $x = substr ( $x , 1 ) ;
710 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
712 $l = array_pop ( $ltd ) ;
713 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
714 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
717 array_push ( $tr , false ) ;
718 array_push ( $td , false ) ;
719 array_push ( $ltd , '' ) ;
720 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
722 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) # Caption
724 if ( '|+' == substr ( $x , 0 , 2 ) )
727 $x = substr ( $x , 1 ) ;
729 $after = substr ( $x , 1 ) ;
730 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
731 $after = explode ( '||' , $after ) ;
733 foreach ( $after AS $theline )
738 $tra = array_pop ( $ltr ) ;
739 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
740 array_push ( $tr , true ) ;
741 array_push ( $ltr , '' ) ;
744 $l = array_pop ( $ltd ) ;
745 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
746 if ( $fc == '|' ) $l = 'td' ;
747 else if ( $fc == '!' ) $l = 'th' ;
748 else if ( $fc == '+' ) $l = 'caption' ;
750 array_push ( $ltd , $l ) ;
751 $y = explode ( '|' , $theline , 2 ) ;
752 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
753 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
755 array_push ( $td , true ) ;
760 # Closing open td, tr && table
761 while ( count ( $td ) > 0 )
763 if ( array_pop ( $td ) ) $t[] = '</td>' ;
764 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
768 $t = implode ( "\n" , $t ) ;
769 # $t = $this->removeHTMLtags( $t );
770 wfProfileOut( $fname );
774 # Parses the text and adds the result to the strip state
775 # Returns the strip tag
776 function stripParse( $text, $newline, $args )
778 $text = $this->strip( $text, $this->mStripState
);
779 $text = $this->internalParse( $text, (bool)$newline, $args, false );
780 return $newline.$this->insertStripItem( $text, $this->mStripState
);
783 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
784 $fname = 'Parser::internalParse';
785 wfProfileIn( $fname );
787 $text = $this->removeHTMLtags( $text );
788 $text = $this->replaceVariables( $text, $args );
790 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
792 $text = $this->doHeadings( $text );
793 if($this->mOptions
->getUseDynamicDates()) {
794 global $wgDateFormatter;
795 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
797 $text = $this->doAllQuotes( $text );
798 // $text = $this->doExponent( $text );
799 $text = $this->replaceExternalLinks( $text );
800 $text = $this->replaceInternalLinks ( $text );
801 $text = $this->replaceInternalLinks ( $text );
802 //$text = $this->doTokenizedParser ( $text );
803 $text = $this->doTableStuff ( $text ) ;
804 $text = $this->magicISBN( $text );
805 $text = $this->magicRFC( $text );
806 $text = $this->formatHeadings( $text, $isMain );
807 $sk =& $this->mOptions
->getSkin();
808 $text = $sk->transformContent( $text );
810 if ( !isset ( $this->categoryMagicDone
) ) {
811 $text .= $this->categoryMagic () ;
812 $this->categoryMagicDone
= true ;
815 wfProfileOut( $fname );
819 # Parse ^^ tokens and return html
820 /* private */ function doExponent ( $text )
822 $fname = 'Parser::doExponent';
823 wfProfileIn( $fname);
824 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
825 wfProfileOut( $fname);
829 # Parse headers and return html
830 /* private */ function doHeadings( $text ) {
831 $fname = 'Parser::doHeadings';
832 wfProfileIn( $fname );
833 for ( $i = 6; $i >= 1; --$i ) {
834 $h = substr( '======', 0, $i );
835 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
836 "<h{$i}>\\1</h{$i}>\\2", $text );
838 wfProfileOut( $fname );
842 /* private */ function doAllQuotes( $text ) {
843 $fname = 'Parser::doAllQuotes';
844 wfProfileIn( $fname );
846 $lines = explode( "\n", $text );
847 foreach ( $lines as $line ) {
848 $outtext .= $this->doQuotes ( '', $line, '' ) . "\n";
850 $outtext = substr($outtext, 0,-1);
851 wfProfileOut( $fname );
855 /* private */ function doQuotes( $pre, $text, $mode ) {
856 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
857 $m1_strong = ($m[1] == "") ?
"" : "<strong>{$m[1]}</strong>";
858 $m1_em = ($m[1] == "") ?
"" : "<em>{$m[1]}</em>";
859 if ( substr ($m[2], 0, 1) == '\'' ) {
860 $m[2] = substr ($m[2], 1);
862 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ?
'both' : 'emstrong' );
863 } else if ($mode == 'strong') {
864 return $m1_strong . $this->doQuotes ( '', $m[2], '' );
865 } else if (($mode == 'emstrong') ||
($mode == 'both')) {
866 return $this->doQuotes ( '', $pre.$m1_strong.$m[2], 'em' );
867 } else if ($mode == 'strongem') {
868 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( '', $m[2], 'em' );
870 return $m[1] . $this->doQuotes ( '', $m[2], 'strong' );
873 if ($mode == 'strong') {
874 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ?
'both' : 'strongem' );
875 } else if ($mode == 'em') {
876 return $m1_em . $this->doQuotes ( '', $m[2], '' );
877 } else if ($mode == 'emstrong') {
878 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( '', $m[2], 'strong' );
879 } else if (($mode == 'strongem') ||
($mode == 'both')) {
880 return $this->doQuotes ( '', $pre.$m1_em.$m[2], 'strong' );
882 return $m[1] . $this->doQuotes ( '', $m[2], 'em' );
886 $text_strong = ($text == '') ?
'' : "<strong>{$text}</strong>";
887 $text_em = ($text == '') ?
'' : "<em>{$text}</em>";
890 } else if ($mode == 'em') {
891 return $pre . $text_em;
892 } else if ($mode == 'strong') {
893 return $pre . $text_strong;
894 } else if ($mode == 'strongem') {
895 return (($pre == '') && ($text == '')) ?
'' : "<strong>{$pre}{$text_em}</strong>";
897 return (($pre == '') && ($text == '')) ?
'' : "<em>{$pre}{$text_strong}</em>";
902 # Note: we have to do external links before the internal ones,
903 # and otherwise take great care in the order of things here, so
904 # that we don't end up interpreting some URLs twice.
906 /* private */ function replaceExternalLinks( $text ) {
907 $fname = 'Parser::replaceExternalLinks';
908 wfProfileIn( $fname );
909 $text = $this->subReplaceExternalLinks( $text, 'http', true );
910 $text = $this->subReplaceExternalLinks( $text, 'https', true );
911 $text = $this->subReplaceExternalLinks( $text, 'ftp', false );
912 $text = $this->subReplaceExternalLinks( $text, 'irc', false );
913 $text = $this->subReplaceExternalLinks( $text, 'gopher', false );
914 $text = $this->subReplaceExternalLinks( $text, 'news', false );
915 $text = $this->subReplaceExternalLinks( $text, 'mailto', false );
916 wfProfileOut( $fname );
920 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber ) {
921 $unique = '4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3';
922 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
924 # this is the list of separators that should be ignored if they
925 # are the last character of an URL but that should be included
926 # if they occur within the URL, e.g. "go to www.foo.com, where .."
927 # in this case, the last comma should not become part of the URL,
928 # but in "www.foo.com/123,2342,32.htm" it should.
930 $fnc = 'A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF';
931 $images = 'gif|png|jpg|jpeg';
933 # PLEASE NOTE: The curly braces { } are not part of the regex,
934 # they are interpreted as part of the string (used to tell PHP
935 # that the content of the string should be inserted there).
936 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
937 "((?i){$images})([^{$uc}]|$)/";
939 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
940 $sk =& $this->mOptions
->getSkin();
942 if ( $autonumber and $this->mOptions
->getAllowExternalImages() ) { # Use img tags only for HTTP urls
943 $s = preg_replace( $e1, '\\1' . $sk->makeImage( "{$unique}:\\3" .
944 '/\\4.\\5', '\\4.\\5' ) . '\\6', $s );
946 $s = preg_replace( $e2, '\\1' . "<a href=\"{$unique}:\\3\"" .
947 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
948 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
950 $s = str_replace( $unique, $protocol, $s );
952 $a = explode( "[{$protocol}:", " " . $s );
953 $s = array_shift( $a );
954 $s = substr( $s, 1 );
956 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
957 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
959 foreach ( $a as $line ) {
960 if ( preg_match( $e1, $line, $m ) ) {
961 $link = "{$protocol}:{$m[1]}";
963 if ( $autonumber ) { $text = "[" . ++
$this->mAutonumber
. "]"; }
964 else { $text = wfEscapeHTML( $link ); }
965 } else if ( preg_match( $e2, $line, $m ) ) {
966 $link = "{$protocol}:{$m[1]}";
970 $s .= "[{$protocol}:" . $line;
973 if( $link == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
976 # Expand the URL for printable version
977 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
979 $la = $sk->getExternalLinkAttributes( $link, $text );
980 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
987 /* private */ function replaceInternalLinks( $s ) {
988 global $wgLang, $wgLinkCache;
989 global $wgNamespacesWithSubpages, $wgLanguageCode;
990 static $fname = 'Parser::replaceInternalLinks' ;
991 wfProfileIn( $fname );
993 wfProfileIn( $fname.'-setup' );
995 # the % is needed to support urlencoded titles as well
996 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
997 $sk =& $this->mOptions
->getSkin();
999 $a = explode( '[[', ' ' . $s );
1000 $s = array_shift( $a );
1001 $s = substr( $s, 1 );
1003 # Match a link having the form [[namespace:link|alternate]]trail
1005 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1006 # Match the end of a line for a word that's not followed by whitespace,
1007 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1008 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1010 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1011 # Special and Media are pseudo-namespaces; no pages actually exist in them
1012 static $image = FALSE;
1013 static $special = FALSE;
1014 static $media = FALSE;
1015 static $category = FALSE;
1016 if ( !$image ) { $image = Namespace::getImage(); }
1017 if ( !$special ) { $special = Namespace::getSpecial(); }
1018 if ( !$media ) { $media = Namespace::getMedia(); }
1019 if ( !$category ) { $category = Namespace::getCategory(); }
1021 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1023 if ( $useLinkPrefixExtension ) {
1024 if ( preg_match( $e2, $s, $m ) ) {
1025 $first_prefix = $m[2];
1028 $first_prefix = false;
1034 wfProfileOut( $fname.'-setup' );
1036 foreach ( $a as $line ) {
1037 wfProfileIn( $fname.'-prefixhandling' );
1038 if ( $useLinkPrefixExtension ) {
1039 if ( preg_match( $e2, $s, $m ) ) {
1047 $prefix = $first_prefix;
1048 $first_prefix = false;
1051 wfProfileOut( $fname.'-prefixhandling' );
1053 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1055 # fix up urlencoded title texts
1056 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1058 } else { # Invalid form; output directly
1059 $s .= $prefix . '[[' . $line ;
1063 /* Valid link forms:
1065 :Foobar -- override special treatment of prefix (images, language links)
1066 /Foobar -- convert to CurrentPage/Foobar
1067 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1069 $c = substr($m[1],0,1);
1070 $noforce = ($c != ':');
1071 if( $c == '/' ) { # subpage
1072 if(substr($m[1],-1,1)=='/') { # / at end means we don't want the slash to be shown
1073 $m[1]=substr($m[1],1,strlen($m[1])-2);
1076 $noslash=substr($m[1],1);
1078 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) { # subpages allowed here
1079 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1082 } # this might be changed for ugliness reasons
1084 $link = $noslash; # no subpage allowed, use standard link
1086 } elseif( $noforce ) { # no subpage
1089 $link = substr( $m[1], 1 );
1091 $wasblank = ( '' == $text );
1095 $nt = Title
::newFromText( $link );
1097 $s .= $prefix . '[[' . $line;
1100 $ns = $nt->getNamespace();
1101 $iw = $nt->getInterWiki();
1103 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1104 array_push( $this->mOutput
->mLanguageLinks
, $nt->getPrefixedText() );
1105 $tmp = $prefix . $trail ;
1106 $s .= (trim($tmp) == '')?
'': $tmp;
1109 if ( $ns == $image ) {
1110 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1111 $wgLinkCache->addImageLinkObj( $nt );
1114 if ( $ns == $category ) {
1115 $t = $nt->getText() ;
1116 $nnt = Title
::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1118 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1119 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1120 $wgLinkCache->resume();
1122 $sortkey = $wasblank ?
$this->mTitle
->getPrefixedText() : $text;
1123 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1124 $this->mOutput
->mCategoryLinks
[] = $t ;
1125 $s .= $prefix . $trail ;
1129 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
1130 ( strpos( $link, '#' ) == FALSE ) ) {
1131 # Self-links are handled specially; generally de-link and change to bold.
1132 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1136 if( $ns == $media ) {
1137 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1138 $wgLinkCache->addImageLinkObj( $nt );
1140 } elseif( $ns == $special ) {
1141 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1144 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1146 wfProfileOut( $fname );
1150 # Some functions here used by doBlockLevels()
1152 /* private */ function closeParagraph() {
1154 if ( '' != $this->mLastSection
) {
1155 $result = '</' . $this->mLastSection
. ">\n";
1157 $this->mInPre
= false;
1158 $this->mLastSection
= '';
1161 # getCommon() returns the length of the longest common substring
1162 # of both arguments, starting at the beginning of both.
1164 /* private */ function getCommon( $st1, $st2 ) {
1165 $fl = strlen( $st1 );
1166 $shorter = strlen( $st2 );
1167 if ( $fl < $shorter ) { $shorter = $fl; }
1169 for ( $i = 0; $i < $shorter; ++
$i ) {
1170 if ( $st1{$i} != $st2{$i} ) { break; }
1174 # These next three functions open, continue, and close the list
1175 # element appropriate to the prefix character passed into them.
1177 /* private */ function openList( $char )
1179 $result = $this->closeParagraph();
1181 if ( '*' == $char ) { $result .= '<ul><li>'; }
1182 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1183 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1184 else if ( ';' == $char ) {
1185 $result .= '<dl><dt>';
1186 $this->mDTopen
= true;
1188 else { $result = '<!-- ERR 1 -->'; }
1193 /* private */ function nextItem( $char ) {
1194 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1195 else if ( ':' == $char ||
';' == $char ) {
1197 if ( $this->mDTopen
) { $close = '</dt>'; }
1198 if ( ';' == $char ) {
1199 $this->mDTopen
= true;
1200 return $close . '<dt>';
1202 $this->mDTopen
= false;
1203 return $close . '<dd>';
1206 return '<!-- ERR 2 -->';
1209 /* private */function closeList( $char ) {
1210 if ( '*' == $char ) { $text = '</li></ul>'; }
1211 else if ( '#' == $char ) { $text = '</li></ol>'; }
1212 else if ( ':' == $char ) {
1213 if ( $this->mDTopen
) {
1214 $this->mDTopen
= false;
1215 $text = '</dt></dl>';
1217 $text = '</dd></dl>';
1220 else { return '<!-- ERR 3 -->'; }
1224 /* private */ function doBlockLevels( $text, $linestart ) {
1225 $fname = 'Parser::doBlockLevels';
1226 wfProfileIn( $fname );
1228 # Parsing through the text line by line. The main thing
1229 # happening here is handling of block-level elements p, pre,
1230 # and making lists from lines starting with * # : etc.
1232 $textLines = explode( "\n", $text );
1234 $lastPrefix = $output = $lastLine = '';
1235 $this->mDTopen
= $inBlockElem = false;
1237 $paragraphStack = false;
1239 if ( !$linestart ) {
1240 $output .= array_shift( $textLines );
1242 foreach ( $textLines as $oLine ) {
1243 $lastPrefixLength = strlen( $lastPrefix );
1244 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1245 $preOpenMatch = preg_match("/<pre/i", $oLine );
1246 if (!$this->mInPre
) {
1247 $this->mInPre
= !empty($preOpenMatch);
1249 if ( !$this->mInPre
) {
1250 # Multiple prefixes may abut each other for nested lists.
1251 $prefixLength = strspn( $oLine, '*#:;' );
1252 $pref = substr( $oLine, 0, $prefixLength );
1255 $pref2 = str_replace( ';', ':', $pref );
1256 $t = substr( $oLine, $prefixLength );
1258 # Don't interpret any other prefixes in preformatted text
1260 $pref = $pref2 = '';
1265 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1266 # Same as the last item, so no need to deal with nesting or opening stuff
1267 $output .= $this->nextItem( substr( $pref, -1 ) );
1268 $paragraphStack = false;
1270 if ( ";" == substr( $pref, -1 ) ) {
1271 # The one nasty exception: definition lists work like this:
1272 # ; title : definition text
1273 # So we check for : in the remainder text to split up the
1274 # title and definition, without b0rking links.
1275 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1276 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1278 $output .= $term . $this->nextItem( ':' );
1282 } elseif( $prefixLength ||
$lastPrefixLength ) {
1283 # Either open or close a level...
1284 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1285 $paragraphStack = false;
1287 while( $commonPrefixLength < $lastPrefixLength ) {
1288 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1289 --$lastPrefixLength;
1291 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1292 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1294 while ( $prefixLength > $commonPrefixLength ) {
1295 $char = substr( $pref, $commonPrefixLength, 1 );
1296 $output .= $this->openList( $char );
1298 if ( ';' == $char ) {
1299 # FIXME: This is dupe of code above
1300 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1302 $output .= $term . $this->nextItem( ":" );
1306 ++
$commonPrefixLength;
1308 $lastPrefix = $pref2;
1310 if( 0 == $prefixLength ) {
1311 # No prefix (not in list)--go to paragraph mode
1312 $uniq_prefix = UNIQ_PREFIX
;
1313 // XXX: use a stack for nestable elements like span, table and div
1314 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1315 $closematch = preg_match(
1316 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1317 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1318 if ( $openmatch or $closematch ) {
1319 $paragraphStack = false;
1320 $output .= $this->closeParagraph();
1321 if($preOpenMatch and !$preCloseMatch) {
1322 $this->mInPre
= true;
1324 if ( $closematch ) {
1325 $inBlockElem = false;
1327 $inBlockElem = true;
1329 } else if ( !$inBlockElem && !$this->mInPre
) {
1330 if ( " " == $t{0} and trim($t) != '' ) {
1332 if ($this->mLastSection
!= 'pre') {
1333 $paragraphStack = false;
1334 $output .= $this->closeParagraph().'<pre>';
1335 $this->mLastSection
= 'pre';
1339 if ( '' == trim($t) ) {
1340 if ( $paragraphStack ) {
1341 $output .= $paragraphStack.'<br />';
1342 $paragraphStack = false;
1343 $this->mLastSection
= 'p';
1345 if ($this->mLastSection
!= 'p' ) {
1346 $output .= $this->closeParagraph();
1347 $this->mLastSection
= '';
1348 $paragraphStack = '<p>';
1350 $paragraphStack = '</p><p>';
1354 if ( $paragraphStack ) {
1355 $output .= $paragraphStack;
1356 $paragraphStack = false;
1357 $this->mLastSection
= 'p';
1358 } else if ($this->mLastSection
!= 'p') {
1359 $output .= $this->closeParagraph().'<p>';
1360 $this->mLastSection
= 'p';
1366 if ($paragraphStack === false) {
1370 while ( $prefixLength ) {
1371 $output .= $this->closeList( $pref2{$prefixLength-1} );
1374 if ( '' != $this->mLastSection
) {
1375 $output .= '</' . $this->mLastSection
. '>';
1376 $this->mLastSection
= '';
1379 wfProfileOut( $fname );
1383 # Return value of a magic variable (like PAGENAME)
1384 function getVariableValue( $index ) {
1385 global $wgLang, $wgSitename, $wgServer;
1388 case MAG_CURRENTMONTH
:
1390 case MAG_CURRENTMONTHNAME
:
1391 return $wgLang->getMonthName( date('n') );
1392 case MAG_CURRENTMONTHNAMEGEN
:
1393 return $wgLang->getMonthNameGen( date('n') );
1394 case MAG_CURRENTDAY
:
1397 return $this->mTitle
->getText();
1399 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1400 return $wgLang->getNsText($this->mTitle
->getNamespace()); // Patch by Dori
1401 case MAG_CURRENTDAYNAME
:
1402 return $wgLang->getWeekdayName( date('w')+
1 );
1403 case MAG_CURRENTYEAR
:
1405 case MAG_CURRENTTIME
:
1406 return $wgLang->time( wfTimestampNow(), false );
1407 case MAG_NUMBEROFARTICLES
:
1408 return wfNumberOfArticles();
1418 # initialise the magic variables (like CURRENTMONTHNAME)
1419 function initialiseVariables() {
1420 global $wgVariableIDs;
1421 $this->mVariables
= array();
1422 foreach ( $wgVariableIDs as $id ) {
1423 $mw =& MagicWord
::get( $id );
1424 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1428 /* private */ function replaceVariables( $text, $args = array() ) {
1429 global $wgLang, $wgScript, $wgArticlePath;
1431 $fname = 'Parser::replaceVariables';
1432 wfProfileIn( $fname );
1435 if ( !$this->mVariables
) {
1436 $this->initialiseVariables();
1438 $titleChars = Title
::legalChars();
1439 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1441 # This function is called recursively. To keep track of arguments we need a stack:
1442 array_push( $this->mArgStack
, $args );
1444 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1445 $GLOBALS['wgCurParser'] =& $this;
1448 if ( $this->mOutputType
== OT_HTML
) {
1449 # Variable substitution
1450 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1452 # Argument substitution
1453 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1455 # Template substitution
1456 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1457 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1459 array_pop( $this->mArgStack
);
1461 wfProfileOut( $fname );
1465 function variableSubstitution( $matches ) {
1466 if ( array_key_exists( $matches[1], $this->mVariables
) ) {
1467 $text = $this->mVariables
[$matches[1]];
1468 $this->mOutput
->mContainsOldMagic
= true;
1470 $text = $matches[0];
1475 function braceSubstitution( $matches ) {
1476 global $wgLinkCache, $wgLang;
1477 $fname = 'Parser::braceSubstitution';
1484 # $newline is an optional newline character before the braces
1485 # $part1 is the bit before the first |, and must contain only title characters
1486 # $args is a list of arguments, starting from index 0, not including $part1
1488 $newline = $matches[1];
1489 $part1 = $matches[2];
1490 # If the third subpattern matched anything, it will start with |
1491 if ( $matches[3] !== '' ) {
1492 $args = explode( '|', substr( $matches[3], 1 ) );
1496 $argc = count( $args );
1499 if ( strpos( $matches[0], '{{{' ) !== false ) {
1500 $text = $matches[0];
1507 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1508 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1509 if ( $this->mOutputType
!= OT_WIKI
) {
1510 # Invalid SUBST not replaced at PST time
1511 # Return without further processing
1512 $text = $matches[0];
1516 } elseif ( $this->mOutputType
== OT_WIKI
) {
1517 # SUBST not found in PST pass, do nothing
1518 $text = $matches[0];
1523 # MSG, MSGNW and INT
1526 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1527 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1530 # Remove obsolete MSG:
1531 $mwMsg =& MagicWord
::get( MAG_MSG
);
1532 $mwMsg->matchStartAndRemove( $part1 );
1535 # Check if it is an internal message
1536 $mwInt =& MagicWord
::get( MAG_INT
);
1537 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1538 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1539 $text = wfMsgReal( $part1, $args, true );
1547 # Check for NS: (namespace expansion)
1548 $mwNs = MagicWord
::get( MAG_NS
);
1549 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1550 if ( intval( $part1 ) ) {
1551 $text = $wgLang->getNsText( intval( $part1 ) );
1554 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1555 if ( !is_null( $index ) ) {
1556 $text = $wgLang->getNsText( $index );
1563 # LOCALURL and LOCALURLE
1565 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1566 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1568 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1569 $func = 'getLocalURL';
1570 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1571 $func = 'escapeLocalURL';
1576 if ( $func !== '' ) {
1577 $title = Title
::newFromText( $part1 );
1578 if ( !is_null( $title ) ) {
1580 $text = $title->$func( $args[0] );
1582 $text = $title->$func();
1589 # Internal variables
1590 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1591 $text = $this->mVariables
[$part1];
1593 $this->mOutput
->mContainsOldMagic
= true;
1596 # Arguments input from the caller
1597 $inputArgs = end( $this->mArgStack );
1598 if ( !$found && array_key_exists( $part1, $inputArgs ) ) {
1599 $text = $inputArgs[$part1];
1603 # Load from database
1605 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1606 if ( !is_null( $title ) && !$title->isExternal() ) {
1607 # Check for excessive inclusion
1608 $dbk = $title->getPrefixedDBkey();
1609 if ( $this->incrementIncludeCount( $dbk ) ) {
1610 $article = new Article( $title );
1611 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1612 if ( $articleContent !== false ) {
1614 $text = $articleContent;
1619 # If the title is valid but undisplayable, make a link to it
1620 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1621 $text = '[[' . $title->getPrefixedText() . ']]';
1627 # Recursive parsing, escaping and link table handling
1628 # Only for HTML output
1629 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1630 $text = wfEscapeWikiText( $text );
1631 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1632 # Clean up argument array
1633 $assocArgs = array();
1635 foreach( $args as $arg ) {
1636 $eqpos = strpos( $arg, '=' );
1637 if ( $eqpos === false ) {
1638 $assocArgs[$index++
] = $arg;
1640 $name = trim( substr( $arg, 0, $eqpos ) );
1641 $value = trim( substr( $arg, $eqpos+
1 ) );
1642 if ( $value === false ) {
1645 if ( $name !== false ) {
1646 $assocArgs[$name] = $value;
1651 # Do not enter included links in link table
1652 if ( !is_null( $title ) ) {
1653 $wgLinkCache->suspend();
1656 # Run full parser on the included text
1657 $text = $this->stripParse( $text, $newline, $assocArgs );
1659 # Resume the link cache and register the inclusion as a link
1660 if ( !is_null( $title ) ) {
1661 $wgLinkCache->resume();
1662 $wgLinkCache->addLinkObj( $title );
1673 # Triple brace replacement -- used for template arguments
1674 function argSubstitution( $matches ) {
1675 $newline = $matches[1];
1676 $arg = trim( $matches[2] );
1677 $text = $matches[0];
1678 $inputArgs = end( $this->mArgStack
);
1680 if ( array_key_exists( $arg, $inputArgs ) ) {
1681 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1687 # Returns true if the function is allowed to include this entity
1688 function incrementIncludeCount( $dbk ) {
1689 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1690 $this->mIncludeCount
[$dbk] = 0;
1692 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1700 # Cleans up HTML, removes dangerous tags and attributes
1701 /* private */ function removeHTMLtags( $text ) {
1702 global $wgUseTidy, $wgUserHtml;
1703 $fname = 'Parser::removeHTMLtags';
1704 wfProfileIn( $fname );
1707 $htmlpairs = array( # Tags that must be closed
1708 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1709 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1710 'strike', 'strong', 'tt', 'var', 'div', 'center',
1711 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1712 'ruby', 'rt' , 'rb' , 'rp', 'p'
1714 $htmlsingle = array(
1715 'br', 'hr', 'li', 'dt', 'dd'
1717 $htmlnest = array( # Tags that can be nested--??
1718 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1719 'dl', 'font', 'big', 'small', 'sub', 'sup'
1721 $tabletags = array( # Can only appear inside table
1725 $htmlpairs = array();
1726 $htmlsingle = array();
1727 $htmlnest = array();
1728 $tabletags = array();
1731 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1732 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1734 $htmlattrs = $this->getHTMLattrs () ;
1736 # Remove HTML comments
1737 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1739 $bits = explode( '<', $text );
1740 $text = array_shift( $bits );
1742 $tagstack = array(); $tablestack = array();
1743 foreach ( $bits as $x ) {
1744 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1745 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1747 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1748 error_reporting( $prev );
1751 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1755 if ( ! in_array( $t, $htmlsingle ) &&
1756 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
1757 @array_push
( $tagstack, $ot );
1760 if ( $t == 'table' ) {
1761 $tagstack = array_pop( $tablestack );
1766 # Keep track for later
1767 if ( in_array( $t, $tabletags ) &&
1768 ! in_array( 'table', $tagstack ) ) {
1770 } else if ( in_array( $t, $tagstack ) &&
1771 ! in_array ( $t , $htmlnest ) ) {
1773 } else if ( ! in_array( $t, $htmlsingle ) ) {
1774 if ( $t == 'table' ) {
1775 array_push( $tablestack, $tagstack );
1776 $tagstack = array();
1778 array_push( $tagstack, $t );
1780 # Strip non-approved attributes from the tag
1781 $newparams = $this->fixTagAttributes($params);
1785 $rest = str_replace( '>', '>', $rest );
1786 $text .= "<$slash$t $newparams$brace$rest";
1790 $text .= '<' . str_replace( '>', '>', $x);
1792 # Close off any remaining tags
1793 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1795 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1798 # this might be possible using tidy itself
1799 foreach ( $bits as $x ) {
1800 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1802 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1803 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1804 $newparams = $this->fixTagAttributes($params);
1805 $rest = str_replace( '>', '>', $rest );
1806 $text .= "<$slash$t $newparams$brace$rest";
1808 $text .= '<' . str_replace( '>', '>', $x);
1812 wfProfileOut( $fname );
1819 * This function accomplishes several tasks:
1820 * 1) Auto-number headings if that option is enabled
1821 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1822 * 3) Add a Table of contents on the top for users who have enabled the option
1823 * 4) Auto-anchor headings
1825 * It loops through all headlines, collects the necessary data, then splits up the
1826 * string and re-inserts the newly formatted headlines.
1830 /* private */ function formatHeadings( $text, $isMain=true ) {
1831 global $wgInputEncoding;
1833 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
1834 $doShowToc = $this->mOptions
->getShowToc();
1835 $forceTocHere = false;
1836 if( !$this->mTitle
->userCanEdit() ) {
1838 $rightClickHack = 0;
1840 $showEditLink = $this->mOptions
->getEditSection();
1841 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
1844 # Inhibit editsection links if requested in the page
1845 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
1846 if( $esw->matchAndRemove( $text ) ) {
1849 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1851 $mw =& MagicWord
::get( MAG_NOTOC
);
1852 if( $mw->matchAndRemove( $text ) ) {
1856 # never add the TOC to the Main Page. This is an entry page that should not
1857 # be more than 1-2 screens large anyway
1858 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
1862 # Get all headlines for numbering them and adding funky stuff like [edit]
1863 # links - this is for later, but we need the number of headlines right now
1864 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1866 # if there are fewer than 4 headlines in the article, do not show TOC
1867 if( $numMatches < 4 ) {
1871 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
1872 # override above conditions and always show TOC at that place
1873 $mw =& MagicWord
::get( MAG_TOC
);
1874 if ($mw->match( $text ) ) {
1876 $forceTocHere = true;
1878 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1879 # override above conditions and always show TOC above first header
1880 $mw =& MagicWord
::get( MAG_FORCETOC
);
1881 if ($mw->matchAndRemove( $text ) ) {
1888 # We need this to perform operations on the HTML
1889 $sk =& $this->mOptions
->getSkin();
1894 # Ugh .. the TOC should have neat indentation levels which can be
1895 # passed to the skin functions. These are determined here
1900 $sublevelCount = array();
1903 foreach( $matches[3] as $headline ) {
1906 $prevlevel = $level;
1908 $level = $matches[1][$headlineCount];
1909 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
1910 # reset when we enter a new level
1911 $sublevelCount[$level] = 0;
1912 $toc .= $sk->tocIndent( $level - $prevlevel );
1913 $toclevel +
= $level - $prevlevel;
1915 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
1916 # reset when we step back a level
1917 $sublevelCount[$level+
1]=0;
1918 $toc .= $sk->tocUnindent( $prevlevel - $level );
1919 $toclevel -= $prevlevel - $level;
1921 # count number of headlines for each level
1922 @$sublevelCount[$level]++
;
1923 if( $doNumberHeadings ||
$doShowToc ) {
1925 for( $i = 1; $i <= $level; $i++
) {
1926 if( !empty( $sublevelCount[$i] ) ) {
1930 $numbering .= $sublevelCount[$i];
1936 # The canonized header is a version of the header text safe to use for links
1937 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1938 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
1939 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
1942 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
1943 $tocline = trim( $canonized_headline );
1944 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
1945 $replacearray = array(
1949 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
1950 $refer[$headlineCount] = $canonized_headline;
1952 # count how many in assoc. array so we can track dupes in anchors
1953 @$refers[$canonized_headline]++
;
1954 $refcount[$headlineCount]=$refers[$canonized_headline];
1956 # Prepend the number to the heading text
1958 if( $doNumberHeadings ||
$doShowToc ) {
1959 $tocline = $numbering . ' ' . $tocline;
1961 # Don't number the heading if it is the only one (looks silly)
1962 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1963 # the two are different if the line contains a link
1964 $headline=$numbering . ' ' . $headline;
1968 # Create the anchor for linking from the TOC to the section
1969 $anchor = $canonized_headline;
1970 if($refcount[$headlineCount] > 1 ) {
1971 $anchor .= '_' . $refcount[$headlineCount];
1974 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1976 if( $showEditLink ) {
1977 if ( empty( $head[$headlineCount] ) ) {
1978 $head[$headlineCount] = '';
1980 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
1983 # Add the edit section span
1984 if( $rightClickHack ) {
1985 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
1988 # give headline the correct <h#> tag
1989 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1995 $toclines = $headlineCount;
1996 $toc .= $sk->tocUnindent( $toclevel );
1997 $toc = $sk->tocTable( $toc );
2000 # split up and insert constructed headlines
2002 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2005 foreach( $blocks as $block ) {
2006 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2007 # This is the [edit] link that appears for the top block of text when
2008 # section editing is enabled
2010 # Disabled because it broke block formatting
2011 # For example, a bullet point in the top line
2012 # $full .= $sk->editSectionLink(0);
2015 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2016 # Top anchor now in skin
2020 if( !empty( $head[$i] ) ) {
2026 $mw =& MagicWord
::get( MAG_TOC
);
2027 return $mw->replace( $toc, $full );
2033 # Return an HTML link for the "ISBN 123456" text
2034 /* private */ function magicISBN( $text ) {
2036 $fname = 'Parser::magicISBN';
2037 wfProfileIn( $fname );
2039 $a = split( 'ISBN ', " $text" );
2040 if ( count ( $a ) < 2 ) {
2041 wfProfileOut( $fname );
2044 $text = substr( array_shift( $a ), 1);
2045 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2047 foreach ( $a as $x ) {
2048 $isbn = $blank = '' ;
2049 while ( ' ' == $x{0} ) {
2051 $x = substr( $x, 1 );
2053 while ( strstr( $valid, $x{0} ) != false ) {
2055 $x = substr( $x, 1 );
2057 $num = str_replace( '-', '', $isbn );
2058 $num = str_replace( ' ', '', $num );
2061 $text .= "ISBN $blank$x";
2063 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2064 $text .= '<a href="' .
2065 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2066 "\" class=\"internal\">ISBN $isbn</a>";
2070 wfProfileOut( $fname );
2074 # Return an HTML link for the "RFC 1234" text
2075 /* private */ function magicRFC( $text ) {
2078 $a = split( 'RFC ', ' '.$text );
2079 if ( count ( $a ) < 2 ) return $text;
2080 $text = substr( array_shift( $a ), 1);
2081 $valid = '0123456789';
2083 foreach ( $a as $x ) {
2084 $rfc = $blank = '' ;
2085 while ( ' ' == $x{0} ) {
2087 $x = substr( $x, 1 );
2089 while ( strstr( $valid, $x{0} ) != false ) {
2091 $x = substr( $x, 1 );
2095 $text .= "RFC $blank$x";
2097 $url = wfmsg( 'rfcurl' );
2098 $url = str_replace( '$1', $rfc, $url);
2099 $sk =& $this->mOptions
->getSkin();
2100 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2101 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2107 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2108 $this->mOptions
= $options;
2109 $this->mTitle
=& $title;
2110 $this->mOutputType
= OT_WIKI
;
2112 if ( $clearState ) {
2113 $this->clearState();
2116 $stripState = false;
2120 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2124 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2125 "/<br *?>/i" => "<br />",
2127 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2129 $text = $this->strip( $text, $stripState, false );
2130 $text = $this->pstPass2( $text, $user );
2131 $text = $this->unstrip( $text, $stripState );
2132 $text = $this->unstripNoWiki( $text, $stripState );
2136 /* private */ function pstPass2( $text, &$user ) {
2137 global $wgLang, $wgLocaltimezone, $wgCurParser;
2139 # Variable replacement
2140 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2141 $text = $this->replaceVariables( $text );
2145 $n = $user->getName();
2146 $k = $user->getOption( 'nickname' );
2147 if ( '' == $k ) { $k = $n; }
2148 if(isset($wgLocaltimezone)) {
2149 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2151 /* Note: this is an ugly timezone hack for the European wikis */
2152 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2153 ' (' . date( 'T' ) . ')';
2154 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2156 $text = preg_replace( '/~~~~~/', $d, $text );
2157 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText(
2158 Namespace::getUser() ) . ":$n|$k]] $d", $text );
2159 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText(
2160 Namespace::getUser() ) . ":$n|$k]]", $text );
2162 # Context links: [[|name]] and [[name (context)|]]
2164 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2165 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2166 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2167 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2169 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2170 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2171 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2172 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2173 # [[ns:page (cont)|]]
2175 $t = $this->mTitle
->getText();
2176 if ( preg_match( $conpat, $t, $m ) ) {
2179 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2180 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2181 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2183 if ( '' == $context ) {
2184 $text = preg_replace( $p2, '[[\\1]]', $text );
2186 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2190 $mw =& MagicWord::get( MAG_SUBST );
2191 $wgCurParser = $this->fork();
2192 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2193 $this->merge( $wgCurParser );
2196 # Trim trailing whitespace
2197 # MAG_END (__END__) tag allows for trailing
2198 # whitespace to be deliberately included
2199 $text = rtrim( $text );
2200 $mw =& MagicWord
::get( MAG_END
);
2201 $mw->matchAndRemove( $text );
2206 # Set up some variables which are usually set up in parse()
2207 # so that an external function can call some class members with confidence
2208 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2209 $this->mTitle
=& $title;
2210 $this->mOptions
= $options;
2211 $this->mOutputType
= $outputType;
2212 if ( $clearState ) {
2213 $this->clearState();
2217 function transformMsg( $text, $options ) {
2219 static $executing = false;
2221 # Guard against infinite recursion
2227 $this->mTitle
= $wgTitle;
2228 $this->mOptions
= $options;
2229 $this->mOutputType
= OT_MSG
;
2230 $this->clearState();
2231 $text = $this->replaceVariables( $text );
2237 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2238 # Callback will be called with the text within
2239 # Transform and return the text within
2240 function setHook( $tag, $callback ) {
2241 $oldVal = @$this->mTagHooks
[$tag];
2242 $this->mTagHooks
[$tag] = $callback;
2249 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2250 var $mCacheTime; # Used in ParserCache
2252 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2253 $containsOldMagic = false )
2255 $this->mText
= $text;
2256 $this->mLanguageLinks
= $languageLinks;
2257 $this->mCategoryLinks
= $categoryLinks;
2258 $this->mContainsOldMagic
= $containsOldMagic;
2259 $this->mCacheTime
= "";
2262 function getText() { return $this->mText
; }
2263 function getLanguageLinks() { return $this->mLanguageLinks
; }
2264 function getCategoryLinks() { return $this->mCategoryLinks
; }
2265 function getCacheTime() { return $this->mCacheTime
; }
2266 function containsOldMagic() { return $this->mContainsOldMagic
; }
2267 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2268 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2269 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2270 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2271 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2273 function merge( $other ) {
2274 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2275 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2276 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2283 # All variables are private
2284 var $mUseTeX; # Use texvc to expand <math> tags
2285 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2286 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2287 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2288 var $mAllowExternalImages; # Allow external images inline
2289 var $mSkin; # Reference to the preferred skin
2290 var $mDateFormat; # Date format index
2291 var $mEditSection; # Create "edit section" links
2292 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2293 var $mNumberHeadings; # Automatically number headings
2294 var $mShowToc; # Show table of contents
2296 function getUseTeX() { return $this->mUseTeX
; }
2297 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
2298 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2299 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2300 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2301 function getSkin() { return $this->mSkin
; }
2302 function getDateFormat() { return $this->mDateFormat
; }
2303 function getEditSection() { return $this->mEditSection
; }
2304 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2305 function getNumberHeadings() { return $this->mNumberHeadings
; }
2306 function getShowToc() { return $this->mShowToc
; }
2308 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2309 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
2310 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2311 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2312 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2313 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2314 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2315 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2316 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2317 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2319 function setSkin( &$x ) { $this->mSkin
=& $x; }
2321 /* static */ function newFromUser( &$user ) {
2322 $popts = new ParserOptions
;
2323 $popts->initialiseFromUser( $user );
2327 function initialiseFromUser( &$userInput ) {
2328 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2330 if ( !$userInput ) {
2332 $user->setLoaded( true );
2334 $user =& $userInput;
2337 $this->mUseTeX
= $wgUseTeX;
2338 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2339 $this->mUseDynamicDates
= $wgUseDynamicDates;
2340 $this->mInterwikiMagic
= $wgInterwikiMagic;
2341 $this->mAllowExternalImages
= $wgAllowExternalImages;
2342 $this->mSkin
=& $user->getSkin();
2343 $this->mDateFormat
= $user->getOption( 'date' );
2344 $this->mEditSection
= $user->getOption( 'editsection' );
2345 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2346 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2347 $this->mShowToc
= $user->getOption( 'showtoc' );
2353 # Regex callbacks, used in Parser::replaceVariables
2354 function wfBraceSubstitution( $matches )
2356 global $wgCurParser;
2357 return $wgCurParser->braceSubstitution( $matches );
2360 function wfArgSubstitution( $matches )
2362 global $wgCurParser;
2363 return $wgCurParser->argSubstitution( $matches );
2366 function wfVariableSubstitution( $matches )
2368 global $wgCurParser;
2369 return $wgCurParser->variableSubstitution( $matches );