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');
51 # Constants needed for external link processing
53 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
54 define( 'HTTP_PROTOCOLS', 'http|https' );
55 # Everything except bracket, space, or control characters
56 define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
57 define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
59 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
60 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
61 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
62 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
63 define( 'EXT_IMAGE_REGEX',
64 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
65 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
66 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
74 # Cleared with clearState():
75 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
76 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
79 var $mOptions, $mTitle, $mOutputType,
80 $mTemplates, // cache of already loaded templates, avoids
81 // multiple SQL queries for the same string
82 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
83 // in this path. Used for loop detection.
86 $this->mTemplates
= array();
87 $this->mTemplatePath
= array();
88 $this->mTagHooks
= array();
92 function clearState() {
93 $this->mOutput
= new ParserOutput
;
94 $this->mAutonumber
= 0;
95 $this->mLastSection
= "";
96 $this->mDTopen
= false;
97 $this->mVariables
= false;
98 $this->mIncludeCount
= array();
99 $this->mStripState
= array();
100 $this->mArgStack
= array();
101 $this->mInPre
= false;
104 # First pass--just handle <nowiki> sections, pass the rest off
105 # to internalParse() which does all the real work.
107 # Returns a ParserOutput
109 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
111 $fname = "Parser::parse";
112 wfProfileIn( $fname );
118 $this->mOptions
= $options;
119 $this->mTitle
=& $title;
120 $this->mOutputType
= OT_HTML
;
123 $text = $this->strip( $text, $this->mStripState
);
124 $text = $this->internalParse( $text, $linestart );
125 $text = $this->unstrip( $text, $this->mStripState
);
126 # Clean up special characters, only run once, next-to-last before doBlockLevels
129 # french spaces, last one Guillemet-left
130 # only if there is something before the space
131 '/(.) (\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
132 # french spaces, Guillemet-right
133 "/(\\302\\253) /i"=>"\\1 ",
134 '/<hr *>/i' => '<hr />',
135 '/<br *>/i' => '<br />',
136 '/<center *>/i' => '<div class="center">',
137 '/<\\/center *>/i' => '</div>',
138 # Clean up spare ampersands; note that we probably ought to be
139 # more careful about named entities.
140 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
142 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
145 # french spaces, last one Guillemet-left
146 '/ (\\?|:|!|\\302\\273)/i' => ' \\1',
147 # french spaces, Guillemet-right
148 '/(\\302\\253) /i' => '\\1 ',
149 '/([^> ]+(0(1|3|9);)[^< ]*)/i' => '<span class="diacrit">\\1</span>',
150 '/<center *>/i' => '<div class="center">',
151 '/<\\/center *>/i' => '</div>'
153 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
156 $text = $this->doBlockLevels( $text, $linestart );
157 $text = $this->unstripNoWiki( $text, $this->mStripState
);
159 $text = $this->tidy($text);
161 $this->mOutput
->setText( $text );
162 wfProfileOut( $fname );
163 return $this->mOutput
;
166 /* static */ function getRandomString() {
167 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
170 # Replaces all occurrences of <$tag>content</$tag> in the text
171 # with a random marker and returns the new text. the output parameter
172 # $content will be an associative array filled with data on the form
173 # $unique_marker => content.
175 # If $content is already set, the additional entries will be appended
177 # If $tag is set to STRIP_COMMENTS, the function will extract
178 # <!-- HTML comments -->
180 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
181 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
188 while ( '' != $text ) {
189 if($tag==STRIP_COMMENTS
) {
190 $p = preg_split( '/<!--/i', $text, 2 );
192 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
195 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
198 if($tag==STRIP_COMMENTS
) {
199 $q = preg_split( '/-->/i', $p[1], 2 );
201 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
203 $marker = $rnd . sprintf('%08X', $n++
);
204 $content[$marker] = $q[0];
205 $stripped .= $marker;
212 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
213 # If $render is set, performs necessary rendering operations on plugins
214 # Returns the text, and fills an array with data needed in unstrip()
215 # If the $state is already a valid strip state, it adds to the state
217 # When $stripcomments is set, HTML comments <!-- like this -->
218 # will be stripped in addition to other tags. This is important
219 # for section editing, where these comments cause confusion when
220 # counting the sections in the wikisource
221 function strip( $text, &$state, $stripcomments = false ) {
222 $render = ($this->mOutputType
== OT_HTML
);
223 $html_content = array();
224 $nowiki_content = array();
225 $math_content = array();
226 $pre_content = array();
227 $comment_content = array();
228 $ext_content = array();
230 # Replace any instances of the placeholders
231 $uniq_prefix = UNIQ_PREFIX
;
232 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
237 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
238 foreach( $html_content as $marker => $content ) {
240 # Raw and unchecked for validity.
241 $html_content[$marker] = $content;
243 $html_content[$marker] = "<html>$content</html>";
249 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
250 foreach( $nowiki_content as $marker => $content ) {
252 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
254 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
259 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
260 foreach( $math_content as $marker => $content ){
262 if( $this->mOptions
->getUseTeX() ) {
263 $math_content[$marker] = renderMath( $content );
265 $math_content[$marker] = "<math>$content<math>";
268 $math_content[$marker] = "<math>$content</math>";
273 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
274 foreach( $pre_content as $marker => $content ){
276 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
278 $pre_content[$marker] = "<pre>$content</pre>";
284 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
285 foreach( $comment_content as $marker => $content ){
286 $comment_content[$marker] = "<!--$content-->";
291 foreach ( $this->mTagHooks
as $tag => $callback ) {
292 $ext_contents[$tag] = array();
293 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
294 foreach( $ext_content[$tag] as $marker => $content ) {
296 $ext_content[$tag][$marker] = $callback( $content );
298 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
303 # Merge state with the pre-existing state, if there is one
305 $state['html'] = $state['html'] +
$html_content;
306 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
307 $state['math'] = $state['math'] +
$math_content;
308 $state['pre'] = $state['pre'] +
$pre_content;
309 $state['comment'] = $state['comment'] +
$comment_content;
311 foreach( $ext_content as $tag => $array ) {
312 if ( array_key_exists( $tag, $state ) ) {
313 $state[$tag] = $state[$tag] +
$array;
318 'html' => $html_content,
319 'nowiki' => $nowiki_content,
320 'math' => $math_content,
321 'pre' => $pre_content,
322 'comment' => $comment_content,
328 # always call unstripNoWiki() after this one
329 function unstrip( $text, &$state ) {
330 # Must expand in reverse order, otherwise nested tags will be corrupted
331 $contentDict = end( $state );
332 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
333 if( key($state) != 'nowiki' && key($state) != 'html') {
334 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
335 $text = str_replace( key( $contentDict ), $content, $text );
342 # always call this after unstrip() to preserve the order
343 function unstripNoWiki( $text, &$state ) {
344 # Must expand in reverse order, otherwise nested tags will be corrupted
345 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
346 $text = str_replace( key( $state['nowiki'] ), $content, $text );
351 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
352 $text = str_replace( key( $state['html'] ), $content, $text );
359 # Add an item to the strip state
360 # Returns the unique tag which must be inserted into the stripped text
361 # The tag will be replaced with the original text in unstrip()
363 function insertStripItem( $text, &$state ) {
364 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
373 $state['item'][$rnd] = $text;
378 # generate a list of subcategories and pages for a category
379 # depending on wfMsg("usenewcategorypage") it either calls the new
380 # or the old code. The new code will not work properly for some
381 # languages due to sorting issues, so they might want to turn it
383 function categoryMagic() {
384 $msg = wfMsg('usenewcategorypage');
385 if ( '0' == @$msg[0] )
387 return $this->oldCategoryMagic();
389 return $this->newCategoryMagic();
393 # This method generates the list of subcategories and pages for a category
394 function oldCategoryMagic () {
396 $fname = 'Parser::oldCategoryMagic';
398 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
400 if ( $this->mTitle
->getNamespace() != NS_CATEGORY
) return "" ; # This ain't a category page
402 $r = "<br style=\"clear:both;\"/>\n";
405 $sk =& $this->mOptions
->getSkin() ;
407 $articles = array() ;
408 $children = array() ;
410 $id = $this->mTitle
->getArticleID() ;
413 $dbr =& wfGetDB( DB_SLAVE
);
414 $cur = $dbr->tableName( 'cur' );
415 $categorylinks = $dbr->tableName( 'categorylinks' );
417 $t = $dbr->strencode( $this->mTitle
->getDBKey() );
418 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM $cur,$categorylinks " .
419 "WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
420 $res = $dbr->query( $sql, $fname ) ;
421 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
423 # For all pages that link to this category
424 foreach ( $data AS $x )
426 $t = $wgLang->getNsText ( $x->cur_namespace
) ;
427 if ( $t != "" ) $t .= ":" ;
428 $t .= $x->cur_title
;
430 if ( $x->cur_namespace
== NS_CATEGORY
) {
431 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
433 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
436 $dbr->freeResult ( $res ) ;
438 # Showing subcategories
439 if ( count ( $children ) > 0 ) {
440 $r .= '<h2>'.wfMsg('subcategories')."</h2>\n" ;
441 $r .= implode ( ', ' , $children ) ;
444 # Showing pages in this category
445 if ( count ( $articles ) > 0 ) {
446 $ti = $this->mTitle
->getText() ;
447 $h = wfMsg( 'category_header', $ti );
448 $r .= "<h2>{$h}</h2>\n" ;
449 $r .= implode ( ', ' , $articles ) ;
457 function newCategoryMagic () {
459 if ( !$this->mOptions
->getUseCategoryMagic() ) return ; # Doesn't use categories at all
461 if ( $this->mTitle
->getNamespace() != NS_CATEGORY
) return '' ; # This ain't a category page
463 $r = "<br style=\"clear:both;\"/>\n";
466 $sk =& $this->mOptions
->getSkin() ;
468 $articles = array() ;
469 $articles_start_char = array();
470 $children = array() ;
471 $children_start_char = array();
473 $id = $this->mTitle
->getArticleID() ;
476 $dbr =& wfGetDB( DB_SLAVE
);
477 $cur = $dbr->tableName( 'cur' );
478 $categorylinks = $dbr->tableName( 'categorylinks' );
480 $t = $dbr->strencode( $this->mTitle
->getDBKey() );
481 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM " .
482 "$cur,$categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
483 $res = $dbr->query ( $sql ) ;
484 while ( $x = $dbr->fetchObject ( $res ) )
486 $t = $ns = $wgLang->getNsText ( $x->cur_namespace
) ;
487 if ( $t != '' ) $t .= ':' ;
488 $t .= $x->cur_title
;
490 if ( $x->cur_namespace
== NS_CATEGORY
) {
491 $ctitle = str_replace( '_',' ',$x->cur_title
);
492 array_push ( $children, $sk->makeKnownLink ( $t, $ctitle ) ) ; # Subcategory
494 // If there's a link from Category:A to Category:B, the sortkey of the resulting
495 // entry in the categorylinks table is Category:A, not A, which it SHOULD be.
496 // Workaround: If sortkey == "Category:".$title, than use $title for sorting,
497 // else use sortkey...
498 if ( ($ns.":".$ctitle) == $x->cl_sortkey
) {
499 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title
) );
501 array_push ( $children_start_char, $wgLang->firstChar( $x->cl_sortkey
) ) ;
504 array_push ( $articles , $sk->makeKnownLink ( $t ) ) ; # Page in this category
505 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey
) ) ;
508 $dbr->freeResult ( $res ) ;
510 $ti = $this->mTitle
->getText() ;
512 # Don't show subcategories section if there are none.
513 if ( count ( $children ) > 0 )
515 # Showing subcategories
516 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n"
517 . wfMsg( 'subcategorycount', count( $children ) );
518 if ( count ( $children ) > 6 ) {
520 // divide list into three equal chunks
521 $chunk = (int) (count ( $children ) / 3);
523 // get and display header
524 $r .= '<table width="100%"><tr valign="top">';
529 // loop through the chunks
530 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
532 $chunkIndex++
, $startChunk = $endChunk, $endChunk +
= $chunk +
1)
536 // output all subcategories to category
537 for ($index = $startChunk ;
538 $index < $endChunk && $index < count($children);
541 // check for change of starting letter or begging of chunk
542 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
543 ||
($index == $startChunk) )
545 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
548 $r .= "<li>{$children[$index]}</li>";
554 $r .= '</tr></table>';
556 // for short lists of subcategories to category.
558 $r .= "<h3>{$children_start_char[0]}</h3>\n";
559 $r .= '<ul><li>'.$children[0].'</li>';
560 for ($index = 1; $index < count($children); $index++
)
562 if ($children_start_char[$index] != $children_start_char[$index - 1])
564 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
567 $r .= "<li>{$children[$index]}</li>";
571 } # END of if ( count($children) > 0 )
573 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n" .
574 wfMsg( 'categoryarticlecount', count( $articles ) );
576 # Showing articles in this category
577 if ( count ( $articles ) > 6) {
578 $ti = $this->mTitle
->getText() ;
580 // divide list into three equal chunks
581 $chunk = (int) (count ( $articles ) / 3);
583 // get and display header
584 $r .= '<table width="100%"><tr valign="top">';
586 // loop through the chunks
587 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
589 $chunkIndex++
, $startChunk = $endChunk, $endChunk +
= $chunk +
1)
594 // output all articles in category
595 for ($index = $startChunk ;
596 $index < $endChunk && $index < count($articles);
599 // check for change of starting letter or begging of chunk
600 if ( ($articles_start_char[$index] != $articles_start_char[$index - 1])
601 ||
($index == $startChunk) )
603 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
606 $r .= "<li>{$articles[$index]}</li>";
612 $r .= '</tr></table>';
613 } elseif ( count ( $articles ) > 0) {
614 // for short lists of articles in categories.
615 $ti = $this->mTitle
->getText() ;
617 $r .= '<h3>'.$articles_start_char[0]."</h3>\n";
618 $r .= '<ul><li>'.$articles[0].'</li>';
619 for ($index = 1; $index < count($articles); $index++
)
621 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
623 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
626 $r .= "<li>{$articles[$index]}</li>";
635 # Return allowed HTML attributes
636 function getHTMLattrs () {
637 $htmlattrs = array( # Allowed attributes--no scripting, etc.
638 'title', 'align', 'lang', 'dir', 'width', 'height',
639 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
640 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
641 /* FONT */ 'type', 'start', 'value', 'compact',
642 /* For various lists, mostly deprecated but safe */
643 'summary', 'width', 'border', 'frame', 'rules',
644 'cellspacing', 'cellpadding', 'valign', 'char',
645 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
646 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
647 'id', 'class', 'name', 'style' /* For CSS */
652 # Remove non approved attributes and javascript in css
653 function fixTagAttributes ( $t ) {
654 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
655 $htmlattrs = $this->getHTMLattrs() ;
657 # Strip non-approved attributes from the tag
659 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
660 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
663 $t = str_replace ( "<></>" , "" , $t ) ; # This should fix bug 980557
665 # Strip javascript "expression" from stylesheets. Brute force approach:
666 # If anythin offensive is found, all attributes of the HTML tag are dropped
669 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
670 wfMungeToUtf8( $t ) ) )
678 # interface with html tidy, used if $wgUseTidy = true
679 function tidy ( $text ) {
680 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
681 global $wgInputEncoding, $wgOutputEncoding;
682 $fname = 'Parser::tidy';
683 wfProfileIn( $fname );
686 switch(strtoupper($wgOutputEncoding)) {
688 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
691 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
694 $wgTidyOpts .= ' -raw';
697 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
698 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
699 '<head><title>test</title></head><body>'.$text.'</body></html>';
700 $descriptorspec = array(
701 0 => array('pipe', 'r'),
702 1 => array('pipe', 'w'),
703 2 => array('file', '/dev/null', 'a')
705 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
706 if (is_resource($process)) {
707 fwrite($pipes[0], $wrappedtext);
709 while (!feof($pipes[1])) {
710 $cleansource .= fgets($pipes[1], 1024);
713 $return_value = proc_close($process);
716 wfProfileOut( $fname );
718 if( $cleansource == '' && $text != '') {
719 wfDebug( "Tidy error detected!\n" );
720 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
726 # parse the wiki syntax used to render tables
727 function doTableStuff ( $t ) {
728 $fname = 'Parser::doTableStuff';
729 wfProfileIn( $fname );
731 $t = explode ( "\n" , $t ) ;
732 $td = array () ; # Is currently a td tag open?
733 $ltd = array () ; # Was it TD or TH?
734 $tr = array () ; # Is currently a tr tag open?
735 $ltr = array () ; # tr attributes
736 $indent_level = 0; # indent level of the table
737 foreach ( $t AS $k => $x )
740 $fc = substr ( $x , 0 , 1 ) ;
741 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) )
743 $indent_level = strlen( $matches[1] );
745 str_repeat( "<dl><dd>", $indent_level ) .
746 "<table " . $this->fixTagAttributes ( $matches[2] ) . '>' ;
747 array_push ( $td , false ) ;
748 array_push ( $ltd , '' ) ;
749 array_push ( $tr , false ) ;
750 array_push ( $ltr , '' ) ;
752 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
753 else if ( '|}' == substr ( $x , 0 , 2 ) )
756 $l = array_pop ( $ltd ) ;
757 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
758 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
760 $t[$k] = $z . str_repeat( "</dd></dl>", $indent_level );
762 else if ( '|-' == substr ( $x , 0 , 2 ) ) # Allows for |---------------
764 $x = substr ( $x , 1 ) ;
765 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
767 $l = array_pop ( $ltd ) ;
768 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
769 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
772 array_push ( $tr , false ) ;
773 array_push ( $td , false ) ;
774 array_push ( $ltd , '' ) ;
775 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
777 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) # Caption
779 if ( '|+' == substr ( $x , 0 , 2 ) )
782 $x = substr ( $x , 1 ) ;
784 $after = substr ( $x , 1 ) ;
785 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
786 $after = explode ( '||' , $after ) ;
788 foreach ( $after AS $theline )
793 $tra = array_pop ( $ltr ) ;
794 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
795 array_push ( $tr , true ) ;
796 array_push ( $ltr , '' ) ;
799 $l = array_pop ( $ltd ) ;
800 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
801 if ( $fc == '|' ) $l = 'td' ;
802 else if ( $fc == '!' ) $l = 'th' ;
803 else if ( $fc == '+' ) $l = 'caption' ;
805 array_push ( $ltd , $l ) ;
806 $y = explode ( '|' , $theline , 2 ) ;
807 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
808 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
810 array_push ( $td , true ) ;
815 # Closing open td, tr && table
816 while ( count ( $td ) > 0 )
818 if ( array_pop ( $td ) ) $t[] = '</td>' ;
819 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
823 $t = implode ( "\n" , $t ) ;
824 # $t = $this->removeHTMLtags( $t );
825 wfProfileOut( $fname );
829 # Parses the text and adds the result to the strip state
830 # Returns the strip tag
831 function stripParse( $text, $newline, $args )
833 $text = $this->strip( $text, $this->mStripState
);
834 $text = $this->internalParse( $text, (bool)$newline, $args, false );
835 return $newline.$this->insertStripItem( $text, $this->mStripState
);
838 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
839 $fname = 'Parser::internalParse';
840 wfProfileIn( $fname );
842 $text = $this->removeHTMLtags( $text );
843 $text = $this->replaceVariables( $text, $args );
845 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
847 $text = $this->doHeadings( $text );
848 if($this->mOptions
->getUseDynamicDates()) {
849 global $wgDateFormatter;
850 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
852 $text = $this->doAllQuotes( $text );
853 $text = $this->replaceExternalLinks( $text );
854 $text = $this->doMagicLinks( $text );
855 $text = $this->replaceInternalLinks ( $text );
856 $text = $this->replaceInternalLinks ( $text );
858 $text = $this->unstrip( $text, $this->mStripState
);
859 $text = $this->unstripNoWiki( $text, $this->mStripState
);
861 $text = $this->doTableStuff( $text );
862 $text = $this->formatHeadings( $text, $isMain );
863 $sk =& $this->mOptions
->getSkin();
864 $text = $sk->transformContent( $text );
866 if ( $isMain && !isset ( $this->categoryMagicDone
) ) {
867 $text .= $this->categoryMagic () ;
868 $this->categoryMagicDone
= true ;
871 wfProfileOut( $fname );
875 /* private */ function &doMagicLinks( &$text ) {
876 $text = $this->magicISBN( $text );
877 $text = $this->magicGEO( $text );
878 $text = $this->magicRFC( $text );
882 # Parse ^^ tokens and return html
883 /* private */ function doExponent ( $text )
885 $fname = 'Parser::doExponent';
886 wfProfileIn( $fname);
887 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
888 wfProfileOut( $fname);
892 # Parse headers and return html
893 /* private */ function doHeadings( $text ) {
894 $fname = 'Parser::doHeadings';
895 wfProfileIn( $fname );
896 for ( $i = 6; $i >= 1; --$i ) {
897 $h = substr( '======', 0, $i );
898 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
899 "<h{$i}>\\1</h{$i}>\\2", $text );
901 wfProfileOut( $fname );
905 /* private */ function doAllQuotes( $text ) {
906 $fname = 'Parser::doAllQuotes';
907 wfProfileIn( $fname );
909 $lines = explode( "\n", $text );
910 foreach ( $lines as $line ) {
911 $outtext .= $this->doQuotes ( $line ) . "\n";
913 $outtext = substr($outtext, 0,-1);
914 wfProfileOut( $fname );
918 /* private */ function doQuotes( $text ) {
919 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
920 if (count ($arr) == 1)
924 # First, do some preliminary work. This may shift some apostrophes from
925 # being mark-up to being text. It also counts the number of occurrences
926 # of bold and italics mark-ups.
934 # If there are ever four apostrophes, assume the first is supposed to
935 # be text, and the remaining three constitute mark-up for bold text.
936 if (strlen ($arr[$i]) == 4)
941 # If there are more than 5 apostrophes in a row, assume they're all
942 # text except for the last 5.
943 else if (strlen ($arr[$i]) > 5)
945 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
948 # Count the number of occurrences of bold and italics mark-ups.
949 # We are not counting sequences of five apostrophes.
950 if (strlen ($arr[$i]) == 2) $numitalics++
; else
951 if (strlen ($arr[$i]) == 3) $numbold++
;
956 # If there is an odd number of both bold and italics, it is likely
957 # that one of the bold ones was meant to be an apostrophe followed
958 # by italics. Which one we cannot know for certain, but it is more
959 # likely to be one that has a single-letter word before it.
960 if (($numbold %
2 == 1) && ($numitalics %
2 == 1))
963 $firstsingleletterword = -1;
964 $firstmultiletterword = -1;
968 if (($i %
2 == 1) and (strlen ($r) == 3))
970 $x1 = substr ($arr[$i-1], -1);
971 $x2 = substr ($arr[$i-1], -2, 1);
973 if ($firstspace == -1) $firstspace = $i;
974 } else if ($x2 == " ") {
975 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
977 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
983 # If there is a single-letter word, use it!
984 if ($firstsingleletterword > -1)
986 $arr [ $firstsingleletterword ] = "''";
987 $arr [ $firstsingleletterword-1 ] .= "'";
989 # If not, but there's a multi-letter word, use that one.
990 else if ($firstmultiletterword > -1)
992 $arr [ $firstmultiletterword ] = "''";
993 $arr [ $firstmultiletterword-1 ] .= "'";
995 # ... otherwise use the first one that has neither.
998 $arr [ $firstspace ] = "''";
999 $arr [ $firstspace-1 ] .= "'";
1003 # Now let's actually convert our apostrophic mush to HTML!
1008 foreach ($arr as $r)
1012 if ($state == 'both')
1019 if (strlen ($r) == 2)
1022 { $output .= "</em>"; $state = ''; }
1023 else if ($state == 'strongem')
1024 { $output .= "</em>"; $state = 'strong'; }
1025 else if ($state == 'emstrong')
1026 { $output .= "</strong></em><strong>"; $state = 'strong'; }
1027 else if ($state == 'both')
1028 { $output .= "<strong><em>{$buffer}</em>"; $state = 'strong'; }
1029 else # $state can be 'strong' or ''
1030 { $output .= "<em>"; $state .= 'em'; }
1032 else if (strlen ($r) == 3)
1034 if ($state == 'strong')
1035 { $output .= "</strong>"; $state = ''; }
1036 else if ($state == 'strongem')
1037 { $output .= "</em></strong><em>"; $state = 'em'; }
1038 else if ($state == 'emstrong')
1039 { $output .= "</strong>"; $state = 'em'; }
1040 else if ($state == 'both')
1041 { $output .= "<em><strong>{$buffer}</strong>"; $state = 'em'; }
1042 else # $state can be 'em' or ''
1043 { $output .= "<strong>"; $state .= 'strong'; }
1045 else if (strlen ($r) == 5)
1047 if ($state == 'strong')
1048 { $output .= "</strong><em>"; $state = 'em'; }
1049 else if ($state == 'em')
1050 { $output .= "</em><strong>"; $state = 'strong'; }
1051 else if ($state == 'strongem')
1052 { $output .= "</em></strong>"; $state = ''; }
1053 else if ($state == 'emstrong')
1054 { $output .= "</strong></em>"; $state = ''; }
1055 else if ($state == 'both')
1056 { $output .= "<em><strong>{$buffer}</strong></em>"; $state = ''; }
1057 else # ($state == '')
1058 { $buffer = ''; $state = 'both'; }
1063 # Now close all remaining tags. Notice that the order is important.
1064 if ($state == 'strong' ||
$state == 'emstrong')
1065 $output .= "</strong>";
1066 if ($state == 'em' ||
$state == 'strongem' ||
$state == 'emstrong')
1068 if ($state == 'strongem')
1069 $output .= "</strong>";
1070 if ($state == 'both')
1071 $output .= "<strong><em>{$buffer}</em></strong>";
1076 # Note: we have to do external links before the internal ones,
1077 # and otherwise take great care in the order of things here, so
1078 # that we don't end up interpreting some URLs twice.
1080 /* private */ function replaceExternalLinks( $text ) {
1081 $fname = 'Parser::replaceExternalLinks';
1082 wfProfileIn( $fname );
1084 $sk =& $this->mOptions
->getSkin();
1085 $linktrail = wfMsg('linktrail');
1086 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1088 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1091 while ( $i<count( $bits ) ) {
1093 $protocol = $bits[$i++
];
1094 $text = $bits[$i++
];
1095 $trail = $bits[$i++
];
1097 # If the link text is an image URL, replace it with an <img> tag
1098 # This happened by accident in the original parser, but some people used it extensively
1099 $img = $this->maybeMakeImageLink( $text );
1100 if ( $img !== false ) {
1106 # No link text, e.g. [http://domain.tld/some.link]
1107 if ( $text == '' ) {
1108 # Autonumber if allowed
1109 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1110 $text = "[" . ++
$this->mAutonumber
. "]";
1112 # Otherwise just use the URL
1113 $text = wfEscapeHTML( $url );
1116 # Have link text, e.g. [http://domain.tld/some.link text]s
1118 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1124 $encUrl = htmlspecialchars( $url );
1125 # Bit in parentheses showing the URL for the printable version
1126 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $url ) ) {
1129 # Expand the URL for printable version
1130 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
1133 # Process the trail (i.e. everything after this link up until start of the next link),
1134 # replacing any non-bracketed links
1135 $trail = $this->replaceFreeExternalLinks( $trail );
1137 $la = $sk->getExternalLinkAttributes( $url, $text );
1139 # Use the encoded URL
1140 # This means that users can paste URLs directly into the text
1141 # Funny characters like ö aren't valid in URLs anyway
1142 # This was changed in August 2004
1143 $s .= "<a href=\"{$url}\" {$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
1146 wfProfileOut( $fname );
1150 # Replace anything that looks like a URL with a link
1151 function replaceFreeExternalLinks( $text ) {
1152 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1153 $s = array_shift( $bits );
1156 $sk =& $this->mOptions
->getSkin();
1158 while ( $i < count( $bits ) ){
1159 $protocol = $bits[$i++
];
1160 $remainder = $bits[$i++
];
1162 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1163 # Found some characters after the protocol that look promising
1164 $url = $protocol . $m[1];
1167 # Move trailing punctuation to $trail
1169 # If there is no left bracket, then consider right brackets fair game too
1170 if ( strpos( $url, '(' ) === false ) {
1174 $numSepChars = strspn( strrev( $url ), $sep );
1175 if ( $numSepChars ) {
1176 $trail = substr( $url, -$numSepChars ) . $trail;
1177 $url = substr( $url, 0, -$numSepChars );
1180 # Replace & from obsolete syntax with &
1181 $url = str_replace( '&', '&', $url );
1183 # Is this an external image?
1184 $text = $this->maybeMakeImageLink( $url );
1185 if ( $text === false ) {
1186 # Not an image, make a link
1187 $text = $sk->makeExternalLink( $url, $url );
1189 $s .= $text . $trail;
1191 $s .= $protocol . $remainder;
1197 function maybeMakeImageLink( $url ) {
1198 $sk =& $this->mOptions
->getSkin();
1200 if ( $this->mOptions
->getAllowExternalImages() ) {
1201 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1203 $text = $sk->makeImage( htmlspecialchars( $url ) );
1209 /* private */ function replaceInternalLinks( $s ) {
1210 global $wgLang, $wgLinkCache;
1211 global $wgNamespacesWithSubpages, $wgLanguageCode;
1212 static $fname = 'Parser::replaceInternalLinks' ;
1213 wfProfileIn( $fname );
1215 wfProfileIn( $fname.'-setup' );
1217 # the % is needed to support urlencoded titles as well
1218 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1219 $sk =& $this->mOptions
->getSkin();
1221 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1223 $a = explode( '[[', ' ' . $s );
1224 $s = array_shift( $a );
1225 $s = substr( $s, 1 );
1227 # Match a link having the form [[namespace:link|alternate]]trail
1229 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1230 # Match the end of a line for a word that's not followed by whitespace,
1231 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1232 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1234 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1235 # Special and Media are pseudo-namespaces; no pages actually exist in them
1237 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1239 if ( $useLinkPrefixExtension ) {
1240 if ( preg_match( $e2, $s, $m ) ) {
1241 $first_prefix = $m[2];
1244 $first_prefix = false;
1250 wfProfileOut( $fname.'-setup' );
1252 foreach ( $a as $line ) {
1253 wfProfileIn( $fname.'-prefixhandling' );
1254 if ( $useLinkPrefixExtension ) {
1255 if ( preg_match( $e2, $s, $m ) ) {
1263 $prefix = $first_prefix;
1264 $first_prefix = false;
1267 wfProfileOut( $fname.'-prefixhandling' );
1269 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1271 # fix up urlencoded title texts
1272 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1274 } else { # Invalid form; output directly
1275 $s .= $prefix . '[[' . $line ;
1279 /* Valid link forms:
1281 :Foobar -- override special treatment of prefix (images, language links)
1282 /Foobar -- convert to CurrentPage/Foobar
1283 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1285 $c = substr($m[1],0,1);
1286 $noforce = ($c != ':');
1287 if( $c == '/' ) { # subpage
1288 if(substr($m[1],-1,1)=='/') { # / at end means we don't want the slash to be shown
1289 $m[1]=substr($m[1],1,strlen($m[1])-2);
1292 $noslash=substr($m[1],1);
1294 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) { # subpages allowed here
1295 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1298 } # this might be changed for ugliness reasons
1300 $link = $noslash; # no subpage allowed, use standard link
1302 } elseif( $noforce ) { # no subpage
1305 $link = substr( $m[1], 1 );
1307 $wasblank = ( '' == $text );
1311 $nt = Title
::newFromText( $link );
1313 $s .= $prefix . '[[' . $line;
1316 $ns = $nt->getNamespace();
1317 $iw = $nt->getInterWiki();
1319 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1320 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1321 $tmp = $prefix . $trail ;
1322 $s .= (trim($tmp) == '')?
'': $tmp;
1325 if ( $ns == NS_IMAGE
) {
1326 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1327 $wgLinkCache->addImageLinkObj( $nt );
1330 if ( $ns == NS_CATEGORY
) {
1331 $t = $nt->getText() ;
1332 $nnt = Title
::newFromText ( Namespace::getCanonicalName(NS_CATEGORY
).":".$t ) ;
1334 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1335 $pPLC=$sk->postParseLinkColour();
1336 $sk->postParseLinkColour( false );
1337 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1338 $sk->postParseLinkColour( $pPLC );
1339 $wgLinkCache->resume();
1341 $sortkey = $wasblank ?
$this->mTitle
->getPrefixedText() : $text;
1342 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1343 $this->mOutput
->mCategoryLinks
[] = $t ;
1344 $s .= $prefix . $trail ;
1348 if( ( $nt->getPrefixedText() == $this->mTitle
->getPrefixedText() ) &&
1349 ( strpos( $link, '#' ) == FALSE ) ) {
1350 # Self-links are handled specially; generally de-link and change to bold.
1351 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1355 if( $ns == NS_MEDIA
) {
1356 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1357 $wgLinkCache->addImageLinkObj( $nt );
1359 } elseif( $ns == NS_SPECIAL
) {
1360 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1363 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1365 wfProfileOut( $fname );
1369 # Some functions here used by doBlockLevels()
1371 /* private */ function closeParagraph() {
1373 if ( '' != $this->mLastSection
) {
1374 $result = '</' . $this->mLastSection
. ">\n";
1376 $this->mInPre
= false;
1377 $this->mLastSection
= '';
1380 # getCommon() returns the length of the longest common substring
1381 # of both arguments, starting at the beginning of both.
1383 /* private */ function getCommon( $st1, $st2 ) {
1384 $fl = strlen( $st1 );
1385 $shorter = strlen( $st2 );
1386 if ( $fl < $shorter ) { $shorter = $fl; }
1388 for ( $i = 0; $i < $shorter; ++
$i ) {
1389 if ( $st1{$i} != $st2{$i} ) { break; }
1393 # These next three functions open, continue, and close the list
1394 # element appropriate to the prefix character passed into them.
1396 /* private */ function openList( $char )
1398 $result = $this->closeParagraph();
1400 if ( '*' == $char ) { $result .= '<ul><li>'; }
1401 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1402 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1403 else if ( ';' == $char ) {
1404 $result .= '<dl><dt>';
1405 $this->mDTopen
= true;
1407 else { $result = '<!-- ERR 1 -->'; }
1412 /* private */ function nextItem( $char ) {
1413 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1414 else if ( ':' == $char ||
';' == $char ) {
1416 if ( $this->mDTopen
) { $close = '</dt>'; }
1417 if ( ';' == $char ) {
1418 $this->mDTopen
= true;
1419 return $close . '<dt>';
1421 $this->mDTopen
= false;
1422 return $close . '<dd>';
1425 return '<!-- ERR 2 -->';
1428 /* private */function closeList( $char ) {
1429 if ( '*' == $char ) { $text = '</li></ul>'; }
1430 else if ( '#' == $char ) { $text = '</li></ol>'; }
1431 else if ( ':' == $char ) {
1432 if ( $this->mDTopen
) {
1433 $this->mDTopen
= false;
1434 $text = '</dt></dl>';
1436 $text = '</dd></dl>';
1439 else { return '<!-- ERR 3 -->'; }
1443 /* private */ function doBlockLevels( $text, $linestart ) {
1444 $fname = 'Parser::doBlockLevels';
1445 wfProfileIn( $fname );
1447 # Parsing through the text line by line. The main thing
1448 # happening here is handling of block-level elements p, pre,
1449 # and making lists from lines starting with * # : etc.
1451 $textLines = explode( "\n", $text );
1453 $lastPrefix = $output = $lastLine = '';
1454 $this->mDTopen
= $inBlockElem = false;
1456 $paragraphStack = false;
1458 if ( !$linestart ) {
1459 $output .= array_shift( $textLines );
1461 foreach ( $textLines as $oLine ) {
1462 $lastPrefixLength = strlen( $lastPrefix );
1463 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1464 $preOpenMatch = preg_match("/<pre/i", $oLine );
1465 if ( !$this->mInPre
) {
1466 # Multiple prefixes may abut each other for nested lists.
1467 $prefixLength = strspn( $oLine, '*#:;' );
1468 $pref = substr( $oLine, 0, $prefixLength );
1471 $pref2 = str_replace( ';', ':', $pref );
1472 $t = substr( $oLine, $prefixLength );
1473 $this->mInPre
= !empty($preOpenMatch);
1475 # Don't interpret any other prefixes in preformatted text
1477 $pref = $pref2 = '';
1482 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1483 # Same as the last item, so no need to deal with nesting or opening stuff
1484 $output .= $this->nextItem( substr( $pref, -1 ) );
1485 $paragraphStack = false;
1487 if ( ";" == substr( $pref, -1 ) ) {
1488 # The one nasty exception: definition lists work like this:
1489 # ; title : definition text
1490 # So we check for : in the remainder text to split up the
1491 # title and definition, without b0rking links.
1492 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1493 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1495 $output .= $term . $this->nextItem( ':' );
1499 } elseif( $prefixLength ||
$lastPrefixLength ) {
1500 # Either open or close a level...
1501 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1502 $paragraphStack = false;
1504 while( $commonPrefixLength < $lastPrefixLength ) {
1505 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1506 --$lastPrefixLength;
1508 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1509 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1511 while ( $prefixLength > $commonPrefixLength ) {
1512 $char = substr( $pref, $commonPrefixLength, 1 );
1513 $output .= $this->openList( $char );
1515 if ( ';' == $char ) {
1516 # FIXME: This is dupe of code above
1517 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1519 $output .= $term . $this->nextItem( ":" );
1523 ++
$commonPrefixLength;
1525 $lastPrefix = $pref2;
1527 if( 0 == $prefixLength ) {
1528 # No prefix (not in list)--go to paragraph mode
1529 $uniq_prefix = UNIQ_PREFIX
;
1530 // XXX: use a stack for nestable elements like span, table and div
1531 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1532 $closematch = preg_match(
1533 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1534 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1535 if ( $openmatch or $closematch ) {
1536 $paragraphStack = false;
1537 $output .= $this->closeParagraph();
1538 if($preOpenMatch and !$preCloseMatch) {
1539 $this->mInPre
= true;
1541 if ( $closematch ) {
1542 $inBlockElem = false;
1544 $inBlockElem = true;
1546 } else if ( !$inBlockElem && !$this->mInPre
) {
1547 if ( " " == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1549 if ($this->mLastSection
!= 'pre') {
1550 $paragraphStack = false;
1551 $output .= $this->closeParagraph().'<pre>';
1552 $this->mLastSection
= 'pre';
1556 if ( '' == trim($t) ) {
1557 if ( $paragraphStack ) {
1558 $output .= $paragraphStack.'<br />';
1559 $paragraphStack = false;
1560 $this->mLastSection
= 'p';
1562 if ($this->mLastSection
!= 'p' ) {
1563 $output .= $this->closeParagraph();
1564 $this->mLastSection
= '';
1565 $paragraphStack = '<p>';
1567 $paragraphStack = '</p><p>';
1571 if ( $paragraphStack ) {
1572 $output .= $paragraphStack;
1573 $paragraphStack = false;
1574 $this->mLastSection
= 'p';
1575 } else if ($this->mLastSection
!= 'p') {
1576 $output .= $this->closeParagraph().'<p>';
1577 $this->mLastSection
= 'p';
1583 if ($paragraphStack === false) {
1587 while ( $prefixLength ) {
1588 $output .= $this->closeList( $pref2{$prefixLength-1} );
1591 if ( '' != $this->mLastSection
) {
1592 $output .= '</' . $this->mLastSection
. '>';
1593 $this->mLastSection
= '';
1596 wfProfileOut( $fname );
1600 # Return value of a magic variable (like PAGENAME)
1601 function getVariableValue( $index ) {
1602 global $wgLang, $wgSitename, $wgServer;
1605 case MAG_CURRENTMONTH
:
1606 return $wgLang->formatNum( date( 'm' ) );
1607 case MAG_CURRENTMONTHNAME
:
1608 return $wgLang->getMonthName( date('n') );
1609 case MAG_CURRENTMONTHNAMEGEN
:
1610 return $wgLang->getMonthNameGen( date('n') );
1611 case MAG_CURRENTDAY
:
1612 return $wgLang->formatNum( date('j') );
1614 return $this->mTitle
->getText();
1616 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1617 return $wgLang->getNsText($this->mTitle
->getNamespace()); // Patch by Dori
1618 case MAG_CURRENTDAYNAME
:
1619 return $wgLang->getWeekdayName( date('w')+
1 );
1620 case MAG_CURRENTYEAR
:
1621 return $wgLang->formatNum( date( 'Y' ) );
1622 case MAG_CURRENTTIME
:
1623 return $wgLang->time( wfTimestampNow(), false );
1624 case MAG_NUMBEROFARTICLES
:
1625 return $wgLang->formatNum( wfNumberOfArticles() );
1635 # initialise the magic variables (like CURRENTMONTHNAME)
1636 function initialiseVariables() {
1637 global $wgVariableIDs;
1638 $this->mVariables
= array();
1639 foreach ( $wgVariableIDs as $id ) {
1640 $mw =& MagicWord
::get( $id );
1641 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1645 /* private */ function replaceVariables( $text, $args = array() ) {
1646 global $wgLang, $wgScript, $wgArticlePath;
1648 # Prevent too big inclusions
1649 if(strlen($text)> MAX_INCLUDE_SIZE
)
1652 $fname = 'Parser::replaceVariables';
1653 wfProfileIn( $fname );
1656 $titleChars = Title
::legalChars();
1657 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1659 # This function is called recursively. To keep track of arguments we need a stack:
1660 array_push( $this->mArgStack
, $args );
1662 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1663 $GLOBALS['wgCurParser'] =& $this;
1666 if ( $this->mOutputType
== OT_HTML
) {
1667 # Variable substitution
1668 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1670 # Argument substitution
1671 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1673 # Template substitution
1674 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1675 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1677 array_pop( $this->mArgStack
);
1679 wfProfileOut( $fname );
1683 function variableSubstitution( $matches ) {
1684 if ( !$this->mVariables
) {
1685 $this->initialiseVariables();
1687 if ( array_key_exists( $matches[1], $this->mVariables
) ) {
1688 $text = $this->mVariables
[$matches[1]];
1689 $this->mOutput
->mContainsOldMagic
= true;
1691 $text = $matches[0];
1696 # Split template arguments
1697 function getTemplateArgs( $argsString ) {
1698 if ( $argsString === '' ) {
1702 $args = explode( '|', substr( $argsString, 1 ) );
1704 # If any of the arguments contains a '[[' but no ']]', it needs to be
1705 # merged with the next arg because the '|' character between belongs
1706 # to the link syntax and not the template parameter syntax.
1707 $argc = count($args);
1709 for ( $i = 0; $i < $argc-1; $i++
) {
1710 if ( substr_count ( $args[$i], "[[" ) != substr_count ( $args[$i], "]]" ) ) {
1711 $args[$i] .= "|".$args[$i+
1];
1712 array_splice($args, $i+
1, 1);
1721 function braceSubstitution( $matches ) {
1722 global $wgLinkCache, $wgLang;
1723 $fname = 'Parser::braceSubstitution';
1730 # $newline is an optional newline character before the braces
1731 # $part1 is the bit before the first |, and must contain only title characters
1732 # $args is a list of arguments, starting from index 0, not including $part1
1734 $newline = $matches[1];
1735 $part1 = $matches[2];
1736 # If the third subpattern matched anything, it will start with |
1738 $args = $this->getTemplateArgs($matches[3]);
1739 $argc = count( $args );
1742 if ( strpos( $matches[0], '{{{' ) !== false ) {
1743 $text = $matches[0];
1750 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1751 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1752 if ( $this->mOutputType
!= OT_WIKI
) {
1753 # Invalid SUBST not replaced at PST time
1754 # Return without further processing
1755 $text = $matches[0];
1759 } elseif ( $this->mOutputType
== OT_WIKI
) {
1760 # SUBST not found in PST pass, do nothing
1761 $text = $matches[0];
1766 # MSG, MSGNW and INT
1769 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1770 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1773 # Remove obsolete MSG:
1774 $mwMsg =& MagicWord
::get( MAG_MSG
);
1775 $mwMsg->matchStartAndRemove( $part1 );
1778 # Check if it is an internal message
1779 $mwInt =& MagicWord
::get( MAG_INT
);
1780 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1781 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1782 $text = wfMsgReal( $part1, $args, true );
1790 # Check for NS: (namespace expansion)
1791 $mwNs = MagicWord
::get( MAG_NS
);
1792 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1793 if ( intval( $part1 ) ) {
1794 $text = $wgLang->getNsText( intval( $part1 ) );
1797 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1798 if ( !is_null( $index ) ) {
1799 $text = $wgLang->getNsText( $index );
1806 # LOCALURL and LOCALURLE
1808 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1809 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1811 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1812 $func = 'getLocalURL';
1813 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1814 $func = 'escapeLocalURL';
1819 if ( $func !== '' ) {
1820 $title = Title
::newFromText( $part1 );
1821 if ( !is_null( $title ) ) {
1823 $text = $title->$func( $args[0] );
1825 $text = $title->$func();
1832 # Internal variables
1833 if ( !$this->mVariables
) {
1834 $this->initialiseVariables();
1836 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1837 $text = $this->mVariables
[$part1];
1839 $this->mOutput
->mContainsOldMagic
= true;
1842 # Template table test
1844 # Did we encounter this template already? If yes, it is in the cache
1845 # and we need to check for loops.
1846 if ( isset( $this->mTemplates
[$part1] ) ) {
1847 # Infinite loop test
1848 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1852 # set $text to cached message.
1853 $text = $this->mTemplates
[$part1];
1857 # Load from database
1859 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1860 if ( !is_null( $title ) && !$title->isExternal() ) {
1861 # Check for excessive inclusion
1862 $dbk = $title->getPrefixedDBkey();
1863 if ( $this->incrementIncludeCount( $dbk ) ) {
1864 # This should never be reached.
1865 $article = new Article( $title );
1866 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1867 if ( $articleContent !== false ) {
1869 $text = $articleContent;
1874 # If the title is valid but undisplayable, make a link to it
1875 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1876 $text = '[[' . $title->getPrefixedText() . ']]';
1880 # Template cache array insertion
1881 $this->mTemplates
[$part1] = $text;
1885 # Recursive parsing, escaping and link table handling
1886 # Only for HTML output
1887 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1888 $text = wfEscapeWikiText( $text );
1889 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1890 # Clean up argument array
1891 $assocArgs = array();
1893 foreach( $args as $arg ) {
1894 $eqpos = strpos( $arg, '=' );
1895 if ( $eqpos === false ) {
1896 $assocArgs[$index++
] = $arg;
1898 $name = trim( substr( $arg, 0, $eqpos ) );
1899 $value = trim( substr( $arg, $eqpos+
1 ) );
1900 if ( $value === false ) {
1903 if ( $name !== false ) {
1904 $assocArgs[$name] = $value;
1909 # Do not enter included links in link table
1910 if ( !is_null( $title ) ) {
1911 $wgLinkCache->suspend();
1914 # Add a new element to the templace recursion path
1915 $this->mTemplatePath
[$part1] = 1;
1917 $text = $this->stripParse( $text, $newline, $assocArgs );
1919 # Resume the link cache and register the inclusion as a link
1920 if ( !is_null( $title ) ) {
1921 $wgLinkCache->resume();
1922 $wgLinkCache->addLinkObj( $title );
1925 # Empties the template path
1926 $this->mTemplatePath
= array();
1935 # Triple brace replacement -- used for template arguments
1936 function argSubstitution( $matches ) {
1937 $newline = $matches[1];
1938 $arg = trim( $matches[2] );
1939 $text = $matches[0];
1940 $inputArgs = end( $this->mArgStack
);
1942 if ( array_key_exists( $arg, $inputArgs ) ) {
1943 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1949 # Returns true if the function is allowed to include this entity
1950 function incrementIncludeCount( $dbk ) {
1951 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1952 $this->mIncludeCount
[$dbk] = 0;
1954 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1962 # Cleans up HTML, removes dangerous tags and attributes
1963 /* private */ function removeHTMLtags( $text ) {
1964 global $wgUseTidy, $wgUserHtml;
1965 $fname = 'Parser::removeHTMLtags';
1966 wfProfileIn( $fname );
1969 $htmlpairs = array( # Tags that must be closed
1970 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1971 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1972 'strike', 'strong', 'tt', 'var', 'div', 'center',
1973 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1974 'ruby', 'rt' , 'rb' , 'rp', 'p'
1976 $htmlsingle = array(
1977 'br', 'hr', 'li', 'dt', 'dd'
1979 $htmlnest = array( # Tags that can be nested--??
1980 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1981 'dl', 'font', 'big', 'small', 'sub', 'sup'
1983 $tabletags = array( # Can only appear inside table
1987 $htmlpairs = array();
1988 $htmlsingle = array();
1989 $htmlnest = array();
1990 $tabletags = array();
1993 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1994 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1996 $htmlattrs = $this->getHTMLattrs () ;
1998 # Remove HTML comments
1999 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
2001 $bits = explode( '<', $text );
2002 $text = array_shift( $bits );
2004 $tagstack = array(); $tablestack = array();
2005 foreach ( $bits as $x ) {
2006 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
2007 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2009 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2010 error_reporting( $prev );
2013 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2017 if ( ! in_array( $t, $htmlsingle ) &&
2018 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
2019 @array_push
( $tagstack, $ot );
2022 if ( $t == 'table' ) {
2023 $tagstack = array_pop( $tablestack );
2028 # Keep track for later
2029 if ( in_array( $t, $tabletags ) &&
2030 ! in_array( 'table', $tagstack ) ) {
2032 } else if ( in_array( $t, $tagstack ) &&
2033 ! in_array ( $t , $htmlnest ) ) {
2035 } else if ( ! in_array( $t, $htmlsingle ) ) {
2036 if ( $t == 'table' ) {
2037 array_push( $tablestack, $tagstack );
2038 $tagstack = array();
2040 array_push( $tagstack, $t );
2042 # Strip non-approved attributes from the tag
2043 $newparams = $this->fixTagAttributes($params);
2047 $rest = str_replace( '>', '>', $rest );
2048 $text .= "<$slash$t $newparams$brace$rest";
2052 $text .= '<' . str_replace( '>', '>', $x);
2054 # Close off any remaining tags
2055 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2057 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2060 # this might be possible using tidy itself
2061 foreach ( $bits as $x ) {
2062 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2064 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2065 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2066 $newparams = $this->fixTagAttributes($params);
2067 $rest = str_replace( '>', '>', $rest );
2068 $text .= "<$slash$t $newparams$brace$rest";
2070 $text .= '<' . str_replace( '>', '>', $x);
2074 wfProfileOut( $fname );
2081 * This function accomplishes several tasks:
2082 * 1) Auto-number headings if that option is enabled
2083 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2084 * 3) Add a Table of contents on the top for users who have enabled the option
2085 * 4) Auto-anchor headings
2087 * It loops through all headlines, collects the necessary data, then splits up the
2088 * string and re-inserts the newly formatted headlines.
2092 /* private */ function formatHeadings( $text, $isMain=true ) {
2093 global $wgInputEncoding, $wgMaxTocLevel;
2095 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2096 $doShowToc = $this->mOptions
->getShowToc();
2097 $forceTocHere = false;
2098 if( !$this->mTitle
->userCanEdit() ) {
2100 $rightClickHack = 0;
2102 $showEditLink = $this->mOptions
->getEditSection();
2103 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2106 # Inhibit editsection links if requested in the page
2107 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2108 if( $esw->matchAndRemove( $text ) ) {
2111 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2113 $mw =& MagicWord
::get( MAG_NOTOC
);
2114 if( $mw->matchAndRemove( $text ) ) {
2118 # never add the TOC to the Main Page. This is an entry page that should not
2119 # be more than 1-2 screens large anyway
2120 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2124 # Get all headlines for numbering them and adding funky stuff like [edit]
2125 # links - this is for later, but we need the number of headlines right now
2126 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2128 # if there are fewer than 4 headlines in the article, do not show TOC
2129 if( $numMatches < 4 ) {
2133 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2134 # override above conditions and always show TOC at that place
2135 $mw =& MagicWord
::get( MAG_TOC
);
2136 if ($mw->match( $text ) ) {
2138 $forceTocHere = true;
2140 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2141 # override above conditions and always show TOC above first header
2142 $mw =& MagicWord
::get( MAG_FORCETOC
);
2143 if ($mw->matchAndRemove( $text ) ) {
2150 # We need this to perform operations on the HTML
2151 $sk =& $this->mOptions
->getSkin();
2156 # Ugh .. the TOC should have neat indentation levels which can be
2157 # passed to the skin functions. These are determined here
2162 $sublevelCount = array();
2165 foreach( $matches[3] as $headline ) {
2168 $prevlevel = $level;
2170 $level = $matches[1][$headlineCount];
2171 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2172 # reset when we enter a new level
2173 $sublevelCount[$level] = 0;
2174 $toc .= $sk->tocIndent( $level - $prevlevel );
2175 $toclevel +
= $level - $prevlevel;
2177 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2178 # reset when we step back a level
2179 $sublevelCount[$level+
1]=0;
2180 $toc .= $sk->tocUnindent( $prevlevel - $level );
2181 $toclevel -= $prevlevel - $level;
2183 # count number of headlines for each level
2184 @$sublevelCount[$level]++
;
2185 if( $doNumberHeadings ||
$doShowToc ) {
2187 for( $i = 1; $i <= $level; $i++
) {
2188 if( !empty( $sublevelCount[$i] ) ) {
2192 $numbering .= $sublevelCount[$i];
2198 # The canonized header is a version of the header text safe to use for links
2199 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2200 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2201 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2204 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2205 $tocline = trim( $canonized_headline );
2206 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2207 $replacearray = array(
2211 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2212 $refer[$headlineCount] = $canonized_headline;
2214 # count how many in assoc. array so we can track dupes in anchors
2215 @$refers[$canonized_headline]++
;
2216 $refcount[$headlineCount]=$refers[$canonized_headline];
2218 # Prepend the number to the heading text
2220 if( $doNumberHeadings ||
$doShowToc ) {
2221 $tocline = $numbering . ' ' . $tocline;
2223 # Don't number the heading if it is the only one (looks silly)
2224 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2225 # the two are different if the line contains a link
2226 $headline=$numbering . ' ' . $headline;
2230 # Create the anchor for linking from the TOC to the section
2231 $anchor = $canonized_headline;
2232 if($refcount[$headlineCount] > 1 ) {
2233 $anchor .= '_' . $refcount[$headlineCount];
2235 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2236 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2238 if( $showEditLink ) {
2239 if ( empty( $head[$headlineCount] ) ) {
2240 $head[$headlineCount] = '';
2242 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+
1);
2245 # Add the edit section span
2246 if( $rightClickHack ) {
2247 $headline = $sk->editSectionScript($headlineCount+
1,$headline);
2250 # give headline the correct <h#> tag
2251 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
2257 $toclines = $headlineCount;
2258 $toc .= $sk->tocUnindent( $toclevel );
2259 $toc = $sk->tocTable( $toc );
2262 # split up and insert constructed headlines
2264 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2267 foreach( $blocks as $block ) {
2268 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2269 # This is the [edit] link that appears for the top block of text when
2270 # section editing is enabled
2272 # Disabled because it broke block formatting
2273 # For example, a bullet point in the top line
2274 # $full .= $sk->editSectionLink(0);
2277 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2278 # Top anchor now in skin
2282 if( !empty( $head[$i] ) ) {
2288 $mw =& MagicWord
::get( MAG_TOC
);
2289 return $mw->replace( $toc, $full );
2295 # Return an HTML link for the "ISBN 123456" text
2296 /* private */ function magicISBN( $text ) {
2298 $fname = 'Parser::magicISBN';
2299 wfProfileIn( $fname );
2301 $a = split( 'ISBN ', " $text" );
2302 if ( count ( $a ) < 2 ) {
2303 wfProfileOut( $fname );
2306 $text = substr( array_shift( $a ), 1);
2307 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2309 foreach ( $a as $x ) {
2310 $isbn = $blank = '' ;
2311 while ( ' ' == $x{0} ) {
2313 $x = substr( $x, 1 );
2315 while ( strstr( $valid, $x{0} ) != false ) {
2317 $x = substr( $x, 1 );
2319 $num = str_replace( '-', '', $isbn );
2320 $num = str_replace( ' ', '', $num );
2323 $text .= "ISBN $blank$x";
2325 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2326 $text .= '<a href="' .
2327 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2328 "\" class=\"internal\">ISBN $isbn</a>";
2332 wfProfileOut( $fname );
2336 # Return an HTML link for the "GEO ..." text
2337 /* private */ function magicGEO( $text ) {
2338 global $wgLang, $wgUseGeoMode;
2339 if ( !isset ( $wgUseGeoMode ) ||
!$wgUseGeoMode ) return $text ;
2340 $fname = 'Parser::magicGEO';
2341 wfProfileIn( $fname );
2343 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2344 $directions = array ( "N" => "North" , "S" => "South" , "E" => "East" , "W" => "West" ) ;
2345 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2346 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2347 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2348 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2350 $a = split( 'GEO ', " $text" );
2351 if ( count ( $a ) < 2 ) {
2352 wfProfileOut( $fname );
2355 $text = substr( array_shift( $a ), 1);
2356 $valid = '0123456789.+-:';
2358 foreach ( $a as $x ) {
2359 $geo = $blank = '' ;
2360 while ( ' ' == $x{0} ) {
2362 $x = substr( $x, 1 );
2364 while ( strstr( $valid, $x{0} ) != false ) {
2366 $x = substr( $x, 1 );
2368 $num = str_replace( '+', '', $geo );
2369 $num = str_replace( ' ', '', $num );
2371 if ( '' == $num ||
count ( explode ( ":" , $num , 3 ) ) < 2 ) {
2372 $text .= "GEO $blank$x";
2374 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2375 $text .= '<a href="' .
2376 $titleObj->escapeLocalUrl( "coordinates={$num}" ) .
2377 "\" class=\"internal\">GEO $geo</a>";
2381 wfProfileOut( $fname );
2385 # Return an HTML link for the "RFC 1234" text
2386 /* private */ function magicRFC( $text ) {
2389 $a = split( 'RFC ', ' '.$text );
2390 if ( count ( $a ) < 2 ) return $text;
2391 $text = substr( array_shift( $a ), 1);
2392 $valid = '0123456789';
2394 foreach ( $a as $x ) {
2395 $rfc = $blank = '' ;
2396 while ( ' ' == $x{0} ) {
2398 $x = substr( $x, 1 );
2400 while ( strstr( $valid, $x{0} ) != false ) {
2402 $x = substr( $x, 1 );
2406 $text .= "RFC $blank$x";
2408 $url = wfmsg( 'rfcurl' );
2409 $url = str_replace( '$1', $rfc, $url);
2410 $sk =& $this->mOptions
->getSkin();
2411 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2412 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2418 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2419 $this->mOptions
= $options;
2420 $this->mTitle
=& $title;
2421 $this->mOutputType
= OT_WIKI
;
2423 if ( $clearState ) {
2424 $this->clearState();
2427 $stripState = false;
2431 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2435 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2436 "/<br *?>/i" => "<br />",
2438 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2440 $text = $this->strip( $text, $stripState, false );
2441 $text = $this->pstPass2( $text, $user );
2442 $text = $this->unstrip( $text, $stripState );
2443 $text = $this->unstripNoWiki( $text, $stripState );
2447 /* private */ function pstPass2( $text, &$user ) {
2448 global $wgLang, $wgLocaltimezone, $wgCurParser;
2450 # Variable replacement
2451 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2452 $text = $this->replaceVariables( $text );
2456 $n = $user->getName();
2457 $k = $user->getOption( 'nickname' );
2458 if ( '' == $k ) { $k = $n; }
2459 if(isset($wgLocaltimezone)) {
2460 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2462 /* Note: this is an ugly timezone hack for the European wikis */
2463 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2464 ' (' . date( 'T' ) . ')';
2465 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2467 $text = preg_replace( '/~~~~~/', $d, $text );
2468 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2469 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2471 # Context links: [[|name]] and [[name (context)|]]
2473 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2474 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2475 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2476 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2478 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2479 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2480 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2481 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2482 # [[ns:page (cont)|]]
2484 $t = $this->mTitle
->getText();
2485 if ( preg_match( $conpat, $t, $m ) ) {
2488 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2489 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2490 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2492 if ( '' == $context ) {
2493 $text = preg_replace( $p2, '[[\\1]]', $text );
2495 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2499 $mw =& MagicWord::get( MAG_SUBST );
2500 $wgCurParser = $this->fork();
2501 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2502 $this->merge( $wgCurParser );
2505 # Trim trailing whitespace
2506 # MAG_END (__END__) tag allows for trailing
2507 # whitespace to be deliberately included
2508 $text = rtrim( $text );
2509 $mw =& MagicWord
::get( MAG_END
);
2510 $mw->matchAndRemove( $text );
2515 # Set up some variables which are usually set up in parse()
2516 # so that an external function can call some class members with confidence
2517 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2518 $this->mTitle
=& $title;
2519 $this->mOptions
= $options;
2520 $this->mOutputType
= $outputType;
2521 if ( $clearState ) {
2522 $this->clearState();
2526 function transformMsg( $text, $options ) {
2528 static $executing = false;
2530 # Guard against infinite recursion
2536 $this->mTitle
= $wgTitle;
2537 $this->mOptions
= $options;
2538 $this->mOutputType
= OT_MSG
;
2539 $this->clearState();
2540 $text = $this->replaceVariables( $text );
2546 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2547 # Callback will be called with the text within
2548 # Transform and return the text within
2549 function setHook( $tag, $callback ) {
2550 $oldVal = @$this->mTagHooks
[$tag];
2551 $this->mTagHooks
[$tag] = $callback;
2558 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2559 var $mCacheTime; # Used in ParserCache
2561 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2562 $containsOldMagic = false )
2564 $this->mText
= $text;
2565 $this->mLanguageLinks
= $languageLinks;
2566 $this->mCategoryLinks
= $categoryLinks;
2567 $this->mContainsOldMagic
= $containsOldMagic;
2568 $this->mCacheTime
= "";
2571 function getText() { return $this->mText
; }
2572 function getLanguageLinks() { return $this->mLanguageLinks
; }
2573 function getCategoryLinks() { return $this->mCategoryLinks
; }
2574 function getCacheTime() { return $this->mCacheTime
; }
2575 function containsOldMagic() { return $this->mContainsOldMagic
; }
2576 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2577 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2578 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2579 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2580 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2582 function merge( $other ) {
2583 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2584 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2585 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2592 # All variables are private
2593 var $mUseTeX; # Use texvc to expand <math> tags
2594 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2595 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2596 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2597 var $mAllowExternalImages; # Allow external images inline
2598 var $mSkin; # Reference to the preferred skin
2599 var $mDateFormat; # Date format index
2600 var $mEditSection; # Create "edit section" links
2601 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2602 var $mNumberHeadings; # Automatically number headings
2603 var $mShowToc; # Show table of contents
2605 function getUseTeX() { return $this->mUseTeX
; }
2606 function getUseCategoryMagic() { return $this->mUseCategoryMagic
; }
2607 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2608 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2609 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2610 function getSkin() { return $this->mSkin
; }
2611 function getDateFormat() { return $this->mDateFormat
; }
2612 function getEditSection() { return $this->mEditSection
; }
2613 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2614 function getNumberHeadings() { return $this->mNumberHeadings
; }
2615 function getShowToc() { return $this->mShowToc
; }
2617 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2618 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic
, $x ); }
2619 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2620 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2621 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2622 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2623 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2624 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2625 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2626 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2628 function setSkin( &$x ) { $this->mSkin
=& $x; }
2630 /* static */ function newFromUser( &$user ) {
2631 $popts = new ParserOptions
;
2632 $popts->initialiseFromUser( $user );
2636 function initialiseFromUser( &$userInput ) {
2637 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2639 if ( !$userInput ) {
2641 $user->setLoaded( true );
2643 $user =& $userInput;
2646 $this->mUseTeX
= $wgUseTeX;
2647 $this->mUseCategoryMagic
= $wgUseCategoryMagic;
2648 $this->mUseDynamicDates
= $wgUseDynamicDates;
2649 $this->mInterwikiMagic
= $wgInterwikiMagic;
2650 $this->mAllowExternalImages
= $wgAllowExternalImages;
2651 $this->mSkin
=& $user->getSkin();
2652 $this->mDateFormat
= $user->getOption( 'date' );
2653 $this->mEditSection
= $user->getOption( 'editsection' );
2654 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2655 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2656 $this->mShowToc
= $user->getOption( 'showtoc' );
2662 # Regex callbacks, used in Parser::replaceVariables
2663 function wfBraceSubstitution( $matches )
2665 global $wgCurParser;
2666 return $wgCurParser->braceSubstitution( $matches );
2669 function wfArgSubstitution( $matches )
2671 global $wgCurParser;
2672 return $wgCurParser->argSubstitution( $matches );
2675 function wfVariableSubstitution( $matches )
2677 global $wgCurParser;
2678 return $wgCurParser->variableSubstitution( $matches );