4 * File for Parser and related classes
9 require_once( 'Sanitizer.php' );
12 * Update this version number when the ParserOutput format
13 * changes in an incompatible way, so the parser cache
14 * can automatically discard old data.
16 define( 'MW_PARSER_VERSION', '1.4.0' );
19 * Variable substitution O(N^2) attack
21 * Without countermeasures, it would be possible to attack the parser by saving
22 * a page filled with a large number of inclusions of large pages. The size of
23 * the generated page would be proportional to the square of the input size.
24 * Hence, we limit the number of inclusions of any given page, thus bringing any
25 * attack back to O(N).
28 define( 'MAX_INCLUDE_REPEAT', 100 );
29 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
31 define( 'RLH_FOR_UPDATE', 1 );
33 # Allowed values for $mOutputType
34 define( 'OT_HTML', 1 );
35 define( 'OT_WIKI', 2 );
36 define( 'OT_MSG' , 3 );
38 # string parameter for extractTags which will cause it
39 # to strip HTML comments in addition to regular
40 # <XML>-style tags. This should not be anything we
41 # may want to use in wikisyntax
42 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
44 # prefix for escaping, used in two functions at least
45 define( 'UNIQ_PREFIX', 'NaodW29');
47 # Constants needed for external link processing
48 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
49 define( 'HTTP_PROTOCOLS', 'http|https' );
50 # Everything except bracket, space, or control characters
51 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
53 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
54 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
55 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
56 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
57 define( 'EXT_IMAGE_REGEX',
58 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
59 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
60 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
66 * Processes wiki markup
69 * There are three main entry points into the Parser class:
71 * produces HTML output
73 * produces altered wiki markup.
75 * performs brace substitution on MediaWiki messages
78 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
80 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
83 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
84 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
87 * * only within ParserOptions
100 # Cleared with clearState():
101 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
102 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
105 var $mOptions, $mTitle, $mOutputType,
106 $mTemplates, // cache of already loaded templates, avoids
107 // multiple SQL queries for the same string
108 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
109 // in this path. Used for loop detection.
119 $this->mTemplates
= array();
120 $this->mTemplatePath
= array();
121 $this->mTagHooks
= array();
130 function clearState() {
131 $this->mOutput
= new ParserOutput
;
132 $this->mAutonumber
= 0;
133 $this->mLastSection
= '';
134 $this->mDTopen
= false;
135 $this->mVariables
= false;
136 $this->mIncludeCount
= array();
137 $this->mStripState
= array();
138 $this->mArgStack
= array();
139 $this->mInPre
= false;
143 * First pass--just handle <nowiki> sections, pass the rest off
144 * to internalParse() which does all the real work.
147 * @param string $text Text we want to parse
148 * @param Title &$title A title object
149 * @param array $options
150 * @param boolean $linestart
151 * @param boolean $clearState
152 * @return ParserOutput a ParserOutput
154 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
155 global $wgUseTidy, $wgContLang;
156 $fname = 'Parser::parse';
157 wfProfileIn( $fname );
163 $this->mOptions
= $options;
164 $this->mTitle
=& $title;
165 $this->mOutputType
= OT_HTML
;
168 global $fnord; $fnord = 1;
169 //$text = $this->strip( $text, $this->mStripState );
170 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
171 $x =& $this->mStripState
;
172 $text = $this->strip( $text, $x );
174 $text = $this->internalParse( $text, $linestart );
175 $text = $this->unstrip( $text, $this->mStripState
);
176 # Clean up special characters, only run once, next-to-last before doBlockLevels
179 # french spaces, last one Guillemet-left
180 # only if there is something before the space
181 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
182 # french spaces, Guillemet-right
183 '/(\\302\\253) /i' => '\\1 ',
184 '/<hr *>/i' => '<hr />',
185 '/<br *>/i' => '<br />',
186 '/<center *>/i' => '<div class="center">',
187 '/<\\/center *>/i' => '</div>',
189 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
190 $text = Sanitizer
::normalizeCharReferences( $text );
193 # french spaces, last one Guillemet-left
194 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
195 # french spaces, Guillemet-right
196 '/(\\302\\253) /i' => '\\1 ',
197 '/<center *>/i' => '<div class="center">',
198 '/<\\/center *>/i' => '</div>'
200 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
203 $text = $this->doBlockLevels( $text, $linestart );
205 $this->replaceLinkHolders( $text );
206 $text = $wgContLang->convert($text);
208 $text = $this->unstripNoWiki( $text, $this->mStripState
);
211 $text = Parser
::tidy($text);
214 $this->mOutput
->setText( $text );
215 wfProfileOut( $fname );
216 return $this->mOutput
;
220 * Get a random string
225 function getRandomString() {
226 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
230 * Replaces all occurrences of <$tag>content</$tag> in the text
231 * with a random marker and returns the new text. the output parameter
232 * $content will be an associative array filled with data on the form
233 * $unique_marker => content.
235 * If $content is already set, the additional entries will be appended
236 * If $tag is set to STRIP_COMMENTS, the function will extract
237 * <!-- HTML comments -->
242 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
243 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
250 while ( '' != $text ) {
251 if($tag==STRIP_COMMENTS
) {
252 $p = preg_split( '/<!--/i', $text, 2 );
254 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
257 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
260 if($tag==STRIP_COMMENTS
) {
261 $q = preg_split( '/-->/i', $p[1], 2 );
263 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
265 $marker = $rnd . sprintf('%08X', $n++
);
266 $content[$marker] = $q[0];
267 $stripped .= $marker;
275 * Strips and renders nowiki, pre, math, hiero
276 * If $render is set, performs necessary rendering operations on plugins
277 * Returns the text, and fills an array with data needed in unstrip()
278 * If the $state is already a valid strip state, it adds to the state
280 * @param bool $stripcomments when set, HTML comments <!-- like this -->
281 * will be stripped in addition to other tags. This is important
282 * for section editing, where these comments cause confusion when
283 * counting the sections in the wikisource
287 function strip( $text, &$state, $stripcomments = false ) {
288 $render = ($this->mOutputType
== OT_HTML
);
289 $html_content = array();
290 $nowiki_content = array();
291 $math_content = array();
292 $pre_content = array();
293 $comment_content = array();
294 $ext_content = array();
295 $gallery_content = array();
297 # Replace any instances of the placeholders
298 $uniq_prefix = UNIQ_PREFIX
;
299 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
302 global $wgRawHtml, $wgWhitelistEdit;
303 if( $wgRawHtml && $wgWhitelistEdit ) {
304 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
305 foreach( $html_content as $marker => $content ) {
307 # Raw and unchecked for validity.
308 $html_content[$marker] = $content;
310 $html_content[$marker] = '<html>'.$content.'</html>';
316 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
317 foreach( $nowiki_content as $marker => $content ) {
319 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
321 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
326 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
327 foreach( $math_content as $marker => $content ){
329 if( $this->mOptions
->getUseTeX() ) {
330 $math_content[$marker] = renderMath( $content );
332 $math_content[$marker] = '<math>'.$content.'<math>';
335 $math_content[$marker] = '<math>'.$content.'</math>';
340 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
341 foreach( $pre_content as $marker => $content ){
343 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
345 $pre_content[$marker] = '<pre>'.$content.'</pre>';
350 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
351 foreach( $gallery_content as $marker => $content ) {
352 require_once( 'ImageGallery.php' );
354 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
356 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
362 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
363 foreach( $comment_content as $marker => $content ){
364 $comment_content[$marker] = '<!--'.$content.'-->';
369 foreach ( $this->mTagHooks
as $tag => $callback ) {
370 $ext_contents[$tag] = array();
371 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
372 foreach( $ext_content[$tag] as $marker => $content ) {
374 $ext_content[$tag][$marker] = $callback( $content );
376 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
381 # Merge state with the pre-existing state, if there is one
383 $state['html'] = $state['html'] +
$html_content;
384 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
385 $state['math'] = $state['math'] +
$math_content;
386 $state['pre'] = $state['pre'] +
$pre_content;
387 $state['comment'] = $state['comment'] +
$comment_content;
388 $state['gallery'] = $state['gallery'] +
$gallery_content;
390 foreach( $ext_content as $tag => $array ) {
391 if ( array_key_exists( $tag, $state ) ) {
392 $state[$tag] = $state[$tag] +
$array;
397 'html' => $html_content,
398 'nowiki' => $nowiki_content,
399 'math' => $math_content,
400 'pre' => $pre_content,
401 'comment' => $comment_content,
402 'gallery' => $gallery_content,
409 * restores pre, math, and hiero removed by strip()
411 * always call unstripNoWiki() after this one
414 function unstrip( $text, &$state ) {
415 # Must expand in reverse order, otherwise nested tags will be corrupted
416 $contentDict = end( $state );
417 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
418 if( key($state) != 'nowiki' && key($state) != 'html') {
419 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
420 $text = str_replace( key( $contentDict ), $content, $text );
429 * always call this after unstrip() to preserve the order
433 function unstripNoWiki( $text, &$state ) {
434 # Must expand in reverse order, otherwise nested tags will be corrupted
435 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
436 $text = str_replace( key( $state['nowiki'] ), $content, $text );
441 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
442 $text = str_replace( key( $state['html'] ), $content, $text );
450 * Add an item to the strip state
451 * Returns the unique tag which must be inserted into the stripped text
452 * The tag will be replaced with the original text in unstrip()
456 function insertStripItem( $text, &$state ) {
457 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
466 $state['item'][$rnd] = $text;
471 * interface with html tidy, used if $wgUseTidy = true
476 function tidy ( $text ) {
477 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
478 global $wgInputEncoding, $wgOutputEncoding;
479 $fname = 'Parser::tidy';
480 wfProfileIn( $fname );
484 switch(strtoupper($wgOutputEncoding)) {
486 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
489 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
495 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
496 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
497 '<head><title>test</title></head><body>'.$text.'</body></html>';
498 $descriptorspec = array(
499 0 => array('pipe', 'r'),
500 1 => array('pipe', 'w'),
501 2 => array('file', '/dev/null', 'a')
503 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
504 if (is_resource($process)) {
505 fwrite($pipes[0], $wrappedtext);
507 while (!feof($pipes[1])) {
508 $cleansource .= fgets($pipes[1], 1024);
511 $return_value = proc_close($process);
514 wfProfileOut( $fname );
516 if( $cleansource == '' && $text != '') {
517 wfDebug( "Tidy error detected!\n" );
518 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
525 * parse the wiki syntax used to render tables
529 function doTableStuff ( $t ) {
530 $fname = 'Parser::doTableStuff';
531 wfProfileIn( $fname );
533 $t = explode ( "\n" , $t ) ;
534 $td = array () ; # Is currently a td tag open?
535 $ltd = array () ; # Was it TD or TH?
536 $tr = array () ; # Is currently a tr tag open?
537 $ltr = array () ; # tr attributes
538 $indent_level = 0; # indent level of the table
539 foreach ( $t AS $k => $x )
542 $fc = substr ( $x , 0 , 1 ) ;
543 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
544 $indent_level = strlen( $matches[1] );
546 str_repeat( '<dl><dd>', $indent_level ) .
547 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
548 array_push ( $td , false ) ;
549 array_push ( $ltd , '' ) ;
550 array_push ( $tr , false ) ;
551 array_push ( $ltr , '' ) ;
553 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
554 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
556 $l = array_pop ( $ltd ) ;
557 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
558 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
560 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
562 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
563 $x = substr ( $x , 1 ) ;
564 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
566 $l = array_pop ( $ltd ) ;
567 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
568 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
571 array_push ( $tr , false ) ;
572 array_push ( $td , false ) ;
573 array_push ( $ltd , '' ) ;
574 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
576 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
578 if ( '|+' == substr ( $x , 0 , 2 ) ) {
580 $x = substr ( $x , 1 ) ;
582 $after = substr ( $x , 1 ) ;
583 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
584 $after = explode ( '||' , $after ) ;
587 # Loop through each table cell
588 foreach ( $after AS $theline )
593 $tra = array_pop ( $ltr ) ;
594 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
595 array_push ( $tr , true ) ;
596 array_push ( $ltr , '' ) ;
599 $l = array_pop ( $ltd ) ;
600 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
601 if ( $fc == '|' ) $l = 'td' ;
602 else if ( $fc == '!' ) $l = 'th' ;
603 else if ( $fc == '+' ) $l = 'caption' ;
605 array_push ( $ltd , $l ) ;
608 $y = explode ( '|' , $theline , 2 ) ;
609 # Note that a '|' inside an invalid link should not
610 # be mistaken as delimiting cell parameters
611 if ( strpos( $y[0], '[[' ) !== false ) {
612 $y = array ($theline);
614 if ( count ( $y ) == 1 )
615 $y = "{$z}<{$l}>{$y[0]}" ;
616 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$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 = Sanitizer::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 = Sanitizer
::removeHTMLtags( $text );
650 $text = $this->replaceVariables( $text, $args );
652 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
654 $text = $this->doHeadings( $text );
655 if($this->mOptions
->getUseDynamicDates()) {
656 global $wgDateFormatter;
657 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
659 $text = $this->doAllQuotes( $text );
660 $text = $this->replaceInternalLinks( $text );
661 $text = $this->replaceExternalLinks( $text );
663 # replaceInternalLinks may sometimes leave behind
664 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
665 $text = str_replace("http-noparse://","http://",$text);
667 $text = $this->doMagicLinks( $text );
668 $text = $this->doTableStuff( $text );
669 $text = $this->formatHeadings( $text, $isMain );
671 wfProfileOut( $fname );
676 * Replace special strings like "ISBN xxx" and "RFC xxx" with
677 * magic external links.
681 function &doMagicLinks( &$text ) {
682 global $wgUseGeoMode;
683 $text = $this->magicISBN( $text );
684 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
685 $text = $this->magicGEO( $text );
687 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
688 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
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.
756 foreach ( $arr as $r )
758 if ( ( $i %
2 ) == 1 )
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;
793 foreach ( $arr as $r )
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: this is all very hackish and the order of execution matters a lot.
909 * Make sure to run maintenance/parserTests.php if you change this code.
913 function replaceExternalLinks( $text ) {
914 $fname = 'Parser::replaceExternalLinks';
915 wfProfileIn( $fname );
917 $sk =& $this->mOptions
->getSkin();
919 $linktrail = $wgContLang->linkTrail();
921 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
923 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
926 while ( $i<count( $bits ) ) {
928 $protocol = $bits[$i++
];
930 $trail = $bits[$i++
];
932 # The characters '<' and '>' (which were escaped by
933 # removeHTMLtags()) should not be included in
934 # URLs, per RFC 2396.
935 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
936 $text = substr($url, $m2[0][1]) . ' ' . $text;
937 $url = substr($url, 0, $m2[0][1]);
940 # If the link text is an image URL, replace it with an <img> tag
941 # This happened by accident in the original parser, but some people used it extensively
942 $img = $this->maybeMakeImageLink( $text );
943 if ( $img !== false ) {
949 # Set linktype for CSS - if URL==text, link is essentially free
950 $linktype = ($text == $url) ?
'free' : 'text';
952 # No link text, e.g. [http://domain.tld/some.link]
954 # Autonumber if allowed
955 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
956 $text = '[' . ++
$this->mAutonumber
. ']';
957 $linktype = 'autonumber';
959 # Otherwise just use the URL
960 $text = htmlspecialchars( $url );
964 # Have link text, e.g. [http://domain.tld/some.link text]s
966 if ( preg_match( $linktrail, $trail, $m2 ) ) {
972 # Replace & from obsolete syntax with &.
973 # All HTML entities will be escaped by makeExternalLink()
974 # or maybeMakeImageLink()
975 $url = str_replace( '&', '&', $url );
977 # Process the trail (i.e. everything after this link up until start of the next link),
978 # replacing any non-bracketed links
979 $trail = $this->replaceFreeExternalLinks( $trail );
981 # Use the encoded URL
982 # This means that users can paste URLs directly into the text
983 # Funny characters like ö aren't valid in URLs anyway
984 # This was changed in August 2004
985 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
988 wfProfileOut( $fname );
993 * Replace anything that looks like a URL with a link
996 function replaceFreeExternalLinks( $text ) {
997 $fname = 'Parser::replaceFreeExternalLinks';
998 wfProfileIn( $fname );
1000 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1001 $s = array_shift( $bits );
1004 $sk =& $this->mOptions
->getSkin();
1006 while ( $i < count( $bits ) ){
1007 $protocol = $bits[$i++
];
1008 $remainder = $bits[$i++
];
1010 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1011 # Found some characters after the protocol that look promising
1012 $url = $protocol . $m[1];
1015 # The characters '<' and '>' (which were escaped by
1016 # removeHTMLtags()) should not be included in
1017 # URLs, per RFC 2396.
1018 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1019 $trail = substr($url, $m2[0][1]) . $trail;
1020 $url = substr($url, 0, $m2[0][1]);
1023 # Move trailing punctuation to $trail
1025 # If there is no left bracket, then consider right brackets fair game too
1026 if ( strpos( $url, '(' ) === false ) {
1030 $numSepChars = strspn( strrev( $url ), $sep );
1031 if ( $numSepChars ) {
1032 $trail = substr( $url, -$numSepChars ) . $trail;
1033 $url = substr( $url, 0, -$numSepChars );
1036 # Replace & from obsolete syntax with &.
1037 # All HTML entities will be escaped by makeExternalLink()
1038 # or maybeMakeImageLink()
1039 $url = str_replace( '&', '&', $url );
1041 # Is this an external image?
1042 $text = $this->maybeMakeImageLink( $url );
1043 if ( $text === false ) {
1044 # Not an image, make a link
1045 $text = $sk->makeExternalLink( $url, $url, true, 'free' );
1047 $s .= $text . $trail;
1049 $s .= $protocol . $remainder;
1057 * make an image if it's allowed
1060 function maybeMakeImageLink( $url ) {
1061 $sk =& $this->mOptions
->getSkin();
1063 if ( $this->mOptions
->getAllowExternalImages() ) {
1064 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1066 $text = $sk->makeImage( htmlspecialchars( $url ) );
1073 * Process [[ ]] wikilinks
1077 function replaceInternalLinks( $s ) {
1078 global $wgLang, $wgContLang, $wgLinkCache;
1079 global $wgDisableLangConversion;
1080 static $fname = 'Parser::replaceInternalLinks' ;
1082 wfProfileIn( $fname );
1084 wfProfileIn( $fname.'-setup' );
1086 # the % is needed to support urlencoded titles as well
1087 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1089 $sk =& $this->mOptions
->getSkin();
1090 global $wgUseOldExistenceCheck;
1091 # "Post-parse link colour check" works only on wiki text since it's now
1092 # in Parser. Enable it, then disable it when we're done.
1093 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1095 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1097 #split the entire text string on occurences of [[
1098 $a = explode( '[[', ' ' . $s );
1099 #get the first element (all text up to first [[), and remove the space we added
1100 $s = array_shift( $a );
1101 $s = substr( $s, 1 );
1103 # Match a link having the form [[namespace:link|alternate]]trail
1105 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1106 # Match cases where there is no "]]", which might still be images
1107 static $e1_img = FALSE;
1108 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1109 # Match the end of a line for a word that's not followed by whitespace,
1110 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1111 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1113 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1115 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1117 if ( $useLinkPrefixExtension ) {
1118 if ( preg_match( $e2, $s, $m ) ) {
1119 $first_prefix = $m[2];
1122 $first_prefix = false;
1128 $selflink = $this->mTitle
->getPrefixedText();
1129 wfProfileOut( $fname.'-setup' );
1131 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1132 $useSubpages = $this->areSubpagesAllowed();
1134 # Loop for each link
1135 for ($k = 0; isset( $a[$k] ); $k++
) {
1137 if ( $useLinkPrefixExtension ) {
1138 wfProfileIn( $fname.'-prefixhandling' );
1139 if ( preg_match( $e2, $s, $m ) ) {
1147 $prefix = $first_prefix;
1148 $first_prefix = false;
1150 wfProfileOut( $fname.'-prefixhandling' );
1153 $might_be_img = false;
1155 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1157 # fix up urlencoded title texts
1158 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1160 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1161 $might_be_img = true;
1163 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1165 } else { # Invalid form; output directly
1166 $s .= $prefix . '[[' . $line ;
1170 # Don't allow internal links to pages containing
1171 # PROTO: where PROTO is a valid URL protocol; these
1172 # should be external links.
1173 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1174 $s .= $prefix . '[[' . $line ;
1178 # Make subpage if necessary
1179 if( $useSubpages ) {
1180 $link = $this->maybeDoSubpageLink( $m[1], $text );
1185 $noforce = (substr($m[1], 0, 1) != ':');
1187 # Strip off leading ':'
1188 $link = substr($link, 1);
1191 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1193 $s .= $prefix . '[[' . $line;
1197 #check other language variants of the link
1198 #if the article does not exist
1199 if( $checkVariantLink
1200 && $nt->getArticleID() == 0 ) {
1201 $wgContLang->findVariantLink($link, $nt);
1204 $ns = $nt->getNamespace();
1205 $iw = $nt->getInterWiki();
1207 if ($might_be_img) { # if this is actually an invalid link
1208 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1210 while (isset ($a[$k+
1]) ) {
1211 #look at the next 'line' to see if we can close it there
1212 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1213 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1214 # the first ]] closes the inner link, the second the image
1216 $text .= '[[' . $m[1];
1219 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1220 #if there's exactly one ]] that's fine, we'll keep looking
1221 $text .= '[[' . $m[0];
1223 #if $next_line is invalid too, we need look no further
1224 $text .= '[[' . $next_line;
1229 # we couldn't find the end of this imageLink, so output it raw
1230 #but don't ignore what might be perfectly normal links in the text we've examined
1231 $text = $this->replaceInternalLinks($text);
1232 $s .= $prefix . '[[' . $link . '|' . $text;
1233 # note: no $trail, because without an end, there *is* no trail
1236 } else { #it's not an image, so output it raw
1237 $s .= $prefix . '[[' . $link . '|' . $text;
1238 # note: no $trail, because without an end, there *is* no trail
1243 $wasblank = ( '' == $text );
1244 if( $wasblank ) $text = $link;
1247 # Link not escaped by : , create the various objects
1251 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1252 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1253 $tmp = $prefix . $trail ;
1254 $s .= (trim($tmp) == '')?
'': $tmp;
1258 if ( $ns == NS_IMAGE
) {
1259 wfProfileIn( "$fname-image" );
1261 # recursively parse links inside the image caption
1262 # actually, this will parse them in any other parameters, too,
1263 # but it might be hard to fix that, and it doesn't matter ATM
1264 $text = $this->replaceExternalLinks($text);
1265 $text = $this->replaceInternalLinks($text);
1267 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1268 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1269 $wgLinkCache->addImageLinkObj( $nt );
1271 wfProfileOut( "$fname-image" );
1275 if ( $ns == NS_CATEGORY
) {
1276 wfProfileIn( "$fname-category" );
1277 $t = $nt->getText();
1279 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1280 $pPLC=$sk->postParseLinkColour();
1281 $sk->postParseLinkColour( false );
1282 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1283 $sk->postParseLinkColour( $pPLC );
1284 $wgLinkCache->resume();
1287 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1288 $sortkey = $this->mTitle
->getText();
1290 $sortkey = $this->mTitle
->getPrefixedText();
1295 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1296 $this->mOutput
->addCategoryLink( $t );
1297 $s .= $prefix . $trail ;
1299 wfProfileOut( "$fname-category" );
1304 if( ( $nt->getPrefixedText() === $selflink ) &&
1305 ( $nt->getFragment() === '' ) ) {
1306 # Self-links are handled specially; generally de-link and change to bold.
1307 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1311 # Special and Media are pseudo-namespaces; no pages actually exist in them
1312 if( $ns == NS_MEDIA
) {
1313 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1314 $wgLinkCache->addImageLinkObj( $nt );
1316 } elseif( $ns == NS_SPECIAL
) {
1317 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1320 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1322 $sk->postParseLinkColour( $saveParseColour );
1323 wfProfileOut( $fname );
1328 * Return true if subpage links should be expanded on this page.
1331 function areSubpagesAllowed() {
1332 # Some namespaces don't allow subpages
1333 global $wgNamespacesWithSubpages;
1334 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1338 * Handle link to subpage if necessary
1339 * @param string $target the source of the link
1340 * @param string &$text the link text, modified as necessary
1341 * @return string the full name of the link
1344 function maybeDoSubpageLink($target, &$text) {
1347 # :Foobar -- override special treatment of prefix (images, language links)
1348 # /Foobar -- convert to CurrentPage/Foobar
1349 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1350 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1351 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1353 $fname = 'Parser::maybeDoSubpageLink';
1354 wfProfileIn( $fname );
1355 $ret = $target; # default return value is no change
1357 # Some namespaces don't allow subpages,
1358 # so only perform processing if subpages are allowed
1359 if( $this->areSubpagesAllowed() ) {
1360 # Look at the first character
1361 if( $target != '' && $target{0} == '/' ) {
1362 # / at end means we don't want the slash to be shown
1363 if( substr( $target, -1, 1 ) == '/' ) {
1364 $target = substr( $target, 1, -1 );
1367 $noslash = substr( $target, 1 );
1370 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1371 if( '' === $text ) {
1373 } # this might be changed for ugliness reasons
1375 # check for .. subpage backlinks
1377 $nodotdot = $target;
1378 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1380 $nodotdot = substr( $nodotdot, 3 );
1382 if($dotdotcount > 0) {
1383 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1384 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1385 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1386 # / at the end means don't show full path
1387 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1388 $nodotdot = substr( $nodotdot, 0, -1 );
1389 if( '' === $text ) {
1393 $nodotdot = trim( $nodotdot );
1394 if( $nodotdot != '' ) {
1395 $ret .= '/' . $nodotdot;
1402 wfProfileOut( $fname );
1407 * Used by doBlockLevels()
1410 /* private */ function closeParagraph() {
1412 if ( '' != $this->mLastSection
) {
1413 $result = '</' . $this->mLastSection
. ">\n";
1415 $this->mInPre
= false;
1416 $this->mLastSection
= '';
1419 # getCommon() returns the length of the longest common substring
1420 # of both arguments, starting at the beginning of both.
1422 /* private */ function getCommon( $st1, $st2 ) {
1423 $fl = strlen( $st1 );
1424 $shorter = strlen( $st2 );
1425 if ( $fl < $shorter ) { $shorter = $fl; }
1427 for ( $i = 0; $i < $shorter; ++
$i ) {
1428 if ( $st1{$i} != $st2{$i} ) { break; }
1432 # These next three functions open, continue, and close the list
1433 # element appropriate to the prefix character passed into them.
1435 /* private */ function openList( $char ) {
1436 $result = $this->closeParagraph();
1438 if ( '*' == $char ) { $result .= '<ul><li>'; }
1439 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1440 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1441 else if ( ';' == $char ) {
1442 $result .= '<dl><dt>';
1443 $this->mDTopen
= true;
1445 else { $result = '<!-- ERR 1 -->'; }
1450 /* private */ function nextItem( $char ) {
1451 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1452 else if ( ':' == $char ||
';' == $char ) {
1454 if ( $this->mDTopen
) { $close = '</dt>'; }
1455 if ( ';' == $char ) {
1456 $this->mDTopen
= true;
1457 return $close . '<dt>';
1459 $this->mDTopen
= false;
1460 return $close . '<dd>';
1463 return '<!-- ERR 2 -->';
1466 /* private */ function closeList( $char ) {
1467 if ( '*' == $char ) { $text = '</li></ul>'; }
1468 else if ( '#' == $char ) { $text = '</li></ol>'; }
1469 else if ( ':' == $char ) {
1470 if ( $this->mDTopen
) {
1471 $this->mDTopen
= false;
1472 $text = '</dt></dl>';
1474 $text = '</dd></dl>';
1477 else { return '<!-- ERR 3 -->'; }
1483 * Make lists from lines starting with ':', '*', '#', etc.
1486 * @return string the lists rendered as HTML
1488 function doBlockLevels( $text, $linestart ) {
1489 $fname = 'Parser::doBlockLevels';
1490 wfProfileIn( $fname );
1492 # Parsing through the text line by line. The main thing
1493 # happening here is handling of block-level elements p, pre,
1494 # and making lists from lines starting with * # : etc.
1496 $textLines = explode( "\n", $text );
1498 $lastPrefix = $output = $lastLine = '';
1499 $this->mDTopen
= $inBlockElem = false;
1501 $paragraphStack = false;
1503 if ( !$linestart ) {
1504 $output .= array_shift( $textLines );
1506 foreach ( $textLines as $oLine ) {
1507 $lastPrefixLength = strlen( $lastPrefix );
1508 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1509 $preOpenMatch = preg_match('/<pre/i', $oLine );
1510 if ( !$this->mInPre
) {
1511 # Multiple prefixes may abut each other for nested lists.
1512 $prefixLength = strspn( $oLine, '*#:;' );
1513 $pref = substr( $oLine, 0, $prefixLength );
1516 $pref2 = str_replace( ';', ':', $pref );
1517 $t = substr( $oLine, $prefixLength );
1518 $this->mInPre
= !empty($preOpenMatch);
1520 # Don't interpret any other prefixes in preformatted text
1522 $pref = $pref2 = '';
1527 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1528 # Same as the last item, so no need to deal with nesting or opening stuff
1529 $output .= $this->nextItem( substr( $pref, -1 ) );
1530 $paragraphStack = false;
1532 if ( substr( $pref, -1 ) == ';') {
1533 # The one nasty exception: definition lists work like this:
1534 # ; title : definition text
1535 # So we check for : in the remainder text to split up the
1536 # title and definition, without b0rking links.
1537 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1539 $output .= $term . $this->nextItem( ':' );
1542 } elseif( $prefixLength ||
$lastPrefixLength ) {
1543 # Either open or close a level...
1544 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1545 $paragraphStack = false;
1547 while( $commonPrefixLength < $lastPrefixLength ) {
1548 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1549 --$lastPrefixLength;
1551 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1552 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1554 while ( $prefixLength > $commonPrefixLength ) {
1555 $char = substr( $pref, $commonPrefixLength, 1 );
1556 $output .= $this->openList( $char );
1558 if ( ';' == $char ) {
1559 # FIXME: This is dupe of code above
1560 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1562 $output .= $term . $this->nextItem( ':' );
1565 ++
$commonPrefixLength;
1567 $lastPrefix = $pref2;
1569 if( 0 == $prefixLength ) {
1570 wfProfileIn( "$fname-paragraph" );
1571 # No prefix (not in list)--go to paragraph mode
1572 $uniq_prefix = UNIQ_PREFIX
;
1573 // XXX: use a stack for nestable elements like span, table and div
1574 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1575 $closematch = preg_match(
1576 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1577 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1578 if ( $openmatch or $closematch ) {
1579 $paragraphStack = false;
1580 $output .= $this->closeParagraph();
1581 if($preOpenMatch and !$preCloseMatch) {
1582 $this->mInPre
= true;
1584 if ( $closematch ) {
1585 $inBlockElem = false;
1587 $inBlockElem = true;
1589 } else if ( !$inBlockElem && !$this->mInPre
) {
1590 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1592 if ($this->mLastSection
!= 'pre') {
1593 $paragraphStack = false;
1594 $output .= $this->closeParagraph().'<pre>';
1595 $this->mLastSection
= 'pre';
1597 $t = substr( $t, 1 );
1600 if ( '' == trim($t) ) {
1601 if ( $paragraphStack ) {
1602 $output .= $paragraphStack.'<br />';
1603 $paragraphStack = false;
1604 $this->mLastSection
= 'p';
1606 if ($this->mLastSection
!= 'p' ) {
1607 $output .= $this->closeParagraph();
1608 $this->mLastSection
= '';
1609 $paragraphStack = '<p>';
1611 $paragraphStack = '</p><p>';
1615 if ( $paragraphStack ) {
1616 $output .= $paragraphStack;
1617 $paragraphStack = false;
1618 $this->mLastSection
= 'p';
1619 } else if ($this->mLastSection
!= 'p') {
1620 $output .= $this->closeParagraph().'<p>';
1621 $this->mLastSection
= 'p';
1626 wfProfileOut( "$fname-paragraph" );
1628 if ($paragraphStack === false) {
1632 while ( $prefixLength ) {
1633 $output .= $this->closeList( $pref2{$prefixLength-1} );
1636 if ( '' != $this->mLastSection
) {
1637 $output .= '</' . $this->mLastSection
. '>';
1638 $this->mLastSection
= '';
1641 wfProfileOut( $fname );
1646 * Split up a string on ':', ignoring any occurences inside
1647 * <a>..</a> or <span>...</span>
1648 * @param string $str the string to split
1649 * @param string &$before set to everything before the ':'
1650 * @param string &$after set to everything after the ':'
1651 * return string the position of the ':', or false if none found
1653 function findColonNoLinks($str, &$before, &$after) {
1654 # I wonder if we should make this count all tags, not just <a>
1655 # and <span>. That would prevent us from matching a ':' that
1656 # comes in the middle of italics other such formatting....
1658 $fname = 'Parser::findColonNoLinks';
1659 wfProfileIn( $fname );
1662 $colon = strpos($str, ':', $pos);
1664 if ($colon !== false) {
1665 $before = substr($str, 0, $colon);
1666 $after = substr($str, $colon +
1);
1668 # Skip any ':' within <a> or <span> pairs
1669 $a = substr_count($before, '<a');
1670 $s = substr_count($before, '<span');
1671 $ca = substr_count($before, '</a>');
1672 $cs = substr_count($before, '</span>');
1674 if ($a <= $ca and $s <= $cs) {
1675 # Tags are balanced before ':'; ok
1680 } while ($colon !== false);
1681 wfProfileOut( $fname );
1686 * Return value of a magic variable (like PAGENAME)
1690 function getVariableValue( $index ) {
1691 global $wgContLang, $wgSitename, $wgServer;
1694 * Some of these require message or data lookups and can be
1695 * expensive to check many times.
1697 static $varCache = array();
1698 if( isset( $varCache[$index] ) ) return $varCache[$index];
1701 case MAG_CURRENTMONTH
:
1702 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1703 case MAG_CURRENTMONTHNAME
:
1704 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1705 case MAG_CURRENTMONTHNAMEGEN
:
1706 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1707 case MAG_CURRENTDAY
:
1708 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1710 return $this->mTitle
->getText();
1712 return $this->mTitle
->getPartialURL();
1714 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1715 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1716 case MAG_CURRENTDAYNAME
:
1717 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1718 case MAG_CURRENTYEAR
:
1719 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1720 case MAG_CURRENTTIME
:
1721 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1722 case MAG_CURRENTWEEK
:
1723 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1724 case MAG_CURRENTDOW
:
1725 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1726 case MAG_NUMBEROFARTICLES
:
1727 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1738 * initialise the magic variables (like CURRENTMONTHNAME)
1742 function initialiseVariables() {
1743 $fname = 'Parser::initialiseVariables';
1744 wfProfileIn( $fname );
1745 global $wgVariableIDs;
1746 $this->mVariables
= array();
1747 foreach ( $wgVariableIDs as $id ) {
1748 $mw =& MagicWord
::get( $id );
1749 $mw->addToArray( $this->mVariables
, $id );
1751 wfProfileOut( $fname );
1755 * Replace magic variables, templates, and template arguments
1756 * with the appropriate text. Templates are substituted recursively,
1757 * taking care to avoid infinite loops.
1759 * Note that the substitution depends on value of $mOutputType:
1760 * OT_WIKI: only {{subst:}} templates
1761 * OT_MSG: only magic variables
1762 * OT_HTML: all templates and magic variables
1764 * @param string $tex The text to transform
1765 * @param array $args Key-value pairs representing template parameters to substitute
1768 function replaceVariables( $text, $args = array() ) {
1769 global $wgLang, $wgScript, $wgArticlePath;
1771 # Prevent too big inclusions
1772 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1776 $fname = 'Parser::replaceVariables';
1777 wfProfileIn( $fname );
1779 $titleChars = Title
::legalChars();
1781 # This function is called recursively. To keep track of arguments we need a stack:
1782 array_push( $this->mArgStack
, $args );
1784 # Variable substitution
1785 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1787 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1788 # Argument substitution
1789 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1791 # Template substitution
1792 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1793 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1795 array_pop( $this->mArgStack
);
1797 wfProfileOut( $fname );
1802 * Replace magic variables
1805 function variableSubstitution( $matches ) {
1806 $fname = 'parser::variableSubstitution';
1807 $varname = $matches[1];
1808 wfProfileIn( $fname );
1809 if ( !$this->mVariables
) {
1810 $this->initialiseVariables();
1813 if ( $this->mOutputType
== OT_WIKI
) {
1814 # Do only magic variables prefixed by SUBST
1815 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1816 if (!$mwSubst->matchStartAndRemove( $varname ))
1818 # Note that if we don't substitute the variable below,
1819 # we don't remove the {{subst:}} magic word, in case
1820 # it is a template rather than a magic variable.
1822 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1823 $id = $this->mVariables
[$varname];
1824 $text = $this->getVariableValue( $id );
1825 $this->mOutput
->mContainsOldMagic
= true;
1827 $text = $matches[0];
1829 wfProfileOut( $fname );
1833 # Split template arguments
1834 function getTemplateArgs( $argsString ) {
1835 if ( $argsString === '' ) {
1839 $args = explode( '|', substr( $argsString, 1 ) );
1841 # If any of the arguments contains a '[[' but no ']]', it needs to be
1842 # merged with the next arg because the '|' character between belongs
1843 # to the link syntax and not the template parameter syntax.
1844 $argc = count($args);
1846 for ( $i = 0; $i < $argc-1; $i++
) {
1847 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1848 $args[$i] .= '|'.$args[$i+
1];
1849 array_splice($args, $i+
1, 1);
1859 * Return the text of a template, after recursively
1860 * replacing any variables or templates within the template.
1862 * @param array $matches The parts of the template
1863 * $matches[1]: the title, i.e. the part before the |
1864 * $matches[2]: the parameters (including a leading |), if any
1865 * @return string the text of the template
1868 function braceSubstitution( $matches ) {
1869 global $wgLinkCache, $wgContLang;
1870 $fname = 'Parser::braceSubstitution';
1871 wfProfileIn( $fname );
1879 # Need to know if the template comes at the start of a line,
1880 # to treat the beginning of the template like the beginning
1881 # of a line for tables and block-level elements.
1882 $linestart = $matches[1];
1884 # $part1 is the bit before the first |, and must contain only title characters
1885 # $args is a list of arguments, starting from index 0, not including $part1
1887 $part1 = $matches[2];
1888 # If the third subpattern matched anything, it will start with |
1890 $args = $this->getTemplateArgs($matches[3]);
1891 $argc = count( $args );
1893 # Don't parse {{{}}} because that's only for template arguments
1894 if ( $linestart === '{' ) {
1895 $text = $matches[0];
1902 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1903 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1904 # One of two possibilities is true:
1905 # 1) Found SUBST but not in the PST phase
1906 # 2) Didn't find SUBST and in the PST phase
1907 # In either case, return without further processing
1908 $text = $matches[0];
1914 # MSG, MSGNW and INT
1917 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1918 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1921 # Remove obsolete MSG:
1922 $mwMsg =& MagicWord
::get( MAG_MSG
);
1923 $mwMsg->matchStartAndRemove( $part1 );
1926 # Check if it is an internal message
1927 $mwInt =& MagicWord
::get( MAG_INT
);
1928 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1929 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1930 $text = $linestart . wfMsgReal( $part1, $args, true );
1938 # Check for NS: (namespace expansion)
1939 $mwNs = MagicWord
::get( MAG_NS
);
1940 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1941 if ( intval( $part1 ) ) {
1942 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1945 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1946 if ( !is_null( $index ) ) {
1947 $text = $linestart . $wgContLang->getNsText( $index );
1954 # LOCALURL and LOCALURLE
1956 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1957 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1959 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1960 $func = 'getLocalURL';
1961 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1962 $func = 'escapeLocalURL';
1967 if ( $func !== '' ) {
1968 $title = Title
::newFromText( $part1 );
1969 if ( !is_null( $title ) ) {
1971 $text = $linestart . $title->$func( $args[0] );
1973 $text = $linestart . $title->$func();
1981 if ( !$found && $argc == 1 ) {
1982 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1983 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1984 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1989 # Template table test
1991 # Did we encounter this template already? If yes, it is in the cache
1992 # and we need to check for loops.
1993 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
1994 # set $text to cached message.
1995 $text = $linestart . $this->mTemplates
[$part1];
1998 # Infinite loop test
1999 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2002 $text .= '<!-- WARNING: template loop detected -->';
2006 # Load from database
2007 $itcamefromthedatabase = false;
2010 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2011 if ($subpage !== '') {
2012 $ns = $this->mTitle
->getNamespace();
2014 $title = Title
::newFromText( $part1, $ns );
2015 if ( !is_null( $title ) && !$title->isExternal() ) {
2016 # Check for excessive inclusion
2017 $dbk = $title->getPrefixedDBkey();
2018 if ( $this->incrementIncludeCount( $dbk ) ) {
2019 # This should never be reached.
2020 $article = new Article( $title );
2021 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2022 if ( $articleContent !== false ) {
2024 $text = $linestart . $articleContent;
2025 $itcamefromthedatabase = true;
2029 # If the title is valid but undisplayable, make a link to it
2030 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2031 $text = $linestart . '[['.$title->getPrefixedText().']]';
2035 # Template cache array insertion
2037 $this->mTemplates
[$part1] = $text;
2042 # Recursive parsing, escaping and link table handling
2043 # Only for HTML output
2044 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2045 $text = wfEscapeWikiText( $text );
2046 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2047 # Clean up argument array
2048 $assocArgs = array();
2050 foreach( $args as $arg ) {
2051 $eqpos = strpos( $arg, '=' );
2052 if ( $eqpos === false ) {
2053 $assocArgs[$index++
] = $arg;
2055 $name = trim( substr( $arg, 0, $eqpos ) );
2056 $value = trim( substr( $arg, $eqpos+
1 ) );
2057 if ( $value === false ) {
2060 if ( $name !== false ) {
2061 $assocArgs[$name] = $value;
2066 # Add a new element to the templace recursion path
2067 $this->mTemplatePath
[$part1] = 1;
2069 $text = $this->strip( $text, $this->mStripState
);
2070 $text = Sanitizer
::removeHTMLtags( $text );
2071 $text = $this->replaceVariables( $text, $assocArgs );
2073 # Resume the link cache and register the inclusion as a link
2074 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2075 $wgLinkCache->addLinkObj( $title );
2078 # If the template begins with a table or block-level
2079 # element, it should be treated as beginning a new line.
2080 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2081 $text = "\n" . $text;
2085 # Empties the template path
2086 $this->mTemplatePath
= array();
2088 wfProfileOut( $fname );
2091 # replace ==section headers==
2092 # XXX this needs to go away once we have a better parser.
2093 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2094 if( !is_null( $title ) )
2095 $encodedname = base64_encode($title->getPrefixedDBkey());
2097 $encodedname = base64_encode("");
2098 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2099 PREG_SPLIT_DELIM_CAPTURE
);
2102 for( $i = 0; $i < count($m); $i +
= 2 ) {
2104 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2106 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2110 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2111 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2112 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2119 # Empties the template path
2120 $this->mTemplatePath
= array();
2123 wfProfileOut( $fname );
2126 wfProfileOut( $fname );
2132 * Triple brace replacement -- used for template arguments
2135 function argSubstitution( $matches ) {
2136 $arg = trim( $matches[1] );
2137 $text = $matches[0];
2138 $inputArgs = end( $this->mArgStack
);
2140 if ( array_key_exists( $arg, $inputArgs ) ) {
2141 $text = $inputArgs[$arg];
2148 * Returns true if the function is allowed to include this entity
2151 function incrementIncludeCount( $dbk ) {
2152 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2153 $this->mIncludeCount
[$dbk] = 0;
2155 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2163 * This function accomplishes several tasks:
2164 * 1) Auto-number headings if that option is enabled
2165 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2166 * 3) Add a Table of contents on the top for users who have enabled the option
2167 * 4) Auto-anchor headings
2169 * It loops through all headlines, collects the necessary data, then splits up the
2170 * string and re-inserts the newly formatted headlines.
2172 * @param string $text
2173 * @param boolean $isMain
2176 function formatHeadings( $text, $isMain=true ) {
2177 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2179 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2180 $doShowToc = $this->mOptions
->getShowToc();
2181 $forceTocHere = false;
2182 if( !$this->mTitle
->userCanEdit() ) {
2184 $rightClickHack = 0;
2186 $showEditLink = $this->mOptions
->getEditSection();
2187 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2190 # Inhibit editsection links if requested in the page
2191 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2192 if( $esw->matchAndRemove( $text ) ) {
2195 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2197 $mw =& MagicWord
::get( MAG_NOTOC
);
2198 if( $mw->matchAndRemove( $text ) ) {
2202 # never add the TOC to the Main Page. This is an entry page that should not
2203 # be more than 1-2 screens large anyway
2204 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2208 # Get all headlines for numbering them and adding funky stuff like [edit]
2209 # links - this is for later, but we need the number of headlines right now
2210 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2212 # if there are fewer than 4 headlines in the article, do not show TOC
2213 if( $numMatches < 4 ) {
2217 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2218 # override above conditions and always show TOC at that place
2220 $mw =& MagicWord
::get( MAG_TOC
);
2221 if($mw->match( $text ) ) {
2223 $forceTocHere = true;
2225 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2226 # override above conditions and always show TOC above first header
2227 $mw =& MagicWord
::get( MAG_FORCETOC
);
2228 if ($mw->matchAndRemove( $text ) ) {
2233 # Never ever show TOC if no headers
2234 if( $numMatches < 1 ) {
2238 # We need this to perform operations on the HTML
2239 $sk =& $this->mOptions
->getSkin();
2243 $sectionCount = 0; # headlineCount excluding template sections
2245 # Ugh .. the TOC should have neat indentation levels which can be
2246 # passed to the skin functions. These are determined here
2250 $sublevelCount = array();
2251 $levelCount = array();
2258 foreach( $matches[3] as $headline ) {
2260 $templatetitle = '';
2261 $templatesection = 0;
2264 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2266 $templatetitle = base64_decode($mat[1]);
2267 $templatesection = 1 +
(int)base64_decode($mat[2]);
2268 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2272 $prevlevel = $level;
2273 $prevtoclevel = $toclevel;
2275 $level = $matches[1][$headlineCount];
2277 if( $doNumberHeadings ||
$doShowToc ) {
2279 if ( $level > $prevlevel ) {
2280 # Increase TOC level
2282 $sublevelCount[$toclevel] = 0;
2283 $toc .= $sk->tocIndent();
2285 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2286 # Decrease TOC level, find level to jump to
2288 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2289 # Can only go down to level 1
2292 for ($i = $toclevel; $i > 0; $i--) {
2293 if ( $levelCount[$i] == $level ) {
2294 # Found last matching level
2298 elseif ( $levelCount[$i] < $level ) {
2299 # Found first matching level below current level
2306 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2309 # No change in level, end TOC line
2310 $toc .= $sk->tocLineEnd();
2313 $levelCount[$toclevel] = $level;
2315 # count number of headlines for each level
2316 @$sublevelCount[$toclevel]++
;
2318 for( $i = 1; $i <= $toclevel; $i++
) {
2319 if( !empty( $sublevelCount[$i] ) ) {
2323 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2329 # The canonized header is a version of the header text safe to use for links
2330 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2331 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2332 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2334 # Remove link placeholders by the link text.
2335 # <!--LINK number-->
2337 # link text with suffix
2338 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2339 "\$wgLinkHolders['texts'][\$1]",
2340 $canonized_headline );
2341 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2342 "\$wgInterwikiLinkHolders[\$1]",
2343 $canonized_headline );
2346 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2347 $tocline = trim( $canonized_headline );
2348 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2349 $replacearray = array(
2353 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2354 $refer[$headlineCount] = $canonized_headline;
2356 # count how many in assoc. array so we can track dupes in anchors
2357 @$refers[$canonized_headline]++
;
2358 $refcount[$headlineCount]=$refers[$canonized_headline];
2360 # Don't number the heading if it is the only one (looks silly)
2361 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2362 # the two are different if the line contains a link
2363 $headline=$numbering . ' ' . $headline;
2366 # Create the anchor for linking from the TOC to the section
2367 $anchor = $canonized_headline;
2368 if($refcount[$headlineCount] > 1 ) {
2369 $anchor .= '_' . $refcount[$headlineCount];
2371 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2372 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2374 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2375 if ( empty( $head[$headlineCount] ) ) {
2376 $head[$headlineCount] = '';
2379 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2381 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2384 # Add the edit section span
2385 if( $rightClickHack ) {
2387 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2389 $headline = $sk->editSectionScript($this->mTitle
, $sectionCount+
1,$headline);
2392 # give headline the correct <h#> tag
2393 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2401 $toclines = $headlineCount;
2402 $toc .= $sk->tocUnindent( $toclevel - 1 );
2403 $toc = $sk->tocList( $toc );
2406 # split up and insert constructed headlines
2408 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2411 foreach( $blocks as $block ) {
2412 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2413 # This is the [edit] link that appears for the top block of text when
2414 # section editing is enabled
2416 # Disabled because it broke block formatting
2417 # For example, a bullet point in the top line
2418 # $full .= $sk->editSectionLink(0);
2421 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2422 # Top anchor now in skin
2426 if( !empty( $head[$i] ) ) {
2432 $mw =& MagicWord
::get( MAG_TOC
);
2433 return $mw->replace( $toc, $full );
2440 * Return an HTML link for the "ISBN 123456" text
2443 function magicISBN( $text ) {
2445 $fname = 'Parser::magicISBN';
2446 wfProfileIn( $fname );
2448 $a = split( 'ISBN ', ' '.$text );
2449 if ( count ( $a ) < 2 ) {
2450 wfProfileOut( $fname );
2453 $text = substr( array_shift( $a ), 1);
2454 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2456 foreach ( $a as $x ) {
2457 $isbn = $blank = '' ;
2458 while ( ' ' == $x{0} ) {
2460 $x = substr( $x, 1 );
2462 if ( $x == '' ) { # blank isbn
2463 $text .= "ISBN $blank";
2466 while ( strstr( $valid, $x{0} ) != false ) {
2468 $x = substr( $x, 1 );
2470 $num = str_replace( '-', '', $isbn );
2471 $num = str_replace( ' ', '', $num );
2474 $text .= "ISBN $blank$x";
2476 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2477 $text .= '<a href="' .
2478 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2479 "\" class=\"internal\">ISBN $isbn</a>";
2483 wfProfileOut( $fname );
2488 * Return an HTML link for the "GEO ..." text
2491 function magicGEO( $text ) {
2492 global $wgLang, $wgUseGeoMode;
2493 $fname = 'Parser::magicGEO';
2494 wfProfileIn( $fname );
2496 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2497 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2498 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2499 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2500 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2501 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2503 $a = split( 'GEO ', ' '.$text );
2504 if ( count ( $a ) < 2 ) {
2505 wfProfileOut( $fname );
2508 $text = substr( array_shift( $a ), 1);
2509 $valid = '0123456789.+-:';
2511 foreach ( $a as $x ) {
2512 $geo = $blank = '' ;
2513 while ( ' ' == $x{0} ) {
2515 $x = substr( $x, 1 );
2517 while ( strstr( $valid, $x{0} ) != false ) {
2519 $x = substr( $x, 1 );
2521 $num = str_replace( '+', '', $geo );
2522 $num = str_replace( ' ', '', $num );
2524 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2525 $text .= "GEO $blank$x";
2527 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2528 $text .= '<a href="' .
2529 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2530 "\" class=\"internal\">GEO $geo</a>";
2534 wfProfileOut( $fname );
2539 * Return an HTML link for the "RFC 1234" text
2541 * @param string $text text to be processed
2543 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2546 $valid = '0123456789';
2549 $a = split( $keyword, ' '.$text );
2550 if ( count ( $a ) < 2 ) {
2553 $text = substr( array_shift( $a ), 1);
2555 /* Check if keyword is preceed by [[.
2556 * This test is made here cause of the array_shift above
2557 * that prevent the test to be done in the foreach.
2559 if ( substr( $text, -2 ) == '[[' ) {
2563 foreach ( $a as $x ) {
2564 /* token might be empty if we have RFC RFC 1234 */
2572 /** remove and save whitespaces in $blank */
2573 while ( $x{0} == ' ' ) {
2575 $x = substr( $x, 1 );
2578 /** remove and save the rfc number in $id */
2579 while ( strstr( $valid, $x{0} ) != false ) {
2581 $x = substr( $x, 1 );
2585 /* call back stripped spaces*/
2586 $text .= $keyword.$blank.$x;
2587 } elseif( $internal ) {
2589 $text .= $keyword.$id.$x;
2591 /* build the external link*/
2592 $url = wfmsg( $urlmsg );
2593 $url = str_replace( '$1', $id, $url);
2594 $sk =& $this->mOptions
->getSkin();
2595 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2596 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2599 /* Check if the next RFC keyword is preceed by [[ */
2600 $internal = ( substr($x,-2) == '[[' );
2606 * Transform wiki markup when saving a page by doing \r\n -> \n
2607 * conversion, substitting signatures, {{subst:}} templates, etc.
2609 * @param string $text the text to transform
2610 * @param Title &$title the Title object for the current article
2611 * @param User &$user the User object describing the current user
2612 * @param ParserOptions $options parsing options
2613 * @param bool $clearState whether to clear the parser state first
2614 * @return string the altered wiki markup
2617 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2618 $this->mOptions
= $options;
2619 $this->mTitle
=& $title;
2620 $this->mOutputType
= OT_WIKI
;
2622 if ( $clearState ) {
2623 $this->clearState();
2626 $stripState = false;
2630 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2631 $text = $this->strip( $text, $stripState, false );
2632 $text = $this->pstPass2( $text, $user );
2633 $text = $this->unstrip( $text, $stripState );
2634 $text = $this->unstripNoWiki( $text, $stripState );
2639 * Pre-save transform helper function
2642 function pstPass2( $text, &$user ) {
2643 global $wgLang, $wgContLang, $wgLocaltimezone;
2645 # Variable replacement
2646 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2647 $text = $this->replaceVariables( $text );
2651 $n = $user->getName();
2652 $k = $user->getOption( 'nickname' );
2653 if ( '' == $k ) { $k = $n; }
2654 if ( isset( $wgLocaltimezone ) ) {
2655 $oldtz = getenv( 'TZ' );
2656 putenv( 'TZ='.$wgLocaltimezone );
2658 /* Note: this is an ugly timezone hack for the European wikis */
2659 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2660 ' (' . date( 'T' ) . ')';
2661 if ( isset( $wgLocaltimezone ) ) {
2662 putenv( 'TZ='.$oldtzs );
2665 if( $user->getOption( 'fancysig' ) ) {
2668 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2670 $text = preg_replace( '/~~~~~/', $d, $text );
2671 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2672 $text = preg_replace( '/~~~/', $sigText, $text );
2674 # Context links: [[|name]] and [[name (context)|]]
2676 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2677 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2678 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2679 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2681 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2682 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2683 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2684 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2686 $t = $this->mTitle
->getText();
2687 if ( preg_match( $conpat, $t, $m ) ) {
2690 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2691 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2692 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2694 if ( '' == $context ) {
2695 $text = preg_replace( $p2, '[[\\1]]', $text );
2697 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2700 # Trim trailing whitespace
2701 # MAG_END (__END__) tag allows for trailing
2702 # whitespace to be deliberately included
2703 $text = rtrim( $text );
2704 $mw =& MagicWord
::get( MAG_END
);
2705 $mw->matchAndRemove( $text );
2711 * Set up some variables which are usually set up in parse()
2712 * so that an external function can call some class members with confidence
2715 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2716 $this->mTitle
=& $title;
2717 $this->mOptions
= $options;
2718 $this->mOutputType
= $outputType;
2719 if ( $clearState ) {
2720 $this->clearState();
2725 * Transform a MediaWiki message by replacing magic variables.
2727 * @param string $text the text to transform
2728 * @param ParserOptions $options options
2729 * @return string the text with variables substituted
2732 function transformMsg( $text, $options ) {
2734 static $executing = false;
2736 # Guard against infinite recursion
2742 $this->mTitle
= $wgTitle;
2743 $this->mOptions
= $options;
2744 $this->mOutputType
= OT_MSG
;
2745 $this->clearState();
2746 $text = $this->replaceVariables( $text );
2753 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2754 * Callback will be called with the text within
2755 * Transform and return the text within
2758 function setHook( $tag, $callback ) {
2759 $oldVal = @$this->mTagHooks
[$tag];
2760 $this->mTagHooks
[$tag] = $callback;
2765 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2766 * Placeholders created in Skin::makeLinkObj()
2767 * Returns an array of links found, indexed by PDBK:
2771 * $options is a bit field, RLH_FOR_UPDATE to select for update
2773 function replaceLinkHolders( &$text, $options = 0 ) {
2774 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2775 global $wgInterwikiLinkHolders;
2776 global $outputReplace;
2778 if ( $wgUseOldExistenceCheck ) {
2782 $fname = 'Parser::replaceLinkHolders';
2783 wfProfileIn( $fname );
2788 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2789 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2790 wfProfileIn( $fname.'-check' );
2791 $dbr =& wfGetDB( DB_SLAVE
);
2792 $page = $dbr->tableName( 'page' );
2793 $sk = $wgUser->getSkin();
2794 $threshold = $wgUser->getOption('stubthreshold');
2797 asort( $wgLinkHolders['namespaces'] );
2801 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2803 $title = $wgLinkHolders['titles'][$key];
2805 # Skip invalid entries.
2806 # Result will be ugly, but prevents crash.
2807 if ( is_null( $title ) ) {
2810 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2812 # Check if it's in the link cache already
2813 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2814 $colours[$pdbk] = 1;
2815 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2816 $colours[$pdbk] = 0;
2818 # Not in the link cache, add it to the query
2819 if ( !isset( $current ) ) {
2823 $query = "SELECT page_id, page_namespace, page_title";
2824 if ( $threshold > 0 ) {
2825 $textTable = $dbr->tableName( 'text' );
2826 $query .= ', LENGTH(old_text) AS page_len, page_is_redirect';
2827 $tables .= ", $textTable";
2828 $join = 'page_latest=old_id AND';
2830 $query .= " FROM $tables WHERE $join (page_namespace=$val AND page_title IN(";
2831 } elseif ( $current != $val ) {
2833 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2838 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2843 if ( $options & RLH_FOR_UPDATE
) {
2844 $query .= ' FOR UPDATE';
2847 $res = $dbr->query( $query, $fname );
2849 # Fetch data and form into an associative array
2850 # non-existent = broken
2853 while ( $s = $dbr->fetchObject($res) ) {
2854 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2855 $pdbk = $title->getPrefixedDBkey();
2856 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2858 if ( $threshold > 0 ) {
2859 $size = $s->page_len
;
2860 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$length < $threshold ) {
2861 $colours[$pdbk] = 1;
2863 $colours[$pdbk] = 2;
2866 $colours[$pdbk] = 1;
2870 wfProfileOut( $fname.'-check' );
2872 # Construct search and replace arrays
2873 wfProfileIn( $fname.'-construct' );
2874 $outputReplace = array();
2875 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2876 $pdbk = $pdbks[$key];
2877 $searchkey = '<!--LINK '.$key.'-->';
2878 $title = $wgLinkHolders['titles'][$key];
2879 if ( empty( $colours[$pdbk] ) ) {
2880 $wgLinkCache->addBadLink( $pdbk );
2881 $colours[$pdbk] = 0;
2882 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2883 $wgLinkHolders['texts'][$key],
2884 $wgLinkHolders['queries'][$key] );
2885 } elseif ( $colours[$pdbk] == 1 ) {
2886 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2887 $wgLinkHolders['texts'][$key],
2888 $wgLinkHolders['queries'][$key] );
2889 } elseif ( $colours[$pdbk] == 2 ) {
2890 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2891 $wgLinkHolders['texts'][$key],
2892 $wgLinkHolders['queries'][$key] );
2895 wfProfileOut( $fname.'-construct' );
2898 wfProfileIn( $fname.'-replace' );
2900 $text = preg_replace_callback(
2901 '/(<!--LINK .*?-->)/',
2902 "outputReplaceMatches",
2904 wfProfileOut( $fname.'-replace' );
2907 if ( !empty( $wgInterwikiLinkHolders ) ) {
2908 wfProfileIn( $fname.'-interwiki' );
2909 $outputReplace = $wgInterwikiLinkHolders;
2910 $text = preg_replace_callback(
2911 '/<!--IWLINK (.*?)-->/',
2912 "outputReplaceMatches",
2914 wfProfileOut( $fname.'-interwiki' );
2917 wfProfileOut( $fname );
2922 * Renders an image gallery from a text with one line per image.
2923 * text labels may be given by using |-style alternative text. E.g.
2924 * Image:one.jpg|The number "1"
2925 * Image:tree.jpg|A tree
2926 * given as text will return the HTML of a gallery with two images,
2927 * labeled 'The number "1"' and
2930 function renderImageGallery( $text ) {
2931 global $wgLinkCache;
2932 $ig = new ImageGallery();
2933 $ig->setShowBytes( false );
2934 $ig->setShowFilename( false );
2935 $lines = explode( "\n", $text );
2937 foreach ( $lines as $line ) {
2938 # match lines like these:
2939 # Image:someimage.jpg|This is some image
2940 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2942 if ( count( $matches ) == 0 ) {
2945 $nt = Title
::newFromURL( $matches[1] );
2946 if( is_null( $nt ) ) {
2947 # Bogus title. Ignore these so we don't bomb out later.
2950 if ( isset( $matches[3] ) ) {
2951 $label = $matches[3];
2956 # FIXME: Use the full wiki parser and add its links
2957 # to the page's links.
2958 $html = $this->mOptions
->mSkin
->formatComment( $label );
2960 $ig->add( Image
::newFromTitle( $nt ), $html );
2961 $wgLinkCache->addImageLinkObj( $nt );
2963 return $ig->toHTML();
2969 * @package MediaWiki
2973 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2974 var $mCacheTime; # Used in ParserCache
2975 var $mVersion; # Compatibility check
2977 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2978 $containsOldMagic = false )
2980 $this->mText
= $text;
2981 $this->mLanguageLinks
= $languageLinks;
2982 $this->mCategoryLinks
= $categoryLinks;
2983 $this->mContainsOldMagic
= $containsOldMagic;
2984 $this->mCacheTime
= '';
2985 $this->mVersion
= MW_PARSER_VERSION
;
2988 function getText() { return $this->mText
; }
2989 function getLanguageLinks() { return $this->mLanguageLinks
; }
2990 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
2991 function getCacheTime() { return $this->mCacheTime
; }
2992 function containsOldMagic() { return $this->mContainsOldMagic
; }
2993 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2994 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2995 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2996 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2997 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2998 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3000 function merge( $other ) {
3001 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3002 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3003 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3007 * Return true if this cached output object predates the global or
3008 * per-article cache invalidation timestamps, or if it comes from
3009 * an incompatible older version.
3011 * @param string $touched the affected article's last touched timestamp
3015 function expired( $touched ) {
3016 global $wgCacheEpoch;
3017 return $this->getCacheTime() <= $touched ||
3018 $this->getCacheTime() <= $wgCacheEpoch ||
3019 !isset( $this->mVersion
) ||
3020 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3025 * Set options of the Parser
3027 * @package MediaWiki
3031 # All variables are private
3032 var $mUseTeX; # Use texvc to expand <math> tags
3033 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3034 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3035 var $mAllowExternalImages; # Allow external images inline
3036 var $mSkin; # Reference to the preferred skin
3037 var $mDateFormat; # Date format index
3038 var $mEditSection; # Create "edit section" links
3039 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3040 var $mNumberHeadings; # Automatically number headings
3041 var $mShowToc; # Show table of contents
3043 function getUseTeX() { return $this->mUseTeX
; }
3044 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3045 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3046 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3047 function getSkin() { return $this->mSkin
; }
3048 function getDateFormat() { return $this->mDateFormat
; }
3049 function getEditSection() { return $this->mEditSection
; }
3050 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
3051 function getNumberHeadings() { return $this->mNumberHeadings
; }
3052 function getShowToc() { return $this->mShowToc
; }
3054 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3055 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3056 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3057 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3058 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3059 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3060 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
3061 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3062 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
3064 function setSkin( &$x ) { $this->mSkin
=& $x; }
3067 * Get parser options
3070 function newFromUser( &$user ) {
3071 $popts = new ParserOptions
;
3072 $popts->initialiseFromUser( $user );
3076 /** Get user options */
3077 function initialiseFromUser( &$userInput ) {
3078 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3079 $fname = 'ParserOptions::initialiseFromUser';
3080 wfProfileIn( $fname );
3081 if ( !$userInput ) {
3083 $user->setLoaded( true );
3085 $user =& $userInput;
3088 $this->mUseTeX
= $wgUseTeX;
3089 $this->mUseDynamicDates
= $wgUseDynamicDates;
3090 $this->mInterwikiMagic
= $wgInterwikiMagic;
3091 $this->mAllowExternalImages
= $wgAllowExternalImages;
3092 wfProfileIn( $fname.'-skin' );
3093 $this->mSkin
=& $user->getSkin();
3094 wfProfileOut( $fname.'-skin' );
3095 $this->mDateFormat
= $user->getOption( 'date' );
3096 $this->mEditSection
= $user->getOption( 'editsection' );
3097 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
3098 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3099 $this->mShowToc
= $user->getOption( 'showtoc' );
3100 wfProfileOut( $fname );
3105 * Callback function used by Parser::replaceLinkHolders()
3106 * to substitute link placeholders.
3108 function &outputReplaceMatches( $matches ) {
3109 global $outputReplace;
3110 return $outputReplace[$matches[1]];
3114 * Return the total number of articles
3116 function wfNumberOfArticles() {
3117 global $wgNumberOfArticles;
3120 return $wgNumberOfArticles;
3124 * Get various statistics from the database
3127 function wfLoadSiteStats() {
3128 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3129 $fname = 'wfLoadSiteStats';
3131 if ( -1 != $wgNumberOfArticles ) return;
3132 $dbr =& wfGetDB( DB_SLAVE
);
3133 $s = $dbr->selectRow( 'site_stats',
3134 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3135 array( 'ss_row_id' => 1 ), $fname
3138 if ( $s === false ) {
3141 $wgTotalViews = $s->ss_total_views
;
3142 $wgTotalEdits = $s->ss_total_edits
;
3143 $wgNumberOfArticles = $s->ss_good_articles
;
3149 * Basicly replacing " > and < with HTML entities ( ", >, <)
3151 * @param string $in Text that might contain HTML tags
3152 * @return string Escaped string
3154 function wfEscapeHTMLTagsOnly( $in ) {
3156 array( '"', '>', '<' ),
3157 array( '"', '>', '<' ),