3 // require_once('Tokenizer.php');
6 * File for Parser and related classes
13 * Variable substitution O(N^2) attack
15 * Without countermeasures, it would be possible to attack the parser by saving
16 * a page filled with a large number of inclusions of large pages. The size of
17 * the generated page would be proportional to the square of the input size.
18 * Hence, we limit the number of inclusions of any given page, thus bringing any
19 * attack back to O(N).
21 define( 'MAX_INCLUDE_REPEAT', 100 );
22 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
24 # Allowed values for $mOutputType
25 define( 'OT_HTML', 1 );
26 define( 'OT_WIKI', 2 );
27 define( 'OT_MSG' , 3 );
29 # string parameter for extractTags which will cause it
30 # to strip HTML comments in addition to regular
31 # <XML>-style tags. This should not be anything we
32 # may want to use in wikisyntax
33 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
35 # prefix for escaping, used in two functions at least
36 define( 'UNIQ_PREFIX', 'NaodW29');
38 # Constants needed for external link processing
39 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
40 define( 'HTTP_PROTOCOLS', 'http|https' );
41 # Everything except bracket, space, or control characters
42 define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
43 define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
45 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
46 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
47 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
48 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
49 define( 'EXT_IMAGE_REGEX',
50 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
51 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
52 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
58 * Processes wiki markup
61 * There are three main entry points into the Parser class:
63 * produces HTML output
65 * produces altered wiki markup.
67 * performs brace substitution on MediaWiki messages
70 * objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
72 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
75 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
76 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
79 * * only within ParserOptions
92 # Cleared with clearState():
93 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
94 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
97 var $mOptions, $mTitle, $mOutputType,
98 $mTemplates, // cache of already loaded templates, avoids
99 // multiple SQL queries for the same string
100 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
101 // in this path. Used for loop detection.
110 $this->mTemplates
= array();
111 $this->mTemplatePath
= array();
112 $this->mTagHooks
= array();
121 function clearState() {
122 $this->mOutput
= new ParserOutput
;
123 $this->mAutonumber
= 0;
124 $this->mLastSection
= "";
125 $this->mDTopen
= false;
126 $this->mVariables
= false;
127 $this->mIncludeCount
= array();
128 $this->mStripState
= array();
129 $this->mArgStack
= array();
130 $this->mInPre
= false;
134 * First pass--just handle <nowiki> sections, pass the rest off
135 * to internalParse() which does all the real work.
138 * @return ParserOutput a ParserOutput
140 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
142 $fname = 'Parser::parse';
143 wfProfileIn( $fname );
149 $this->mOptions
= $options;
150 $this->mTitle
=& $title;
151 $this->mOutputType
= OT_HTML
;
154 $text = $this->strip( $text, $this->mStripState
);
155 $text = $this->internalParse( $text, $linestart );
156 $text = $this->unstrip( $text, $this->mStripState
);
157 # Clean up special characters, only run once, next-to-last before doBlockLevels
160 # french spaces, last one Guillemet-left
161 # only if there is something before the space
162 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
163 # french spaces, Guillemet-right
164 "/(\\302\\253) /i"=>"\\1 ",
165 '/<hr *>/i' => '<hr />',
166 '/<br *>/i' => '<br />',
167 '/<center *>/i' => '<div class="center">',
168 '/<\\/center *>/i' => '</div>',
169 # Clean up spare ampersands; note that we probably ought to be
170 # more careful about named entities.
171 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
173 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
176 # french spaces, last one Guillemet-left
177 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
178 # french spaces, Guillemet-right
179 '/(\\302\\253) /i' => '\\1 ',
180 '/<center *>/i' => '<div class="center">',
181 '/<\\/center *>/i' => '</div>'
183 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
186 $text = $this->doBlockLevels( $text, $linestart );
187 $text = $this->unstripNoWiki( $text, $this->mStripState
);
189 $text = $this->tidy($text);
191 $this->mOutput
->setText( $text );
192 wfProfileOut( $fname );
193 return $this->mOutput
;
197 * Get a random string
202 function getRandomString() {
203 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
207 * Replaces all occurrences of <$tag>content</$tag> in the text
208 * with a random marker and returns the new text. the output parameter
209 * $content will be an associative array filled with data on the form
210 * $unique_marker => content.
212 * If $content is already set, the additional entries will be appended
213 * If $tag is set to STRIP_COMMENTS, the function will extract
214 * <!-- HTML comments -->
219 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
220 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
227 while ( '' != $text ) {
228 if($tag==STRIP_COMMENTS
) {
229 $p = preg_split( '/<!--/i', $text, 2 );
231 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
234 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
237 if($tag==STRIP_COMMENTS
) {
238 $q = preg_split( '/-->/i', $p[1], 2 );
240 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
242 $marker = $rnd . sprintf('%08X', $n++
);
243 $content[$marker] = $q[0];
244 $stripped .= $marker;
252 * Strips and renders nowiki, pre, math, hiero
253 * If $render is set, performs necessary rendering operations on plugins
254 * Returns the text, and fills an array with data needed in unstrip()
255 * If the $state is already a valid strip state, it adds to the state
257 * @param bool $stripcomments when set, HTML comments <!-- like this -->
258 * will be stripped in addition to other tags. This is important
259 * for section editing, where these comments cause confusion when
260 * counting the sections in the wikisource
264 function strip( $text, &$state, $stripcomments = false ) {
265 $render = ($this->mOutputType
== OT_HTML
);
266 $html_content = array();
267 $nowiki_content = array();
268 $math_content = array();
269 $pre_content = array();
270 $comment_content = array();
271 $ext_content = array();
273 # Replace any instances of the placeholders
274 $uniq_prefix = UNIQ_PREFIX
;
275 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
278 global $wgRawHtml, $wgWhitelistEdit;
279 if( $wgRawHtml && $wgWhitelistEdit ) {
280 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
281 foreach( $html_content as $marker => $content ) {
283 # Raw and unchecked for validity.
284 $html_content[$marker] = $content;
286 $html_content[$marker] = '<html>'.$content.'</html>';
292 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
293 foreach( $nowiki_content as $marker => $content ) {
295 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
297 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
302 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
303 foreach( $math_content as $marker => $content ){
305 if( $this->mOptions
->getUseTeX() ) {
306 $math_content[$marker] = renderMath( $content );
308 $math_content[$marker] = '<math>'.$content.'<math>';
311 $math_content[$marker] = '<math>'.$content.'</math>';
316 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
317 foreach( $pre_content as $marker => $content ){
319 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
321 $pre_content[$marker] = '<pre>'.$content.'</pre>';
327 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
328 foreach( $comment_content as $marker => $content ){
329 $comment_content[$marker] = '<!--'.$content.'-->';
334 foreach ( $this->mTagHooks
as $tag => $callback ) {
335 $ext_contents[$tag] = array();
336 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
337 foreach( $ext_content[$tag] as $marker => $content ) {
339 $ext_content[$tag][$marker] = $callback( $content );
341 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
346 # Merge state with the pre-existing state, if there is one
348 $state['html'] = $state['html'] +
$html_content;
349 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
350 $state['math'] = $state['math'] +
$math_content;
351 $state['pre'] = $state['pre'] +
$pre_content;
352 $state['comment'] = $state['comment'] +
$comment_content;
354 foreach( $ext_content as $tag => $array ) {
355 if ( array_key_exists( $tag, $state ) ) {
356 $state[$tag] = $state[$tag] +
$array;
361 'html' => $html_content,
362 'nowiki' => $nowiki_content,
363 'math' => $math_content,
364 'pre' => $pre_content,
365 'comment' => $comment_content,
372 * restores pre, math, and heiro removed by strip()
374 * always call unstripNoWiki() after this one
377 function unstrip( $text, &$state ) {
378 # Must expand in reverse order, otherwise nested tags will be corrupted
379 $contentDict = end( $state );
380 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
381 if( key($state) != 'nowiki' && key($state) != 'html') {
382 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
383 $text = str_replace( key( $contentDict ), $content, $text );
392 * always call this after unstrip() to preserve the order
396 function unstripNoWiki( $text, &$state ) {
397 # Must expand in reverse order, otherwise nested tags will be corrupted
398 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
399 $text = str_replace( key( $state['nowiki'] ), $content, $text );
404 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
405 $text = str_replace( key( $state['html'] ), $content, $text );
413 * Add an item to the strip state
414 * Returns the unique tag which must be inserted into the stripped text
415 * The tag will be replaced with the original text in unstrip()
419 function insertStripItem( $text, &$state ) {
420 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
429 $state['item'][$rnd] = $text;
434 * Return allowed HTML attributes
438 function getHTMLattrs () {
439 $htmlattrs = array( # Allowed attributes--no scripting, etc.
440 'title', 'align', 'lang', 'dir', 'width', 'height',
441 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
442 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
443 /* FONT */ 'type', 'start', 'value', 'compact',
444 /* For various lists, mostly deprecated but safe */
445 'summary', 'width', 'border', 'frame', 'rules',
446 'cellspacing', 'cellpadding', 'valign', 'char',
447 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
448 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
449 'id', 'class', 'name', 'style' /* For CSS */
455 * Remove non approved attributes and javascript in css
459 function fixTagAttributes ( $t ) {
460 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
461 $htmlattrs = $this->getHTMLattrs() ;
463 # Strip non-approved attributes from the tag
465 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
466 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
469 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
471 # Strip javascript "expression" from stylesheets. Brute force approach:
472 # If anythin offensive is found, all attributes of the HTML tag are dropped
475 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
476 wfMungeToUtf8( $t ) ) )
485 * interface with html tidy, used if $wgUseTidy = true
489 function tidy ( $text ) {
490 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
491 global $wgInputEncoding, $wgOutputEncoding;
492 $fname = 'Parser::tidy';
493 wfProfileIn( $fname );
496 switch(strtoupper($wgOutputEncoding)) {
498 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
501 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
504 $wgTidyOpts .= ' -raw';
507 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
508 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
509 '<head><title>test</title></head><body>'.$text.'</body></html>';
510 $descriptorspec = array(
511 0 => array('pipe', 'r'),
512 1 => array('pipe', 'w'),
513 2 => array('file', '/dev/null', 'a')
515 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
516 if (is_resource($process)) {
517 fwrite($pipes[0], $wrappedtext);
519 while (!feof($pipes[1])) {
520 $cleansource .= fgets($pipes[1], 1024);
523 $return_value = proc_close($process);
526 wfProfileOut( $fname );
528 if( $cleansource == '' && $text != '') {
529 wfDebug( "Tidy error detected!\n" );
530 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
537 * parse the wiki syntax used to render tables
541 function doTableStuff ( $t ) {
542 $fname = 'Parser::doTableStuff';
543 wfProfileIn( $fname );
545 $t = explode ( "\n" , $t ) ;
546 $td = array () ; # Is currently a td tag open?
547 $ltd = array () ; # Was it TD or TH?
548 $tr = array () ; # Is currently a tr tag open?
549 $ltr = array () ; # tr attributes
550 $indent_level = 0; # indent level of the table
551 foreach ( $t AS $k => $x )
554 $fc = substr ( $x , 0 , 1 ) ;
555 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
556 $indent_level = strlen( $matches[1] );
558 str_repeat( '<dl><dd>', $indent_level ) .
559 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
560 array_push ( $td , false ) ;
561 array_push ( $ltd , '' ) ;
562 array_push ( $tr , false ) ;
563 array_push ( $ltr , '' ) ;
565 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
566 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
568 $l = array_pop ( $ltd ) ;
569 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
570 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
572 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
574 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
575 $x = substr ( $x , 1 ) ;
576 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
578 $l = array_pop ( $ltd ) ;
579 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
580 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
583 array_push ( $tr , false ) ;
584 array_push ( $td , false ) ;
585 array_push ( $ltd , '' ) ;
586 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
588 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
589 if ( '|+' == substr ( $x , 0 , 2 ) ) {
591 $x = substr ( $x , 1 ) ;
593 $after = substr ( $x , 1 ) ;
594 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
595 $after = explode ( '||' , $after ) ;
597 foreach ( $after AS $theline )
602 $tra = array_pop ( $ltr ) ;
603 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
604 array_push ( $tr , true ) ;
605 array_push ( $ltr , '' ) ;
608 $l = array_pop ( $ltd ) ;
609 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
610 if ( $fc == '|' ) $l = 'td' ;
611 else if ( $fc == '!' ) $l = 'th' ;
612 else if ( $fc == '+' ) $l = 'caption' ;
614 array_push ( $ltd , $l ) ;
615 $y = explode ( '|' , $theline , 2 ) ;
616 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
617 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
619 array_push ( $td , true ) ;
624 # Closing open td, tr && table
625 while ( count ( $td ) > 0 )
627 if ( array_pop ( $td ) ) $t[] = '</td>' ;
628 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
632 $t = implode ( "\n" , $t ) ;
633 # $t = $this->removeHTMLtags( $t );
634 wfProfileOut( $fname );
639 * Helper function for parse() that transforms wiki markup into
640 * HTML. Only called for $mOutputType == OT_HTML.
644 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
647 $fname = 'Parser::internalParse';
648 wfProfileIn( $fname );
650 $text = $this->removeHTMLtags( $text );
651 $text = $this->replaceVariables( $text, $args );
653 $text = $wgLang->convert($text);
655 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
657 $text = $this->doHeadings( $text );
658 if($this->mOptions
->getUseDynamicDates()) {
659 global $wgDateFormatter;
660 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
662 $text = $this->doAllQuotes( $text );
663 $text = $this->replaceExternalLinks( $text );
664 $text = $this->doMagicLinks( $text );
665 $text = $this->replaceInternalLinks ( $text );
666 # Another call to replace links and images inside captions of images
667 $text = $this->replaceInternalLinks ( $text );
669 $text = $this->unstrip( $text, $this->mStripState
);
670 $text = $this->unstripNoWiki( $text, $this->mStripState
);
672 $text = $this->doTableStuff( $text );
673 $text = $this->formatHeadings( $text, $isMain );
674 $sk =& $this->mOptions
->getSkin();
675 $text = $sk->transformContent( $text );
677 wfProfileOut( $fname );
682 * Replace special strings like "ISBN xxx" and "RFC xxx" with
683 * magic external links.
687 function &doMagicLinks( &$text ) {
688 global $wgUseGeoMode;
689 $text = $this->magicISBN( $text );
690 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
691 $text = $this->magicGEO( $text );
693 $text = $this->magicRFC( $text );
698 * Parse ^^ tokens and return html
702 function doExponent ( $text ) {
703 $fname = 'Parser::doExponent';
704 wfProfileIn( $fname);
705 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
706 wfProfileOut( $fname);
711 * Parse headers and return html
715 function doHeadings( $text ) {
716 $fname = 'Parser::doHeadings';
717 wfProfileIn( $fname );
718 for ( $i = 6; $i >= 1; --$i ) {
719 $h = substr( '======', 0, $i );
720 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
721 "<h{$i}>\\1</h{$i}>\\2", $text );
723 wfProfileOut( $fname );
728 * Replace single quotes with HTML markup
730 * @return string the altered text
732 function doAllQuotes( $text ) {
733 $fname = 'Parser::doAllQuotes';
734 wfProfileIn( $fname );
736 $lines = explode( "\n", $text );
737 foreach ( $lines as $line ) {
738 $outtext .= $this->doQuotes ( $line ) . "\n";
740 $outtext = substr($outtext, 0,-1);
741 wfProfileOut( $fname );
746 * Helper function for doAllQuotes()
749 function doQuotes( $text ) {
750 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
751 if (count ($arr) == 1)
755 # First, do some preliminary work. This may shift some apostrophes from
756 # being mark-up to being text. It also counts the number of occurrences
757 # of bold and italics mark-ups.
765 # If there are ever four apostrophes, assume the first is supposed to
766 # be text, and the remaining three constitute mark-up for bold text.
767 if (strlen ($arr[$i]) == 4)
772 # If there are more than 5 apostrophes in a row, assume they're all
773 # text except for the last 5.
774 else if (strlen ($arr[$i]) > 5)
776 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
779 # Count the number of occurrences of bold and italics mark-ups.
780 # We are not counting sequences of five apostrophes.
781 if (strlen ($arr[$i]) == 2) $numitalics++
; else
782 if (strlen ($arr[$i]) == 3) $numbold++
; else
783 if (strlen ($arr[$i]) == 5) { $numitalics++
; $numbold++
; }
788 # If there is an odd number of both bold and italics, it is likely
789 # that one of the bold ones was meant to be an apostrophe followed
790 # by italics. Which one we cannot know for certain, but it is more
791 # likely to be one that has a single-letter word before it.
792 if (($numbold %
2 == 1) && ($numitalics %
2 == 1))
795 $firstsingleletterword = -1;
796 $firstmultiletterword = -1;
800 if (($i %
2 == 1) and (strlen ($r) == 3))
802 $x1 = substr ($arr[$i-1], -1);
803 $x2 = substr ($arr[$i-1], -2, 1);
805 if ($firstspace == -1) $firstspace = $i;
806 } else if ($x2 == ' ') {
807 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
809 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
815 # If there is a single-letter word, use it!
816 if ($firstsingleletterword > -1)
818 $arr [ $firstsingleletterword ] = "''";
819 $arr [ $firstsingleletterword-1 ] .= "'";
821 # If not, but there's a multi-letter word, use that one.
822 else if ($firstmultiletterword > -1)
824 $arr [ $firstmultiletterword ] = "''";
825 $arr [ $firstmultiletterword-1 ] .= "'";
827 # ... otherwise use the first one that has neither.
828 # (notice that it is possible for all three to be -1 if, for example,
829 # there is only one pentuple-apostrophe in the line)
830 else if ($firstspace > -1)
832 $arr [ $firstspace ] = "''";
833 $arr [ $firstspace-1 ] .= "'";
837 # Now let's actually convert our apostrophic mush to HTML!
846 if ($state == 'both')
853 if (strlen ($r) == 2)
856 { $output .= '</i>'; $state = ''; }
857 else if ($state == 'bi')
858 { $output .= '</i>'; $state = 'b'; }
859 else if ($state == 'ib')
860 { $output .= '</b></i><b>'; $state = 'b'; }
861 else if ($state == 'both')
862 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
863 else # $state can be 'b' or ''
864 { $output .= '<i>'; $state .= 'i'; }
866 else if (strlen ($r) == 3)
869 { $output .= '</b>'; $state = ''; }
870 else if ($state == 'bi')
871 { $output .= '</i></b><i>'; $state = 'i'; }
872 else if ($state == 'ib')
873 { $output .= '</b>'; $state = 'i'; }
874 else if ($state == 'both')
875 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
876 else # $state can be 'i' or ''
877 { $output .= '<b>'; $state .= 'b'; }
879 else if (strlen ($r) == 5)
882 { $output .= '</b><i>'; $state = 'i'; }
883 else if ($state == 'i')
884 { $output .= '</i><b>'; $state = 'b'; }
885 else if ($state == 'bi')
886 { $output .= '</i></b>'; $state = ''; }
887 else if ($state == 'ib')
888 { $output .= '</b></i>'; $state = ''; }
889 else if ($state == 'both')
890 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
891 else # ($state == '')
892 { $buffer = ''; $state = 'both'; }
897 # Now close all remaining tags. Notice that the order is important.
898 if ($state == 'b' ||
$state == 'ib')
900 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
904 if ($state == 'both')
905 $output .= '<b><i>'.$buffer.'</i></b>';
911 * Replace external links
913 * Note: we have to do external links before the internal ones,
914 * and otherwise take great care in the order of things here, so
915 * that we don't end up interpreting some URLs twice.
919 function replaceExternalLinks( $text ) {
920 $fname = 'Parser::replaceExternalLinks';
921 wfProfileIn( $fname );
923 $sk =& $this->mOptions
->getSkin();
924 $linktrail = wfMsg('linktrail');
925 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
927 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
930 while ( $i<count( $bits ) ) {
932 $protocol = $bits[$i++
];
934 $trail = $bits[$i++
];
936 # If the link text is an image URL, replace it with an <img> tag
937 # This happened by accident in the original parser, but some people used it extensively
938 $img = $this->maybeMakeImageLink( $text );
939 if ( $img !== false ) {
945 # No link text, e.g. [http://domain.tld/some.link]
947 # Autonumber if allowed
948 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
949 $text = '[' . ++
$this->mAutonumber
. ']';
951 # Otherwise just use the URL
952 $text = htmlspecialchars( $url );
955 # Have link text, e.g. [http://domain.tld/some.link text]s
957 if ( preg_match( $linktrail, $trail, $m2 ) ) {
963 $encUrl = htmlspecialchars( $url );
964 # Bit in parentheses showing the URL for the printable version
965 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
968 # Expand the URL for printable version
969 if ( ! $sk->suppressUrlExpansion() ) {
970 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
976 # Process the trail (i.e. everything after this link up until start of the next link),
977 # replacing any non-bracketed links
978 $trail = $this->replaceFreeExternalLinks( $trail );
980 $la = $sk->getExternalLinkAttributes( $url, $text );
982 # Use the encoded URL
983 # This means that users can paste URLs directly into the text
984 # Funny characters like ö aren't valid in URLs anyway
985 # This was changed in August 2004
986 $s .= "<a href=\"{$url}\" {$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
989 wfProfileOut( $fname );
994 * Replace anything that looks like a URL with a link
997 function replaceFreeExternalLinks( $text ) {
998 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
999 $s = array_shift( $bits );
1002 $sk =& $this->mOptions
->getSkin();
1004 while ( $i < count( $bits ) ){
1005 $protocol = $bits[$i++
];
1006 $remainder = $bits[$i++
];
1008 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1009 # Found some characters after the protocol that look promising
1010 $url = $protocol . $m[1];
1013 # Move trailing punctuation to $trail
1015 # If there is no left bracket, then consider right brackets fair game too
1016 if ( strpos( $url, '(' ) === false ) {
1020 $numSepChars = strspn( strrev( $url ), $sep );
1021 if ( $numSepChars ) {
1022 $trail = substr( $url, -$numSepChars ) . $trail;
1023 $url = substr( $url, 0, -$numSepChars );
1026 # Replace & from obsolete syntax with &
1027 $url = str_replace( '&', '&', $url );
1029 # Is this an external image?
1030 $text = $this->maybeMakeImageLink( $url );
1031 if ( $text === false ) {
1032 # Not an image, make a link
1033 $text = $sk->makeExternalLink( $url, $url );
1035 $s .= $text . $trail;
1037 $s .= $protocol . $remainder;
1044 * make an image if it's allowed
1047 function maybeMakeImageLink( $url ) {
1048 $sk =& $this->mOptions
->getSkin();
1050 if ( $this->mOptions
->getAllowExternalImages() ) {
1051 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1053 $text = $sk->makeImage( htmlspecialchars( $url ) );
1060 * Process [[ ]] wikilinks
1064 function replaceInternalLinks( $s ) {
1065 global $wgLang, $wgLinkCache;
1066 global $wgNamespacesWithSubpages;
1067 static $fname = 'Parser::replaceInternalLinks' ;
1068 wfProfileIn( $fname );
1070 wfProfileIn( $fname.'-setup' );
1072 # the % is needed to support urlencoded titles as well
1073 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1074 $sk =& $this->mOptions
->getSkin();
1076 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1078 $a = explode( '[[', ' ' . $s );
1079 $s = array_shift( $a );
1080 $s = substr( $s, 1 );
1082 # Match a link having the form [[namespace:link|alternate]]trail
1084 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1085 # Match the end of a line for a word that's not followed by whitespace,
1086 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1087 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1089 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1090 # Special and Media are pseudo-namespaces; no pages actually exist in them
1092 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1094 if ( $useLinkPrefixExtension ) {
1095 if ( preg_match( $e2, $s, $m ) ) {
1096 $first_prefix = $m[2];
1099 $first_prefix = false;
1105 wfProfileOut( $fname.'-setup' );
1107 # start procedeeding each line
1108 foreach ( $a as $line ) {
1109 wfProfileIn( $fname.'-prefixhandling' );
1110 if ( $useLinkPrefixExtension ) {
1111 if ( preg_match( $e2, $s, $m ) ) {
1119 $prefix = $first_prefix;
1120 $first_prefix = false;
1123 wfProfileOut( $fname.'-prefixhandling' );
1125 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1127 # fix up urlencoded title texts
1128 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1130 } else { # Invalid form; output directly
1131 $s .= $prefix . '[[' . $line ;
1137 # :Foobar -- override special treatment of prefix (images, language links)
1138 # /Foobar -- convert to CurrentPage/Foobar
1139 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1141 # Look at the first character
1142 $c = substr($m[1],0,1);
1143 $noforce = ($c != ':');
1147 # / at end means we don't want the slash to be shown
1148 if(substr($m[1],-1,1)=='/') {
1149 $m[1]=substr($m[1],1,strlen($m[1])-2);
1152 $noslash=substr($m[1],1);
1155 # Some namespaces don't allow subpages
1156 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) {
1157 # subpages allowed here
1158 $link = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1161 } # this might be changed for ugliness reasons
1163 # no subpage allowed, use standard link
1167 } elseif( $noforce ) { # no subpage
1170 # We don't want to keep the first character
1171 $link = substr( $m[1], 1 );
1174 $wasblank = ( '' == $text );
1175 if( $wasblank ) $text = $link;
1177 $nt = Title
::newFromText( $link );
1179 $s .= $prefix . '[[' . $line;
1183 $ns = $nt->getNamespace();
1184 $iw = $nt->getInterWiki();
1186 # Link not escaped by : , create the various objects
1190 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1191 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1192 $tmp = $prefix . $trail ;
1193 $s .= (trim($tmp) == '')?
'': $tmp;
1197 if ( $ns == NS_IMAGE
) {
1198 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1199 $wgLinkCache->addImageLinkObj( $nt );
1203 if ( $ns == NS_CATEGORY
) {
1204 $t = $nt->getText() ;
1205 $nnt = Title
::newFromText ( Namespace::getCanonicalName(NS_CATEGORY
).':'.$t ) ;
1207 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1208 $pPLC=$sk->postParseLinkColour();
1209 $sk->postParseLinkColour( false );
1210 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1211 $sk->postParseLinkColour( $pPLC );
1212 $wgLinkCache->resume();
1215 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1216 $sortkey = $this->mTitle
->getText();
1218 $sortkey = $this->mTitle
->getPrefixedText();
1223 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1224 $this->mOutput
->mCategoryLinks
[] = $t ;
1225 $s .= $prefix . $trail ;
1230 if( ( $nt->getPrefixedText() === $this->mTitle
->getPrefixedText() ) &&
1231 ( strpos( $link, '#' ) === FALSE ) ) {
1232 # Self-links are handled specially; generally de-link and change to bold.
1233 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1237 if( $ns == NS_MEDIA
) {
1238 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1239 $wgLinkCache->addImageLinkObj( $nt );
1241 } elseif( $ns == NS_SPECIAL
) {
1242 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1245 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1247 wfProfileOut( $fname );
1252 * Used by doBlockLevels()
1255 /* private */ function closeParagraph() {
1257 if ( '' != $this->mLastSection
) {
1258 $result = '</' . $this->mLastSection
. ">\n";
1260 $this->mInPre
= false;
1261 $this->mLastSection
= '';
1264 # getCommon() returns the length of the longest common substring
1265 # of both arguments, starting at the beginning of both.
1267 /* private */ function getCommon( $st1, $st2 ) {
1268 $fl = strlen( $st1 );
1269 $shorter = strlen( $st2 );
1270 if ( $fl < $shorter ) { $shorter = $fl; }
1272 for ( $i = 0; $i < $shorter; ++
$i ) {
1273 if ( $st1{$i} != $st2{$i} ) { break; }
1277 # These next three functions open, continue, and close the list
1278 # element appropriate to the prefix character passed into them.
1280 /* private */ function openList( $char ) {
1281 $result = $this->closeParagraph();
1283 if ( '*' == $char ) { $result .= '<ul><li>'; }
1284 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1285 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1286 else if ( ';' == $char ) {
1287 $result .= '<dl><dt>';
1288 $this->mDTopen
= true;
1290 else { $result = '<!-- ERR 1 -->'; }
1295 /* private */ function nextItem( $char ) {
1296 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1297 else if ( ':' == $char ||
';' == $char ) {
1299 if ( $this->mDTopen
) { $close = '</dt>'; }
1300 if ( ';' == $char ) {
1301 $this->mDTopen
= true;
1302 return $close . '<dt>';
1304 $this->mDTopen
= false;
1305 return $close . '<dd>';
1308 return '<!-- ERR 2 -->';
1311 /* private */ function closeList( $char ) {
1312 if ( '*' == $char ) { $text = '</li></ul>'; }
1313 else if ( '#' == $char ) { $text = '</li></ol>'; }
1314 else if ( ':' == $char ) {
1315 if ( $this->mDTopen
) {
1316 $this->mDTopen
= false;
1317 $text = '</dt></dl>';
1319 $text = '</dd></dl>';
1322 else { return '<!-- ERR 3 -->'; }
1328 * Make lists from lines starting with ':', '*', '#', etc.
1331 * @return string the lists rendered as HTML
1333 function doBlockLevels( $text, $linestart ) {
1334 $fname = 'Parser::doBlockLevels';
1335 wfProfileIn( $fname );
1337 # Parsing through the text line by line. The main thing
1338 # happening here is handling of block-level elements p, pre,
1339 # and making lists from lines starting with * # : etc.
1341 $textLines = explode( "\n", $text );
1343 $lastPrefix = $output = $lastLine = '';
1344 $this->mDTopen
= $inBlockElem = false;
1346 $paragraphStack = false;
1348 if ( !$linestart ) {
1349 $output .= array_shift( $textLines );
1351 foreach ( $textLines as $oLine ) {
1352 $lastPrefixLength = strlen( $lastPrefix );
1353 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1354 $preOpenMatch = preg_match('/<pre/i', $oLine );
1355 if ( !$this->mInPre
) {
1356 # Multiple prefixes may abut each other for nested lists.
1357 $prefixLength = strspn( $oLine, '*#:;' );
1358 $pref = substr( $oLine, 0, $prefixLength );
1361 $pref2 = str_replace( ';', ':', $pref );
1362 $t = substr( $oLine, $prefixLength );
1363 $this->mInPre
= !empty($preOpenMatch);
1365 # Don't interpret any other prefixes in preformatted text
1367 $pref = $pref2 = '';
1372 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1373 # Same as the last item, so no need to deal with nesting or opening stuff
1374 $output .= $this->nextItem( substr( $pref, -1 ) );
1375 $paragraphStack = false;
1377 if ( substr( $pref, -1 ) == ';') {
1378 # The one nasty exception: definition lists work like this:
1379 # ; title : definition text
1380 # So we check for : in the remainder text to split up the
1381 # title and definition, without b0rking links.
1382 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1383 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1385 $output .= $term . $this->nextItem( ':' );
1389 } elseif( $prefixLength ||
$lastPrefixLength ) {
1390 # Either open or close a level...
1391 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1392 $paragraphStack = false;
1394 while( $commonPrefixLength < $lastPrefixLength ) {
1395 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1396 --$lastPrefixLength;
1398 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1399 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1401 while ( $prefixLength > $commonPrefixLength ) {
1402 $char = substr( $pref, $commonPrefixLength, 1 );
1403 $output .= $this->openList( $char );
1405 if ( ';' == $char ) {
1406 # FIXME: This is dupe of code above
1407 if( preg_match( '/^(.*?(?:\s| )):(.*)$/', $t, $match ) ) {
1409 $output .= $term . $this->nextItem( ':' );
1413 ++
$commonPrefixLength;
1415 $lastPrefix = $pref2;
1417 if( 0 == $prefixLength ) {
1418 # No prefix (not in list)--go to paragraph mode
1419 $uniq_prefix = UNIQ_PREFIX
;
1420 // XXX: use a stack for nestable elements like span, table and div
1421 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1422 $closematch = preg_match(
1423 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1424 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1425 if ( $openmatch or $closematch ) {
1426 $paragraphStack = false;
1427 $output .= $this->closeParagraph();
1428 if($preOpenMatch and !$preCloseMatch) {
1429 $this->mInPre
= true;
1431 if ( $closematch ) {
1432 $inBlockElem = false;
1434 $inBlockElem = true;
1436 } else if ( !$inBlockElem && !$this->mInPre
) {
1437 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1439 if ($this->mLastSection
!= 'pre') {
1440 $paragraphStack = false;
1441 $output .= $this->closeParagraph().'<pre>';
1442 $this->mLastSection
= 'pre';
1444 $t = substr( $t, 1 );
1447 if ( '' == trim($t) ) {
1448 if ( $paragraphStack ) {
1449 $output .= $paragraphStack.'<br />';
1450 $paragraphStack = false;
1451 $this->mLastSection
= 'p';
1453 if ($this->mLastSection
!= 'p' ) {
1454 $output .= $this->closeParagraph();
1455 $this->mLastSection
= '';
1456 $paragraphStack = '<p>';
1458 $paragraphStack = '</p><p>';
1462 if ( $paragraphStack ) {
1463 $output .= $paragraphStack;
1464 $paragraphStack = false;
1465 $this->mLastSection
= 'p';
1466 } else if ($this->mLastSection
!= 'p') {
1467 $output .= $this->closeParagraph().'<p>';
1468 $this->mLastSection
= 'p';
1474 if ($paragraphStack === false) {
1478 while ( $prefixLength ) {
1479 $output .= $this->closeList( $pref2{$prefixLength-1} );
1482 if ( '' != $this->mLastSection
) {
1483 $output .= '</' . $this->mLastSection
. '>';
1484 $this->mLastSection
= '';
1487 wfProfileOut( $fname );
1492 * Return value of a magic variable (like PAGENAME)
1496 function getVariableValue( $index ) {
1497 global $wgLang, $wgSitename, $wgServer;
1500 case MAG_CURRENTMONTH
:
1501 return $wgLang->formatNum( date( 'm' ) );
1502 case MAG_CURRENTMONTHNAME
:
1503 return $wgLang->getMonthName( date('n') );
1504 case MAG_CURRENTMONTHNAMEGEN
:
1505 return $wgLang->getMonthNameGen( date('n') );
1506 case MAG_CURRENTDAY
:
1507 return $wgLang->formatNum( date('j') );
1509 return $this->mTitle
->getText();
1511 return $this->mTitle
->getPartialURL();
1513 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1514 return $wgLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1515 case MAG_CURRENTDAYNAME
:
1516 return $wgLang->getWeekdayName( date('w')+
1 );
1517 case MAG_CURRENTYEAR
:
1518 return $wgLang->formatNum( date( 'Y' ) );
1519 case MAG_CURRENTTIME
:
1520 return $wgLang->time( wfTimestampNow(), false );
1521 case MAG_NUMBEROFARTICLES
:
1522 return $wgLang->formatNum( wfNumberOfArticles() );
1533 * initialise the magic variables (like CURRENTMONTHNAME)
1537 function initialiseVariables() {
1538 global $wgVariableIDs;
1539 $this->mVariables
= array();
1540 foreach ( $wgVariableIDs as $id ) {
1541 $mw =& MagicWord
::get( $id );
1542 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1547 * Replace magic variables, templates, and template arguments
1548 * with the appropriate text. Templates are substituted recursively,
1549 * taking care to avoid infinite loops.
1551 * Note that the substitution depends on value of $mOutputType:
1552 * OT_WIKI: only {{subst:}} templates
1553 * OT_MSG: only magic variables
1554 * OT_HTML: all templates and magic variables
1556 * @param string $tex The text to transform
1557 * @param array $args Key-value pairs representing template parameters to substitute
1560 function replaceVariables( $text, $args = array() ) {
1561 global $wgLang, $wgScript, $wgArticlePath;
1563 # Prevent too big inclusions
1564 if(strlen($text)> MAX_INCLUDE_SIZE
)
1567 $fname = 'Parser::replaceVariables';
1568 wfProfileIn( $fname );
1570 $titleChars = Title
::legalChars();
1572 # This function is called recursively. To keep track of arguments we need a stack:
1573 array_push( $this->mArgStack
, $args );
1575 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1576 $GLOBALS['wgCurParser'] =& $this;
1578 if ( $this->mOutputType
== OT_HTML
) {
1579 # Argument substitution
1580 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1582 # Template substitution
1583 $regex = '/{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1584 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1586 array_pop( $this->mArgStack
);
1588 wfProfileOut( $fname );
1592 # Split template arguments
1593 function getTemplateArgs( $argsString ) {
1594 if ( $argsString === '' ) {
1598 $args = explode( '|', substr( $argsString, 1 ) );
1600 # If any of the arguments contains a '[[' but no ']]', it needs to be
1601 # merged with the next arg because the '|' character between belongs
1602 # to the link syntax and not the template parameter syntax.
1603 $argc = count($args);
1605 for ( $i = 0; $i < $argc-1; $i++
) {
1606 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1607 $args[$i] .= '|'.$args[$i+
1];
1608 array_splice($args, $i+
1, 1);
1618 * Return the text of a template, after recursively
1619 * replacing any variables or templates within the template.
1621 * @param array $matches The parts of the template
1622 * $matches[1]: the title, i.e. the part before the |
1623 * $matches[2]: the parameters (including a leading |), if any
1624 * @return string the text of the template
1627 function braceSubstitution( $matches ) {
1628 global $wgLinkCache, $wgLang;
1629 $fname = 'Parser::braceSubstitution';
1636 # $part1 is the bit before the first |, and must contain only title characters
1637 # $args is a list of arguments, starting from index 0, not including $part1
1639 $part1 = $matches[1];
1640 # If the second subpattern matched anything, it will start with |
1642 $args = $this->getTemplateArgs($matches[2]);
1643 $argc = count( $args );
1646 if ( strpos( $matches[0], '{{{' ) !== false ) {
1647 $text = $matches[0];
1654 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1655 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1656 if ( $this->mOutputType
!= OT_WIKI
) {
1657 # Invalid SUBST not replaced at PST time
1658 # Return without further processing
1659 $text = $matches[0];
1663 } elseif ( $this->mOutputType
== OT_WIKI
) {
1664 # SUBST not found in PST pass, do nothing
1665 $text = $matches[0];
1670 # MSG, MSGNW and INT
1673 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1674 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1677 # Remove obsolete MSG:
1678 $mwMsg =& MagicWord
::get( MAG_MSG
);
1679 $mwMsg->matchStartAndRemove( $part1 );
1682 # Check if it is an internal message
1683 $mwInt =& MagicWord
::get( MAG_INT
);
1684 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1685 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1686 $text = wfMsgReal( $part1, $args, true );
1694 # Check for NS: (namespace expansion)
1695 $mwNs = MagicWord
::get( MAG_NS
);
1696 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1697 if ( intval( $part1 ) ) {
1698 $text = $wgLang->getNsText( intval( $part1 ) );
1701 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1702 if ( !is_null( $index ) ) {
1703 $text = $wgLang->getNsText( $index );
1710 # LOCALURL and LOCALURLE
1712 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1713 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1715 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1716 $func = 'getLocalURL';
1717 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1718 $func = 'escapeLocalURL';
1723 if ( $func !== '' ) {
1724 $title = Title
::newFromText( $part1 );
1725 if ( !is_null( $title ) ) {
1727 $text = $title->$func( $args[0] );
1729 $text = $title->$func();
1736 # Internal variables
1737 if ( !$this->mVariables
) {
1738 $this->initialiseVariables();
1740 if ( !$found && array_key_exists( $part1, $this->mVariables
) ) {
1741 $text = $this->mVariables
[$part1];
1743 $this->mOutput
->mContainsOldMagic
= true;
1747 if ( !$found && $argc == 1 ) {
1748 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1749 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1750 $text = $wgLang->convertGrammar( $args[0], $part1 );
1755 # Template table test
1757 # Did we encounter this template already? If yes, it is in the cache
1758 # and we need to check for loops.
1759 if ( isset( $this->mTemplates
[$part1] ) ) {
1760 # Infinite loop test
1761 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1765 # set $text to cached message.
1766 $text = $this->mTemplates
[$part1];
1770 # Load from database
1772 $title = Title
::newFromText( $part1, NS_TEMPLATE
);
1773 if ( !is_null( $title ) && !$title->isExternal() ) {
1774 # Check for excessive inclusion
1775 $dbk = $title->getPrefixedDBkey();
1776 if ( $this->incrementIncludeCount( $dbk ) ) {
1777 # This should never be reached.
1778 $article = new Article( $title );
1779 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1780 if ( $articleContent !== false ) {
1782 $text = $articleContent;
1786 # If the title is valid but undisplayable, make a link to it
1787 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
1788 $text = '[['.$title->getPrefixedText().']]';
1792 # Template cache array insertion
1793 $this->mTemplates
[$part1] = $text;
1797 # Recursive parsing, escaping and link table handling
1798 # Only for HTML output
1799 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
1800 $text = wfEscapeWikiText( $text );
1801 } elseif ( $this->mOutputType
== OT_HTML
&& $found && !$noparse) {
1802 # Clean up argument array
1803 $assocArgs = array();
1805 foreach( $args as $arg ) {
1806 $eqpos = strpos( $arg, '=' );
1807 if ( $eqpos === false ) {
1808 $assocArgs[$index++
] = $arg;
1810 $name = trim( substr( $arg, 0, $eqpos ) );
1811 $value = trim( substr( $arg, $eqpos+
1 ) );
1812 if ( $value === false ) {
1815 if ( $name !== false ) {
1816 $assocArgs[$name] = $value;
1821 # Do not enter included links in link table
1822 if ( !is_null( $title ) ) {
1823 $wgLinkCache->suspend();
1826 # Add a new element to the templace recursion path
1827 $this->mTemplatePath
[$part1] = 1;
1829 $text = $this->strip( $text, $this->mStripState
);
1830 $text = $this->removeHTMLtags( $text );
1831 $text = $this->replaceVariables( $text, $assocArgs );
1833 # Resume the link cache and register the inclusion as a link
1834 if ( !is_null( $title ) ) {
1835 $wgLinkCache->resume();
1836 $wgLinkCache->addLinkObj( $title );
1840 # Empties the template path
1841 $this->mTemplatePath
= array();
1846 # replace ==section headers==
1847 # XXX this needs to go away once we have a better parser.
1848 if ( $this->mOutputType
!= OT_WIKI
) {
1849 for ( $i = 1; $i <= 6; ++
$i ) {
1850 $h = substr( '======', 0, $i );
1851 $text = preg_replace( "/^{$h}([^=].*){$h}\\s?$/m",
1852 "${h}\\1 __MWTEMPLATESECTION__${h}\\2", $text );
1860 * Triple brace replacement -- used for template arguments
1863 function argSubstitution( $matches ) {
1864 $arg = trim( $matches[1] );
1865 $text = $matches[0];
1866 $inputArgs = end( $this->mArgStack
);
1868 if ( array_key_exists( $arg, $inputArgs ) ) {
1869 $text = $this->strip( $inputArgs[$arg], $this->mStripState
);
1870 $text = $this->removeHTMLtags( $text );
1871 $text = $this->replaceVariables( $text, array() );
1878 * Returns true if the function is allowed to include this entity
1881 function incrementIncludeCount( $dbk ) {
1882 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
1883 $this->mIncludeCount
[$dbk] = 0;
1885 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
1894 * Cleans up HTML, removes dangerous tags and attributes, and
1895 * removes HTML comments
1898 function removeHTMLtags( $text ) {
1899 global $wgUseTidy, $wgUserHtml;
1900 $fname = 'Parser::removeHTMLtags';
1901 wfProfileIn( $fname );
1904 $htmlpairs = array( # Tags that must be closed
1905 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1906 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1907 'strike', 'strong', 'tt', 'var', 'div', 'center',
1908 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1909 'ruby', 'rt' , 'rb' , 'rp', 'p'
1911 $htmlsingle = array(
1912 'br', 'hr', 'li', 'dt', 'dd'
1914 $htmlnest = array( # Tags that can be nested--??
1915 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1916 'dl', 'font', 'big', 'small', 'sub', 'sup'
1918 $tabletags = array( # Can only appear inside table
1922 $htmlpairs = array();
1923 $htmlsingle = array();
1924 $htmlnest = array();
1925 $tabletags = array();
1928 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1929 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1931 $htmlattrs = $this->getHTMLattrs () ;
1933 # Remove HTML comments
1934 $text = $this->removeHTMLcomments( $text );
1936 $bits = explode( '<', $text );
1937 $text = array_shift( $bits );
1939 $tagstack = array(); $tablestack = array();
1940 foreach ( $bits as $x ) {
1941 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
1942 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1944 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1945 error_reporting( $prev );
1948 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1952 if ( ! in_array( $t, $htmlsingle ) &&
1953 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
1954 @array_push
( $tagstack, $ot );
1957 if ( $t == 'table' ) {
1958 $tagstack = array_pop( $tablestack );
1963 # Keep track for later
1964 if ( in_array( $t, $tabletags ) &&
1965 ! in_array( 'table', $tagstack ) ) {
1967 } else if ( in_array( $t, $tagstack ) &&
1968 ! in_array ( $t , $htmlnest ) ) {
1970 } else if ( ! in_array( $t, $htmlsingle ) ) {
1971 if ( $t == 'table' ) {
1972 array_push( $tablestack, $tagstack );
1973 $tagstack = array();
1975 array_push( $tagstack, $t );
1977 # Strip non-approved attributes from the tag
1978 $newparams = $this->fixTagAttributes($params);
1982 $rest = str_replace( '>', '>', $rest );
1983 $text .= "<$slash$t $newparams$brace$rest";
1987 $text .= '<' . str_replace( '>', '>', $x);
1989 # Close off any remaining tags
1990 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1992 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1995 # this might be possible using tidy itself
1996 foreach ( $bits as $x ) {
1997 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1999 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2000 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2001 $newparams = $this->fixTagAttributes($params);
2002 $rest = str_replace( '>', '>', $rest );
2003 $text .= "<$slash$t $newparams$brace$rest";
2005 $text .= '<' . str_replace( '>', '>', $x);
2009 wfProfileOut( $fname );
2014 * Remove '<!--', '-->', and everything between.
2015 * To avoid leaving blank lines, when a comment is both preceded
2016 * and followed by a newline (ignoring spaces), trim leading and
2017 * trailing spaces and one of the newlines.
2021 function removeHTMLcomments( $text ) {
2022 $fname='Parser::removeHTMLcomments';
2023 wfProfileIn( $fname );
2024 while (($start = strpos($text, '<!--')) !== false) {
2025 $end = strpos($text, '-->', $start +
4);
2026 if ($end === false) {
2027 # Unterminated comment; bail out
2033 # Trim space and newline if the comment is both
2034 # preceded and followed by a newline
2035 $spaceStart = max($start - 1, 0);
2036 $spaceLen = $end - $spaceStart;
2037 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2041 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2043 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2044 # Remove the comment, leading and trailing
2045 # spaces, and leave only one newline.
2046 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2049 # Remove just the comment.
2050 $text = substr_replace($text, '', $start, $end - $start);
2053 wfProfileOut( $fname );
2058 * This function accomplishes several tasks:
2059 * 1) Auto-number headings if that option is enabled
2060 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2061 * 3) Add a Table of contents on the top for users who have enabled the option
2062 * 4) Auto-anchor headings
2064 * It loops through all headlines, collects the necessary data, then splits up the
2065 * string and re-inserts the newly formatted headlines.
2068 /* private */ function formatHeadings( $text, $isMain=true ) {
2069 global $wgInputEncoding, $wgMaxTocLevel, $wgLang, $wgLinkHolders;
2071 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2072 $doShowToc = $this->mOptions
->getShowToc();
2073 $forceTocHere = false;
2074 if( !$this->mTitle
->userCanEdit() ) {
2076 $rightClickHack = 0;
2078 $showEditLink = $this->mOptions
->getEditSection();
2079 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2082 # Inhibit editsection links if requested in the page
2083 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2084 if( $esw->matchAndRemove( $text ) ) {
2087 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2089 $mw =& MagicWord
::get( MAG_NOTOC
);
2090 if( $mw->matchAndRemove( $text ) ) {
2094 # never add the TOC to the Main Page. This is an entry page that should not
2095 # be more than 1-2 screens large anyway
2096 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2100 # Get all headlines for numbering them and adding funky stuff like [edit]
2101 # links - this is for later, but we need the number of headlines right now
2102 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2104 # if there are fewer than 4 headlines in the article, do not show TOC
2105 if( $numMatches < 4 ) {
2109 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2110 # override above conditions and always show TOC at that place
2111 $mw =& MagicWord
::get( MAG_TOC
);
2112 if ($mw->match( $text ) ) {
2114 $forceTocHere = true;
2116 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2117 # override above conditions and always show TOC above first header
2118 $mw =& MagicWord
::get( MAG_FORCETOC
);
2119 if ($mw->matchAndRemove( $text ) ) {
2126 # We need this to perform operations on the HTML
2127 $sk =& $this->mOptions
->getSkin();
2131 $sectionCount = 0; # headlineCount excluding template sections
2133 # Ugh .. the TOC should have neat indentation levels which can be
2134 # passed to the skin functions. These are determined here
2139 $sublevelCount = array();
2142 foreach( $matches[3] as $headline ) {
2144 if (strstr($headline, "__MWTEMPLATESECTION__")) {
2146 $headline = str_replace("__MWTEMPLATESECTION__", "", $headline);
2150 $prevlevel = $level;
2152 $level = $matches[1][$headlineCount];
2153 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2154 # reset when we enter a new level
2155 $sublevelCount[$level] = 0;
2156 $toc .= $sk->tocIndent( $level - $prevlevel );
2157 $toclevel +
= $level - $prevlevel;
2159 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2160 # reset when we step back a level
2161 $sublevelCount[$level+
1]=0;
2162 $toc .= $sk->tocUnindent( $prevlevel - $level );
2163 $toclevel -= $prevlevel - $level;
2165 # count number of headlines for each level
2166 @$sublevelCount[$level]++
;
2167 if( $doNumberHeadings ||
$doShowToc ) {
2169 for( $i = 1; $i <= $level; $i++
) {
2170 if( !empty( $sublevelCount[$i] ) ) {
2174 $numbering .= $wgLang->formatNum( $sublevelCount[$i] );
2180 # The canonized header is a version of the header text safe to use for links
2181 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2182 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2183 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2185 # Remove link placeholders by the link text.
2186 # <!--LINK number-->
2188 # link text with suffix
2189 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2190 "\$wgLinkHolders['texts'][\$1]",
2191 $canonized_headline );
2194 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2195 $tocline = trim( $canonized_headline );
2196 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2197 $replacearray = array(
2201 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2202 $refer[$headlineCount] = $canonized_headline;
2204 # count how many in assoc. array so we can track dupes in anchors
2205 @$refers[$canonized_headline]++
;
2206 $refcount[$headlineCount]=$refers[$canonized_headline];
2208 # Prepend the number to the heading text
2210 if( $doNumberHeadings ||
$doShowToc ) {
2211 $tocline = $numbering . ' ' . $tocline;
2213 # Don't number the heading if it is the only one (looks silly)
2214 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2215 # the two are different if the line contains a link
2216 $headline=$numbering . ' ' . $headline;
2220 # Create the anchor for linking from the TOC to the section
2221 $anchor = $canonized_headline;
2222 if($refcount[$headlineCount] > 1 ) {
2223 $anchor .= '_' . $refcount[$headlineCount];
2225 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2226 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2228 if( $showEditLink && !$istemplate ) {
2229 if ( empty( $head[$headlineCount] ) ) {
2230 $head[$headlineCount] = '';
2232 $head[$headlineCount] .= $sk->editSectionLink($sectionCount+
1);
2235 # Add the edit section span
2236 if( $rightClickHack ) {
2237 $headline = $sk->editSectionScript($sectionCount+
1,$headline);
2240 # give headline the correct <h#> tag
2241 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2249 $toclines = $headlineCount;
2250 $toc .= $sk->tocUnindent( $toclevel );
2251 $toc = $sk->tocTable( $toc );
2254 # split up and insert constructed headlines
2256 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2259 foreach( $blocks as $block ) {
2260 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2261 # This is the [edit] link that appears for the top block of text when
2262 # section editing is enabled
2264 # Disabled because it broke block formatting
2265 # For example, a bullet point in the top line
2266 # $full .= $sk->editSectionLink(0);
2269 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2270 # Top anchor now in skin
2274 if( !empty( $head[$i] ) ) {
2280 $mw =& MagicWord
::get( MAG_TOC
);
2281 return $mw->replace( $toc, $full );
2288 * Return an HTML link for the "ISBN 123456" text
2291 function magicISBN( $text ) {
2293 $fname = 'Parser::magicISBN';
2294 wfProfileIn( $fname );
2296 $a = split( 'ISBN ', ' '.$text );
2297 if ( count ( $a ) < 2 ) {
2298 wfProfileOut( $fname );
2301 $text = substr( array_shift( $a ), 1);
2302 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2304 foreach ( $a as $x ) {
2305 $isbn = $blank = '' ;
2306 while ( ' ' == $x{0} ) {
2308 $x = substr( $x, 1 );
2310 if ( $x == '' ) { # blank isbn
2311 $text .= "ISBN $blank";
2314 while ( strstr( $valid, $x{0} ) != false ) {
2316 $x = substr( $x, 1 );
2318 $num = str_replace( '-', '', $isbn );
2319 $num = str_replace( ' ', '', $num );
2322 $text .= "ISBN $blank$x";
2324 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2325 $text .= '<a href="' .
2326 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2327 "\" class=\"internal\">ISBN $isbn</a>";
2331 wfProfileOut( $fname );
2336 * Return an HTML link for the "GEO ..." text
2339 function magicGEO( $text ) {
2340 global $wgLang, $wgUseGeoMode;
2341 $fname = 'Parser::magicGEO';
2342 wfProfileIn( $fname );
2344 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2345 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2346 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2347 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2348 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2349 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2351 $a = split( 'GEO ', ' '.$text );
2352 if ( count ( $a ) < 2 ) {
2353 wfProfileOut( $fname );
2356 $text = substr( array_shift( $a ), 1);
2357 $valid = '0123456789.+-:';
2359 foreach ( $a as $x ) {
2360 $geo = $blank = '' ;
2361 while ( ' ' == $x{0} ) {
2363 $x = substr( $x, 1 );
2365 while ( strstr( $valid, $x{0} ) != false ) {
2367 $x = substr( $x, 1 );
2369 $num = str_replace( '+', '', $geo );
2370 $num = str_replace( ' ', '', $num );
2372 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2373 $text .= "GEO $blank$x";
2375 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2376 $text .= '<a href="' .
2377 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2378 "\" class=\"internal\">GEO $geo</a>";
2382 wfProfileOut( $fname );
2387 * Return an HTML link for the "RFC 1234" text
2389 * @param string $text text to be processed
2391 function magicRFC( $text ) {
2394 $valid = '0123456789';
2397 $a = split( 'RFC ', ' '.$text );
2398 if ( count ( $a ) < 2 ) return $text;
2399 $text = substr( array_shift( $a ), 1);
2401 /* Check if RFC keyword is preceed by [[.
2402 * This test is made here cause of the array_shift above
2403 * that prevent the test to be done in the foreach.
2405 if(substr($text, -2) == '[[') { $internal = true; }
2407 foreach ( $a as $x ) {
2408 /* token might be empty if we have RFC RFC 1234 */
2414 $rfc = $blank = '' ;
2416 /** remove and save whitespaces in $blank */
2417 while ( $x{0} == ' ' ) {
2419 $x = substr( $x, 1 );
2422 /** remove and save the rfc number in $rfc */
2423 while ( strstr( $valid, $x{0} ) != false ) {
2425 $x = substr( $x, 1 );
2429 /* call back stripped spaces*/
2430 $text .= "RFC $blank$x";
2431 } elseif( $internal) {
2433 $text .= "RFC $rfc$x";
2435 /* build the external link*/
2436 $url = wfmsg( 'rfcurl' );
2437 $url = str_replace( '$1', $rfc, $url);
2438 $sk =& $this->mOptions
->getSkin();
2439 $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
2440 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2443 /* Check if the next RFC keyword is preceed by [[ */
2444 $internal = (substr($x,-2) == '[[');
2450 * Transform wiki markup when saving a page by doing \r\n -> \n
2451 * conversion, substitting signatures, {{subst:}} templates, etc.
2453 * @param string $text the text to transform
2454 * @param Title &$title the Title object for the current article
2455 * @param User &$user the User object describing the current user
2456 * @param ParserOptions $options parsing options
2457 * @param bool $clearState whether to clear the parser state first
2458 * @return string the altered wiki markup
2461 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2462 $this->mOptions
= $options;
2463 $this->mTitle
=& $title;
2464 $this->mOutputType
= OT_WIKI
;
2466 if ( $clearState ) {
2467 $this->clearState();
2470 $stripState = false;
2474 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2478 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2479 "/<br *?>/i" => "<br />",
2481 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2483 $text = $this->strip( $text, $stripState, false );
2484 $text = $this->pstPass2( $text, $user );
2485 $text = $this->unstrip( $text, $stripState );
2486 $text = $this->unstripNoWiki( $text, $stripState );
2491 * Pre-save transform helper function
2494 function pstPass2( $text, &$user ) {
2495 global $wgLang, $wgLocaltimezone, $wgCurParser;
2497 # Variable replacement
2498 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2499 $text = $this->replaceVariables( $text );
2503 $n = $user->getName();
2504 $k = $user->getOption( 'nickname' );
2505 if ( '' == $k ) { $k = $n; }
2506 if(isset($wgLocaltimezone)) {
2507 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2509 /* Note: this is an ugly timezone hack for the European wikis */
2510 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2511 ' (' . date( 'T' ) . ')';
2512 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2514 $text = preg_replace( '/~~~~~/', $d, $text );
2515 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2516 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2518 # Context links: [[|name]] and [[name (context)|]]
2520 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2521 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2522 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2523 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2525 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2526 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2527 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2528 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2530 $t = $this->mTitle
->getText();
2531 if ( preg_match( $conpat, $t, $m ) ) {
2534 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2535 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2536 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2538 if ( '' == $context ) {
2539 $text = preg_replace( $p2, '[[\\1]]', $text );
2541 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2545 $mw =& MagicWord::get( MAG_SUBST );
2546 $wgCurParser = $this->fork();
2547 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2548 $this->merge( $wgCurParser );
2551 # Trim trailing whitespace
2552 # MAG_END (__END__) tag allows for trailing
2553 # whitespace to be deliberately included
2554 $text = rtrim( $text );
2555 $mw =& MagicWord
::get( MAG_END
);
2556 $mw->matchAndRemove( $text );
2562 * Set up some variables which are usually set up in parse()
2563 * so that an external function can call some class members with confidence
2566 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2567 $this->mTitle
=& $title;
2568 $this->mOptions
= $options;
2569 $this->mOutputType
= $outputType;
2570 if ( $clearState ) {
2571 $this->clearState();
2576 * Transform a MediaWiki message by replacing magic variables.
2578 * @param string $text the text to transform
2579 * @param ParserOptions $options options
2580 * @return string the text with variables substituted
2583 function transformMsg( $text, $options ) {
2585 static $executing = false;
2587 # Guard against infinite recursion
2593 $this->mTitle
= $wgTitle;
2594 $this->mOptions
= $options;
2595 $this->mOutputType
= OT_MSG
;
2596 $this->clearState();
2597 $text = $this->replaceVariables( $text );
2604 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2605 * Callback will be called with the text within
2606 * Transform and return the text within
2609 function setHook( $tag, $callback ) {
2610 $oldVal = @$this->mTagHooks
[$tag];
2611 $this->mTagHooks
[$tag] = $callback;
2618 * @package MediaWiki
2622 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2623 var $mCacheTime; # Used in ParserCache
2625 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2626 $containsOldMagic = false )
2628 $this->mText
= $text;
2629 $this->mLanguageLinks
= $languageLinks;
2630 $this->mCategoryLinks
= $categoryLinks;
2631 $this->mContainsOldMagic
= $containsOldMagic;
2632 $this->mCacheTime
= '';
2635 function getText() { return $this->mText
; }
2636 function getLanguageLinks() { return $this->mLanguageLinks
; }
2637 function getCategoryLinks() { return $this->mCategoryLinks
; }
2638 function getCacheTime() { return $this->mCacheTime
; }
2639 function containsOldMagic() { return $this->mContainsOldMagic
; }
2640 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2641 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2642 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2643 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2644 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2646 function merge( $other ) {
2647 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2648 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2649 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2655 * Set options of the Parser
2657 * @package MediaWiki
2661 # All variables are private
2662 var $mUseTeX; # Use texvc to expand <math> tags
2663 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2664 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2665 var $mAllowExternalImages; # Allow external images inline
2666 var $mSkin; # Reference to the preferred skin
2667 var $mDateFormat; # Date format index
2668 var $mEditSection; # Create "edit section" links
2669 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2670 var $mNumberHeadings; # Automatically number headings
2671 var $mShowToc; # Show table of contents
2673 function getUseTeX() { return $this->mUseTeX
; }
2674 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
2675 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
2676 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
2677 function getSkin() { return $this->mSkin
; }
2678 function getDateFormat() { return $this->mDateFormat
; }
2679 function getEditSection() { return $this->mEditSection
; }
2680 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
2681 function getNumberHeadings() { return $this->mNumberHeadings
; }
2682 function getShowToc() { return $this->mShowToc
; }
2684 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
2685 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
2686 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
2687 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
2688 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
2689 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
2690 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
2691 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
2692 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
2694 function setSkin( &$x ) { $this->mSkin
=& $x; }
2696 # Get parser options
2697 /* static */ function newFromUser( &$user ) {
2698 $popts = new ParserOptions
;
2699 $popts->initialiseFromUser( $user );
2704 function initialiseFromUser( &$userInput ) {
2705 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2707 $fname = 'ParserOptions::initialiseFromUser';
2708 wfProfileIn( $fname );
2709 if ( !$userInput ) {
2711 $user->setLoaded( true );
2713 $user =& $userInput;
2716 $this->mUseTeX
= $wgUseTeX;
2717 $this->mUseDynamicDates
= $wgUseDynamicDates;
2718 $this->mInterwikiMagic
= $wgInterwikiMagic;
2719 $this->mAllowExternalImages
= $wgAllowExternalImages;
2720 wfProfileIn( $fname.'-skin' );
2721 $this->mSkin
=& $user->getSkin();
2722 wfProfileOut( $fname.'-skin' );
2723 $this->mDateFormat
= $user->getOption( 'date' );
2724 $this->mEditSection
= $user->getOption( 'editsection' );
2725 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
2726 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
2727 $this->mShowToc
= $user->getOption( 'showtoc' );
2728 wfProfileOut( $fname );
2734 # Regex callbacks, used in Parser::replaceVariables
2735 function wfBraceSubstitution( $matches ) {
2736 global $wgCurParser;
2737 return $wgCurParser->braceSubstitution( $matches );
2740 function wfArgSubstitution( $matches ) {
2741 global $wgCurParser;
2742 return $wgCurParser->argSubstitution( $matches );
2746 * Return the total number of articles
2748 function wfNumberOfArticles() {
2749 global $wgNumberOfArticles;
2752 return $wgNumberOfArticles;
2756 * Get various statistics from the database
2759 function wfLoadSiteStats() {
2760 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2761 $fname = 'wfLoadSiteStats';
2763 if ( -1 != $wgNumberOfArticles ) return;
2764 $dbr =& wfGetDB( DB_SLAVE
);
2765 $s = $dbr->getArray( 'site_stats',
2766 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2767 array( 'ss_row_id' => 1 ), $fname
2770 if ( $s === false ) {
2773 $wgTotalViews = $s->ss_total_views
;
2774 $wgTotalEdits = $s->ss_total_edits
;
2775 $wgNumberOfArticles = $s->ss_good_articles
;
2779 function wfEscapeHTMLTagsOnly( $in ) {
2781 array( '"', '>', '<' ),
2782 array( '"', '>', '<' ),