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
);
188 $text = $this->tidy($text);
190 $this->mOutput
->setText( $text );
191 wfProfileOut( $fname );
192 return $this->mOutput
;
196 * Get a random string
201 function getRandomString() {
202 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
206 * Replaces all occurrences of <$tag>content</$tag> in the text
207 * with a random marker and returns the new text. the output parameter
208 * $content will be an associative array filled with data on the form
209 * $unique_marker => content.
211 * If $content is already set, the additional entries will be appended
212 * If $tag is set to STRIP_COMMENTS, the function will extract
213 * <!-- HTML comments -->
218 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
219 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
226 while ( '' != $text ) {
227 if($tag==STRIP_COMMENTS
) {
228 $p = preg_split( '/<!--/i', $text, 2 );
230 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
233 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
236 if($tag==STRIP_COMMENTS
) {
237 $q = preg_split( '/-->/i', $p[1], 2 );
239 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
241 $marker = $rnd . sprintf('%08X', $n++
);
242 $content[$marker] = $q[0];
243 $stripped .= $marker;
251 * Strips and renders nowiki, pre, math, hiero
252 * If $render is set, performs necessary rendering operations on plugins
253 * Returns the text, and fills an array with data needed in unstrip()
254 * If the $state is already a valid strip state, it adds to the state
256 * @param bool $stripcomments when set, HTML comments <!-- like this -->
257 * will be stripped in addition to other tags. This is important
258 * for section editing, where these comments cause confusion when
259 * counting the sections in the wikisource
263 function strip( $text, &$state, $stripcomments = false ) {
264 $render = ($this->mOutputType
== OT_HTML
);
265 $html_content = array();
266 $nowiki_content = array();
267 $math_content = array();
268 $pre_content = array();
269 $comment_content = array();
270 $ext_content = array();
272 # Replace any instances of the placeholders
273 $uniq_prefix = UNIQ_PREFIX
;
274 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
277 global $wgRawHtml, $wgWhitelistEdit;
278 if( $wgRawHtml && $wgWhitelistEdit ) {
279 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
280 foreach( $html_content as $marker => $content ) {
282 # Raw and unchecked for validity.
283 $html_content[$marker] = $content;
285 $html_content[$marker] = '<html>'.$content.'</html>';
291 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
292 foreach( $nowiki_content as $marker => $content ) {
294 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
296 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
301 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
302 foreach( $math_content as $marker => $content ){
304 if( $this->mOptions
->getUseTeX() ) {
305 $math_content[$marker] = renderMath( $content );
307 $math_content[$marker] = '<math>'.$content.'<math>';
310 $math_content[$marker] = '<math>'.$content.'</math>';
315 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
316 foreach( $pre_content as $marker => $content ){
318 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
320 $pre_content[$marker] = '<pre>'.$content.'</pre>';
326 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
327 foreach( $comment_content as $marker => $content ){
328 $comment_content[$marker] = '<!--'.$content.'-->';
333 foreach ( $this->mTagHooks
as $tag => $callback ) {
334 $ext_contents[$tag] = array();
335 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
336 foreach( $ext_content[$tag] as $marker => $content ) {
338 $ext_content[$tag][$marker] = $callback( $content );
340 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
345 # Merge state with the pre-existing state, if there is one
347 $state['html'] = $state['html'] +
$html_content;
348 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
349 $state['math'] = $state['math'] +
$math_content;
350 $state['pre'] = $state['pre'] +
$pre_content;
351 $state['comment'] = $state['comment'] +
$comment_content;
353 foreach( $ext_content as $tag => $array ) {
354 if ( array_key_exists( $tag, $state ) ) {
355 $state[$tag] = $state[$tag] +
$array;
360 'html' => $html_content,
361 'nowiki' => $nowiki_content,
362 'math' => $math_content,
363 'pre' => $pre_content,
364 'comment' => $comment_content,
371 * restores pre, math, and heiro removed by strip()
373 * always call unstripNoWiki() after this one
376 function unstrip( $text, &$state ) {
377 # Must expand in reverse order, otherwise nested tags will be corrupted
378 $contentDict = end( $state );
379 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
380 if( key($state) != 'nowiki' && key($state) != 'html') {
381 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
382 $text = str_replace( key( $contentDict ), $content, $text );
391 * always call this after unstrip() to preserve the order
395 function unstripNoWiki( $text, &$state ) {
396 # Must expand in reverse order, otherwise nested tags will be corrupted
397 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
398 $text = str_replace( key( $state['nowiki'] ), $content, $text );
403 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
404 $text = str_replace( key( $state['html'] ), $content, $text );
412 * Add an item to the strip state
413 * Returns the unique tag which must be inserted into the stripped text
414 * The tag will be replaced with the original text in unstrip()
418 function insertStripItem( $text, &$state ) {
419 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
428 $state['item'][$rnd] = $text;
433 * Return allowed HTML attributes
437 function getHTMLattrs () {
438 $htmlattrs = array( # Allowed attributes--no scripting, etc.
439 'title', 'align', 'lang', 'dir', 'width', 'height',
440 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
441 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
442 /* FONT */ 'type', 'start', 'value', 'compact',
443 /* For various lists, mostly deprecated but safe */
444 'summary', 'width', 'border', 'frame', 'rules',
445 'cellspacing', 'cellpadding', 'valign', 'char',
446 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
447 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
448 'id', 'class', 'name', 'style' /* For CSS */
454 * Remove non approved attributes and javascript in css
458 function fixTagAttributes ( $t ) {
459 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
460 $htmlattrs = $this->getHTMLattrs() ;
462 # Strip non-approved attributes from the tag
464 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
465 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
468 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
470 # Strip javascript "expression" from stylesheets. Brute force approach:
471 # If anythin offensive is found, all attributes of the HTML tag are dropped
474 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
475 wfMungeToUtf8( $t ) ) )
484 * interface with html tidy, used if $wgUseTidy = true
488 function tidy ( $text ) {
489 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
490 global $wgInputEncoding, $wgOutputEncoding;
491 $fname = 'Parser::tidy';
492 wfProfileIn( $fname );
495 switch(strtoupper($wgOutputEncoding)) {
497 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
500 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
503 $wgTidyOpts .= ' -raw';
506 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
507 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
508 '<head><title>test</title></head><body>'.$text.'</body></html>';
509 $descriptorspec = array(
510 0 => array('pipe', 'r'),
511 1 => array('pipe', 'w'),
512 2 => array('file', '/dev/null', 'a')
514 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
515 if (is_resource($process)) {
516 fwrite($pipes[0], $wrappedtext);
518 while (!feof($pipes[1])) {
519 $cleansource .= fgets($pipes[1], 1024);
522 $return_value = proc_close($process);
525 wfProfileOut( $fname );
527 if( $cleansource == '' && $text != '') {
528 wfDebug( "Tidy error detected!\n" );
529 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
536 * parse the wiki syntax used to render tables
540 function doTableStuff ( $t ) {
541 $fname = 'Parser::doTableStuff';
542 wfProfileIn( $fname );
544 $t = explode ( "\n" , $t ) ;
545 $td = array () ; # Is currently a td tag open?
546 $ltd = array () ; # Was it TD or TH?
547 $tr = array () ; # Is currently a tr tag open?
548 $ltr = array () ; # tr attributes
549 $indent_level = 0; # indent level of the table
550 foreach ( $t AS $k => $x )
553 $fc = substr ( $x , 0 , 1 ) ;
554 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
555 $indent_level = strlen( $matches[1] );
557 str_repeat( '<dl><dd>', $indent_level ) .
558 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
559 array_push ( $td , false ) ;
560 array_push ( $ltd , '' ) ;
561 array_push ( $tr , false ) ;
562 array_push ( $ltr , '' ) ;
564 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
565 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
567 $l = array_pop ( $ltd ) ;
568 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
569 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
571 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
573 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
574 $x = substr ( $x , 1 ) ;
575 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
577 $l = array_pop ( $ltd ) ;
578 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
579 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
582 array_push ( $tr , false ) ;
583 array_push ( $td , false ) ;
584 array_push ( $ltd , '' ) ;
585 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
587 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 ) ;
596 foreach ( $after AS $theline )
601 $tra = array_pop ( $ltr ) ;
602 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
603 array_push ( $tr , true ) ;
604 array_push ( $ltr , '' ) ;
607 $l = array_pop ( $ltd ) ;
608 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
609 if ( $fc == '|' ) $l = 'td' ;
610 else if ( $fc == '!' ) $l = 'th' ;
611 else if ( $fc == '+' ) $l = 'caption' ;
613 array_push ( $ltd , $l ) ;
614 $y = explode ( '|' , $theline , 2 ) ;
615 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
616 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
618 array_push ( $td , true ) ;
623 # Closing open td, tr && table
624 while ( count ( $td ) > 0 )
626 if ( array_pop ( $td ) ) $t[] = '</td>' ;
627 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
631 $t = implode ( "\n" , $t ) ;
632 # $t = $this->removeHTMLtags( $t );
633 wfProfileOut( $fname );
638 * Helper function for parse() that transforms wiki markup into
639 * HTML. Only called for $mOutputType == OT_HTML.
643 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
646 $fname = 'Parser::internalParse';
647 wfProfileIn( $fname );
649 $text = $this->removeHTMLtags( $text );
650 $text = $this->replaceVariables( $text, $args );
652 $text = $wgContLang->convert($text);
654 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
656 $text = $this->doHeadings( $text );
657 if($this->mOptions
->getUseDynamicDates()) {
658 global $wgDateFormatter;
659 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
661 $text = $this->doAllQuotes( $text );
662 $text = $this->doMagicLinks( $text );
663 $text = $this->replaceInternalLinks ( $text );
664 # Another call to replace links and images inside captions of images
665 $text = $this->replaceInternalLinks ( $text );
666 $text = $this->replaceExternalLinks( $text );
667 $text = $this->doTableStuff( $text );
668 $text = $this->formatHeadings( $text, $isMain );
669 $sk =& $this->mOptions
->getSkin();
670 $text = $sk->transformContent( $text );
672 wfProfileOut( $fname );
677 * Replace special strings like "ISBN xxx" and "RFC xxx" with
678 * magic external links.
682 function &doMagicLinks( &$text ) {
683 global $wgUseGeoMode;
684 $text = $this->magicISBN( $text );
685 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
686 $text = $this->magicGEO( $text );
688 $text = $this->magicRFC( $text );
693 * Parse ^^ tokens and return html
697 function doExponent ( $text ) {
698 $fname = 'Parser::doExponent';
699 wfProfileIn( $fname);
700 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
701 wfProfileOut( $fname);
706 * Parse headers and return html
710 function doHeadings( $text ) {
711 $fname = 'Parser::doHeadings';
712 wfProfileIn( $fname );
713 for ( $i = 6; $i >= 1; --$i ) {
714 $h = substr( '======', 0, $i );
715 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
716 "<h{$i}>\\1</h{$i}>\\2", $text );
718 wfProfileOut( $fname );
723 * Replace single quotes with HTML markup
725 * @return string the altered text
727 function doAllQuotes( $text ) {
728 $fname = 'Parser::doAllQuotes';
729 wfProfileIn( $fname );
731 $lines = explode( "\n", $text );
732 foreach ( $lines as $line ) {
733 $outtext .= $this->doQuotes ( $line ) . "\n";
735 $outtext = substr($outtext, 0,-1);
736 wfProfileOut( $fname );
741 * Helper function for doAllQuotes()
744 function doQuotes( $text ) {
745 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
746 if (count ($arr) == 1)
750 # First, do some preliminary work. This may shift some apostrophes from
751 # being mark-up to being text. It also counts the number of occurrences
752 # of bold and italics mark-ups.
760 # If there are ever four apostrophes, assume the first is supposed to
761 # be text, and the remaining three constitute mark-up for bold text.
762 if (strlen ($arr[$i]) == 4)
767 # If there are more than 5 apostrophes in a row, assume they're all
768 # text except for the last 5.
769 else if (strlen ($arr[$i]) > 5)
771 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
774 # Count the number of occurrences of bold and italics mark-ups.
775 # We are not counting sequences of five apostrophes.
776 if (strlen ($arr[$i]) == 2) $numitalics++
; else
777 if (strlen ($arr[$i]) == 3) $numbold++
; else
778 if (strlen ($arr[$i]) == 5) { $numitalics++
; $numbold++
; }
783 # If there is an odd number of both bold and italics, it is likely
784 # that one of the bold ones was meant to be an apostrophe followed
785 # by italics. Which one we cannot know for certain, but it is more
786 # likely to be one that has a single-letter word before it.
787 if (($numbold %
2 == 1) && ($numitalics %
2 == 1))
790 $firstsingleletterword = -1;
791 $firstmultiletterword = -1;
795 if (($i %
2 == 1) and (strlen ($r) == 3))
797 $x1 = substr ($arr[$i-1], -1);
798 $x2 = substr ($arr[$i-1], -2, 1);
800 if ($firstspace == -1) $firstspace = $i;
801 } else if ($x2 == ' ') {
802 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
804 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
810 # If there is a single-letter word, use it!
811 if ($firstsingleletterword > -1)
813 $arr [ $firstsingleletterword ] = "''";
814 $arr [ $firstsingleletterword-1 ] .= "'";
816 # If not, but there's a multi-letter word, use that one.
817 else if ($firstmultiletterword > -1)
819 $arr [ $firstmultiletterword ] = "''";
820 $arr [ $firstmultiletterword-1 ] .= "'";
822 # ... otherwise use the first one that has neither.
823 # (notice that it is possible for all three to be -1 if, for example,
824 # there is only one pentuple-apostrophe in the line)
825 else if ($firstspace > -1)
827 $arr [ $firstspace ] = "''";
828 $arr [ $firstspace-1 ] .= "'";
832 # Now let's actually convert our apostrophic mush to HTML!
841 if ($state == 'both')
848 if (strlen ($r) == 2)
851 { $output .= '</i>'; $state = ''; }
852 else if ($state == 'bi')
853 { $output .= '</i>'; $state = 'b'; }
854 else if ($state == 'ib')
855 { $output .= '</b></i><b>'; $state = 'b'; }
856 else if ($state == 'both')
857 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
858 else # $state can be 'b' or ''
859 { $output .= '<i>'; $state .= 'i'; }
861 else if (strlen ($r) == 3)
864 { $output .= '</b>'; $state = ''; }
865 else if ($state == 'bi')
866 { $output .= '</i></b><i>'; $state = 'i'; }
867 else if ($state == 'ib')
868 { $output .= '</b>'; $state = 'i'; }
869 else if ($state == 'both')
870 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
871 else # $state can be 'i' or ''
872 { $output .= '<b>'; $state .= 'b'; }
874 else if (strlen ($r) == 5)
877 { $output .= '</b><i>'; $state = 'i'; }
878 else if ($state == 'i')
879 { $output .= '</i><b>'; $state = 'b'; }
880 else if ($state == 'bi')
881 { $output .= '</i></b>'; $state = ''; }
882 else if ($state == 'ib')
883 { $output .= '</b></i>'; $state = ''; }
884 else if ($state == 'both')
885 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
886 else # ($state == '')
887 { $buffer = ''; $state = 'both'; }
892 # Now close all remaining tags. Notice that the order is important.
893 if ($state == 'b' ||
$state == 'ib')
895 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
899 if ($state == 'both')
900 $output .= '<b><i>'.$buffer.'</i></b>';
906 * Replace external links
908 * Note: we have to do external links before the internal ones,
909 * and otherwise take great care in the order of things here, so
910 * that we don't end up interpreting some URLs twice.
914 function replaceExternalLinks( $text ) {
915 $fname = 'Parser::replaceExternalLinks';
916 wfProfileIn( $fname );
918 $sk =& $this->mOptions
->getSkin();
919 $linktrail = wfMsgForContent('linktrail');
920 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
922 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
925 while ( $i<count( $bits ) ) {
927 $protocol = $bits[$i++
];
929 $trail = $bits[$i++
];
931 # If the link text is an image URL, replace it with an <img> tag
932 # This happened by accident in the original parser, but some people used it extensively
933 $img = $this->maybeMakeImageLink( $text );
934 if ( $img !== false ) {
940 # No link text, e.g. [http://domain.tld/some.link]
942 # Autonumber if allowed
943 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
944 $text = '[' . ++
$this->mAutonumber
. ']';
946 # Otherwise just use the URL
947 $text = htmlspecialchars( $url );
950 # Have link text, e.g. [http://domain.tld/some.link text]s
952 if ( preg_match( $linktrail, $trail, $m2 ) ) {
958 $encUrl = htmlspecialchars( $url );
959 # Bit in parentheses showing the URL for the printable version
960 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
963 # Expand the URL for printable version
964 if ( ! $sk->suppressUrlExpansion() ) {
965 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
971 # Process the trail (i.e. everything after this link up until start of the next link),
972 # replacing any non-bracketed links
973 $trail = $this->replaceFreeExternalLinks( $trail );
975 $la = $sk->getExternalLinkAttributes( $url, $text );
977 # Use the encoded URL
978 # This means that users can paste URLs directly into the text
979 # Funny characters like ö aren't valid in URLs anyway
980 # This was changed in August 2004
981 $s .= "<a href=\"{$url}\"{$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
984 wfProfileOut( $fname );
989 * Replace anything that looks like a URL with a link
992 function replaceFreeExternalLinks( $text ) {
993 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
994 $s = array_shift( $bits );
997 $sk =& $this->mOptions
->getSkin();
999 while ( $i < count( $bits ) ){
1000 $protocol = $bits[$i++
];
1001 $remainder = $bits[$i++
];
1003 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1004 # Found some characters after the protocol that look promising
1005 $url = $protocol . $m[1];
1008 # Move trailing punctuation to $trail
1010 # If there is no left bracket, then consider right brackets fair game too
1011 if ( strpos( $url, '(' ) === false ) {
1015 $numSepChars = strspn( strrev( $url ), $sep );
1016 if ( $numSepChars ) {
1017 $trail = substr( $url, -$numSepChars ) . $trail;
1018 $url = substr( $url, 0, -$numSepChars );
1021 # Replace & from obsolete syntax with &
1022 $url = str_replace( '&', '&', $url );
1024 # Is this an external image?
1025 $text = $this->maybeMakeImageLink( $url );
1026 if ( $text === false ) {
1027 # Not an image, make a link
1028 $text = $sk->makeExternalLink( $url, $url );
1030 $s .= $text . $trail;
1032 $s .= $protocol . $remainder;
1039 * make an image if it's allowed
1042 function maybeMakeImageLink( $url ) {
1043 $sk =& $this->mOptions
->getSkin();
1045 if ( $this->mOptions
->getAllowExternalImages() ) {
1046 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1048 $text = $sk->makeImage( htmlspecialchars( $url ) );
1055 * Process [[ ]] wikilinks
1059 function replaceInternalLinks( $s ) {
1060 global $wgLang, $wgContLang, $wgLinkCache;
1061 global $wgNamespacesWithSubpages;
1062 static $fname = 'Parser::replaceInternalLinks' ;
1063 wfProfileIn( $fname );
1065 wfProfileIn( $fname.'-setup' );
1067 # the % is needed to support urlencoded titles as well
1068 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1069 $sk =& $this->mOptions
->getSkin();
1071 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1073 $a = explode( '[[', ' ' . $s );
1074 $s = array_shift( $a );
1075 $s = substr( $s, 1 );
1077 # Match a link having the form [[namespace:link|alternate]]trail
1079 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1080 # Match the end of a line for a word that's not followed by whitespace,
1081 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1082 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1084 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1085 # Special and Media are pseudo-namespaces; no pages actually exist in them
1087 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1089 if ( $useLinkPrefixExtension ) {
1090 if ( preg_match( $e2, $s, $m ) ) {
1091 $first_prefix = $m[2];
1094 $first_prefix = false;
1100 wfProfileOut( $fname.'-setup' );
1102 # start procedeeding each line
1103 foreach ( $a as $line ) {
1104 wfProfileIn( $fname.'-prefixhandling' );
1105 if ( $useLinkPrefixExtension ) {
1106 if ( preg_match( $e2, $s, $m ) ) {
1114 $prefix = $first_prefix;
1115 $first_prefix = false;
1118 wfProfileOut( $fname.'-prefixhandling' );
1120 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1122 # fix up urlencoded title texts
1123 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1125 } else { # Invalid form; output directly
1126 $s .= $prefix . '[[' . $line ;
1130 # Don't allow internal links to pages containing
1131 # PROTO: where PROTO is a valid URL protocol; these
1132 # should be external links.
1133 if (preg_match('/((?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1134 $s .= $prefix . '[[' . $line ;
1140 # :Foobar -- override special treatment of prefix (images, language links)
1141 # /Foobar -- convert to CurrentPage/Foobar
1142 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1144 # Look at the first character
1145 $c = substr($m[1],0,1);
1146 $noforce = ($c != ':');
1150 # / at end means we don't want the slash to be shown
1151 if(substr($m[1],-1,1)=='/') {
1152 $m[1]=substr($m[1],1,strlen($m[1])-2);
1155 $noslash=substr($m[1],1);
1158 # Some namespaces don't allow subpages
1159 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) {
1160 # subpages allowed here
1161 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1164 } # this might be changed for ugliness reasons
1166 # no subpage allowed, use standard link
1170 } elseif( $noforce ) { # no subpage
1173 # We don't want to keep the first character
1174 $link = substr( $m[1], 1 );
1177 $wasblank = ( '' == $text );
1178 if( $wasblank ) $text = $link;
1180 $nt = Title
::newFromText( $link );
1182 $s .= $prefix . '[[' . $line;
1186 $ns = $nt->getNamespace();
1187 $iw = $nt->getInterWiki();
1189 # Link not escaped by : , create the various objects
1193 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1194 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1195 $tmp = $prefix . $trail ;
1196 $s .= (trim($tmp) == '')?
'': $tmp;
1200 if ( $ns == NS_IMAGE
) {
1201 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1202 $wgLinkCache->addImageLinkObj( $nt );
1206 if ( $ns == NS_CATEGORY
) {
1207 $t = $nt->getText() ;
1208 $nnt = Title
::newFromText ( Namespace::getCanonicalName(NS_CATEGORY
).':'.$t ) ;
1210 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1211 $pPLC=$sk->postParseLinkColour();
1212 $sk->postParseLinkColour( false );
1213 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1214 $sk->postParseLinkColour( $pPLC );
1215 $wgLinkCache->resume();
1218 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1219 $sortkey = $this->mTitle
->getText();
1221 $sortkey = $this->mTitle
->getPrefixedText();
1226 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1227 $this->mOutput
->mCategoryLinks
[] = $t ;
1228 $s .= $prefix . $trail ;
1233 if( ( $nt->getPrefixedText() === $this->mTitle
->getPrefixedText() ) &&
1234 ( strpos( $link, '#' ) === FALSE ) ) {
1235 # Self-links are handled specially; generally de-link and change to bold.
1236 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1240 if( $ns == NS_MEDIA
) {
1241 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1242 $wgLinkCache->addImageLinkObj( $nt );
1244 } elseif( $ns == NS_SPECIAL
) {
1245 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1248 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1250 wfProfileOut( $fname );
1255 * Used by doBlockLevels()
1258 /* private */ function closeParagraph() {
1260 if ( '' != $this->mLastSection
) {
1261 $result = '</' . $this->mLastSection
. ">\n";
1263 $this->mInPre
= false;
1264 $this->mLastSection
= '';
1267 # getCommon() returns the length of the longest common substring
1268 # of both arguments, starting at the beginning of both.
1270 /* private */ function getCommon( $st1, $st2 ) {
1271 $fl = strlen( $st1 );
1272 $shorter = strlen( $st2 );
1273 if ( $fl < $shorter ) { $shorter = $fl; }
1275 for ( $i = 0; $i < $shorter; ++
$i ) {
1276 if ( $st1{$i} != $st2{$i} ) { break; }
1280 # These next three functions open, continue, and close the list
1281 # element appropriate to the prefix character passed into them.
1283 /* private */ function openList( $char ) {
1284 $result = $this->closeParagraph();
1286 if ( '*' == $char ) { $result .= '<ul><li>'; }
1287 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1288 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1289 else if ( ';' == $char ) {
1290 $result .= '<dl><dt>';
1291 $this->mDTopen
= true;
1293 else { $result = '<!-- ERR 1 -->'; }
1298 /* private */ function nextItem( $char ) {
1299 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1300 else if ( ':' == $char ||
';' == $char ) {
1302 if ( $this->mDTopen
) { $close = '</dt>'; }
1303 if ( ';' == $char ) {
1304 $this->mDTopen
= true;
1305 return $close . '<dt>';
1307 $this->mDTopen
= false;
1308 return $close . '<dd>';
1311 return '<!-- ERR 2 -->';
1314 /* private */ function closeList( $char ) {
1315 if ( '*' == $char ) { $text = '</li></ul>'; }
1316 else if ( '#' == $char ) { $text = '</li></ol>'; }
1317 else if ( ':' == $char ) {
1318 if ( $this->mDTopen
) {
1319 $this->mDTopen
= false;
1320 $text = '</dt></dl>';
1322 $text = '</dd></dl>';
1325 else { return '<!-- ERR 3 -->'; }
1331 * Make lists from lines starting with ':', '*', '#', etc.
1334 * @return string the lists rendered as HTML
1336 function doBlockLevels( $text, $linestart ) {
1337 $fname = 'Parser::doBlockLevels';
1338 wfProfileIn( $fname );
1340 # Parsing through the text line by line. The main thing
1341 # happening here is handling of block-level elements p, pre,
1342 # and making lists from lines starting with * # : etc.
1344 $textLines = explode( "\n", $text );
1346 $lastPrefix = $output = $lastLine = '';
1347 $this->mDTopen
= $inBlockElem = false;
1349 $paragraphStack = false;
1351 if ( !$linestart ) {
1352 $output .= array_shift( $textLines );
1354 foreach ( $textLines as $oLine ) {
1355 $lastPrefixLength = strlen( $lastPrefix );
1356 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1357 $preOpenMatch = preg_match('/<pre/i', $oLine );
1358 if ( !$this->mInPre
) {
1359 # Multiple prefixes may abut each other for nested lists.
1360 $prefixLength = strspn( $oLine, '*#:;' );
1361 $pref = substr( $oLine, 0, $prefixLength );
1364 $pref2 = str_replace( ';', ':', $pref );
1365 $t = substr( $oLine, $prefixLength );
1366 $this->mInPre
= !empty($preOpenMatch);
1368 # Don't interpret any other prefixes in preformatted text
1370 $pref = $pref2 = '';
1375 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1376 # Same as the last item, so no need to deal with nesting or opening stuff
1377 $output .= $this->nextItem( substr( $pref, -1 ) );
1378 $paragraphStack = false;
1380 if ( substr( $pref, -1 ) == ';') {
1381 # The one nasty exception: definition lists work like this:
1382 # ; title : definition text
1383 # So we check for : in the remainder text to split up the
1384 # title and definition, without b0rking links.
1385 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1386 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1388 $output .= $term . $this->nextItem( ':' );
1392 } elseif( $prefixLength ||
$lastPrefixLength ) {
1393 # Either open or close a level...
1394 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1395 $paragraphStack = false;
1397 while( $commonPrefixLength < $lastPrefixLength ) {
1398 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1399 --$lastPrefixLength;
1401 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1402 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1404 while ( $prefixLength > $commonPrefixLength ) {
1405 $char = substr( $pref, $commonPrefixLength, 1 );
1406 $output .= $this->openList( $char );
1408 if ( ';' == $char ) {
1409 # FIXME: This is dupe of code above
1410 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1412 $output .= $term . $this->nextItem( ':' );
1416 ++
$commonPrefixLength;
1418 $lastPrefix = $pref2;
1420 if( 0 == $prefixLength ) {
1421 # No prefix (not in list)--go to paragraph mode
1422 $uniq_prefix = UNIQ_PREFIX
;
1423 // XXX: use a stack for nestable elements like span, table and div
1424 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1425 $closematch = preg_match(
1426 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1427 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1428 if ( $openmatch or $closematch ) {
1429 $paragraphStack = false;
1430 $output .= $this->closeParagraph();
1431 if($preOpenMatch and !$preCloseMatch) {
1432 $this->mInPre
= true;
1434 if ( $closematch ) {
1435 $inBlockElem = false;
1437 $inBlockElem = true;
1439 } else if ( !$inBlockElem && !$this->mInPre
) {
1440 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1442 if ($this->mLastSection
!= 'pre') {
1443 $paragraphStack = false;
1444 $output .= $this->closeParagraph().'<pre>';
1445 $this->mLastSection
= 'pre';
1447 $t = substr( $t, 1 );
1450 if ( '' == trim($t) ) {
1451 if ( $paragraphStack ) {
1452 $output .= $paragraphStack.'<br />';
1453 $paragraphStack = false;
1454 $this->mLastSection
= 'p';
1456 if ($this->mLastSection
!= 'p' ) {
1457 $output .= $this->closeParagraph();
1458 $this->mLastSection
= '';
1459 $paragraphStack = '<p>';
1461 $paragraphStack = '</p><p>';
1465 if ( $paragraphStack ) {
1466 $output .= $paragraphStack;
1467 $paragraphStack = false;
1468 $this->mLastSection
= 'p';
1469 } else if ($this->mLastSection
!= 'p') {
1470 $output .= $this->closeParagraph().'<p>';
1471 $this->mLastSection
= 'p';
1477 if ($paragraphStack === false) {
1481 while ( $prefixLength ) {
1482 $output .= $this->closeList( $pref2{$prefixLength-1} );
1485 if ( '' != $this->mLastSection
) {
1486 $output .= '</' . $this->mLastSection
. '>';
1487 $this->mLastSection
= '';
1490 wfProfileOut( $fname );
1495 * Return value of a magic variable (like PAGENAME)
1499 function getVariableValue( $index ) {
1500 global $wgContLang, $wgSitename, $wgServer;
1503 case MAG_CURRENTMONTH
:
1504 return $wgContLang->formatNum( date( 'm' ) );
1505 case MAG_CURRENTMONTHNAME
:
1506 return $wgContLang->getMonthName( date('n') );
1507 case MAG_CURRENTMONTHNAMEGEN
:
1508 return $wgContLang->getMonthNameGen( date('n') );
1509 case MAG_CURRENTDAY
:
1510 return $wgContLang->formatNum( date('j') );
1512 return $this->mTitle
->getText();
1514 return $this->mTitle
->getPartialURL();
1516 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1517 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1518 case MAG_CURRENTDAYNAME
:
1519 return $wgContLang->getWeekdayName( date('w')+
1 );
1520 case MAG_CURRENTYEAR
:
1521 return $wgContLang->formatNum( date( 'Y' ) );
1522 case MAG_CURRENTTIME
:
1523 return $wgContLang->time( wfTimestampNow(), false );
1524 case MAG_NUMBEROFARTICLES
:
1525 return $wgContLang->formatNum( wfNumberOfArticles() );
1536 * initialise the magic variables (like CURRENTMONTHNAME)
1540 function initialiseVariables() {
1541 global $wgVariableIDs;
1542 $this->mVariables
= array();
1543 foreach ( $wgVariableIDs as $id ) {
1544 $mw =& MagicWord
::get( $id );
1545 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1550 * Replace magic variables, templates, and template arguments
1551 * with the appropriate text. Templates are substituted recursively,
1552 * taking care to avoid infinite loops.
1554 * Note that the substitution depends on value of $mOutputType:
1555 * OT_WIKI: only {{subst:}} templates
1556 * OT_MSG: only magic variables
1557 * OT_HTML: all templates and magic variables
1559 * @param string $tex The text to transform
1560 * @param array $args Key-value pairs representing template parameters to substitute
1563 function replaceVariables( $text, $args = array() ) {
1564 global $wgLang, $wgScript, $wgArticlePath;
1566 # Prevent too big inclusions
1567 if(strlen($text)> MAX_INCLUDE_SIZE
)
1570 $fname = 'Parser::replaceVariables';
1571 wfProfileIn( $fname );
1573 $titleChars = Title
::legalChars();
1575 # This function is called recursively. To keep track of arguments we need a stack:
1576 array_push( $this->mArgStack
, $args );
1578 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1579 $GLOBALS['wgCurParser'] =& $this;
1581 # Variable substitution
1582 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", 'wfVariableSubstitution', $text );
1584 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1585 # Argument substitution
1586 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1588 # Template substitution
1589 $regex = '/{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1590 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1592 array_pop( $this->mArgStack
);
1594 wfProfileOut( $fname );
1599 * Replace magic variables
1602 function variableSubstitution( $matches ) {
1603 if ( !$this->mVariables
) {
1604 $this->initialiseVariables();
1607 if ( $this->mOutputType
== OT_WIKI
) {
1608 # Do only magic variables prefixed by SUBST
1609 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1610 if (!$mwSubst->matchStartAndRemove( $matches[1] ))
1612 # Note that if we don't substitute the variable below,
1613 # we don't remove the {{subst:}} magic word, in case
1614 # it is a template rather than a magic variable.
1616 if ( !$skip && array_key_exists( $matches[1], $this->mVariables
) ) {
1617 $text = $this->mVariables
[$matches[1]];
1618 $this->mOutput
->mContainsOldMagic
= true;
1620 $text = $matches[0];
1625 # Split template arguments
1626 function getTemplateArgs( $argsString ) {
1627 if ( $argsString === '' ) {
1631 $args = explode( '|', substr( $argsString, 1 ) );
1633 # If any of the arguments contains a '[[' but no ']]', it needs to be
1634 # merged with the next arg because the '|' character between belongs
1635 # to the link syntax and not the template parameter syntax.
1636 $argc = count($args);
1638 for ( $i = 0; $i < $argc-1; $i++
) {
1639 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1640 $args[$i] .= '|'.$args[$i+
1];
1641 array_splice($args, $i+
1, 1);
1651 * Return the text of a template, after recursively
1652 * replacing any variables or templates within the template.
1654 * @param array $matches The parts of the template
1655 * $matches[1]: the title, i.e. the part before the |
1656 * $matches[2]: the parameters (including a leading |), if any
1657 * @return string the text of the template
1660 function braceSubstitution( $matches ) {
1661 global $wgLinkCache, $wgContLang;
1662 $fname = 'Parser::braceSubstitution';
1666 $itcamefromthedatabase = false;
1670 # $part1 is the bit before the first |, and must contain only title characters
1671 # $args is a list of arguments, starting from index 0, not including $part1
1673 $part1 = $matches[1];
1674 # If the second subpattern matched anything, it will start with |
1676 $args = $this->getTemplateArgs($matches[2]);
1677 $argc = count( $args );
1680 if ( strpos( $matches[0], '{{{' ) !== false ) {
1681 $text = $matches[0];
1688 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1689 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1690 # One of two possibilities is true:
1691 # 1) Found SUBST but not in the PST phase
1692 # 2) Didn't find SUBST and in the PST phase
1693 # In either case, return without further processing
1694 $text = $matches[0];
1700 # MSG, MSGNW and INT
1703 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1704 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1707 # Remove obsolete MSG:
1708 $mwMsg =& MagicWord
::get( MAG_MSG
);
1709 $mwMsg->matchStartAndRemove( $part1 );
1712 # Check if it is an internal message
1713 $mwInt =& MagicWord
::get( MAG_INT
);
1714 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1715 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1716 $text = wfMsgReal( $part1, $args, true );
1724 # Check for NS: (namespace expansion)
1725 $mwNs = MagicWord
::get( MAG_NS
);
1726 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1727 if ( intval( $part1 ) ) {
1728 $text = $wgContLang->getNsText( intval( $part1 ) );
1731 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1732 if ( !is_null( $index ) ) {
1733 $text = $wgContLang->getNsText( $index );
1740 # LOCALURL and LOCALURLE
1742 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1743 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1745 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1746 $func = 'getLocalURL';
1747 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1748 $func = 'escapeLocalURL';
1753 if ( $func !== '' ) {
1754 $title = Title
::newFromText( $part1 );
1755 if ( !is_null( $title ) ) {
1757 $text = $title->$func( $args[0] );
1759 $text = $title->$func();
1767 if ( !$found && $argc == 1 ) {
1768 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1769 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1770 $text = $wgContLang->convertGrammar( $args[0], $part1 );
1775 # Template table test
1777 # Did we encounter this template already? If yes, it is in the cache
1778 # and we need to check for loops.
1779 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
1780 # set $text to cached message.
1781 $text = $this->mTemplates
[$part1];
1784 # Infinite loop test
1785 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1788 $text .= '<!-- WARNING: template loop detected -->';
1792 # Load from database
1794 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1795 if ( !is_null( $title ) && !$title->isExternal() ) {
1796 # Check for excessive inclusion
1797 $dbk = $title->getPrefixedDBkey();
1798 if ( $this->incrementIncludeCount( $dbk ) ) {
1799 # This should never be reached.
1800 $article = new Article( $title );
1801 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1802 if ( $articleContent !== false ) {
1804 $text = $articleContent;
1805 $itcamefromthedatabase = true;
1809 # If the title is valid but undisplayable, make a link to it
1810 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1811 $text = '[['.$title->getPrefixedText().']]';
1815 # Template cache array insertion
1816 $this->mTemplates
[$part1] = $text;
1820 # Recursive parsing, escaping and link table handling
1821 # Only for HTML output
1822 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1823 $text = wfEscapeWikiText( $text );
1824 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
1825 # Clean up argument array
1826 $assocArgs = array();
1828 foreach( $args as $arg ) {
1829 $eqpos = strpos( $arg, '=' );
1830 if ( $eqpos === false ) {
1831 $assocArgs[$index++
] = $arg;
1833 $name = trim( substr( $arg, 0, $eqpos ) );
1834 $value = trim( substr( $arg, $eqpos+
1 ) );
1835 if ( $value === false ) {
1838 if ( $name !== false ) {
1839 $assocArgs[$name] = $value;
1844 # Add a new element to the templace recursion path
1845 $this->mTemplatePath
[$part1] = 1;
1847 $text = $this->strip( $text, $this->mStripState
);
1848 $text = $this->removeHTMLtags( $text );
1849 $text = $this->replaceVariables( $text, $assocArgs );
1851 # Resume the link cache and register the inclusion as a link
1852 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
1853 $wgLinkCache->addLinkObj( $title );
1857 # Empties the template path
1858 $this->mTemplatePath
= array();
1862 # replace ==section headers==
1863 # XXX this needs to go away once we have a better parser.
1864 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
1865 if( !is_null( $title ) )
1866 $encodedname = base64_encode($title->getPrefixedDBkey());
1868 $encodedname = base64_encode("");
1869 $matches = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
1870 PREG_SPLIT_DELIM_CAPTURE
);
1873 for( $i = 0; $i < count($matches); $i +
= 2 ) {
1874 $text .= $matches[$i];
1875 if (!isset($matches[$i +
1]) ||
$matches[$i +
1] == "") continue;
1876 $hl = $matches[$i +
1];
1877 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
1881 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
1882 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
1883 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
1893 * Triple brace replacement -- used for template arguments
1896 function argSubstitution( $matches ) {
1897 $arg = trim( $matches[1] );
1898 $text = $matches[0];
1899 $inputArgs = end( $this->mArgStack
);
1901 if ( array_key_exists( $arg, $inputArgs ) ) {
1902 $text = $inputArgs[$arg];
1909 * Returns true if the function is allowed to include this entity
1912 function incrementIncludeCount( $dbk ) {
1913 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1914 $this->mIncludeCount
[$dbk] = 0;
1916 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1925 * Cleans up HTML, removes dangerous tags and attributes, and
1926 * removes HTML comments
1929 function removeHTMLtags( $text ) {
1930 global $wgUseTidy, $wgUserHtml;
1931 $fname = 'Parser::removeHTMLtags';
1932 wfProfileIn( $fname );
1935 $htmlpairs = array( # Tags that must be closed
1936 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1937 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1938 'strike', 'strong', 'tt', 'var', 'div', 'center',
1939 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1940 'ruby', 'rt' , 'rb' , 'rp', 'p'
1942 $htmlsingle = array(
1943 'br', 'hr', 'li', 'dt', 'dd'
1945 $htmlnest = array( # Tags that can be nested--??
1946 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1947 'dl', 'font', 'big', 'small', 'sub', 'sup'
1949 $tabletags = array( # Can only appear inside table
1953 $htmlpairs = array();
1954 $htmlsingle = array();
1955 $htmlnest = array();
1956 $tabletags = array();
1959 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1960 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1962 $htmlattrs = $this->getHTMLattrs () ;
1964 # Remove HTML comments
1965 $text = $this->removeHTMLcomments( $text );
1967 $bits = explode( '<', $text );
1968 $text = array_shift( $bits );
1970 $tagstack = array(); $tablestack = array();
1971 foreach ( $bits as $x ) {
1972 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1973 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1975 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1976 error_reporting( $prev );
1979 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1983 if ( ! in_array( $t, $htmlsingle ) &&
1984 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
1985 @array_push
( $tagstack, $ot );
1988 if ( $t == 'table' ) {
1989 $tagstack = array_pop( $tablestack );
1994 # Keep track for later
1995 if ( in_array( $t, $tabletags ) &&
1996 ! in_array( 'table', $tagstack ) ) {
1998 } else if ( in_array( $t, $tagstack ) &&
1999 ! in_array ( $t , $htmlnest ) ) {
2001 } else if ( ! in_array( $t, $htmlsingle ) ) {
2002 if ( $t == 'table' ) {
2003 array_push( $tablestack, $tagstack );
2004 $tagstack = array();
2006 array_push( $tagstack, $t );
2008 # Strip non-approved attributes from the tag
2009 $newparams = $this->fixTagAttributes($params);
2013 $rest = str_replace( '>', '>', $rest );
2014 $text .= "<$slash$t $newparams$brace$rest";
2018 $text .= '<' . str_replace( '>', '>', $x);
2020 # Close off any remaining tags
2021 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2023 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2026 # this might be possible using tidy itself
2027 foreach ( $bits as $x ) {
2028 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2030 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2031 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2032 $newparams = $this->fixTagAttributes($params);
2033 $rest = str_replace( '>', '>', $rest );
2034 $text .= "<$slash$t $newparams$brace$rest";
2036 $text .= '<' . str_replace( '>', '>', $x);
2040 wfProfileOut( $fname );
2045 * Remove '<!--', '-->', and everything between.
2046 * To avoid leaving blank lines, when a comment is both preceded
2047 * and followed by a newline (ignoring spaces), trim leading and
2048 * trailing spaces and one of the newlines.
2052 function removeHTMLcomments( $text ) {
2053 $fname='Parser::removeHTMLcomments';
2054 wfProfileIn( $fname );
2055 while (($start = strpos($text, '<!--')) !== false) {
2056 $end = strpos($text, '-->', $start +
4);
2057 if ($end === false) {
2058 # Unterminated comment; bail out
2064 # Trim space and newline if the comment is both
2065 # preceded and followed by a newline
2066 $spaceStart = max($start - 1, 0);
2067 $spaceLen = $end - $spaceStart;
2068 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2072 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2074 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2075 # Remove the comment, leading and trailing
2076 # spaces, and leave only one newline.
2077 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2080 # Remove just the comment.
2081 $text = substr_replace($text, '', $start, $end - $start);
2084 wfProfileOut( $fname );
2089 * This function accomplishes several tasks:
2090 * 1) Auto-number headings if that option is enabled
2091 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2092 * 3) Add a Table of contents on the top for users who have enabled the option
2093 * 4) Auto-anchor headings
2095 * It loops through all headlines, collects the necessary data, then splits up the
2096 * string and re-inserts the newly formatted headlines.
2099 /* private */ function formatHeadings( $text, $isMain=true ) {
2100 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders;
2102 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2103 $doShowToc = $this->mOptions
->getShowToc();
2104 $forceTocHere = false;
2105 if( !$this->mTitle
->userCanEdit() ) {
2107 $rightClickHack = 0;
2109 $showEditLink = $this->mOptions
->getEditSection();
2110 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2113 # Inhibit editsection links if requested in the page
2114 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2115 if( $esw->matchAndRemove( $text ) ) {
2118 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2120 $mw =& MagicWord
::get( MAG_NOTOC
);
2121 if( $mw->matchAndRemove( $text ) ) {
2125 # never add the TOC to the Main Page. This is an entry page that should not
2126 # be more than 1-2 screens large anyway
2127 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2131 # Get all headlines for numbering them and adding funky stuff like [edit]
2132 # links - this is for later, but we need the number of headlines right now
2133 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2135 # if there are fewer than 4 headlines in the article, do not show TOC
2136 if( $numMatches < 4 ) {
2140 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2141 # override above conditions and always show TOC at that place
2142 $mw =& MagicWord
::get( MAG_TOC
);
2143 if ($mw->match( $text ) ) {
2145 $forceTocHere = true;
2147 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2148 # override above conditions and always show TOC above first header
2149 $mw =& MagicWord
::get( MAG_FORCETOC
);
2150 if ($mw->matchAndRemove( $text ) ) {
2157 # We need this to perform operations on the HTML
2158 $sk =& $this->mOptions
->getSkin();
2162 $sectionCount = 0; # headlineCount excluding template sections
2164 # Ugh .. the TOC should have neat indentation levels which can be
2165 # passed to the skin functions. These are determined here
2170 $sublevelCount = array();
2173 foreach( $matches[3] as $headline ) {
2175 $templatetitle = "";
2176 $templatesection = 0;
2178 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2180 $templatetitle = base64_decode($mat[1]);
2181 $templatesection = 1 +
(int)base64_decode($mat[2]);
2182 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2187 $prevlevel = $level;
2189 $level = $matches[1][$headlineCount];
2190 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2191 # reset when we enter a new level
2192 $sublevelCount[$level] = 0;
2193 $toc .= $sk->tocIndent( $level - $prevlevel );
2194 $toclevel +
= $level - $prevlevel;
2196 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2197 # reset when we step back a level
2198 $sublevelCount[$level+
1]=0;
2199 $toc .= $sk->tocUnindent( $prevlevel - $level );
2200 $toclevel -= $prevlevel - $level;
2202 # count number of headlines for each level
2203 @$sublevelCount[$level]++
;
2204 if( $doNumberHeadings ||
$doShowToc ) {
2206 for( $i = 1; $i <= $level; $i++
) {
2207 if( !empty( $sublevelCount[$i] ) ) {
2211 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2217 # The canonized header is a version of the header text safe to use for links
2218 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2219 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2220 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2222 # Remove link placeholders by the link text.
2223 # <!--LINK number-->
2225 # link text with suffix
2226 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2227 "\$wgLinkHolders['texts'][\$1]",
2228 $canonized_headline );
2231 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2232 $tocline = trim( $canonized_headline );
2233 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2234 $replacearray = array(
2238 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2239 $refer[$headlineCount] = $canonized_headline;
2241 # count how many in assoc. array so we can track dupes in anchors
2242 @$refers[$canonized_headline]++
;
2243 $refcount[$headlineCount]=$refers[$canonized_headline];
2245 # Prepend the number to the heading text
2247 if( $doNumberHeadings ||
$doShowToc ) {
2248 $tocline = $numbering . ' ' . $tocline;
2250 # Don't number the heading if it is the only one (looks silly)
2251 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2252 # the two are different if the line contains a link
2253 $headline=$numbering . ' ' . $headline;
2257 # Create the anchor for linking from the TOC to the section
2258 $anchor = $canonized_headline;
2259 if($refcount[$headlineCount] > 1 ) {
2260 $anchor .= '_' . $refcount[$headlineCount];
2262 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2263 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2265 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2266 if ( empty( $head[$headlineCount] ) ) {
2267 $head[$headlineCount] = '';
2270 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2272 $head[$headlineCount] .= $sk->editSectionLink($sectionCount+
1);
2275 # Add the edit section span
2276 if( $rightClickHack ) {
2278 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2280 $headline = $sk->editSectionScript($sectionCount+
1,$headline);
2283 # give headline the correct <h#> tag
2284 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2292 $toclines = $headlineCount;
2293 $toc .= $sk->tocUnindent( $toclevel );
2294 $toc = $sk->tocTable( $toc );
2297 # split up and insert constructed headlines
2299 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2302 foreach( $blocks as $block ) {
2303 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2304 # This is the [edit] link that appears for the top block of text when
2305 # section editing is enabled
2307 # Disabled because it broke block formatting
2308 # For example, a bullet point in the top line
2309 # $full .= $sk->editSectionLink(0);
2312 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2313 # Top anchor now in skin
2317 if( !empty( $head[$i] ) ) {
2323 $mw =& MagicWord
::get( MAG_TOC
);
2324 return $mw->replace( $toc, $full );
2331 * Return an HTML link for the "ISBN 123456" text
2334 function magicISBN( $text ) {
2336 $fname = 'Parser::magicISBN';
2337 wfProfileIn( $fname );
2339 $a = split( 'ISBN ', ' '.$text );
2340 if ( count ( $a ) < 2 ) {
2341 wfProfileOut( $fname );
2344 $text = substr( array_shift( $a ), 1);
2345 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2347 foreach ( $a as $x ) {
2348 $isbn = $blank = '' ;
2349 while ( ' ' == $x{0} ) {
2351 $x = substr( $x, 1 );
2353 if ( $x == '' ) { # blank isbn
2354 $text .= "ISBN $blank";
2357 while ( strstr( $valid, $x{0} ) != false ) {
2359 $x = substr( $x, 1 );
2361 $num = str_replace( '-', '', $isbn );
2362 $num = str_replace( ' ', '', $num );
2365 $text .= "ISBN $blank$x";
2367 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2368 $text .= '<a href="' .
2369 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2370 "\" class=\"internal\">ISBN $isbn</a>";
2374 wfProfileOut( $fname );
2379 * Return an HTML link for the "GEO ..." text
2382 function magicGEO( $text ) {
2383 global $wgLang, $wgUseGeoMode;
2384 $fname = 'Parser::magicGEO';
2385 wfProfileIn( $fname );
2387 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2388 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2389 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2390 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2391 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2392 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2394 $a = split( 'GEO ', ' '.$text );
2395 if ( count ( $a ) < 2 ) {
2396 wfProfileOut( $fname );
2399 $text = substr( array_shift( $a ), 1);
2400 $valid = '0123456789.+-:';
2402 foreach ( $a as $x ) {
2403 $geo = $blank = '' ;
2404 while ( ' ' == $x{0} ) {
2406 $x = substr( $x, 1 );
2408 while ( strstr( $valid, $x{0} ) != false ) {
2410 $x = substr( $x, 1 );
2412 $num = str_replace( '+', '', $geo );
2413 $num = str_replace( ' ', '', $num );
2415 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2416 $text .= "GEO $blank$x";
2418 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2419 $text .= '<a href="' .
2420 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2421 "\" class=\"internal\">GEO $geo</a>";
2425 wfProfileOut( $fname );
2430 * Return an HTML link for the "RFC 1234" text
2432 * @param string $text text to be processed
2434 function magicRFC( $text ) {
2437 $valid = '0123456789';
2440 $a = split( 'RFC ', ' '.$text );
2441 if ( count ( $a ) < 2 ) return $text;
2442 $text = substr( array_shift( $a ), 1);
2444 /* Check if RFC keyword is preceed by [[.
2445 * This test is made here cause of the array_shift above
2446 * that prevent the test to be done in the foreach.
2448 if(substr($text, -2) == '[[') { $internal = true; }
2450 foreach ( $a as $x ) {
2451 /* token might be empty if we have RFC RFC 1234 */
2457 $rfc = $blank = '' ;
2459 /** remove and save whitespaces in $blank */
2460 while ( $x{0} == ' ' ) {
2462 $x = substr( $x, 1 );
2465 /** remove and save the rfc number in $rfc */
2466 while ( strstr( $valid, $x{0} ) != false ) {
2468 $x = substr( $x, 1 );
2472 /* call back stripped spaces*/
2473 $text .= "RFC $blank$x";
2474 } elseif( $internal) {
2476 $text .= "RFC $rfc$x";
2478 /* build the external link*/
2479 $url = wfmsg( 'rfcurl' );
2480 $url = str_replace( '$1', $rfc, $url);
2481 $sk =& $this->mOptions
->getSkin();
2482 $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
2483 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2486 /* Check if the next RFC keyword is preceed by [[ */
2487 $internal = (substr($x,-2) == '[[');
2493 * Transform wiki markup when saving a page by doing \r\n -> \n
2494 * conversion, substitting signatures, {{subst:}} templates, etc.
2496 * @param string $text the text to transform
2497 * @param Title &$title the Title object for the current article
2498 * @param User &$user the User object describing the current user
2499 * @param ParserOptions $options parsing options
2500 * @param bool $clearState whether to clear the parser state first
2501 * @return string the altered wiki markup
2504 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2505 $this->mOptions
= $options;
2506 $this->mTitle
=& $title;
2507 $this->mOutputType
= OT_WIKI
;
2509 if ( $clearState ) {
2510 $this->clearState();
2513 $stripState = false;
2517 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2521 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2522 "/<br *?>/i" => "<br />",
2524 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2526 $text = $this->strip( $text, $stripState, false );
2527 $text = $this->pstPass2( $text, $user );
2528 $text = $this->unstrip( $text, $stripState );
2529 $text = $this->unstripNoWiki( $text, $stripState );
2534 * Pre-save transform helper function
2537 function pstPass2( $text, &$user ) {
2538 global $wgLang, $wgContLang, $wgLocaltimezone, $wgCurParser;
2540 # Variable replacement
2541 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2542 $text = $this->replaceVariables( $text );
2546 $n = $user->getName();
2547 $k = $user->getOption( 'nickname' );
2548 if ( '' == $k ) { $k = $n; }
2549 if(isset($wgLocaltimezone)) {
2550 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2552 /* Note: this is an ugly timezone hack for the European wikis */
2553 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2554 ' (' . date( 'T' ) . ')';
2555 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2557 $text = preg_replace( '/~~~~~/', $d, $text );
2558 $text = preg_replace( '/~~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2559 $text = preg_replace( '/~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2561 # Context links: [[|name]] and [[name (context)|]]
2563 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2564 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2565 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2566 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2568 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2569 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2570 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2571 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2573 $t = $this->mTitle
->getText();
2574 if ( preg_match( $conpat, $t, $m ) ) {
2577 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2578 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2579 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2581 if ( '' == $context ) {
2582 $text = preg_replace( $p2, '[[\\1]]', $text );
2584 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2587 # Trim trailing whitespace
2588 # MAG_END (__END__) tag allows for trailing
2589 # whitespace to be deliberately included
2590 $text = rtrim( $text );
2591 $mw =& MagicWord
::get( MAG_END
);
2592 $mw->matchAndRemove( $text );
2598 * Set up some variables which are usually set up in parse()
2599 * so that an external function can call some class members with confidence
2602 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2603 $this->mTitle
=& $title;
2604 $this->mOptions
= $options;
2605 $this->mOutputType
= $outputType;
2606 if ( $clearState ) {
2607 $this->clearState();
2612 * Transform a MediaWiki message by replacing magic variables.
2614 * @param string $text the text to transform
2615 * @param ParserOptions $options options
2616 * @return string the text with variables substituted
2619 function transformMsg( $text, $options ) {
2621 static $executing = false;
2623 # Guard against infinite recursion
2629 $this->mTitle
= $wgTitle;
2630 $this->mOptions
= $options;
2631 $this->mOutputType
= OT_MSG
;
2632 $this->clearState();
2633 $text = $this->replaceVariables( $text );
2640 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2641 * Callback will be called with the text within
2642 * Transform and return the text within
2645 function setHook( $tag, $callback ) {
2646 $oldVal = @$this->mTagHooks
[$tag];
2647 $this->mTagHooks
[$tag] = $callback;
2654 * @package MediaWiki
2658 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2659 var $mCacheTime; # Used in ParserCache
2661 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2662 $containsOldMagic = false )
2664 $this->mText
= $text;
2665 $this->mLanguageLinks
= $languageLinks;
2666 $this->mCategoryLinks
= $categoryLinks;
2667 $this->mContainsOldMagic
= $containsOldMagic;
2668 $this->mCacheTime
= '';
2671 function getText() { return $this->mText
; }
2672 function getLanguageLinks() { return $this->mLanguageLinks
; }
2673 function getCategoryLinks() { return $this->mCategoryLinks
; }
2674 function getCacheTime() { return $this->mCacheTime
; }
2675 function containsOldMagic() { return $this->mContainsOldMagic
; }
2676 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2677 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2678 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2679 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2680 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2682 function merge( $other ) {
2683 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2684 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2685 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2691 * Set options of the Parser
2693 * @package MediaWiki
2697 # All variables are private
2698 var $mUseTeX; # Use texvc to expand <math> tags
2699 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2700 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2701 var $mAllowExternalImages; # Allow external images inline
2702 var $mSkin; # Reference to the preferred skin
2703 var $mDateFormat; # Date format index
2704 var $mEditSection; # Create "edit section" links
2705 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2706 var $mNumberHeadings; # Automatically number headings
2707 var $mShowToc; # Show table of contents
2709 function getUseTeX() { return $this->mUseTeX
; }
2710 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2711 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2712 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2713 function getSkin() { return $this->mSkin
; }
2714 function getDateFormat() { return $this->mDateFormat
; }
2715 function getEditSection() { return $this->mEditSection
; }
2716 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2717 function getNumberHeadings() { return $this->mNumberHeadings
; }
2718 function getShowToc() { return $this->mShowToc
; }
2720 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2721 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2722 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2723 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2724 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2725 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2726 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2727 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2728 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2730 function setSkin( &$x ) { $this->mSkin
=& $x; }
2732 # Get parser options
2733 /* static */ function newFromUser( &$user ) {
2734 $popts = new ParserOptions
;
2735 $popts->initialiseFromUser( $user );
2740 function initialiseFromUser( &$userInput ) {
2741 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2743 $fname = 'ParserOptions::initialiseFromUser';
2744 wfProfileIn( $fname );
2745 if ( !$userInput ) {
2747 $user->setLoaded( true );
2749 $user =& $userInput;
2752 $this->mUseTeX
= $wgUseTeX;
2753 $this->mUseDynamicDates
= $wgUseDynamicDates;
2754 $this->mInterwikiMagic
= $wgInterwikiMagic;
2755 $this->mAllowExternalImages
= $wgAllowExternalImages;
2756 wfProfileIn( $fname.'-skin' );
2757 $this->mSkin
=& $user->getSkin();
2758 wfProfileOut( $fname.'-skin' );
2759 $this->mDateFormat
= $user->getOption( 'date' );
2760 $this->mEditSection
= $user->getOption( 'editsection' );
2761 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2762 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2763 $this->mShowToc
= $user->getOption( 'showtoc' );
2764 wfProfileOut( $fname );
2770 # Regex callbacks, used in Parser::replaceVariables
2771 function wfBraceSubstitution( $matches ) {
2772 global $wgCurParser;
2773 return $wgCurParser->braceSubstitution( $matches );
2776 function wfArgSubstitution( $matches ) {
2777 global $wgCurParser;
2778 return $wgCurParser->argSubstitution( $matches );
2781 function wfVariableSubstitution( $matches ) {
2782 global $wgCurParser;
2783 return $wgCurParser->variableSubstitution( $matches );
2787 * Return the total number of articles
2789 function wfNumberOfArticles() {
2790 global $wgNumberOfArticles;
2793 return $wgNumberOfArticles;
2797 * Get various statistics from the database
2800 function wfLoadSiteStats() {
2801 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2802 $fname = 'wfLoadSiteStats';
2804 if ( -1 != $wgNumberOfArticles ) return;
2805 $dbr =& wfGetDB( DB_SLAVE
);
2806 $s = $dbr->getArray( 'site_stats',
2807 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2808 array( 'ss_row_id' => 1 ), $fname
2811 if ( $s === false ) {
2814 $wgTotalViews = $s->ss_total_views
;
2815 $wgTotalEdits = $s->ss_total_edits
;
2816 $wgNumberOfArticles = $s->ss_good_articles
;
2820 function wfEscapeHTMLTagsOnly( $in ) {
2822 array( '"', '>', '<' ),
2823 array( '"', '>', '<' ),