4 * File for Parser and related classes
11 * Variable substitution O(N^2) attack
13 * Without countermeasures, it would be possible to attack the parser by saving
14 * a page filled with a large number of inclusions of large pages. The size of
15 * the generated page would be proportional to the square of the input size.
16 * Hence, we limit the number of inclusions of any given page, thus bringing any
17 * attack back to O(N).
19 define( 'MAX_INCLUDE_REPEAT', 100 );
20 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
22 # Allowed values for $mOutputType
23 define( 'OT_HTML', 1 );
24 define( 'OT_WIKI', 2 );
25 define( 'OT_MSG' , 3 );
27 # string parameter for extractTags which will cause it
28 # to strip HTML comments in addition to regular
29 # <XML>-style tags. This should not be anything we
30 # may want to use in wikisyntax
31 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
33 # prefix for escaping, used in two functions at least
34 define( 'UNIQ_PREFIX', 'NaodW29');
36 # Constants needed for external link processing
37 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
38 define( 'HTTP_PROTOCOLS', 'http|https' );
39 # Everything except bracket, space, or control characters
40 define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
41 define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
43 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
44 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
45 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
46 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
47 define( 'EXT_IMAGE_REGEX',
48 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
49 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
50 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
56 * Processes wiki markup
59 * There are three main entry points into the Parser class:
61 * produces HTML output
63 * produces altered wiki markup.
65 * performs brace substitution on MediaWiki messages
68 * objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
70 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
73 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
74 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
77 * * only within ParserOptions
90 # Cleared with clearState():
91 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
92 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
95 var $mOptions, $mTitle, $mOutputType,
96 $mTemplates, // cache of already loaded templates, avoids
97 // multiple SQL queries for the same string
98 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
99 // in this path. Used for loop detection.
109 $this->mTemplates
= array();
110 $this->mTemplatePath
= array();
111 $this->mTagHooks
= array();
120 function clearState() {
121 $this->mOutput
= new ParserOutput
;
122 $this->mAutonumber
= 0;
123 $this->mLastSection
= "";
124 $this->mDTopen
= false;
125 $this->mVariables
= false;
126 $this->mIncludeCount
= array();
127 $this->mStripState
= array();
128 $this->mArgStack
= array();
129 $this->mInPre
= false;
133 * First pass--just handle <nowiki> sections, pass the rest off
134 * to internalParse() which does all the real work.
137 * @return ParserOutput a ParserOutput
139 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
141 $fname = 'Parser::parse';
142 wfProfileIn( $fname );
148 $this->mOptions
= $options;
149 $this->mTitle
=& $title;
150 $this->mOutputType
= OT_HTML
;
153 $text = $this->strip( $text, $this->mStripState
);
154 $text = $this->internalParse( $text, $linestart );
155 $text = $this->unstrip( $text, $this->mStripState
);
156 # Clean up special characters, only run once, next-to-last before doBlockLevels
159 # french spaces, last one Guillemet-left
160 # only if there is something before the space
161 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
162 # french spaces, Guillemet-right
163 "/(\\302\\253) /i"=>"\\1 ",
164 '/<hr *>/i' => '<hr />',
165 '/<br *>/i' => '<br />',
166 '/<center *>/i' => '<div class="center">',
167 '/<\\/center *>/i' => '</div>',
168 # Clean up spare ampersands; note that we probably ought to be
169 # more careful about named entities.
170 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
172 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
175 # french spaces, last one Guillemet-left
176 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
177 # french spaces, Guillemet-right
178 '/(\\302\\253) /i' => '\\1 ',
179 '/<center *>/i' => '<div class="center">',
180 '/<\\/center *>/i' => '</div>'
182 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
185 $text = $this->doBlockLevels( $text, $linestart );
186 $text = $this->unstripNoWiki( $text, $this->mStripState
);
187 $this->mOutput
->setText( $text );
188 wfProfileOut( $fname );
189 return $this->mOutput
;
193 * Get a random string
198 function getRandomString() {
199 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
203 * Replaces all occurrences of <$tag>content</$tag> in the text
204 * with a random marker and returns the new text. the output parameter
205 * $content will be an associative array filled with data on the form
206 * $unique_marker => content.
208 * If $content is already set, the additional entries will be appended
209 * If $tag is set to STRIP_COMMENTS, the function will extract
210 * <!-- HTML comments -->
215 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
216 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
223 while ( '' != $text ) {
224 if($tag==STRIP_COMMENTS
) {
225 $p = preg_split( '/<!--/i', $text, 2 );
227 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
230 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
233 if($tag==STRIP_COMMENTS
) {
234 $q = preg_split( '/-->/i', $p[1], 2 );
236 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
238 $marker = $rnd . sprintf('%08X', $n++
);
239 $content[$marker] = $q[0];
240 $stripped .= $marker;
248 * Strips and renders nowiki, pre, math, hiero
249 * If $render is set, performs necessary rendering operations on plugins
250 * Returns the text, and fills an array with data needed in unstrip()
251 * If the $state is already a valid strip state, it adds to the state
253 * @param bool $stripcomments when set, HTML comments <!-- like this -->
254 * will be stripped in addition to other tags. This is important
255 * for section editing, where these comments cause confusion when
256 * counting the sections in the wikisource
260 function strip( $text, &$state, $stripcomments = false ) {
261 $render = ($this->mOutputType
== OT_HTML
);
262 $html_content = array();
263 $nowiki_content = array();
264 $math_content = array();
265 $pre_content = array();
266 $comment_content = array();
267 $ext_content = array();
269 # Replace any instances of the placeholders
270 $uniq_prefix = UNIQ_PREFIX
;
271 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
274 global $wgRawHtml, $wgWhitelistEdit;
275 if( $wgRawHtml && $wgWhitelistEdit ) {
276 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
277 foreach( $html_content as $marker => $content ) {
279 # Raw and unchecked for validity.
280 $html_content[$marker] = $content;
282 $html_content[$marker] = '<html>'.$content.'</html>';
288 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
289 foreach( $nowiki_content as $marker => $content ) {
291 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
293 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
298 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
299 foreach( $math_content as $marker => $content ){
301 if( $this->mOptions
->getUseTeX() ) {
302 $math_content[$marker] = renderMath( $content );
304 $math_content[$marker] = '<math>'.$content.'<math>';
307 $math_content[$marker] = '<math>'.$content.'</math>';
312 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
313 foreach( $pre_content as $marker => $content ){
315 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
317 $pre_content[$marker] = '<pre>'.$content.'</pre>';
323 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
324 foreach( $comment_content as $marker => $content ){
325 $comment_content[$marker] = '<!--'.$content.'-->';
330 foreach ( $this->mTagHooks
as $tag => $callback ) {
331 $ext_contents[$tag] = array();
332 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
333 foreach( $ext_content[$tag] as $marker => $content ) {
335 $ext_content[$tag][$marker] = $callback( $content );
337 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
342 # Merge state with the pre-existing state, if there is one
344 $state['html'] = $state['html'] +
$html_content;
345 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
346 $state['math'] = $state['math'] +
$math_content;
347 $state['pre'] = $state['pre'] +
$pre_content;
348 $state['comment'] = $state['comment'] +
$comment_content;
350 foreach( $ext_content as $tag => $array ) {
351 if ( array_key_exists( $tag, $state ) ) {
352 $state[$tag] = $state[$tag] +
$array;
357 'html' => $html_content,
358 'nowiki' => $nowiki_content,
359 'math' => $math_content,
360 'pre' => $pre_content,
361 'comment' => $comment_content,
368 * restores pre, math, and heiro removed by strip()
370 * always call unstripNoWiki() after this one
373 function unstrip( $text, &$state ) {
374 # Must expand in reverse order, otherwise nested tags will be corrupted
375 $contentDict = end( $state );
376 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
377 if( key($state) != 'nowiki' && key($state) != 'html') {
378 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
379 $text = str_replace( key( $contentDict ), $content, $text );
388 * always call this after unstrip() to preserve the order
392 function unstripNoWiki( $text, &$state ) {
393 # Must expand in reverse order, otherwise nested tags will be corrupted
394 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
395 $text = str_replace( key( $state['nowiki'] ), $content, $text );
400 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
401 $text = str_replace( key( $state['html'] ), $content, $text );
409 * Add an item to the strip state
410 * Returns the unique tag which must be inserted into the stripped text
411 * The tag will be replaced with the original text in unstrip()
415 function insertStripItem( $text, &$state ) {
416 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
425 $state['item'][$rnd] = $text;
430 * Return allowed HTML attributes
434 function getHTMLattrs () {
435 $htmlattrs = array( # Allowed attributes--no scripting, etc.
436 'title', 'align', 'lang', 'dir', 'width', 'height',
437 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
438 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
439 /* FONT */ 'type', 'start', 'value', 'compact',
440 /* For various lists, mostly deprecated but safe */
441 'summary', 'width', 'border', 'frame', 'rules',
442 'cellspacing', 'cellpadding', 'valign', 'char',
443 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
444 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
445 'id', 'class', 'name', 'style' /* For CSS */
451 * Remove non approved attributes and javascript in css
455 function fixTagAttributes ( $t ) {
456 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
457 $htmlattrs = $this->getHTMLattrs() ;
459 # Strip non-approved attributes from the tag
461 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
462 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
465 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
467 # Strip javascript "expression" from stylesheets. Brute force approach:
468 # If anythin offensive is found, all attributes of the HTML tag are dropped
471 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
472 wfMungeToUtf8( $t ) ) )
481 * interface with html tidy, used if $wgUseTidy = true
486 function tidy ( $text ) {
487 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
488 global $wgInputEncoding, $wgOutputEncoding;
489 $fname = 'Parser::tidy';
490 wfProfileIn( $fname );
494 switch(strtoupper($wgOutputEncoding)) {
496 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
499 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
505 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
506 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
507 '<head><title>test</title></head><body>'.$text.'</body></html>';
508 $descriptorspec = array(
509 0 => array('pipe', 'r'),
510 1 => array('pipe', 'w'),
511 2 => array('file', '/dev/null', 'a')
513 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
514 if (is_resource($process)) {
515 fwrite($pipes[0], $wrappedtext);
517 while (!feof($pipes[1])) {
518 $cleansource .= fgets($pipes[1], 1024);
521 $return_value = proc_close($process);
524 wfProfileOut( $fname );
526 if( $cleansource == '' && $text != '') {
527 wfDebug( "Tidy error detected!\n" );
528 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
535 * parse the wiki syntax used to render tables
539 function doTableStuff ( $t ) {
540 $fname = 'Parser::doTableStuff';
541 wfProfileIn( $fname );
543 $t = explode ( "\n" , $t ) ;
544 $td = array () ; # Is currently a td tag open?
545 $ltd = array () ; # Was it TD or TH?
546 $tr = array () ; # Is currently a tr tag open?
547 $ltr = array () ; # tr attributes
548 $indent_level = 0; # indent level of the table
549 foreach ( $t AS $k => $x )
552 $fc = substr ( $x , 0 , 1 ) ;
553 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
554 $indent_level = strlen( $matches[1] );
556 str_repeat( '<dl><dd>', $indent_level ) .
557 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
558 array_push ( $td , false ) ;
559 array_push ( $ltd , '' ) ;
560 array_push ( $tr , false ) ;
561 array_push ( $ltr , '' ) ;
563 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
564 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
566 $l = array_pop ( $ltd ) ;
567 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
568 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
570 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
572 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
573 $x = substr ( $x , 1 ) ;
574 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
576 $l = array_pop ( $ltd ) ;
577 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
578 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
581 array_push ( $tr , false ) ;
582 array_push ( $td , false ) ;
583 array_push ( $ltd , '' ) ;
584 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
586 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
588 if ( '|+' == substr ( $x , 0 , 2 ) ) {
590 $x = substr ( $x , 1 ) ;
592 $after = substr ( $x , 1 ) ;
593 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
594 $after = explode ( '||' , $after ) ;
597 # Loop through each table cell
598 foreach ( $after AS $theline )
603 $tra = array_pop ( $ltr ) ;
604 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
605 array_push ( $tr , true ) ;
606 array_push ( $ltr , '' ) ;
609 $l = array_pop ( $ltd ) ;
610 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
611 if ( $fc == '|' ) $l = 'td' ;
612 else if ( $fc == '!' ) $l = 'th' ;
613 else if ( $fc == '+' ) $l = 'caption' ;
615 array_push ( $ltd , $l ) ;
618 $y = explode ( '|' , $theline , 2 ) ;
619 # Note that a '|' inside an invalid link should not
620 # be mistaken as delimiting cell parameters
621 if ( strpos( $y[0], '[[' ) !== false ) {
622 $y = array ($theline);
624 if ( count ( $y ) == 1 )
625 $y = "{$z}<{$l}>{$y[0]}" ;
626 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
628 array_push ( $td , true ) ;
633 # Closing open td, tr && table
634 while ( count ( $td ) > 0 )
636 if ( array_pop ( $td ) ) $t[] = '</td>' ;
637 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
641 $t = implode ( "\n" , $t ) ;
642 # $t = $this->removeHTMLtags( $t );
643 wfProfileOut( $fname );
648 * Helper function for parse() that transforms wiki markup into
649 * HTML. Only called for $mOutputType == OT_HTML.
653 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
656 $fname = 'Parser::internalParse';
657 wfProfileIn( $fname );
659 $text = $this->removeHTMLtags( $text );
660 $text = $this->replaceVariables( $text, $args );
662 $text = $wgContLang->convert($text);
664 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
666 $text = $this->doHeadings( $text );
667 if($this->mOptions
->getUseDynamicDates()) {
668 global $wgDateFormatter;
669 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
671 $text = $this->doAllQuotes( $text );
672 $text = $this->replaceInternalLinks ( $text );
673 # Another call to replace links and images inside captions of images
674 $text = $this->replaceInternalLinks ( $text );
675 $text = $this->replaceExternalLinks( $text );
676 $text = $this->doMagicLinks( $text );
677 $text = $this->doTableStuff( $text );
678 $text = $this->formatHeadings( $text, $isMain );
679 $sk =& $this->mOptions
->getSkin();
680 $text = $sk->transformContent( $text );
682 wfProfileOut( $fname );
687 * Replace special strings like "ISBN xxx" and "RFC xxx" with
688 * magic external links.
692 function &doMagicLinks( &$text ) {
693 global $wgUseGeoMode;
694 $text = $this->magicISBN( $text );
695 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
696 $text = $this->magicGEO( $text );
698 $text = $this->magicRFC( $text );
703 * Parse ^^ tokens and return html
707 function doExponent ( $text ) {
708 $fname = 'Parser::doExponent';
709 wfProfileIn( $fname);
710 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
711 wfProfileOut( $fname);
716 * Parse headers and return html
720 function doHeadings( $text ) {
721 $fname = 'Parser::doHeadings';
722 wfProfileIn( $fname );
723 for ( $i = 6; $i >= 1; --$i ) {
724 $h = substr( '======', 0, $i );
725 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
726 "<h{$i}>\\1</h{$i}>\\2", $text );
728 wfProfileOut( $fname );
733 * Replace single quotes with HTML markup
735 * @return string the altered text
737 function doAllQuotes( $text ) {
738 $fname = 'Parser::doAllQuotes';
739 wfProfileIn( $fname );
741 $lines = explode( "\n", $text );
742 foreach ( $lines as $line ) {
743 $outtext .= $this->doQuotes ( $line ) . "\n";
745 $outtext = substr($outtext, 0,-1);
746 wfProfileOut( $fname );
751 * Helper function for doAllQuotes()
754 function doQuotes( $text ) {
755 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
756 if (count ($arr) == 1)
760 # First, do some preliminary work. This may shift some apostrophes from
761 # being mark-up to being text. It also counts the number of occurrences
762 # of bold and italics mark-ups.
770 # If there are ever four apostrophes, assume the first is supposed to
771 # be text, and the remaining three constitute mark-up for bold text.
772 if (strlen ($arr[$i]) == 4)
777 # If there are more than 5 apostrophes in a row, assume they're all
778 # text except for the last 5.
779 else if (strlen ($arr[$i]) > 5)
781 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
784 # Count the number of occurrences of bold and italics mark-ups.
785 # We are not counting sequences of five apostrophes.
786 if (strlen ($arr[$i]) == 2) $numitalics++
; else
787 if (strlen ($arr[$i]) == 3) $numbold++
; else
788 if (strlen ($arr[$i]) == 5) { $numitalics++
; $numbold++
; }
793 # If there is an odd number of both bold and italics, it is likely
794 # that one of the bold ones was meant to be an apostrophe followed
795 # by italics. Which one we cannot know for certain, but it is more
796 # likely to be one that has a single-letter word before it.
797 if (($numbold %
2 == 1) && ($numitalics %
2 == 1))
800 $firstsingleletterword = -1;
801 $firstmultiletterword = -1;
805 if (($i %
2 == 1) and (strlen ($r) == 3))
807 $x1 = substr ($arr[$i-1], -1);
808 $x2 = substr ($arr[$i-1], -2, 1);
810 if ($firstspace == -1) $firstspace = $i;
811 } else if ($x2 == ' ') {
812 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
814 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
820 # If there is a single-letter word, use it!
821 if ($firstsingleletterword > -1)
823 $arr [ $firstsingleletterword ] = "''";
824 $arr [ $firstsingleletterword-1 ] .= "'";
826 # If not, but there's a multi-letter word, use that one.
827 else if ($firstmultiletterword > -1)
829 $arr [ $firstmultiletterword ] = "''";
830 $arr [ $firstmultiletterword-1 ] .= "'";
832 # ... otherwise use the first one that has neither.
833 # (notice that it is possible for all three to be -1 if, for example,
834 # there is only one pentuple-apostrophe in the line)
835 else if ($firstspace > -1)
837 $arr [ $firstspace ] = "''";
838 $arr [ $firstspace-1 ] .= "'";
842 # Now let's actually convert our apostrophic mush to HTML!
851 if ($state == 'both')
858 if (strlen ($r) == 2)
861 { $output .= '</i>'; $state = ''; }
862 else if ($state == 'bi')
863 { $output .= '</i>'; $state = 'b'; }
864 else if ($state == 'ib')
865 { $output .= '</b></i><b>'; $state = 'b'; }
866 else if ($state == 'both')
867 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
868 else # $state can be 'b' or ''
869 { $output .= '<i>'; $state .= 'i'; }
871 else if (strlen ($r) == 3)
874 { $output .= '</b>'; $state = ''; }
875 else if ($state == 'bi')
876 { $output .= '</i></b><i>'; $state = 'i'; }
877 else if ($state == 'ib')
878 { $output .= '</b>'; $state = 'i'; }
879 else if ($state == 'both')
880 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
881 else # $state can be 'i' or ''
882 { $output .= '<b>'; $state .= 'b'; }
884 else if (strlen ($r) == 5)
887 { $output .= '</b><i>'; $state = 'i'; }
888 else if ($state == 'i')
889 { $output .= '</i><b>'; $state = 'b'; }
890 else if ($state == 'bi')
891 { $output .= '</i></b>'; $state = ''; }
892 else if ($state == 'ib')
893 { $output .= '</b></i>'; $state = ''; }
894 else if ($state == 'both')
895 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
896 else # ($state == '')
897 { $buffer = ''; $state = 'both'; }
902 # Now close all remaining tags. Notice that the order is important.
903 if ($state == 'b' ||
$state == 'ib')
905 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
909 if ($state == 'both')
910 $output .= '<b><i>'.$buffer.'</i></b>';
916 * Replace external links
918 * Note: we have to do external links before the internal ones,
919 * and otherwise take great care in the order of things here, so
920 * that we don't end up interpreting some URLs twice.
924 function replaceExternalLinks( $text ) {
925 $fname = 'Parser::replaceExternalLinks';
926 wfProfileIn( $fname );
928 $sk =& $this->mOptions
->getSkin();
929 $linktrail = wfMsgForContent('linktrail');
930 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
932 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
935 while ( $i<count( $bits ) ) {
937 $protocol = $bits[$i++
];
939 $trail = $bits[$i++
];
941 # If the link text is an image URL, replace it with an <img> tag
942 # This happened by accident in the original parser, but some people used it extensively
943 $img = $this->maybeMakeImageLink( $text );
944 if ( $img !== false ) {
950 # No link text, e.g. [http://domain.tld/some.link]
952 # Autonumber if allowed
953 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
954 $text = '[' . ++
$this->mAutonumber
. ']';
956 # Otherwise just use the URL
957 $text = htmlspecialchars( $url );
960 # Have link text, e.g. [http://domain.tld/some.link text]s
962 if ( preg_match( $linktrail, $trail, $m2 ) ) {
968 $encUrl = htmlspecialchars( $url );
969 # Bit in parentheses showing the URL for the printable version
970 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
973 # Expand the URL for printable version
974 if ( ! $sk->suppressUrlExpansion() ) {
975 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
981 # Process the trail (i.e. everything after this link up until start of the next link),
982 # replacing any non-bracketed links
983 $trail = $this->replaceFreeExternalLinks( $trail );
985 $la = $sk->getExternalLinkAttributes( $url, $text );
987 # Use the encoded URL
988 # This means that users can paste URLs directly into the text
989 # Funny characters like ö aren't valid in URLs anyway
990 # This was changed in August 2004
991 $s .= "<a href=\"{$url}\"{$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
994 wfProfileOut( $fname );
999 * Replace anything that looks like a URL with a link
1002 function replaceFreeExternalLinks( $text ) {
1003 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1004 $s = array_shift( $bits );
1007 $sk =& $this->mOptions
->getSkin();
1009 while ( $i < count( $bits ) ){
1010 $protocol = $bits[$i++
];
1011 $remainder = $bits[$i++
];
1013 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1014 # Found some characters after the protocol that look promising
1015 $url = $protocol . $m[1];
1018 # Move trailing punctuation to $trail
1020 # If there is no left bracket, then consider right brackets fair game too
1021 if ( strpos( $url, '(' ) === false ) {
1025 $numSepChars = strspn( strrev( $url ), $sep );
1026 if ( $numSepChars ) {
1027 $trail = substr( $url, -$numSepChars ) . $trail;
1028 $url = substr( $url, 0, -$numSepChars );
1031 # Replace & from obsolete syntax with &
1032 $url = str_replace( '&', '&', $url );
1034 # Is this an external image?
1035 $text = $this->maybeMakeImageLink( $url );
1036 if ( $text === false ) {
1037 # Not an image, make a link
1038 $text = $sk->makeExternalLink( $url, $url );
1040 $s .= $text . $trail;
1042 $s .= $protocol . $remainder;
1049 * make an image if it's allowed
1052 function maybeMakeImageLink( $url ) {
1053 $sk =& $this->mOptions
->getSkin();
1055 if ( $this->mOptions
->getAllowExternalImages() ) {
1056 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1058 $text = $sk->makeImage( htmlspecialchars( $url ) );
1065 * Process [[ ]] wikilinks
1069 function replaceInternalLinks( $s ) {
1070 global $wgLang, $wgContLang, $wgLinkCache;
1071 static $fname = 'Parser::replaceInternalLinks' ;
1072 wfProfileIn( $fname );
1074 wfProfileIn( $fname.'-setup' );
1076 # the % is needed to support urlencoded titles as well
1077 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1078 $sk =& $this->mOptions
->getSkin();
1080 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1082 $a = explode( '[[', ' ' . $s );
1083 $s = array_shift( $a );
1084 $s = substr( $s, 1 );
1086 # Match a link having the form [[namespace:link|alternate]]trail
1088 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1089 # Match the end of a line for a word that's not followed by whitespace,
1090 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1091 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1093 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1094 # Special and Media are pseudo-namespaces; no pages actually exist in them
1096 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1098 if ( $useLinkPrefixExtension ) {
1099 if ( preg_match( $e2, $s, $m ) ) {
1100 $first_prefix = $m[2];
1103 $first_prefix = false;
1109 wfProfileOut( $fname.'-setup' );
1111 # start procedeeding each line
1112 foreach ( $a as $line ) {
1113 wfProfileIn( $fname.'-prefixhandling' );
1114 if ( $useLinkPrefixExtension ) {
1115 if ( preg_match( $e2, $s, $m ) ) {
1123 $prefix = $first_prefix;
1124 $first_prefix = false;
1127 wfProfileOut( $fname.'-prefixhandling' );
1129 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1131 # fix up urlencoded title texts
1132 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1134 } else { # Invalid form; output directly
1135 $s .= $prefix . '[[' . $line ;
1139 # Don't allow internal links to pages containing
1140 # PROTO: where PROTO is a valid URL protocol; these
1141 # should be external links.
1142 if (preg_match('/((?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1143 $s .= $prefix . '[[' . $line ;
1147 # Make subpage if necessary
1148 $link = $this->maybeDoSubpageLink( $m[1], $text );
1150 $noforce = (substr($m[1], 0, 1) != ':');
1152 # Strip off leading ':'
1153 $link = substr($link, 1);
1156 $wasblank = ( '' == $text );
1157 if( $wasblank ) $text = $link;
1159 $nt = Title
::newFromText( $link );
1161 $s .= $prefix . '[[' . $line;
1165 $ns = $nt->getNamespace();
1166 $iw = $nt->getInterWiki();
1168 # Link not escaped by : , create the various objects
1172 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1173 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1174 $tmp = $prefix . $trail ;
1175 $s .= (trim($tmp) == '')?
'': $tmp;
1179 if ( $ns == NS_IMAGE
) {
1180 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1181 $wgLinkCache->addImageLinkObj( $nt );
1185 if ( $ns == NS_CATEGORY
) {
1186 $t = $nt->getText() ;
1187 $nnt = Title
::newFromText ( Namespace::getCanonicalName(NS_CATEGORY
).':'.$t ) ;
1189 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1190 $pPLC=$sk->postParseLinkColour();
1191 $sk->postParseLinkColour( false );
1192 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1193 $sk->postParseLinkColour( $pPLC );
1194 $wgLinkCache->resume();
1197 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1198 $sortkey = $this->mTitle
->getText();
1200 $sortkey = $this->mTitle
->getPrefixedText();
1205 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1206 $this->mOutput
->mCategoryLinks
[] = $t ;
1207 $s .= $prefix . $trail ;
1212 if( ( $nt->getPrefixedText() === $this->mTitle
->getPrefixedText() ) &&
1213 ( strpos( $link, '#' ) === FALSE ) ) {
1214 # Self-links are handled specially; generally de-link and change to bold.
1215 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1219 if( $ns == NS_MEDIA
) {
1220 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1221 $wgLinkCache->addImageLinkObj( $nt );
1223 } elseif( $ns == NS_SPECIAL
) {
1224 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1227 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1229 wfProfileOut( $fname );
1234 * Handle link to subpage if necessary
1235 * @param $target string the source of the link
1236 * @param &$text the link text, modified as necessary
1237 * @return string the full name of the link
1240 function maybeDoSubpageLink($target, &$text) {
1243 # :Foobar -- override special treatment of prefix (images, language links)
1244 # /Foobar -- convert to CurrentPage/Foobar
1245 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1246 global $wgNamespacesWithSubpages;
1248 $fname = 'Parser::maybeDoSubpageLink';
1249 wfProfileIn( $fname );
1250 # Look at the first character
1251 if( $target{0} == '/' ) {
1252 # / at end means we don't want the slash to be shown
1253 if(substr($target,-1,1)=='/') {
1254 $target=substr($target,1,-1);
1257 $noslash=substr($target,1);
1260 # Some namespaces don't allow subpages
1261 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) {
1262 # subpages allowed here
1263 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1264 if( '' === $text ) {
1266 } # this might be changed for ugliness reasons
1268 # no subpage allowed, use standard link
1276 wfProfileOut( $fname );
1281 * Used by doBlockLevels()
1284 /* private */ function closeParagraph() {
1286 if ( '' != $this->mLastSection
) {
1287 $result = '</' . $this->mLastSection
. ">\n";
1289 $this->mInPre
= false;
1290 $this->mLastSection
= '';
1293 # getCommon() returns the length of the longest common substring
1294 # of both arguments, starting at the beginning of both.
1296 /* private */ function getCommon( $st1, $st2 ) {
1297 $fl = strlen( $st1 );
1298 $shorter = strlen( $st2 );
1299 if ( $fl < $shorter ) { $shorter = $fl; }
1301 for ( $i = 0; $i < $shorter; ++
$i ) {
1302 if ( $st1{$i} != $st2{$i} ) { break; }
1306 # These next three functions open, continue, and close the list
1307 # element appropriate to the prefix character passed into them.
1309 /* private */ function openList( $char ) {
1310 $result = $this->closeParagraph();
1312 if ( '*' == $char ) { $result .= '<ul><li>'; }
1313 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1314 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1315 else if ( ';' == $char ) {
1316 $result .= '<dl><dt>';
1317 $this->mDTopen
= true;
1319 else { $result = '<!-- ERR 1 -->'; }
1324 /* private */ function nextItem( $char ) {
1325 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1326 else if ( ':' == $char ||
';' == $char ) {
1328 if ( $this->mDTopen
) { $close = '</dt>'; }
1329 if ( ';' == $char ) {
1330 $this->mDTopen
= true;
1331 return $close . '<dt>';
1333 $this->mDTopen
= false;
1334 return $close . '<dd>';
1337 return '<!-- ERR 2 -->';
1340 /* private */ function closeList( $char ) {
1341 if ( '*' == $char ) { $text = '</li></ul>'; }
1342 else if ( '#' == $char ) { $text = '</li></ol>'; }
1343 else if ( ':' == $char ) {
1344 if ( $this->mDTopen
) {
1345 $this->mDTopen
= false;
1346 $text = '</dt></dl>';
1348 $text = '</dd></dl>';
1351 else { return '<!-- ERR 3 -->'; }
1357 * Make lists from lines starting with ':', '*', '#', etc.
1360 * @return string the lists rendered as HTML
1362 function doBlockLevels( $text, $linestart ) {
1363 $fname = 'Parser::doBlockLevels';
1364 wfProfileIn( $fname );
1366 # Parsing through the text line by line. The main thing
1367 # happening here is handling of block-level elements p, pre,
1368 # and making lists from lines starting with * # : etc.
1370 $textLines = explode( "\n", $text );
1372 $lastPrefix = $output = $lastLine = '';
1373 $this->mDTopen
= $inBlockElem = false;
1375 $paragraphStack = false;
1377 if ( !$linestart ) {
1378 $output .= array_shift( $textLines );
1380 foreach ( $textLines as $oLine ) {
1381 $lastPrefixLength = strlen( $lastPrefix );
1382 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1383 $preOpenMatch = preg_match('/<pre/i', $oLine );
1384 if ( !$this->mInPre
) {
1385 # Multiple prefixes may abut each other for nested lists.
1386 $prefixLength = strspn( $oLine, '*#:;' );
1387 $pref = substr( $oLine, 0, $prefixLength );
1390 $pref2 = str_replace( ';', ':', $pref );
1391 $t = substr( $oLine, $prefixLength );
1392 $this->mInPre
= !empty($preOpenMatch);
1394 # Don't interpret any other prefixes in preformatted text
1396 $pref = $pref2 = '';
1401 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1402 # Same as the last item, so no need to deal with nesting or opening stuff
1403 $output .= $this->nextItem( substr( $pref, -1 ) );
1404 $paragraphStack = false;
1406 if ( substr( $pref, -1 ) == ';') {
1407 # The one nasty exception: definition lists work like this:
1408 # ; title : definition text
1409 # So we check for : in the remainder text to split up the
1410 # title and definition, without b0rking links.
1411 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1413 $output .= $term . $this->nextItem( ':' );
1416 } elseif( $prefixLength ||
$lastPrefixLength ) {
1417 # Either open or close a level...
1418 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1419 $paragraphStack = false;
1421 while( $commonPrefixLength < $lastPrefixLength ) {
1422 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1423 --$lastPrefixLength;
1425 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1426 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1428 while ( $prefixLength > $commonPrefixLength ) {
1429 $char = substr( $pref, $commonPrefixLength, 1 );
1430 $output .= $this->openList( $char );
1432 if ( ';' == $char ) {
1433 # FIXME: This is dupe of code above
1434 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1436 $output .= $term . $this->nextItem( ':' );
1439 ++
$commonPrefixLength;
1441 $lastPrefix = $pref2;
1443 if( 0 == $prefixLength ) {
1444 # No prefix (not in list)--go to paragraph mode
1445 $uniq_prefix = UNIQ_PREFIX
;
1446 // XXX: use a stack for nestable elements like span, table and div
1447 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1448 $closematch = preg_match(
1449 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1450 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1451 if ( $openmatch or $closematch ) {
1452 $paragraphStack = false;
1453 $output .= $this->closeParagraph();
1454 if($preOpenMatch and !$preCloseMatch) {
1455 $this->mInPre
= true;
1457 if ( $closematch ) {
1458 $inBlockElem = false;
1460 $inBlockElem = true;
1462 } else if ( !$inBlockElem && !$this->mInPre
) {
1463 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1465 if ($this->mLastSection
!= 'pre') {
1466 $paragraphStack = false;
1467 $output .= $this->closeParagraph().'<pre>';
1468 $this->mLastSection
= 'pre';
1470 $t = substr( $t, 1 );
1473 if ( '' == trim($t) ) {
1474 if ( $paragraphStack ) {
1475 $output .= $paragraphStack.'<br />';
1476 $paragraphStack = false;
1477 $this->mLastSection
= 'p';
1479 if ($this->mLastSection
!= 'p' ) {
1480 $output .= $this->closeParagraph();
1481 $this->mLastSection
= '';
1482 $paragraphStack = '<p>';
1484 $paragraphStack = '</p><p>';
1488 if ( $paragraphStack ) {
1489 $output .= $paragraphStack;
1490 $paragraphStack = false;
1491 $this->mLastSection
= 'p';
1492 } else if ($this->mLastSection
!= 'p') {
1493 $output .= $this->closeParagraph().'<p>';
1494 $this->mLastSection
= 'p';
1500 if ($paragraphStack === false) {
1504 while ( $prefixLength ) {
1505 $output .= $this->closeList( $pref2{$prefixLength-1} );
1508 if ( '' != $this->mLastSection
) {
1509 $output .= '</' . $this->mLastSection
. '>';
1510 $this->mLastSection
= '';
1513 wfProfileOut( $fname );
1518 * Split up a string on ':', ignoring any occurences inside
1519 * <a>..</a> or <span>...</span>
1520 * @param $str string the string to split
1521 * @param &$before string set to everything before the ':'
1522 * @param &$after string set to everything after the ':'
1523 * return string the position of the ':', or false if none found
1525 function findColonNoLinks($str, &$before, &$after) {
1526 # I wonder if we should make this count all tags, not just <a>
1527 # and <span>. That would prevent us from matching a ':' that
1528 # comes in the middle of italics other such formatting....
1530 $fname = 'Parser::findColonNoLinks';
1531 wfProfileIn( $fname );
1534 $colon = strpos($str, ':', $pos);
1536 if ($colon !== false) {
1537 $before = substr($str, 0, $colon);
1538 $after = substr($str, $colon +
1);
1540 # Skip any ':' within <a> or <span> pairs
1541 $a = substr_count($before, '<a');
1542 $s = substr_count($before, '<span');
1543 $ca = substr_count($before, '</a>');
1544 $cs = substr_count($before, '</span>');
1546 if ($a <= $ca and $s <= $cs) {
1547 # Tags are balanced before ':'; ok
1552 } while ($colon !== false);
1553 wfProfileOut( $fname );
1558 * Return value of a magic variable (like PAGENAME)
1562 function getVariableValue( $index ) {
1563 global $wgContLang, $wgSitename, $wgServer;
1566 case MAG_CURRENTMONTH
:
1567 return $wgContLang->formatNum( date( 'm' ) );
1568 case MAG_CURRENTMONTHNAME
:
1569 return $wgContLang->getMonthName( date('n') );
1570 case MAG_CURRENTMONTHNAMEGEN
:
1571 return $wgContLang->getMonthNameGen( date('n') );
1572 case MAG_CURRENTDAY
:
1573 return $wgContLang->formatNum( date('j') );
1575 return $this->mTitle
->getText();
1577 return $this->mTitle
->getPartialURL();
1579 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1580 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1581 case MAG_CURRENTDAYNAME
:
1582 return $wgContLang->getWeekdayName( date('w')+
1 );
1583 case MAG_CURRENTYEAR
:
1584 return $wgContLang->formatNum( date( 'Y' ) );
1585 case MAG_CURRENTTIME
:
1586 return $wgContLang->time( wfTimestampNow(), false );
1587 case MAG_NUMBEROFARTICLES
:
1588 return $wgContLang->formatNum( wfNumberOfArticles() );
1599 * initialise the magic variables (like CURRENTMONTHNAME)
1603 function initialiseVariables() {
1604 $fname = 'Parser::initialiseVariables';
1605 wfProfileIn( $fname );
1606 global $wgVariableIDs;
1607 $this->mVariables
= array();
1608 foreach ( $wgVariableIDs as $id ) {
1609 $mw =& MagicWord
::get( $id );
1610 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1612 wfProfileOut( $fname );
1616 * Replace magic variables, templates, and template arguments
1617 * with the appropriate text. Templates are substituted recursively,
1618 * taking care to avoid infinite loops.
1620 * Note that the substitution depends on value of $mOutputType:
1621 * OT_WIKI: only {{subst:}} templates
1622 * OT_MSG: only magic variables
1623 * OT_HTML: all templates and magic variables
1625 * @param string $tex The text to transform
1626 * @param array $args Key-value pairs representing template parameters to substitute
1629 function replaceVariables( $text, $args = array() ) {
1630 global $wgLang, $wgScript, $wgArticlePath;
1632 # Prevent too big inclusions
1633 if(strlen($text)> MAX_INCLUDE_SIZE
)
1636 $fname = 'Parser::replaceVariables';
1637 wfProfileIn( $fname );
1639 $titleChars = Title
::legalChars();
1641 # This function is called recursively. To keep track of arguments we need a stack:
1642 array_push( $this->mArgStack
, $args );
1644 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1645 $GLOBALS['wgCurParser'] =& $this;
1647 # Variable substitution
1648 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", 'wfVariableSubstitution', $text );
1650 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1651 # Argument substitution
1652 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1654 # Template substitution
1655 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1656 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1658 array_pop( $this->mArgStack
);
1660 wfProfileOut( $fname );
1665 * Replace magic variables
1668 function variableSubstitution( $matches ) {
1669 if ( !$this->mVariables
) {
1670 $this->initialiseVariables();
1673 if ( $this->mOutputType
== OT_WIKI
) {
1674 # Do only magic variables prefixed by SUBST
1675 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1676 if (!$mwSubst->matchStartAndRemove( $matches[1] ))
1678 # Note that if we don't substitute the variable below,
1679 # we don't remove the {{subst:}} magic word, in case
1680 # it is a template rather than a magic variable.
1682 if ( !$skip && array_key_exists( $matches[1], $this->mVariables
) ) {
1683 $text = $this->mVariables
[$matches[1]];
1684 $this->mOutput
->mContainsOldMagic
= true;
1686 $text = $matches[0];
1691 # Split template arguments
1692 function getTemplateArgs( $argsString ) {
1693 if ( $argsString === '' ) {
1697 $args = explode( '|', substr( $argsString, 1 ) );
1699 # If any of the arguments contains a '[[' but no ']]', it needs to be
1700 # merged with the next arg because the '|' character between belongs
1701 # to the link syntax and not the template parameter syntax.
1702 $argc = count($args);
1704 for ( $i = 0; $i < $argc-1; $i++
) {
1705 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1706 $args[$i] .= '|'.$args[$i+
1];
1707 array_splice($args, $i+
1, 1);
1717 * Return the text of a template, after recursively
1718 * replacing any variables or templates within the template.
1720 * @param array $matches The parts of the template
1721 * $matches[1]: the title, i.e. the part before the |
1722 * $matches[2]: the parameters (including a leading |), if any
1723 * @return string the text of the template
1726 function braceSubstitution( $matches ) {
1727 global $wgLinkCache, $wgContLang;
1728 $fname = 'Parser::braceSubstitution';
1735 # Need to know if the template comes at the start of a line,
1736 # to treat the beginning of the template like the beginning
1737 # of a line for tables and block-level elements.
1738 $linestart = $matches[1];
1740 # $part1 is the bit before the first |, and must contain only title characters
1741 # $args is a list of arguments, starting from index 0, not including $part1
1743 $part1 = $matches[2];
1744 # If the third subpattern matched anything, it will start with |
1746 $args = $this->getTemplateArgs($matches[3]);
1747 $argc = count( $args );
1749 # Don't parse {{{}}} because that's only for template arguments
1750 if ( $linestart === '{' ) {
1751 $text = $matches[0];
1758 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1759 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1760 # One of two possibilities is true:
1761 # 1) Found SUBST but not in the PST phase
1762 # 2) Didn't find SUBST and in the PST phase
1763 # In either case, return without further processing
1764 $text = $matches[0];
1770 # MSG, MSGNW and INT
1773 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1774 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1777 # Remove obsolete MSG:
1778 $mwMsg =& MagicWord
::get( MAG_MSG
);
1779 $mwMsg->matchStartAndRemove( $part1 );
1782 # Check if it is an internal message
1783 $mwInt =& MagicWord
::get( MAG_INT
);
1784 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1785 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1786 $text = $linestart . wfMsgReal( $part1, $args, true );
1794 # Check for NS: (namespace expansion)
1795 $mwNs = MagicWord
::get( MAG_NS
);
1796 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1797 if ( intval( $part1 ) ) {
1798 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1801 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1802 if ( !is_null( $index ) ) {
1803 $text = $linestart . $wgContLang->getNsText( $index );
1810 # LOCALURL and LOCALURLE
1812 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1813 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1815 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1816 $func = 'getLocalURL';
1817 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1818 $func = 'escapeLocalURL';
1823 if ( $func !== '' ) {
1824 $title = Title
::newFromText( $part1 );
1825 if ( !is_null( $title ) ) {
1827 $text = $linestart . $title->$func( $args[0] );
1829 $text = $linestart . $title->$func();
1837 if ( !$found && $argc == 1 ) {
1838 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1839 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1840 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1845 # Template table test
1847 # Did we encounter this template already? If yes, it is in the cache
1848 # and we need to check for loops.
1849 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
1850 # set $text to cached message.
1851 $text = $linestart . $this->mTemplates
[$part1];
1854 # Infinite loop test
1855 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1858 $text .= '<!-- WARNING: template loop detected -->';
1862 # Load from database
1863 $itcamefromthedatabase = false;
1866 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
1867 if ($subpage !== '') {
1868 $ns = $this->mTitle
->getNamespace();
1870 $title = Title
::newFromText( $part1, $ns );
1871 if ( !is_null( $title ) && !$title->isExternal() ) {
1872 # Check for excessive inclusion
1873 $dbk = $title->getPrefixedDBkey();
1874 if ( $this->incrementIncludeCount( $dbk ) ) {
1875 # This should never be reached.
1876 $article = new Article( $title );
1877 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1878 if ( $articleContent !== false ) {
1880 $text = $linestart . $articleContent;
1881 $itcamefromthedatabase = true;
1885 # If the title is valid but undisplayable, make a link to it
1886 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1887 $text = $linestart . '[['.$title->getPrefixedText().']]';
1891 # Template cache array insertion
1892 $this->mTemplates
[$part1] = $text;
1896 # Recursive parsing, escaping and link table handling
1897 # Only for HTML output
1898 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1899 $text = wfEscapeWikiText( $text );
1900 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
1901 # Clean up argument array
1902 $assocArgs = array();
1904 foreach( $args as $arg ) {
1905 $eqpos = strpos( $arg, '=' );
1906 if ( $eqpos === false ) {
1907 $assocArgs[$index++
] = $arg;
1909 $name = trim( substr( $arg, 0, $eqpos ) );
1910 $value = trim( substr( $arg, $eqpos+
1 ) );
1911 if ( $value === false ) {
1914 if ( $name !== false ) {
1915 $assocArgs[$name] = $value;
1920 # Add a new element to the templace recursion path
1921 $this->mTemplatePath
[$part1] = 1;
1923 $text = $this->strip( $text, $this->mStripState
);
1924 $text = $this->removeHTMLtags( $text );
1925 $text = $this->replaceVariables( $text, $assocArgs );
1927 # Resume the link cache and register the inclusion as a link
1928 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
1929 $wgLinkCache->addLinkObj( $title );
1932 # If the template begins with a table or block-level
1933 # element, it should be treated as beginning a new line.
1934 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
1935 $text = "\n" . $text;
1939 # Empties the template path
1940 $this->mTemplatePath
= array();
1944 # replace ==section headers==
1945 # XXX this needs to go away once we have a better parser.
1946 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
1947 if( !is_null( $title ) )
1948 $encodedname = base64_encode($title->getPrefixedDBkey());
1950 $encodedname = base64_encode("");
1951 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
1952 PREG_SPLIT_DELIM_CAPTURE
);
1955 for( $i = 0; $i < count($m); $i +
= 2 ) {
1957 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
1959 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
1963 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
1964 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
1965 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
1972 # Empties the template path
1973 $this->mTemplatePath
= array();
1982 * Triple brace replacement -- used for template arguments
1985 function argSubstitution( $matches ) {
1986 $arg = trim( $matches[1] );
1987 $text = $matches[0];
1988 $inputArgs = end( $this->mArgStack
);
1990 if ( array_key_exists( $arg, $inputArgs ) ) {
1991 $text = $inputArgs[$arg];
1998 * Returns true if the function is allowed to include this entity
2001 function incrementIncludeCount( $dbk ) {
2002 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2003 $this->mIncludeCount
[$dbk] = 0;
2005 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2014 * Cleans up HTML, removes dangerous tags and attributes, and
2015 * removes HTML comments
2018 function removeHTMLtags( $text ) {
2019 global $wgUseTidy, $wgUserHtml;
2020 $fname = 'Parser::removeHTMLtags';
2021 wfProfileIn( $fname );
2024 $htmlpairs = array( # Tags that must be closed
2025 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2026 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2027 'strike', 'strong', 'tt', 'var', 'div', 'center',
2028 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2029 'ruby', 'rt' , 'rb' , 'rp', 'p'
2031 $htmlsingle = array(
2032 'br', 'hr', 'li', 'dt', 'dd'
2034 $htmlnest = array( # Tags that can be nested--??
2035 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2036 'dl', 'font', 'big', 'small', 'sub', 'sup'
2038 $tabletags = array( # Can only appear inside table
2042 $htmlpairs = array();
2043 $htmlsingle = array();
2044 $htmlnest = array();
2045 $tabletags = array();
2048 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2049 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2051 $htmlattrs = $this->getHTMLattrs () ;
2053 # Remove HTML comments
2054 $text = $this->removeHTMLcomments( $text );
2056 $bits = explode( '<', $text );
2057 $text = array_shift( $bits );
2059 $tagstack = array(); $tablestack = array();
2060 foreach ( $bits as $x ) {
2061 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
2062 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2064 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2065 error_reporting( $prev );
2068 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2072 if ( ! in_array( $t, $htmlsingle ) &&
2073 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
2074 @array_push
( $tagstack, $ot );
2077 if ( $t == 'table' ) {
2078 $tagstack = array_pop( $tablestack );
2083 # Keep track for later
2084 if ( in_array( $t, $tabletags ) &&
2085 ! in_array( 'table', $tagstack ) ) {
2087 } else if ( in_array( $t, $tagstack ) &&
2088 ! in_array ( $t , $htmlnest ) ) {
2090 } else if ( ! in_array( $t, $htmlsingle ) ) {
2091 if ( $t == 'table' ) {
2092 array_push( $tablestack, $tagstack );
2093 $tagstack = array();
2095 array_push( $tagstack, $t );
2097 # Strip non-approved attributes from the tag
2098 $newparams = $this->fixTagAttributes($params);
2102 $rest = str_replace( '>', '>', $rest );
2103 $text .= "<$slash$t $newparams$brace$rest";
2107 $text .= '<' . str_replace( '>', '>', $x);
2109 # Close off any remaining tags
2110 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2112 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2115 # this might be possible using tidy itself
2116 foreach ( $bits as $x ) {
2117 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2119 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2120 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2121 $newparams = $this->fixTagAttributes($params);
2122 $rest = str_replace( '>', '>', $rest );
2123 $text .= "<$slash$t $newparams$brace$rest";
2125 $text .= '<' . str_replace( '>', '>', $x);
2129 wfProfileOut( $fname );
2134 * Remove '<!--', '-->', and everything between.
2135 * To avoid leaving blank lines, when a comment is both preceded
2136 * and followed by a newline (ignoring spaces), trim leading and
2137 * trailing spaces and one of the newlines.
2141 function removeHTMLcomments( $text ) {
2142 $fname='Parser::removeHTMLcomments';
2143 wfProfileIn( $fname );
2144 while (($start = strpos($text, '<!--')) !== false) {
2145 $end = strpos($text, '-->', $start +
4);
2146 if ($end === false) {
2147 # Unterminated comment; bail out
2153 # Trim space and newline if the comment is both
2154 # preceded and followed by a newline
2155 $spaceStart = max($start - 1, 0);
2156 $spaceLen = $end - $spaceStart;
2157 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2161 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2163 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2164 # Remove the comment, leading and trailing
2165 # spaces, and leave only one newline.
2166 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2169 # Remove just the comment.
2170 $text = substr_replace($text, '', $start, $end - $start);
2173 wfProfileOut( $fname );
2178 * This function accomplishes several tasks:
2179 * 1) Auto-number headings if that option is enabled
2180 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2181 * 3) Add a Table of contents on the top for users who have enabled the option
2182 * 4) Auto-anchor headings
2184 * It loops through all headlines, collects the necessary data, then splits up the
2185 * string and re-inserts the newly formatted headlines.
2188 /* private */ function formatHeadings( $text, $isMain=true ) {
2189 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders;
2191 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2192 $doShowToc = $this->mOptions
->getShowToc();
2193 $forceTocHere = false;
2194 if( !$this->mTitle
->userCanEdit() ) {
2196 $rightClickHack = 0;
2198 $showEditLink = $this->mOptions
->getEditSection();
2199 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2202 # Inhibit editsection links if requested in the page
2203 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2204 if( $esw->matchAndRemove( $text ) ) {
2207 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2209 $mw =& MagicWord
::get( MAG_NOTOC
);
2210 if( $mw->matchAndRemove( $text ) ) {
2214 # never add the TOC to the Main Page. This is an entry page that should not
2215 # be more than 1-2 screens large anyway
2216 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2220 # Get all headlines for numbering them and adding funky stuff like [edit]
2221 # links - this is for later, but we need the number of headlines right now
2222 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2224 # if there are fewer than 4 headlines in the article, do not show TOC
2225 if( $numMatches < 4 ) {
2229 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2230 # override above conditions and always show TOC at that place
2231 $mw =& MagicWord
::get( MAG_TOC
);
2232 if ($mw->match( $text ) ) {
2234 $forceTocHere = true;
2236 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2237 # override above conditions and always show TOC above first header
2238 $mw =& MagicWord
::get( MAG_FORCETOC
);
2239 if ($mw->matchAndRemove( $text ) ) {
2246 # We need this to perform operations on the HTML
2247 $sk =& $this->mOptions
->getSkin();
2251 $sectionCount = 0; # headlineCount excluding template sections
2253 # Ugh .. the TOC should have neat indentation levels which can be
2254 # passed to the skin functions. These are determined here
2259 $sublevelCount = array();
2262 foreach( $matches[3] as $headline ) {
2264 $templatetitle = "";
2265 $templatesection = 0;
2267 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2269 $templatetitle = base64_decode($mat[1]);
2270 $templatesection = 1 +
(int)base64_decode($mat[2]);
2271 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2276 $prevlevel = $level;
2278 $level = $matches[1][$headlineCount];
2279 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2280 # reset when we enter a new level
2281 $sublevelCount[$level] = 0;
2282 $toc .= $sk->tocIndent( $level - $prevlevel );
2283 $toclevel +
= $level - $prevlevel;
2285 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2286 # reset when we step back a level
2287 $sublevelCount[$level+
1]=0;
2288 $toc .= $sk->tocUnindent( $prevlevel - $level );
2289 $toclevel -= $prevlevel - $level;
2291 # count number of headlines for each level
2292 @$sublevelCount[$level]++
;
2293 if( $doNumberHeadings ||
$doShowToc ) {
2295 for( $i = 1; $i <= $level; $i++
) {
2296 if( !empty( $sublevelCount[$i] ) ) {
2300 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2306 # The canonized header is a version of the header text safe to use for links
2307 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2308 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2309 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2311 # Remove link placeholders by the link text.
2312 # <!--LINK number-->
2314 # link text with suffix
2315 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2316 "\$wgLinkHolders['texts'][\$1]",
2317 $canonized_headline );
2320 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2321 $tocline = trim( $canonized_headline );
2322 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2323 $replacearray = array(
2327 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2328 $refer[$headlineCount] = $canonized_headline;
2330 # count how many in assoc. array so we can track dupes in anchors
2331 @$refers[$canonized_headline]++
;
2332 $refcount[$headlineCount]=$refers[$canonized_headline];
2334 # Prepend the number to the heading text
2336 if( $doNumberHeadings ||
$doShowToc ) {
2337 $tocline = $numbering . ' ' . $tocline;
2339 # Don't number the heading if it is the only one (looks silly)
2340 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2341 # the two are different if the line contains a link
2342 $headline=$numbering . ' ' . $headline;
2346 # Create the anchor for linking from the TOC to the section
2347 $anchor = $canonized_headline;
2348 if($refcount[$headlineCount] > 1 ) {
2349 $anchor .= '_' . $refcount[$headlineCount];
2351 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2352 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2354 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2355 if ( empty( $head[$headlineCount] ) ) {
2356 $head[$headlineCount] = '';
2359 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2361 $head[$headlineCount] .= $sk->editSectionLink($sectionCount+
1);
2364 # Add the edit section span
2365 if( $rightClickHack ) {
2367 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2369 $headline = $sk->editSectionScript($sectionCount+
1,$headline);
2372 # give headline the correct <h#> tag
2373 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2381 $toclines = $headlineCount;
2382 $toc .= $sk->tocUnindent( $toclevel );
2383 $toc = $sk->tocTable( $toc );
2386 # split up and insert constructed headlines
2388 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2391 foreach( $blocks as $block ) {
2392 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2393 # This is the [edit] link that appears for the top block of text when
2394 # section editing is enabled
2396 # Disabled because it broke block formatting
2397 # For example, a bullet point in the top line
2398 # $full .= $sk->editSectionLink(0);
2401 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2402 # Top anchor now in skin
2406 if( !empty( $head[$i] ) ) {
2412 $mw =& MagicWord
::get( MAG_TOC
);
2413 return $mw->replace( $toc, $full );
2420 * Return an HTML link for the "ISBN 123456" text
2423 function magicISBN( $text ) {
2425 $fname = 'Parser::magicISBN';
2426 wfProfileIn( $fname );
2428 $a = split( 'ISBN ', ' '.$text );
2429 if ( count ( $a ) < 2 ) {
2430 wfProfileOut( $fname );
2433 $text = substr( array_shift( $a ), 1);
2434 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2436 foreach ( $a as $x ) {
2437 $isbn = $blank = '' ;
2438 while ( ' ' == $x{0} ) {
2440 $x = substr( $x, 1 );
2442 if ( $x == '' ) { # blank isbn
2443 $text .= "ISBN $blank";
2446 while ( strstr( $valid, $x{0} ) != false ) {
2448 $x = substr( $x, 1 );
2450 $num = str_replace( '-', '', $isbn );
2451 $num = str_replace( ' ', '', $num );
2454 $text .= "ISBN $blank$x";
2456 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2457 $text .= '<a href="' .
2458 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2459 "\" class=\"internal\">ISBN $isbn</a>";
2463 wfProfileOut( $fname );
2468 * Return an HTML link for the "GEO ..." text
2471 function magicGEO( $text ) {
2472 global $wgLang, $wgUseGeoMode;
2473 $fname = 'Parser::magicGEO';
2474 wfProfileIn( $fname );
2476 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2477 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2478 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2479 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2480 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2481 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2483 $a = split( 'GEO ', ' '.$text );
2484 if ( count ( $a ) < 2 ) {
2485 wfProfileOut( $fname );
2488 $text = substr( array_shift( $a ), 1);
2489 $valid = '0123456789.+-:';
2491 foreach ( $a as $x ) {
2492 $geo = $blank = '' ;
2493 while ( ' ' == $x{0} ) {
2495 $x = substr( $x, 1 );
2497 while ( strstr( $valid, $x{0} ) != false ) {
2499 $x = substr( $x, 1 );
2501 $num = str_replace( '+', '', $geo );
2502 $num = str_replace( ' ', '', $num );
2504 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2505 $text .= "GEO $blank$x";
2507 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2508 $text .= '<a href="' .
2509 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2510 "\" class=\"internal\">GEO $geo</a>";
2514 wfProfileOut( $fname );
2519 * Return an HTML link for the "RFC 1234" text
2521 * @param string $text text to be processed
2523 function magicRFC( $text ) {
2526 $valid = '0123456789';
2529 $a = split( 'RFC ', ' '.$text );
2530 if ( count ( $a ) < 2 ) return $text;
2531 $text = substr( array_shift( $a ), 1);
2533 /* Check if RFC keyword is preceed by [[.
2534 * This test is made here cause of the array_shift above
2535 * that prevent the test to be done in the foreach.
2537 if(substr($text, -2) == '[[') { $internal = true; }
2539 foreach ( $a as $x ) {
2540 /* token might be empty if we have RFC RFC 1234 */
2546 $rfc = $blank = '' ;
2548 /** remove and save whitespaces in $blank */
2549 while ( $x{0} == ' ' ) {
2551 $x = substr( $x, 1 );
2554 /** remove and save the rfc number in $rfc */
2555 while ( strstr( $valid, $x{0} ) != false ) {
2557 $x = substr( $x, 1 );
2561 /* call back stripped spaces*/
2562 $text .= "RFC $blank$x";
2563 } elseif( $internal) {
2565 $text .= "RFC $rfc$x";
2567 /* build the external link*/
2568 $url = wfmsg( 'rfcurl' );
2569 $url = str_replace( '$1', $rfc, $url);
2570 $sk =& $this->mOptions
->getSkin();
2571 $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
2572 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2575 /* Check if the next RFC keyword is preceed by [[ */
2576 $internal = (substr($x,-2) == '[[');
2582 * Transform wiki markup when saving a page by doing \r\n -> \n
2583 * conversion, substitting signatures, {{subst:}} templates, etc.
2585 * @param string $text the text to transform
2586 * @param Title &$title the Title object for the current article
2587 * @param User &$user the User object describing the current user
2588 * @param ParserOptions $options parsing options
2589 * @param bool $clearState whether to clear the parser state first
2590 * @return string the altered wiki markup
2593 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2594 $this->mOptions
= $options;
2595 $this->mTitle
=& $title;
2596 $this->mOutputType
= OT_WIKI
;
2598 if ( $clearState ) {
2599 $this->clearState();
2602 $stripState = false;
2606 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2610 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2611 "/<br *?>/i" => "<br />",
2613 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2615 $text = $this->strip( $text, $stripState, false );
2616 $text = $this->pstPass2( $text, $user );
2617 $text = $this->unstrip( $text, $stripState );
2618 $text = $this->unstripNoWiki( $text, $stripState );
2623 * Pre-save transform helper function
2626 function pstPass2( $text, &$user ) {
2627 global $wgLang, $wgContLang, $wgLocaltimezone, $wgCurParser;
2629 # Variable replacement
2630 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2631 $text = $this->replaceVariables( $text );
2635 $n = $user->getName();
2636 $k = $user->getOption( 'nickname' );
2637 if ( '' == $k ) { $k = $n; }
2638 if(isset($wgLocaltimezone)) {
2639 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2641 /* Note: this is an ugly timezone hack for the European wikis */
2642 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2643 ' (' . date( 'T' ) . ')';
2644 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2646 $text = preg_replace( '/~~~~~/', $d, $text );
2647 $text = preg_replace( '/~~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2648 $text = preg_replace( '/~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2650 # Context links: [[|name]] and [[name (context)|]]
2652 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2653 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2654 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2655 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2657 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2658 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2659 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2660 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2662 $t = $this->mTitle
->getText();
2663 if ( preg_match( $conpat, $t, $m ) ) {
2666 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2667 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2668 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2670 if ( '' == $context ) {
2671 $text = preg_replace( $p2, '[[\\1]]', $text );
2673 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2676 # Trim trailing whitespace
2677 # MAG_END (__END__) tag allows for trailing
2678 # whitespace to be deliberately included
2679 $text = rtrim( $text );
2680 $mw =& MagicWord
::get( MAG_END
);
2681 $mw->matchAndRemove( $text );
2687 * Set up some variables which are usually set up in parse()
2688 * so that an external function can call some class members with confidence
2691 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2692 $this->mTitle
=& $title;
2693 $this->mOptions
= $options;
2694 $this->mOutputType
= $outputType;
2695 if ( $clearState ) {
2696 $this->clearState();
2701 * Transform a MediaWiki message by replacing magic variables.
2703 * @param string $text the text to transform
2704 * @param ParserOptions $options options
2705 * @return string the text with variables substituted
2708 function transformMsg( $text, $options ) {
2710 static $executing = false;
2712 # Guard against infinite recursion
2718 $this->mTitle
= $wgTitle;
2719 $this->mOptions
= $options;
2720 $this->mOutputType
= OT_MSG
;
2721 $this->clearState();
2722 $text = $this->replaceVariables( $text );
2729 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2730 * Callback will be called with the text within
2731 * Transform and return the text within
2734 function setHook( $tag, $callback ) {
2735 $oldVal = @$this->mTagHooks
[$tag];
2736 $this->mTagHooks
[$tag] = $callback;
2743 * @package MediaWiki
2747 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2748 var $mCacheTime; # Used in ParserCache
2750 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2751 $containsOldMagic = false )
2753 $this->mText
= $text;
2754 $this->mLanguageLinks
= $languageLinks;
2755 $this->mCategoryLinks
= $categoryLinks;
2756 $this->mContainsOldMagic
= $containsOldMagic;
2757 $this->mCacheTime
= '';
2760 function getText() { return $this->mText
; }
2761 function getLanguageLinks() { return $this->mLanguageLinks
; }
2762 function getCategoryLinks() { return $this->mCategoryLinks
; }
2763 function getCacheTime() { return $this->mCacheTime
; }
2764 function containsOldMagic() { return $this->mContainsOldMagic
; }
2765 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2766 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2767 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2768 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2769 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2771 function merge( $other ) {
2772 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2773 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2774 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2780 * Set options of the Parser
2782 * @package MediaWiki
2786 # All variables are private
2787 var $mUseTeX; # Use texvc to expand <math> tags
2788 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2789 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2790 var $mAllowExternalImages; # Allow external images inline
2791 var $mSkin; # Reference to the preferred skin
2792 var $mDateFormat; # Date format index
2793 var $mEditSection; # Create "edit section" links
2794 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2795 var $mNumberHeadings; # Automatically number headings
2796 var $mShowToc; # Show table of contents
2798 function getUseTeX() { return $this->mUseTeX
; }
2799 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2800 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2801 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2802 function getSkin() { return $this->mSkin
; }
2803 function getDateFormat() { return $this->mDateFormat
; }
2804 function getEditSection() { return $this->mEditSection
; }
2805 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2806 function getNumberHeadings() { return $this->mNumberHeadings
; }
2807 function getShowToc() { return $this->mShowToc
; }
2809 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2810 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2811 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2812 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2813 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2814 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2815 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2816 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2817 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2819 function setSkin( &$x ) { $this->mSkin
=& $x; }
2821 # Get parser options
2822 /* static */ function newFromUser( &$user ) {
2823 $popts = new ParserOptions
;
2824 $popts->initialiseFromUser( $user );
2829 function initialiseFromUser( &$userInput ) {
2830 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2832 $fname = 'ParserOptions::initialiseFromUser';
2833 wfProfileIn( $fname );
2834 if ( !$userInput ) {
2836 $user->setLoaded( true );
2838 $user =& $userInput;
2841 $this->mUseTeX
= $wgUseTeX;
2842 $this->mUseDynamicDates
= $wgUseDynamicDates;
2843 $this->mInterwikiMagic
= $wgInterwikiMagic;
2844 $this->mAllowExternalImages
= $wgAllowExternalImages;
2845 wfProfileIn( $fname.'-skin' );
2846 $this->mSkin
=& $user->getSkin();
2847 wfProfileOut( $fname.'-skin' );
2848 $this->mDateFormat
= $user->getOption( 'date' );
2849 $this->mEditSection
= $user->getOption( 'editsection' );
2850 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2851 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2852 $this->mShowToc
= $user->getOption( 'showtoc' );
2853 wfProfileOut( $fname );
2859 # Regex callbacks, used in Parser::replaceVariables
2860 function wfBraceSubstitution( $matches ) {
2861 global $wgCurParser;
2862 return $wgCurParser->braceSubstitution( $matches );
2865 function wfArgSubstitution( $matches ) {
2866 global $wgCurParser;
2867 return $wgCurParser->argSubstitution( $matches );
2870 function wfVariableSubstitution( $matches ) {
2871 global $wgCurParser;
2872 return $wgCurParser->variableSubstitution( $matches );
2876 * Return the total number of articles
2878 function wfNumberOfArticles() {
2879 global $wgNumberOfArticles;
2882 return $wgNumberOfArticles;
2886 * Get various statistics from the database
2889 function wfLoadSiteStats() {
2890 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2891 $fname = 'wfLoadSiteStats';
2893 if ( -1 != $wgNumberOfArticles ) return;
2894 $dbr =& wfGetDB( DB_SLAVE
);
2895 $s = $dbr->getArray( 'site_stats',
2896 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2897 array( 'ss_row_id' => 1 ), $fname
2900 if ( $s === false ) {
2903 $wgTotalViews = $s->ss_total_views
;
2904 $wgTotalEdits = $s->ss_total_edits
;
2905 $wgNumberOfArticles = $s->ss_good_articles
;
2909 function wfEscapeHTMLTagsOnly( $in ) {
2911 array( '"', '>', '<' ),
2912 array( '"', '>', '<' ),