3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
13 * Update this version number when the ParserOutput format
14 * changes in an incompatible way, so the parser cache
15 * can automatically discard old data.
17 define( 'MW_PARSER_VERSION', '1.5.0' );
20 * Variable substitution O(N^2) attack
22 * Without countermeasures, it would be possible to attack the parser by saving
23 * a page filled with a large number of inclusions of large pages. The size of
24 * the generated page would be proportional to the square of the input size.
25 * Hence, we limit the number of inclusions of any given page, thus bringing any
26 * attack back to O(N).
29 define( 'MAX_INCLUDE_REPEAT', 100 );
30 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32 define( 'RLH_FOR_UPDATE', 1 );
34 # Allowed values for $mOutputType
35 define( 'OT_HTML', 1 );
36 define( 'OT_WIKI', 2 );
37 define( 'OT_MSG' , 3 );
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45 # prefix for escaping, used in two functions at least
46 define( 'UNIQ_PREFIX', 'NaodW29');
48 # Constants needed for external link processing
49 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
50 define( 'HTTP_PROTOCOLS', 'http|https' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
106 var $mOptions, $mTitle, $mOutputType,
107 $mTemplates, // cache of already loaded templates, avoids
108 // multiple SQL queries for the same string
109 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
110 // in this path. Used for loop detection.
120 $this->mTemplates
= array();
121 $this->mTemplatePath
= array();
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
144 * First pass--just handle <nowiki> sections, pass the rest off
145 * to internalParse() which does all the real work.
148 * @param string $text Text we want to parse
149 * @param Title &$title A title object
150 * @param array $options
151 * @param boolean $linestart
152 * @param boolean $clearState
153 * @return ParserOutput a ParserOutput
155 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
156 global $wgUseTidy, $wgContLang;
157 $fname = 'Parser::parse';
158 wfProfileIn( $fname );
164 $this->mOptions
= $options;
165 $this->mTitle
=& $title;
166 $this->mOutputType
= OT_HTML
;
169 global $fnord; $fnord = 1;
170 //$text = $this->strip( $text, $this->mStripState );
171 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
172 $x =& $this->mStripState
;
173 $text = $this->strip( $text, $x );
175 $text = $this->internalParse( $text, $linestart );
177 $dashReplace = array(
178 '/ - /' => " – ", # N dash
179 '/(?<=[0-9])-(?=[0-9])/' => "–", # N dash between numbers
180 '/ -- /' => " — " # M dash
182 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
185 $text = $this->unstrip( $text, $this->mStripState
);
187 # Clean up special characters, only run once, next-to-last before doBlockLevels
189 # french spaces, last one Guillemet-left
190 # only if there is something before the space
191 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
192 # french spaces, Guillemet-right
193 '/(\\302\\253) /' => '\\1 ',
194 '/<hr *>/i' => '<hr />',
195 '/<br *>/i' => '<br />',
196 '/<center *>/i' => '<div class="center">',
197 '/<\\/center *>/i' => '</div>',
199 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
200 $text = Sanitizer
::normalizeCharReferences( $text );
203 $text = $this->doBlockLevels( $text, $linestart );
205 $this->replaceLinkHolders( $text );
206 $text = $wgContLang->convert($text);
207 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
208 $text = $this->unstripNoWiki( $text, $this->mStripState
);
212 $text = Parser
::tidy($text);
215 $this->mOutput
->setText( $text );
216 wfProfileOut( $fname );
217 return $this->mOutput
;
221 * Get a random string
226 function getRandomString() {
227 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
231 * Replaces all occurrences of <$tag>content</$tag> in the text
232 * with a random marker and returns the new text. the output parameter
233 * $content will be an associative array filled with data on the form
234 * $unique_marker => content.
236 * If $content is already set, the additional entries will be appended
237 * If $tag is set to STRIP_COMMENTS, the function will extract
238 * <!-- HTML comments -->
243 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
244 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
251 while ( '' != $text ) {
252 if($tag==STRIP_COMMENTS
) {
253 $p = preg_split( '/<!--/', $text, 2 );
255 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
258 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
261 if($tag==STRIP_COMMENTS
) {
262 $q = preg_split( '/-->/i', $p[1], 2 );
264 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
266 $marker = $rnd . sprintf('%08X', $n++
);
267 $content[$marker] = $q[0];
268 $stripped .= $marker;
276 * Strips and renders nowiki, pre, math, hiero
277 * If $render is set, performs necessary rendering operations on plugins
278 * Returns the text, and fills an array with data needed in unstrip()
279 * If the $state is already a valid strip state, it adds to the state
281 * @param bool $stripcomments when set, HTML comments <!-- like this -->
282 * will be stripped in addition to other tags. This is important
283 * for section editing, where these comments cause confusion when
284 * counting the sections in the wikisource
288 function strip( $text, &$state, $stripcomments = false ) {
289 $render = ($this->mOutputType
== OT_HTML
);
290 $html_content = array();
291 $nowiki_content = array();
292 $math_content = array();
293 $pre_content = array();
294 $comment_content = array();
295 $ext_content = array();
296 $gallery_content = array();
298 # Replace any instances of the placeholders
299 $uniq_prefix = UNIQ_PREFIX
;
300 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
303 global $wgRawHtml, $wgWhitelistEdit;
304 if( $wgRawHtml && $wgWhitelistEdit ) {
305 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
306 foreach( $html_content as $marker => $content ) {
308 # Raw and unchecked for validity.
309 $html_content[$marker] = $content;
311 $html_content[$marker] = '<html>'.$content.'</html>';
317 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
318 foreach( $nowiki_content as $marker => $content ) {
320 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
322 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
327 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
328 foreach( $math_content as $marker => $content ){
330 if( $this->mOptions
->getUseTeX() ) {
331 $math_content[$marker] = renderMath( $content );
333 $math_content[$marker] = '<math>'.$content.'<math>';
336 $math_content[$marker] = '<math>'.$content.'</math>';
341 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
342 foreach( $pre_content as $marker => $content ){
344 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
346 $pre_content[$marker] = '<pre>'.$content.'</pre>';
351 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
352 foreach( $gallery_content as $marker => $content ) {
353 require_once( 'ImageGallery.php' );
355 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
357 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
363 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
364 foreach( $comment_content as $marker => $content ){
365 $comment_content[$marker] = '<!--'.$content.'-->';
370 foreach ( $this->mTagHooks
as $tag => $callback ) {
371 $ext_contents[$tag] = array();
372 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
373 foreach( $ext_content[$tag] as $marker => $content ) {
375 $ext_content[$tag][$marker] = $callback( $content );
377 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
382 # Merge state with the pre-existing state, if there is one
384 $state['html'] = $state['html'] +
$html_content;
385 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
386 $state['math'] = $state['math'] +
$math_content;
387 $state['pre'] = $state['pre'] +
$pre_content;
388 $state['comment'] = $state['comment'] +
$comment_content;
389 $state['gallery'] = $state['gallery'] +
$gallery_content;
391 foreach( $ext_content as $tag => $array ) {
392 if ( array_key_exists( $tag, $state ) ) {
393 $state[$tag] = $state[$tag] +
$array;
398 'html' => $html_content,
399 'nowiki' => $nowiki_content,
400 'math' => $math_content,
401 'pre' => $pre_content,
402 'comment' => $comment_content,
403 'gallery' => $gallery_content,
410 * restores pre, math, and hiero removed by strip()
412 * always call unstripNoWiki() after this one
415 function unstrip( $text, &$state ) {
416 # Must expand in reverse order, otherwise nested tags will be corrupted
417 $contentDict = end( $state );
418 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
419 if( key($state) != 'nowiki' && key($state) != 'html') {
420 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
421 $text = str_replace( key( $contentDict ), $content, $text );
430 * always call this after unstrip() to preserve the order
434 function unstripNoWiki( $text, &$state ) {
435 # Must expand in reverse order, otherwise nested tags will be corrupted
436 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
437 $text = str_replace( key( $state['nowiki'] ), $content, $text );
442 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
443 $text = str_replace( key( $state['html'] ), $content, $text );
451 * Add an item to the strip state
452 * Returns the unique tag which must be inserted into the stripped text
453 * The tag will be replaced with the original text in unstrip()
457 function insertStripItem( $text, &$state ) {
458 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
467 $state['item'][$rnd] = $text;
472 * Interface with html tidy, used if $wgUseTidy = true.
473 * If tidy isn't able to correct the markup, the original will be
474 * returned in all its glory with a warning comment appended.
476 * Either the external tidy program or the in-process tidy extension
477 * will be used depending on availability. Override the default
478 * $wgTidyInternal setting to disable the internal if it's not working.
480 * @param string $text Hideous HTML input
481 * @return string Corrected HTML output
485 function tidy( $text ) {
486 global $wgTidyInternal;
487 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
488 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
489 '<head><title>test</title></head><body>'.$text.'</body></html>';
490 if( $wgTidyInternal ) {
491 $correctedtext = Parser
::internalTidy( $wrappedtext );
493 $correctedtext = Parser
::externalTidy( $wrappedtext );
495 if( is_null( $correctedtext ) ) {
496 wfDebug( "Tidy error detected!\n" );
497 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
499 return $correctedtext;
503 * Spawn an external HTML tidy process and get corrected markup back from it.
508 function externalTidy( $text ) {
509 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
510 $fname = 'Parser::externalTidy';
511 wfProfileIn( $fname );
516 $descriptorspec = array(
517 0 => array('pipe', 'r'),
518 1 => array('pipe', 'w'),
519 2 => array('file', '/dev/null', 'a')
521 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
522 if (is_resource($process)) {
523 fwrite($pipes[0], $text);
525 while (!feof($pipes[1])) {
526 $cleansource .= fgets($pipes[1], 1024);
529 $return_value = proc_close($process);
532 wfProfileOut( $fname );
534 if( $cleansource == '' && $text != '') {
535 // Some kind of error happened, so we couldn't get the corrected text.
536 // Just give up; we'll use the source text and append a warning.
544 * Use the HTML tidy PECL extension to use the tidy library in-process,
545 * saving the overhead of spawning a new process. Currently written to
546 * the PHP 4.3.x version of the extension, may not work on PHP 5.
548 * 'pear install tidy' should be able to compile the extension module.
553 function internalTidy( $text ) {
555 $fname = 'Parser::internalTidy';
556 wfProfileIn( $fname );
558 tidy_load_config( $wgTidyConf );
559 tidy_set_encoding( 'utf8' );
560 tidy_parse_string( $text );
562 if( tidy_get_status() == 2 ) {
563 // 2 is magic number for fatal error
564 // http://www.php.net/manual/en/function.tidy-get-status.php
567 $cleansource = tidy_get_output();
569 wfProfileOut( $fname );
574 * parse the wiki syntax used to render tables
578 function doTableStuff ( $t ) {
579 $fname = 'Parser::doTableStuff';
580 wfProfileIn( $fname );
582 $t = explode ( "\n" , $t ) ;
583 $td = array () ; # Is currently a td tag open?
584 $ltd = array () ; # Was it TD or TH?
585 $tr = array () ; # Is currently a tr tag open?
586 $ltr = array () ; # tr attributes
587 $indent_level = 0; # indent level of the table
588 foreach ( $t AS $k => $x )
591 $fc = substr ( $x , 0 , 1 ) ;
592 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
593 $indent_level = strlen( $matches[1] );
594 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
595 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
596 array_push ( $td , false ) ;
597 array_push ( $ltd , '' ) ;
598 array_push ( $tr , false ) ;
599 array_push ( $ltr , '' ) ;
601 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
602 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
603 $z = "</table>" . substr ( $x , 2);
604 $l = array_pop ( $ltd ) ;
605 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
606 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
608 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
610 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
611 $x = substr ( $x , 1 ) ;
612 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
614 $l = array_pop ( $ltd ) ;
615 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
616 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
619 array_push ( $tr , false ) ;
620 array_push ( $td , false ) ;
621 array_push ( $ltd , '' ) ;
622 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
624 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
626 if ( '|+' == substr ( $x , 0 , 2 ) ) {
628 $x = substr ( $x , 1 ) ;
630 $after = substr ( $x , 1 ) ;
631 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
632 $after = explode ( '||' , $after ) ;
635 # Loop through each table cell
636 foreach ( $after AS $theline )
641 $tra = array_pop ( $ltr ) ;
642 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
643 array_push ( $tr , true ) ;
644 array_push ( $ltr , '' ) ;
647 $l = array_pop ( $ltd ) ;
648 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
649 if ( $fc == '|' ) $l = 'td' ;
650 else if ( $fc == '!' ) $l = 'th' ;
651 else if ( $fc == '+' ) $l = 'caption' ;
653 array_push ( $ltd , $l ) ;
656 $y = explode ( '|' , $theline , 2 ) ;
657 # Note that a '|' inside an invalid link should not
658 # be mistaken as delimiting cell parameters
659 if ( strpos( $y[0], '[[' ) !== false ) {
660 $y = array ($theline);
662 if ( count ( $y ) == 1 )
663 $y = "{$z}<{$l}>{$y[0]}" ;
664 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
666 array_push ( $td , true ) ;
671 # Closing open td, tr && table
672 while ( count ( $td ) > 0 )
674 if ( array_pop ( $td ) ) $t[] = '</td>' ;
675 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
679 $t = implode ( "\n" , $t ) ;
680 # $t = Sanitizer::removeHTMLtags( $t );
681 wfProfileOut( $fname );
686 * Helper function for parse() that transforms wiki markup into
687 * HTML. Only called for $mOutputType == OT_HTML.
691 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
694 $fname = 'Parser::internalParse';
695 wfProfileIn( $fname );
697 $text = Sanitizer
::removeHTMLtags( $text );
698 $text = $this->replaceVariables( $text, $args );
700 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
702 $text = $this->doHeadings( $text );
703 if($this->mOptions
->getUseDynamicDates()) {
704 $df =& DateFormatter
::getInstance();
705 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
707 $text = $this->doAllQuotes( $text );
708 $text = $this->replaceInternalLinks( $text );
709 $text = $this->replaceExternalLinks( $text );
711 # replaceInternalLinks may sometimes leave behind
712 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
713 $text = str_replace("http-noparse://","http://",$text);
715 $text = $this->doMagicLinks( $text );
716 $text = $this->doTableStuff( $text );
717 $text = $this->formatHeadings( $text, $isMain );
719 wfProfileOut( $fname );
724 * Replace special strings like "ISBN xxx" and "RFC xxx" with
725 * magic external links.
729 function &doMagicLinks( &$text ) {
730 $text = $this->magicISBN( $text );
731 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
732 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
737 * Parse ^^ tokens and return html
741 function doExponent( $text ) {
742 $fname = 'Parser::doExponent';
743 wfProfileIn( $fname );
744 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
745 wfProfileOut( $fname );
750 * Parse headers and return html
754 function doHeadings( $text ) {
755 $fname = 'Parser::doHeadings';
756 wfProfileIn( $fname );
757 for ( $i = 6; $i >= 1; --$i ) {
758 $h = substr( '======', 0, $i );
759 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
760 "<h{$i}>\\1</h{$i}>\\2", $text );
762 wfProfileOut( $fname );
767 * Replace single quotes with HTML markup
769 * @return string the altered text
771 function doAllQuotes( $text ) {
772 $fname = 'Parser::doAllQuotes';
773 wfProfileIn( $fname );
775 $lines = explode( "\n", $text );
776 foreach ( $lines as $line ) {
777 $outtext .= $this->doQuotes ( $line ) . "\n";
779 $outtext = substr($outtext, 0,-1);
780 wfProfileOut( $fname );
785 * Helper function for doAllQuotes()
788 function doQuotes( $text ) {
789 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
790 if ( count( $arr ) == 1 )
794 # First, do some preliminary work. This may shift some apostrophes from
795 # being mark-up to being text. It also counts the number of occurrences
796 # of bold and italics mark-ups.
800 foreach ( $arr as $r )
802 if ( ( $i %
2 ) == 1 )
804 # If there are ever four apostrophes, assume the first is supposed to
805 # be text, and the remaining three constitute mark-up for bold text.
806 if ( strlen( $arr[$i] ) == 4 )
811 # If there are more than 5 apostrophes in a row, assume they're all
812 # text except for the last 5.
813 else if ( strlen( $arr[$i] ) > 5 )
815 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
818 # Count the number of occurrences of bold and italics mark-ups.
819 # We are not counting sequences of five apostrophes.
820 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
821 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
822 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
827 # If there is an odd number of both bold and italics, it is likely
828 # that one of the bold ones was meant to be an apostrophe followed
829 # by italics. Which one we cannot know for certain, but it is more
830 # likely to be one that has a single-letter word before it.
831 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
834 $firstsingleletterword = -1;
835 $firstmultiletterword = -1;
837 foreach ( $arr as $r )
839 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
841 $x1 = substr ($arr[$i-1], -1);
842 $x2 = substr ($arr[$i-1], -2, 1);
844 if ($firstspace == -1) $firstspace = $i;
845 } else if ($x2 == ' ') {
846 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
848 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
854 # If there is a single-letter word, use it!
855 if ($firstsingleletterword > -1)
857 $arr [ $firstsingleletterword ] = "''";
858 $arr [ $firstsingleletterword-1 ] .= "'";
860 # If not, but there's a multi-letter word, use that one.
861 else if ($firstmultiletterword > -1)
863 $arr [ $firstmultiletterword ] = "''";
864 $arr [ $firstmultiletterword-1 ] .= "'";
866 # ... otherwise use the first one that has neither.
867 # (notice that it is possible for all three to be -1 if, for example,
868 # there is only one pentuple-apostrophe in the line)
869 else if ($firstspace > -1)
871 $arr [ $firstspace ] = "''";
872 $arr [ $firstspace-1 ] .= "'";
876 # Now let's actually convert our apostrophic mush to HTML!
885 if ($state == 'both')
892 if (strlen ($r) == 2)
895 { $output .= '</i>'; $state = ''; }
896 else if ($state == 'bi')
897 { $output .= '</i>'; $state = 'b'; }
898 else if ($state == 'ib')
899 { $output .= '</b></i><b>'; $state = 'b'; }
900 else if ($state == 'both')
901 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
902 else # $state can be 'b' or ''
903 { $output .= '<i>'; $state .= 'i'; }
905 else if (strlen ($r) == 3)
908 { $output .= '</b>'; $state = ''; }
909 else if ($state == 'bi')
910 { $output .= '</i></b><i>'; $state = 'i'; }
911 else if ($state == 'ib')
912 { $output .= '</b>'; $state = 'i'; }
913 else if ($state == 'both')
914 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
915 else # $state can be 'i' or ''
916 { $output .= '<b>'; $state .= 'b'; }
918 else if (strlen ($r) == 5)
921 { $output .= '</b><i>'; $state = 'i'; }
922 else if ($state == 'i')
923 { $output .= '</i><b>'; $state = 'b'; }
924 else if ($state == 'bi')
925 { $output .= '</i></b>'; $state = ''; }
926 else if ($state == 'ib')
927 { $output .= '</b></i>'; $state = ''; }
928 else if ($state == 'both')
929 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
930 else # ($state == '')
931 { $buffer = ''; $state = 'both'; }
936 # Now close all remaining tags. Notice that the order is important.
937 if ($state == 'b' ||
$state == 'ib')
939 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
943 if ($state == 'both')
944 $output .= '<b><i>'.$buffer.'</i></b>';
950 * Replace external links
952 * Note: this is all very hackish and the order of execution matters a lot.
953 * Make sure to run maintenance/parserTests.php if you change this code.
957 function replaceExternalLinks( $text ) {
958 $fname = 'Parser::replaceExternalLinks';
959 wfProfileIn( $fname );
961 $sk =& $this->mOptions
->getSkin();
963 $linktrail = $wgContLang->linkTrail();
965 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
967 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
970 while ( $i<count( $bits ) ) {
972 $protocol = $bits[$i++
];
974 $trail = $bits[$i++
];
976 # The characters '<' and '>' (which were escaped by
977 # removeHTMLtags()) should not be included in
978 # URLs, per RFC 2396.
979 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
980 $text = substr($url, $m2[0][1]) . ' ' . $text;
981 $url = substr($url, 0, $m2[0][1]);
984 # If the link text is an image URL, replace it with an <img> tag
985 # This happened by accident in the original parser, but some people used it extensively
986 $img = $this->maybeMakeImageLink( $text );
987 if ( $img !== false ) {
993 # Set linktype for CSS - if URL==text, link is essentially free
994 $linktype = ($text == $url) ?
'free' : 'text';
996 # No link text, e.g. [http://domain.tld/some.link]
998 # Autonumber if allowed
999 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1000 $text = '[' . ++
$this->mAutonumber
. ']';
1001 $linktype = 'autonumber';
1003 # Otherwise just use the URL
1004 $text = htmlspecialchars( $url );
1008 # Have link text, e.g. [http://domain.tld/some.link text]s
1010 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1016 # Replace & from obsolete syntax with &.
1017 # All HTML entities will be escaped by makeExternalLink()
1018 # or maybeMakeImageLink()
1019 $url = str_replace( '&', '&', $url );
1021 # Process the trail (i.e. everything after this link up until start of the next link),
1022 # replacing any non-bracketed links
1023 $trail = $this->replaceFreeExternalLinks( $trail );
1025 # Use the encoded URL
1026 # This means that users can paste URLs directly into the text
1027 # Funny characters like ö aren't valid in URLs anyway
1028 # This was changed in August 2004
1029 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1032 wfProfileOut( $fname );
1037 * Replace anything that looks like a URL with a link
1040 function replaceFreeExternalLinks( $text ) {
1041 $fname = 'Parser::replaceFreeExternalLinks';
1042 wfProfileIn( $fname );
1044 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1045 $s = array_shift( $bits );
1048 $sk =& $this->mOptions
->getSkin();
1050 while ( $i < count( $bits ) ){
1051 $protocol = $bits[$i++
];
1052 $remainder = $bits[$i++
];
1054 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1055 # Found some characters after the protocol that look promising
1056 $url = $protocol . $m[1];
1059 # The characters '<' and '>' (which were escaped by
1060 # removeHTMLtags()) should not be included in
1061 # URLs, per RFC 2396.
1062 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1063 $trail = substr($url, $m2[0][1]) . $trail;
1064 $url = substr($url, 0, $m2[0][1]);
1067 # Move trailing punctuation to $trail
1069 # If there is no left bracket, then consider right brackets fair game too
1070 if ( strpos( $url, '(' ) === false ) {
1074 $numSepChars = strspn( strrev( $url ), $sep );
1075 if ( $numSepChars ) {
1076 $trail = substr( $url, -$numSepChars ) . $trail;
1077 $url = substr( $url, 0, -$numSepChars );
1080 # Replace & from obsolete syntax with &.
1081 # All HTML entities will be escaped by makeExternalLink()
1082 # or maybeMakeImageLink()
1083 $url = str_replace( '&', '&', $url );
1085 # Is this an external image?
1086 $text = $this->maybeMakeImageLink( $url );
1087 if ( $text === false ) {
1088 # Not an image, make a link
1089 $text = $sk->makeExternalLink( $url, $url, true, 'free' );
1091 $s .= $text . $trail;
1093 $s .= $protocol . $remainder;
1101 * make an image if it's allowed
1104 function maybeMakeImageLink( $url ) {
1105 $sk =& $this->mOptions
->getSkin();
1107 if ( $this->mOptions
->getAllowExternalImages() ) {
1108 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1110 $text = $sk->makeImage( htmlspecialchars( $url ) );
1117 * Process [[ ]] wikilinks
1121 function replaceInternalLinks( $s ) {
1122 global $wgLang, $wgContLang, $wgLinkCache;
1123 global $wgDisableLangConversion;
1124 static $fname = 'Parser::replaceInternalLinks' ;
1126 wfProfileIn( $fname );
1128 wfProfileIn( $fname.'-setup' );
1130 # the % is needed to support urlencoded titles as well
1131 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1133 $sk =& $this->mOptions
->getSkin();
1134 global $wgUseOldExistenceCheck;
1135 # "Post-parse link colour check" works only on wiki text since it's now
1136 # in Parser. Enable it, then disable it when we're done.
1137 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1139 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1141 #split the entire text string on occurences of [[
1142 $a = explode( '[[', ' ' . $s );
1143 #get the first element (all text up to first [[), and remove the space we added
1144 $s = array_shift( $a );
1145 $s = substr( $s, 1 );
1147 # Match a link having the form [[namespace:link|alternate]]trail
1149 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1150 # Match cases where there is no "]]", which might still be images
1151 static $e1_img = FALSE;
1152 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1153 # Match the end of a line for a word that's not followed by whitespace,
1154 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1155 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1157 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1159 if( is_null( $this->mTitle
) ) {
1160 wfDebugDieBacktrace( 'nooo' );
1162 $nottalk = !$this->mTitle
->isTalkPage();
1164 if ( $useLinkPrefixExtension ) {
1165 if ( preg_match( $e2, $s, $m ) ) {
1166 $first_prefix = $m[2];
1169 $first_prefix = false;
1175 $selflink = $this->mTitle
->getPrefixedText();
1176 wfProfileOut( $fname.'-setup' );
1178 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1179 $useSubpages = $this->areSubpagesAllowed();
1181 # Loop for each link
1182 for ($k = 0; isset( $a[$k] ); $k++
) {
1184 if ( $useLinkPrefixExtension ) {
1185 wfProfileIn( $fname.'-prefixhandling' );
1186 if ( preg_match( $e2, $s, $m ) ) {
1194 $prefix = $first_prefix;
1195 $first_prefix = false;
1197 wfProfileOut( $fname.'-prefixhandling' );
1200 $might_be_img = false;
1202 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1204 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1205 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1206 # the real problem is with the $e1 regex
1208 if (preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1209 $text .= ']'; # so that replaceExternalLinks($text) works later
1212 # fix up urlencoded title texts
1213 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1215 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1216 $might_be_img = true;
1218 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1220 } else { # Invalid form; output directly
1221 $s .= $prefix . '[[' . $line ;
1225 # Don't allow internal links to pages containing
1226 # PROTO: where PROTO is a valid URL protocol; these
1227 # should be external links.
1228 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1229 $s .= $prefix . '[[' . $line ;
1233 # Make subpage if necessary
1234 if( $useSubpages ) {
1235 $link = $this->maybeDoSubpageLink( $m[1], $text );
1240 $noforce = (substr($m[1], 0, 1) != ':');
1242 # Strip off leading ':'
1243 $link = substr($link, 1);
1246 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1248 $s .= $prefix . '[[' . $line;
1252 #check other language variants of the link
1253 #if the article does not exist
1254 if( $checkVariantLink
1255 && $nt->getArticleID() == 0 ) {
1256 $wgContLang->findVariantLink($link, $nt);
1259 $ns = $nt->getNamespace();
1260 $iw = $nt->getInterWiki();
1262 if ($might_be_img) { # if this is actually an invalid link
1263 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1265 while (isset ($a[$k+
1]) ) {
1266 #look at the next 'line' to see if we can close it there
1267 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1268 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1269 # the first ]] closes the inner link, the second the image
1271 $text .= '[[' . $m[1];
1274 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1275 #if there's exactly one ]] that's fine, we'll keep looking
1276 $text .= '[[' . $m[0];
1278 #if $next_line is invalid too, we need look no further
1279 $text .= '[[' . $next_line;
1284 # we couldn't find the end of this imageLink, so output it raw
1285 #but don't ignore what might be perfectly normal links in the text we've examined
1286 $text = $this->replaceInternalLinks($text);
1287 $s .= $prefix . '[[' . $link . '|' . $text;
1288 # note: no $trail, because without an end, there *is* no trail
1291 } else { #it's not an image, so output it raw
1292 $s .= $prefix . '[[' . $link . '|' . $text;
1293 # note: no $trail, because without an end, there *is* no trail
1298 $wasblank = ( '' == $text );
1299 if( $wasblank ) $text = $link;
1302 # Link not escaped by : , create the various objects
1306 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1307 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1308 $s = rtrim($s . "\n");
1309 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1313 if ( $ns == NS_IMAGE
) {
1314 wfProfileIn( "$fname-image" );
1315 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1316 # recursively parse links inside the image caption
1317 # actually, this will parse them in any other parameters, too,
1318 # but it might be hard to fix that, and it doesn't matter ATM
1319 $text = $this->replaceExternalLinks($text);
1320 $text = $this->replaceInternalLinks($text);
1322 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1323 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1324 $wgLinkCache->addImageLinkObj( $nt );
1326 wfProfileOut( "$fname-image" );
1329 wfProfileOut( "$fname-image" );
1333 if ( $ns == NS_CATEGORY
) {
1334 wfProfileIn( "$fname-category" );
1335 $t = $nt->getText();
1336 $s = rtrim($s . "\n"); # bug 87
1338 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1339 $pPLC=$sk->postParseLinkColour();
1340 $sk->postParseLinkColour( false );
1341 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1342 $sk->postParseLinkColour( $pPLC );
1343 $wgLinkCache->resume();
1346 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1347 $sortkey = $this->mTitle
->getText();
1349 $sortkey = $this->mTitle
->getPrefixedText();
1354 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1355 $this->mOutput
->addCategoryLink( $t );
1358 * Strip the whitespace Category links produce, see bug 87
1359 * @todo We might want to use trim($tmp, "\n") here.
1361 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1363 wfProfileOut( "$fname-category" );
1368 if( ( $nt->getPrefixedText() === $selflink ) &&
1369 ( $nt->getFragment() === '' ) ) {
1370 # Self-links are handled specially; generally de-link and change to bold.
1371 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1375 # Special and Media are pseudo-namespaces; no pages actually exist in them
1376 if( $ns == NS_MEDIA
) {
1377 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1378 $wgLinkCache->addImageLinkObj( $nt );
1380 } elseif( $ns == NS_SPECIAL
) {
1381 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1384 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1386 $sk->postParseLinkColour( $saveParseColour );
1387 wfProfileOut( $fname );
1392 * Return true if subpage links should be expanded on this page.
1395 function areSubpagesAllowed() {
1396 # Some namespaces don't allow subpages
1397 global $wgNamespacesWithSubpages;
1398 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1402 * Handle link to subpage if necessary
1403 * @param string $target the source of the link
1404 * @param string &$text the link text, modified as necessary
1405 * @return string the full name of the link
1408 function maybeDoSubpageLink($target, &$text) {
1411 # :Foobar -- override special treatment of prefix (images, language links)
1412 # /Foobar -- convert to CurrentPage/Foobar
1413 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1414 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1415 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1417 $fname = 'Parser::maybeDoSubpageLink';
1418 wfProfileIn( $fname );
1419 $ret = $target; # default return value is no change
1421 # Some namespaces don't allow subpages,
1422 # so only perform processing if subpages are allowed
1423 if( $this->areSubpagesAllowed() ) {
1424 # Look at the first character
1425 if( $target != '' && $target{0} == '/' ) {
1426 # / at end means we don't want the slash to be shown
1427 if( substr( $target, -1, 1 ) == '/' ) {
1428 $target = substr( $target, 1, -1 );
1431 $noslash = substr( $target, 1 );
1434 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1435 if( '' === $text ) {
1437 } # this might be changed for ugliness reasons
1439 # check for .. subpage backlinks
1441 $nodotdot = $target;
1442 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1444 $nodotdot = substr( $nodotdot, 3 );
1446 if($dotdotcount > 0) {
1447 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1448 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1449 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1450 # / at the end means don't show full path
1451 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1452 $nodotdot = substr( $nodotdot, 0, -1 );
1453 if( '' === $text ) {
1457 $nodotdot = trim( $nodotdot );
1458 if( $nodotdot != '' ) {
1459 $ret .= '/' . $nodotdot;
1466 wfProfileOut( $fname );
1471 * Used by doBlockLevels()
1474 /* private */ function closeParagraph() {
1476 if ( '' != $this->mLastSection
) {
1477 $result = '</' . $this->mLastSection
. ">\n";
1479 $this->mInPre
= false;
1480 $this->mLastSection
= '';
1483 # getCommon() returns the length of the longest common substring
1484 # of both arguments, starting at the beginning of both.
1486 /* private */ function getCommon( $st1, $st2 ) {
1487 $fl = strlen( $st1 );
1488 $shorter = strlen( $st2 );
1489 if ( $fl < $shorter ) { $shorter = $fl; }
1491 for ( $i = 0; $i < $shorter; ++
$i ) {
1492 if ( $st1{$i} != $st2{$i} ) { break; }
1496 # These next three functions open, continue, and close the list
1497 # element appropriate to the prefix character passed into them.
1499 /* private */ function openList( $char ) {
1500 $result = $this->closeParagraph();
1502 if ( '*' == $char ) { $result .= '<ul><li>'; }
1503 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1504 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1505 else if ( ';' == $char ) {
1506 $result .= '<dl><dt>';
1507 $this->mDTopen
= true;
1509 else { $result = '<!-- ERR 1 -->'; }
1514 /* private */ function nextItem( $char ) {
1515 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1516 else if ( ':' == $char ||
';' == $char ) {
1518 if ( $this->mDTopen
) { $close = '</dt>'; }
1519 if ( ';' == $char ) {
1520 $this->mDTopen
= true;
1521 return $close . '<dt>';
1523 $this->mDTopen
= false;
1524 return $close . '<dd>';
1527 return '<!-- ERR 2 -->';
1530 /* private */ function closeList( $char ) {
1531 if ( '*' == $char ) { $text = '</li></ul>'; }
1532 else if ( '#' == $char ) { $text = '</li></ol>'; }
1533 else if ( ':' == $char ) {
1534 if ( $this->mDTopen
) {
1535 $this->mDTopen
= false;
1536 $text = '</dt></dl>';
1538 $text = '</dd></dl>';
1541 else { return '<!-- ERR 3 -->'; }
1547 * Make lists from lines starting with ':', '*', '#', etc.
1550 * @return string the lists rendered as HTML
1552 function doBlockLevels( $text, $linestart ) {
1553 $fname = 'Parser::doBlockLevels';
1554 wfProfileIn( $fname );
1556 # Parsing through the text line by line. The main thing
1557 # happening here is handling of block-level elements p, pre,
1558 # and making lists from lines starting with * # : etc.
1560 $textLines = explode( "\n", $text );
1562 $lastPrefix = $output = $lastLine = '';
1563 $this->mDTopen
= $inBlockElem = false;
1565 $paragraphStack = false;
1567 if ( !$linestart ) {
1568 $output .= array_shift( $textLines );
1570 foreach ( $textLines as $oLine ) {
1571 $lastPrefixLength = strlen( $lastPrefix );
1572 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1573 $preOpenMatch = preg_match('/<pre/i', $oLine );
1574 if ( !$this->mInPre
) {
1575 # Multiple prefixes may abut each other for nested lists.
1576 $prefixLength = strspn( $oLine, '*#:;' );
1577 $pref = substr( $oLine, 0, $prefixLength );
1580 $pref2 = str_replace( ';', ':', $pref );
1581 $t = substr( $oLine, $prefixLength );
1582 $this->mInPre
= !empty($preOpenMatch);
1584 # Don't interpret any other prefixes in preformatted text
1586 $pref = $pref2 = '';
1591 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1592 # Same as the last item, so no need to deal with nesting or opening stuff
1593 $output .= $this->nextItem( substr( $pref, -1 ) );
1594 $paragraphStack = false;
1596 if ( substr( $pref, -1 ) == ';') {
1597 # The one nasty exception: definition lists work like this:
1598 # ; title : definition text
1599 # So we check for : in the remainder text to split up the
1600 # title and definition, without b0rking links.
1601 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1603 $output .= $term . $this->nextItem( ':' );
1606 } elseif( $prefixLength ||
$lastPrefixLength ) {
1607 # Either open or close a level...
1608 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1609 $paragraphStack = false;
1611 while( $commonPrefixLength < $lastPrefixLength ) {
1612 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1613 --$lastPrefixLength;
1615 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1616 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1618 while ( $prefixLength > $commonPrefixLength ) {
1619 $char = substr( $pref, $commonPrefixLength, 1 );
1620 $output .= $this->openList( $char );
1622 if ( ';' == $char ) {
1623 # FIXME: This is dupe of code above
1624 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1626 $output .= $term . $this->nextItem( ':' );
1629 ++
$commonPrefixLength;
1631 $lastPrefix = $pref2;
1633 if( 0 == $prefixLength ) {
1634 wfProfileIn( "$fname-paragraph" );
1635 # No prefix (not in list)--go to paragraph mode
1636 $uniq_prefix = UNIQ_PREFIX
;
1637 // XXX: use a stack for nestable elements like span, table and div
1638 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1639 $closematch = preg_match(
1640 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1641 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1642 if ( $openmatch or $closematch ) {
1643 $paragraphStack = false;
1644 $output .= $this->closeParagraph();
1645 if($preOpenMatch and !$preCloseMatch) {
1646 $this->mInPre
= true;
1648 if ( $closematch ) {
1649 $inBlockElem = false;
1651 $inBlockElem = true;
1653 } else if ( !$inBlockElem && !$this->mInPre
) {
1654 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1656 if ($this->mLastSection
!= 'pre') {
1657 $paragraphStack = false;
1658 $output .= $this->closeParagraph().'<pre>';
1659 $this->mLastSection
= 'pre';
1661 $t = substr( $t, 1 );
1664 if ( '' == trim($t) ) {
1665 if ( $paragraphStack ) {
1666 $output .= $paragraphStack.'<br />';
1667 $paragraphStack = false;
1668 $this->mLastSection
= 'p';
1670 if ($this->mLastSection
!= 'p' ) {
1671 $output .= $this->closeParagraph();
1672 $this->mLastSection
= '';
1673 $paragraphStack = '<p>';
1675 $paragraphStack = '</p><p>';
1679 if ( $paragraphStack ) {
1680 $output .= $paragraphStack;
1681 $paragraphStack = false;
1682 $this->mLastSection
= 'p';
1683 } else if ($this->mLastSection
!= 'p') {
1684 $output .= $this->closeParagraph().'<p>';
1685 $this->mLastSection
= 'p';
1690 wfProfileOut( "$fname-paragraph" );
1692 if ($paragraphStack === false) {
1696 while ( $prefixLength ) {
1697 $output .= $this->closeList( $pref2{$prefixLength-1} );
1700 if ( '' != $this->mLastSection
) {
1701 $output .= '</' . $this->mLastSection
. '>';
1702 $this->mLastSection
= '';
1705 wfProfileOut( $fname );
1710 * Split up a string on ':', ignoring any occurences inside
1711 * <a>..</a> or <span>...</span>
1712 * @param string $str the string to split
1713 * @param string &$before set to everything before the ':'
1714 * @param string &$after set to everything after the ':'
1715 * return string the position of the ':', or false if none found
1717 function findColonNoLinks($str, &$before, &$after) {
1718 # I wonder if we should make this count all tags, not just <a>
1719 # and <span>. That would prevent us from matching a ':' that
1720 # comes in the middle of italics other such formatting....
1722 $fname = 'Parser::findColonNoLinks';
1723 wfProfileIn( $fname );
1726 $colon = strpos($str, ':', $pos);
1728 if ($colon !== false) {
1729 $before = substr($str, 0, $colon);
1730 $after = substr($str, $colon +
1);
1732 # Skip any ':' within <a> or <span> pairs
1733 $a = substr_count($before, '<a');
1734 $s = substr_count($before, '<span');
1735 $ca = substr_count($before, '</a>');
1736 $cs = substr_count($before, '</span>');
1738 if ($a <= $ca and $s <= $cs) {
1739 # Tags are balanced before ':'; ok
1744 } while ($colon !== false);
1745 wfProfileOut( $fname );
1750 * Return value of a magic variable (like PAGENAME)
1754 function getVariableValue( $index ) {
1755 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1758 * Some of these require message or data lookups and can be
1759 * expensive to check many times.
1761 static $varCache = array();
1762 if( isset( $varCache[$index] ) ) return $varCache[$index];
1765 case MAG_CURRENTMONTH
:
1766 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1767 case MAG_CURRENTMONTHNAME
:
1768 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1769 case MAG_CURRENTMONTHNAMEGEN
:
1770 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1771 case MAG_CURRENTMONTHABBREV
:
1772 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1773 case MAG_CURRENTDAY
:
1774 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1776 return $this->mTitle
->getText();
1778 return $this->mTitle
->getPartialURL();
1779 case MAG_REVISIONID
:
1780 return $wgArticle->getRevIdFetched();
1782 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1783 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1784 case MAG_CURRENTDAYNAME
:
1785 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1786 case MAG_CURRENTYEAR
:
1787 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1788 case MAG_CURRENTTIME
:
1789 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1790 case MAG_CURRENTWEEK
:
1791 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1792 case MAG_CURRENTDOW
:
1793 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1794 case MAG_NUMBEROFARTICLES
:
1795 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1806 * initialise the magic variables (like CURRENTMONTHNAME)
1810 function initialiseVariables() {
1811 $fname = 'Parser::initialiseVariables';
1812 wfProfileIn( $fname );
1813 global $wgVariableIDs;
1814 $this->mVariables
= array();
1815 foreach ( $wgVariableIDs as $id ) {
1816 $mw =& MagicWord
::get( $id );
1817 $mw->addToArray( $this->mVariables
, $id );
1819 wfProfileOut( $fname );
1823 * Replace magic variables, templates, and template arguments
1824 * with the appropriate text. Templates are substituted recursively,
1825 * taking care to avoid infinite loops.
1827 * Note that the substitution depends on value of $mOutputType:
1828 * OT_WIKI: only {{subst:}} templates
1829 * OT_MSG: only magic variables
1830 * OT_HTML: all templates and magic variables
1832 * @param string $tex The text to transform
1833 * @param array $args Key-value pairs representing template parameters to substitute
1836 function replaceVariables( $text, $args = array() ) {
1837 global $wgLang, $wgScript, $wgArticlePath;
1839 # Prevent too big inclusions
1840 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1844 $fname = 'Parser::replaceVariables';
1845 wfProfileIn( $fname );
1847 $titleChars = Title
::legalChars();
1849 # This function is called recursively. To keep track of arguments we need a stack:
1850 array_push( $this->mArgStack
, $args );
1852 # Variable substitution
1853 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1855 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1856 # Argument substitution
1857 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1859 # Template substitution
1860 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1861 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1863 array_pop( $this->mArgStack
);
1865 wfProfileOut( $fname );
1870 * Replace magic variables
1873 function variableSubstitution( $matches ) {
1874 $fname = 'parser::variableSubstitution';
1875 $varname = $matches[1];
1876 wfProfileIn( $fname );
1877 if ( !$this->mVariables
) {
1878 $this->initialiseVariables();
1881 if ( $this->mOutputType
== OT_WIKI
) {
1882 # Do only magic variables prefixed by SUBST
1883 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1884 if (!$mwSubst->matchStartAndRemove( $varname ))
1886 # Note that if we don't substitute the variable below,
1887 # we don't remove the {{subst:}} magic word, in case
1888 # it is a template rather than a magic variable.
1890 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1891 $id = $this->mVariables
[$varname];
1892 $text = $this->getVariableValue( $id );
1893 $this->mOutput
->mContainsOldMagic
= true;
1895 $text = $matches[0];
1897 wfProfileOut( $fname );
1901 # Split template arguments
1902 function getTemplateArgs( $argsString ) {
1903 if ( $argsString === '' ) {
1907 $args = explode( '|', substr( $argsString, 1 ) );
1909 # If any of the arguments contains a '[[' but no ']]', it needs to be
1910 # merged with the next arg because the '|' character between belongs
1911 # to the link syntax and not the template parameter syntax.
1912 $argc = count($args);
1914 for ( $i = 0; $i < $argc-1; $i++
) {
1915 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1916 $args[$i] .= '|'.$args[$i+
1];
1917 array_splice($args, $i+
1, 1);
1927 * Return the text of a template, after recursively
1928 * replacing any variables or templates within the template.
1930 * @param array $matches The parts of the template
1931 * $matches[1]: the title, i.e. the part before the |
1932 * $matches[2]: the parameters (including a leading |), if any
1933 * @return string the text of the template
1936 function braceSubstitution( $matches ) {
1937 global $wgLinkCache, $wgContLang;
1938 $fname = 'Parser::braceSubstitution';
1939 wfProfileIn( $fname );
1947 # Need to know if the template comes at the start of a line,
1948 # to treat the beginning of the template like the beginning
1949 # of a line for tables and block-level elements.
1950 $linestart = $matches[1];
1952 # $part1 is the bit before the first |, and must contain only title characters
1953 # $args is a list of arguments, starting from index 0, not including $part1
1955 $part1 = $matches[2];
1956 # If the third subpattern matched anything, it will start with |
1958 $args = $this->getTemplateArgs($matches[3]);
1959 $argc = count( $args );
1961 # Don't parse {{{}}} because that's only for template arguments
1962 if ( $linestart === '{' ) {
1963 $text = $matches[0];
1970 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1971 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1972 # One of two possibilities is true:
1973 # 1) Found SUBST but not in the PST phase
1974 # 2) Didn't find SUBST and in the PST phase
1975 # In either case, return without further processing
1976 $text = $matches[0];
1982 # MSG, MSGNW and INT
1985 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1986 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1989 # Remove obsolete MSG:
1990 $mwMsg =& MagicWord
::get( MAG_MSG
);
1991 $mwMsg->matchStartAndRemove( $part1 );
1994 # Check if it is an internal message
1995 $mwInt =& MagicWord
::get( MAG_INT
);
1996 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1997 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1998 $text = $linestart . wfMsgReal( $part1, $args, true );
2006 # Check for NS: (namespace expansion)
2007 $mwNs = MagicWord
::get( MAG_NS
);
2008 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2009 if ( intval( $part1 ) ) {
2010 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2013 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2014 if ( !is_null( $index ) ) {
2015 $text = $linestart . $wgContLang->getNsText( $index );
2022 # LOCALURL and LOCALURLE
2024 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2025 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2027 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2028 $func = 'getLocalURL';
2029 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2030 $func = 'escapeLocalURL';
2035 if ( $func !== '' ) {
2036 $title = Title
::newFromText( $part1 );
2037 if ( !is_null( $title ) ) {
2039 $text = $linestart . $title->$func( $args[0] );
2041 $text = $linestart . $title->$func();
2049 if ( !$found && $argc == 1 ) {
2050 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2051 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2052 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2057 # Template table test
2059 # Did we encounter this template already? If yes, it is in the cache
2060 # and we need to check for loops.
2061 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2064 # Infinite loop test
2065 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2068 $text = $linestart .
2070 '<!-- WARNING: template loop detected -->';
2071 wfDebug( "$fname: template loop broken at '$part1'\n" );
2073 # set $text to cached message.
2074 $text = $linestart . $this->mTemplates
[$part1];
2078 # Load from database
2079 $itcamefromthedatabase = false;
2080 $lastPathLevel = $this->mTemplatePath
;
2083 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2084 if ($subpage !== '') {
2085 $ns = $this->mTitle
->getNamespace();
2087 $title = Title
::newFromText( $part1, $ns );
2088 if ( !is_null( $title ) && !$title->isExternal() ) {
2089 # Check for excessive inclusion
2090 $dbk = $title->getPrefixedDBkey();
2091 if ( $this->incrementIncludeCount( $dbk ) ) {
2092 # This should never be reached.
2093 $article = new Article( $title );
2094 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2095 if ( $articleContent !== false ) {
2097 $text = $linestart . $articleContent;
2098 $itcamefromthedatabase = true;
2102 # If the title is valid but undisplayable, make a link to it
2103 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2104 $text = $linestart . '[['.$title->getPrefixedText().']]';
2108 # Template cache array insertion
2110 $this->mTemplates
[$part1] = $text;
2115 # Recursive parsing, escaping and link table handling
2116 # Only for HTML output
2117 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2118 $text = wfEscapeWikiText( $text );
2119 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2120 # Clean up argument array
2121 $assocArgs = array();
2123 foreach( $args as $arg ) {
2124 $eqpos = strpos( $arg, '=' );
2125 if ( $eqpos === false ) {
2126 $assocArgs[$index++
] = $arg;
2128 $name = trim( substr( $arg, 0, $eqpos ) );
2129 $value = trim( substr( $arg, $eqpos+
1 ) );
2130 if ( $value === false ) {
2133 if ( $name !== false ) {
2134 $assocArgs[$name] = $value;
2139 # Add a new element to the templace recursion path
2140 $this->mTemplatePath
[$part1] = 1;
2142 if( $this->mOutputType
== OT_HTML
) {
2143 $text = $this->strip( $text, $this->mStripState
);
2144 $text = Sanitizer
::removeHTMLtags( $text );
2146 $text = $this->replaceVariables( $text, $assocArgs );
2148 # Resume the link cache and register the inclusion as a link
2149 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2150 $wgLinkCache->addLinkObj( $title );
2153 # If the template begins with a table or block-level
2154 # element, it should be treated as beginning a new line.
2155 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2156 $text = "\n" . $text;
2159 # Prune lower levels off the recursion check path
2160 $this->mTemplatePath
= $lastPathLevel;
2163 wfProfileOut( $fname );
2166 # replace ==section headers==
2167 # XXX this needs to go away once we have a better parser.
2168 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2169 if( !is_null( $title ) )
2170 $encodedname = base64_encode($title->getPrefixedDBkey());
2172 $encodedname = base64_encode("");
2173 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2174 PREG_SPLIT_DELIM_CAPTURE
);
2177 for( $i = 0; $i < count($m); $i +
= 2 ) {
2179 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2181 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2185 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2186 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2187 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2193 # Prune lower levels off the recursion check path
2194 $this->mTemplatePath
= $lastPathLevel;
2197 wfProfileOut( $fname );
2200 wfProfileOut( $fname );
2206 * Triple brace replacement -- used for template arguments
2209 function argSubstitution( $matches ) {
2210 $arg = trim( $matches[1] );
2211 $text = $matches[0];
2212 $inputArgs = end( $this->mArgStack
);
2214 if ( array_key_exists( $arg, $inputArgs ) ) {
2215 $text = $inputArgs[$arg];
2222 * Returns true if the function is allowed to include this entity
2225 function incrementIncludeCount( $dbk ) {
2226 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2227 $this->mIncludeCount
[$dbk] = 0;
2229 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2237 * This function accomplishes several tasks:
2238 * 1) Auto-number headings if that option is enabled
2239 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2240 * 3) Add a Table of contents on the top for users who have enabled the option
2241 * 4) Auto-anchor headings
2243 * It loops through all headlines, collects the necessary data, then splits up the
2244 * string and re-inserts the newly formatted headlines.
2246 * @param string $text
2247 * @param boolean $isMain
2250 function formatHeadings( $text, $isMain=true ) {
2251 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2253 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2255 $forceTocHere = false;
2256 if( !$this->mTitle
->userCanEdit() ) {
2259 $showEditLink = $this->mOptions
->getEditSection();
2262 # Inhibit editsection links if requested in the page
2263 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2264 if( $esw->matchAndRemove( $text ) ) {
2267 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2269 $mw =& MagicWord
::get( MAG_NOTOC
);
2270 if( $mw->matchAndRemove( $text ) ) {
2274 # Get all headlines for numbering them and adding funky stuff like [edit]
2275 # links - this is for later, but we need the number of headlines right now
2276 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2278 # if there are fewer than 4 headlines in the article, do not show TOC
2279 if( $numMatches < 4 ) {
2283 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2284 # override above conditions and always show TOC at that place
2286 $mw =& MagicWord
::get( MAG_TOC
);
2287 if($mw->match( $text ) ) {
2289 $forceTocHere = true;
2291 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2292 # override above conditions and always show TOC above first header
2293 $mw =& MagicWord
::get( MAG_FORCETOC
);
2294 if ($mw->matchAndRemove( $text ) ) {
2299 # Never ever show TOC if no headers
2300 if( $numMatches < 1 ) {
2304 # We need this to perform operations on the HTML
2305 $sk =& $this->mOptions
->getSkin();
2309 $sectionCount = 0; # headlineCount excluding template sections
2311 # Ugh .. the TOC should have neat indentation levels which can be
2312 # passed to the skin functions. These are determined here
2316 $sublevelCount = array();
2317 $levelCount = array();
2324 foreach( $matches[3] as $headline ) {
2326 $templatetitle = '';
2327 $templatesection = 0;
2330 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2332 $templatetitle = base64_decode($mat[1]);
2333 $templatesection = 1 +
(int)base64_decode($mat[2]);
2334 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2338 $prevlevel = $level;
2339 $prevtoclevel = $toclevel;
2341 $level = $matches[1][$headlineCount];
2343 if( $doNumberHeadings ||
$doShowToc ) {
2345 if ( $level > $prevlevel ) {
2346 # Increase TOC level
2348 $sublevelCount[$toclevel] = 0;
2349 $toc .= $sk->tocIndent();
2351 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2352 # Decrease TOC level, find level to jump to
2354 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2355 # Can only go down to level 1
2358 for ($i = $toclevel; $i > 0; $i--) {
2359 if ( $levelCount[$i] == $level ) {
2360 # Found last matching level
2364 elseif ( $levelCount[$i] < $level ) {
2365 # Found first matching level below current level
2372 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2375 # No change in level, end TOC line
2376 $toc .= $sk->tocLineEnd();
2379 $levelCount[$toclevel] = $level;
2381 # count number of headlines for each level
2382 @$sublevelCount[$toclevel]++
;
2384 for( $i = 1; $i <= $toclevel; $i++
) {
2385 if( !empty( $sublevelCount[$i] ) ) {
2389 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2395 # The canonized header is a version of the header text safe to use for links
2396 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2397 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2398 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2400 # Remove link placeholders by the link text.
2401 # <!--LINK number-->
2403 # link text with suffix
2404 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2405 "\$wgLinkHolders['texts'][\$1]",
2406 $canonized_headline );
2407 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2408 "\$wgInterwikiLinkHolders[\$1]",
2409 $canonized_headline );
2412 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2413 $tocline = trim( $canonized_headline );
2414 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2415 $replacearray = array(
2419 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2420 $refer[$headlineCount] = $canonized_headline;
2422 # count how many in assoc. array so we can track dupes in anchors
2423 @$refers[$canonized_headline]++
;
2424 $refcount[$headlineCount]=$refers[$canonized_headline];
2426 # Don't number the heading if it is the only one (looks silly)
2427 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2428 # the two are different if the line contains a link
2429 $headline=$numbering . ' ' . $headline;
2432 # Create the anchor for linking from the TOC to the section
2433 $anchor = $canonized_headline;
2434 if($refcount[$headlineCount] > 1 ) {
2435 $anchor .= '_' . $refcount[$headlineCount];
2437 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2438 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2440 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2441 if ( empty( $head[$headlineCount] ) ) {
2442 $head[$headlineCount] = '';
2445 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2447 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2450 # give headline the correct <h#> tag
2451 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2459 $toclines = $headlineCount;
2460 $toc .= $sk->tocUnindent( $toclevel - 1 );
2461 $toc = $sk->tocList( $toc );
2464 # split up and insert constructed headlines
2466 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2469 foreach( $blocks as $block ) {
2470 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2471 # This is the [edit] link that appears for the top block of text when
2472 # section editing is enabled
2474 # Disabled because it broke block formatting
2475 # For example, a bullet point in the top line
2476 # $full .= $sk->editSectionLink(0);
2479 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2480 # Top anchor now in skin
2484 if( !empty( $head[$i] ) ) {
2490 $mw =& MagicWord
::get( MAG_TOC
);
2491 return $mw->replace( $toc, $full );
2498 * Return an HTML link for the "ISBN 123456" text
2501 function magicISBN( $text ) {
2503 $fname = 'Parser::magicISBN';
2504 wfProfileIn( $fname );
2506 $a = split( 'ISBN ', ' '.$text );
2507 if ( count ( $a ) < 2 ) {
2508 wfProfileOut( $fname );
2511 $text = substr( array_shift( $a ), 1);
2512 $valid = '0123456789-Xx';
2514 foreach ( $a as $x ) {
2515 $isbn = $blank = '' ;
2516 while ( ' ' == $x{0} ) {
2518 $x = substr( $x, 1 );
2520 if ( $x == '' ) { # blank isbn
2521 $text .= "ISBN $blank";
2524 while ( strstr( $valid, $x{0} ) != false ) {
2526 $x = substr( $x, 1 );
2528 $num = str_replace( '-', '', $isbn );
2529 $num = str_replace( ' ', '', $num );
2530 $num = str_replace( 'x', 'X', $num );
2533 $text .= "ISBN $blank$x";
2535 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2536 $text .= '<a href="' .
2537 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2538 "\" class=\"internal\">ISBN $isbn</a>";
2542 wfProfileOut( $fname );
2547 * Return an HTML link for the "RFC 1234" text
2550 * @param string $text Text to be processed
2551 * @param string $keyword Magic keyword to use (default RFC)
2552 * @param string $urlmsg Interface message to use (default rfcurl)
2555 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2558 $valid = '0123456789';
2561 $a = split( $keyword, ' '.$text );
2562 if ( count ( $a ) < 2 ) {
2565 $text = substr( array_shift( $a ), 1);
2567 /* Check if keyword is preceed by [[.
2568 * This test is made here cause of the array_shift above
2569 * that prevent the test to be done in the foreach.
2571 if ( substr( $text, -2 ) == '[[' ) {
2575 foreach ( $a as $x ) {
2576 /* token might be empty if we have RFC RFC 1234 */
2584 /** remove and save whitespaces in $blank */
2585 while ( $x{0} == ' ' ) {
2587 $x = substr( $x, 1 );
2590 /** remove and save the rfc number in $id */
2591 while ( strstr( $valid, $x{0} ) != false ) {
2593 $x = substr( $x, 1 );
2597 /* call back stripped spaces*/
2598 $text .= $keyword.$blank.$x;
2599 } elseif( $internal ) {
2601 $text .= $keyword.$id.$x;
2603 /* build the external link*/
2604 $url = wfMsg( $urlmsg, $id);
2605 $sk =& $this->mOptions
->getSkin();
2606 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2607 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2610 /* Check if the next RFC keyword is preceed by [[ */
2611 $internal = ( substr($x,-2) == '[[' );
2617 * Transform wiki markup when saving a page by doing \r\n -> \n
2618 * conversion, substitting signatures, {{subst:}} templates, etc.
2620 * @param string $text the text to transform
2621 * @param Title &$title the Title object for the current article
2622 * @param User &$user the User object describing the current user
2623 * @param ParserOptions $options parsing options
2624 * @param bool $clearState whether to clear the parser state first
2625 * @return string the altered wiki markup
2628 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2629 $this->mOptions
= $options;
2630 $this->mTitle
=& $title;
2631 $this->mOutputType
= OT_WIKI
;
2633 if ( $clearState ) {
2634 $this->clearState();
2637 $stripState = false;
2641 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2642 $text = $this->strip( $text, $stripState, false );
2643 $text = $this->pstPass2( $text, $user );
2644 $text = $this->unstrip( $text, $stripState );
2645 $text = $this->unstripNoWiki( $text, $stripState );
2650 * Pre-save transform helper function
2653 function pstPass2( $text, &$user ) {
2654 global $wgLang, $wgContLang, $wgLocaltimezone;
2656 # Variable replacement
2657 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2658 $text = $this->replaceVariables( $text );
2662 $n = $user->getName();
2663 $k = $user->getOption( 'nickname' );
2664 if ( '' == $k ) { $k = $n; }
2665 if ( isset( $wgLocaltimezone ) ) {
2666 $oldtz = getenv( 'TZ' );
2667 putenv( 'TZ='.$wgLocaltimezone );
2670 /* Note: This is the timestamp saved as hardcoded wikitext to
2671 * the database, we use $wgContLang here in order to give
2672 * everyone the same signiture and use the default one rather
2673 * than the one selected in each users preferences.
2675 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2676 ' (' . date( 'T' ) . ')';
2677 if ( isset( $wgLocaltimezone ) ) {
2678 putenv( 'TZ='.$oldtzs );
2681 if( $user->getOption( 'fancysig' ) ) {
2684 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2686 $text = preg_replace( '/~~~~~/', $d, $text );
2687 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2688 $text = preg_replace( '/~~~/', $sigText, $text );
2690 # Context links: [[|name]] and [[name (context)|]]
2692 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2693 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2694 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2695 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2697 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2698 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2699 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2700 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2702 $t = $this->mTitle
->getText();
2703 if ( preg_match( $conpat, $t, $m ) ) {
2706 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2707 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2708 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2710 if ( '' == $context ) {
2711 $text = preg_replace( $p2, '[[\\1]]', $text );
2713 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2716 # Trim trailing whitespace
2717 # MAG_END (__END__) tag allows for trailing
2718 # whitespace to be deliberately included
2719 $text = rtrim( $text );
2720 $mw =& MagicWord
::get( MAG_END
);
2721 $mw->matchAndRemove( $text );
2727 * Set up some variables which are usually set up in parse()
2728 * so that an external function can call some class members with confidence
2731 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2732 $this->mTitle
=& $title;
2733 $this->mOptions
= $options;
2734 $this->mOutputType
= $outputType;
2735 if ( $clearState ) {
2736 $this->clearState();
2741 * Transform a MediaWiki message by replacing magic variables.
2743 * @param string $text the text to transform
2744 * @param ParserOptions $options options
2745 * @return string the text with variables substituted
2748 function transformMsg( $text, $options ) {
2750 static $executing = false;
2752 # Guard against infinite recursion
2758 $this->mTitle
= $wgTitle;
2759 $this->mOptions
= $options;
2760 $this->mOutputType
= OT_MSG
;
2761 $this->clearState();
2762 $text = $this->replaceVariables( $text );
2769 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2770 * Callback will be called with the text within
2771 * Transform and return the text within
2774 function setHook( $tag, $callback ) {
2775 $oldVal = @$this->mTagHooks
[$tag];
2776 $this->mTagHooks
[$tag] = $callback;
2781 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2782 * Placeholders created in Skin::makeLinkObj()
2783 * Returns an array of links found, indexed by PDBK:
2787 * $options is a bit field, RLH_FOR_UPDATE to select for update
2789 function replaceLinkHolders( &$text, $options = 0 ) {
2790 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2791 global $wgInterwikiLinkHolders;
2792 global $outputReplace;
2794 if ( $wgUseOldExistenceCheck ) {
2798 $fname = 'Parser::replaceLinkHolders';
2799 wfProfileIn( $fname );
2804 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2805 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2806 wfProfileIn( $fname.'-check' );
2807 $dbr =& wfGetDB( DB_SLAVE
);
2808 $page = $dbr->tableName( 'page' );
2809 $sk = $wgUser->getSkin();
2810 $threshold = $wgUser->getOption('stubthreshold');
2813 asort( $wgLinkHolders['namespaces'] );
2817 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2819 $title = $wgLinkHolders['titles'][$key];
2821 # Skip invalid entries.
2822 # Result will be ugly, but prevents crash.
2823 if ( is_null( $title ) ) {
2826 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2828 # Check if it's in the link cache already
2829 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2830 $colours[$pdbk] = 1;
2831 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2832 $colours[$pdbk] = 0;
2834 # Not in the link cache, add it to the query
2835 if ( !isset( $current ) ) {
2837 $query = "SELECT page_id, page_namespace, page_title";
2838 if ( $threshold > 0 ) {
2839 $query .= ', page_len, page_is_redirect';
2841 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2842 } elseif ( $current != $val ) {
2844 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2849 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2854 if ( $options & RLH_FOR_UPDATE
) {
2855 $query .= ' FOR UPDATE';
2858 $res = $dbr->query( $query, $fname );
2860 # Fetch data and form into an associative array
2861 # non-existent = broken
2864 while ( $s = $dbr->fetchObject($res) ) {
2865 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2866 $pdbk = $title->getPrefixedDBkey();
2867 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2869 if ( $threshold > 0 ) {
2870 $size = $s->page_len
;
2871 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2872 $colours[$pdbk] = 1;
2874 $colours[$pdbk] = 2;
2877 $colours[$pdbk] = 1;
2881 wfProfileOut( $fname.'-check' );
2883 # Construct search and replace arrays
2884 wfProfileIn( $fname.'-construct' );
2885 $outputReplace = array();
2886 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2887 $pdbk = $pdbks[$key];
2888 $searchkey = '<!--LINK '.$key.'-->';
2889 $title = $wgLinkHolders['titles'][$key];
2890 if ( empty( $colours[$pdbk] ) ) {
2891 $wgLinkCache->addBadLink( $pdbk );
2892 $colours[$pdbk] = 0;
2893 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2894 $wgLinkHolders['texts'][$key],
2895 $wgLinkHolders['queries'][$key] );
2896 } elseif ( $colours[$pdbk] == 1 ) {
2897 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2898 $wgLinkHolders['texts'][$key],
2899 $wgLinkHolders['queries'][$key] );
2900 } elseif ( $colours[$pdbk] == 2 ) {
2901 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2902 $wgLinkHolders['texts'][$key],
2903 $wgLinkHolders['queries'][$key] );
2906 wfProfileOut( $fname.'-construct' );
2909 wfProfileIn( $fname.'-replace' );
2911 $text = preg_replace_callback(
2912 '/(<!--LINK .*?-->)/',
2913 "outputReplaceMatches",
2915 wfProfileOut( $fname.'-replace' );
2918 if ( !empty( $wgInterwikiLinkHolders ) ) {
2919 wfProfileIn( $fname.'-interwiki' );
2920 $outputReplace = $wgInterwikiLinkHolders;
2921 $text = preg_replace_callback(
2922 '/<!--IWLINK (.*?)-->/',
2923 "outputReplaceMatches",
2925 wfProfileOut( $fname.'-interwiki' );
2928 wfProfileOut( $fname );
2933 * Renders an image gallery from a text with one line per image.
2934 * text labels may be given by using |-style alternative text. E.g.
2935 * Image:one.jpg|The number "1"
2936 * Image:tree.jpg|A tree
2937 * given as text will return the HTML of a gallery with two images,
2938 * labeled 'The number "1"' and
2941 function renderImageGallery( $text ) {
2943 global $wgUser, $wgParser, $wgTitle;
2944 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2946 global $wgLinkCache;
2947 $ig = new ImageGallery();
2948 $ig->setShowBytes( false );
2949 $ig->setShowFilename( false );
2950 $lines = explode( "\n", $text );
2952 foreach ( $lines as $line ) {
2953 # match lines like these:
2954 # Image:someimage.jpg|This is some image
2955 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2957 if ( count( $matches ) == 0 ) {
2960 $nt = Title
::newFromURL( $matches[1] );
2961 if( is_null( $nt ) ) {
2962 # Bogus title. Ignore these so we don't bomb out later.
2965 if ( isset( $matches[3] ) ) {
2966 $label = $matches[3];
2971 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
2972 $html = $html->mText
;
2974 $ig->add( new Image( $nt ), $html );
2975 $wgLinkCache->addImageLinkObj( $nt );
2977 return $ig->toHTML();
2983 * @package MediaWiki
2987 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2988 var $mCacheTime; # Used in ParserCache
2989 var $mVersion; # Compatibility check
2990 var $mTitleText; # title text of the chosen language variant
2992 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2993 $containsOldMagic = false, $titletext = '' )
2995 $this->mText
= $text;
2996 $this->mLanguageLinks
= $languageLinks;
2997 $this->mCategoryLinks
= $categoryLinks;
2998 $this->mContainsOldMagic
= $containsOldMagic;
2999 $this->mCacheTime
= '';
3000 $this->mVersion
= MW_PARSER_VERSION
;
3001 $this->mTitleText
= $titletext;
3004 function getText() { return $this->mText
; }
3005 function getLanguageLinks() { return $this->mLanguageLinks
; }
3006 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3007 function getCacheTime() { return $this->mCacheTime
; }
3008 function getTitleText() { return $this->mTitleText
; }
3009 function containsOldMagic() { return $this->mContainsOldMagic
; }
3010 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3011 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3012 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3013 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3014 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3015 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3017 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3019 function merge( $other ) {
3020 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3021 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3022 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3026 * Return true if this cached output object predates the global or
3027 * per-article cache invalidation timestamps, or if it comes from
3028 * an incompatible older version.
3030 * @param string $touched the affected article's last touched timestamp
3034 function expired( $touched ) {
3035 global $wgCacheEpoch;
3036 return $this->getCacheTime() <= $touched ||
3037 $this->getCacheTime() <= $wgCacheEpoch ||
3038 !isset( $this->mVersion
) ||
3039 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3044 * Set options of the Parser
3046 * @package MediaWiki
3050 # All variables are private
3051 var $mUseTeX; # Use texvc to expand <math> tags
3052 var $mUseDynamicDates; # Use DateFormatter to format dates
3053 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3054 var $mAllowExternalImages; # Allow external images inline
3055 var $mSkin; # Reference to the preferred skin
3056 var $mDateFormat; # Date format index
3057 var $mEditSection; # Create "edit section" links
3058 var $mNumberHeadings; # Automatically number headings
3060 function getUseTeX() { return $this->mUseTeX
; }
3061 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3062 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3063 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3064 function getSkin() { return $this->mSkin
; }
3065 function getDateFormat() { return $this->mDateFormat
; }
3066 function getEditSection() { return $this->mEditSection
; }
3067 function getNumberHeadings() { return $this->mNumberHeadings
; }
3069 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3070 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3071 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3072 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3073 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3074 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3075 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3077 function setSkin( &$x ) { $this->mSkin
=& $x; }
3080 * Get parser options
3083 function newFromUser( &$user ) {
3084 $popts = new ParserOptions
;
3085 $popts->initialiseFromUser( $user );
3089 /** Get user options */
3090 function initialiseFromUser( &$userInput ) {
3091 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3092 $fname = 'ParserOptions::initialiseFromUser';
3093 wfProfileIn( $fname );
3094 if ( !$userInput ) {
3096 $user->setLoaded( true );
3098 $user =& $userInput;
3101 $this->mUseTeX
= $wgUseTeX;
3102 $this->mUseDynamicDates
= $wgUseDynamicDates;
3103 $this->mInterwikiMagic
= $wgInterwikiMagic;
3104 $this->mAllowExternalImages
= $wgAllowExternalImages;
3105 wfProfileIn( $fname.'-skin' );
3106 $this->mSkin
=& $user->getSkin();
3107 wfProfileOut( $fname.'-skin' );
3108 $this->mDateFormat
= $user->getOption( 'date' );
3109 $this->mEditSection
= $user->getOption( 'editsection' );
3110 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3111 wfProfileOut( $fname );
3116 * Callback function used by Parser::replaceLinkHolders()
3117 * to substitute link placeholders.
3119 function &outputReplaceMatches( $matches ) {
3120 global $outputReplace;
3121 return $outputReplace[$matches[1]];
3125 * Return the total number of articles
3127 function wfNumberOfArticles() {
3128 global $wgNumberOfArticles;
3131 return $wgNumberOfArticles;
3135 * Get various statistics from the database
3138 function wfLoadSiteStats() {
3139 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3140 $fname = 'wfLoadSiteStats';
3142 if ( -1 != $wgNumberOfArticles ) return;
3143 $dbr =& wfGetDB( DB_SLAVE
);
3144 $s = $dbr->selectRow( 'site_stats',
3145 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3146 array( 'ss_row_id' => 1 ), $fname
3149 if ( $s === false ) {
3152 $wgTotalViews = $s->ss_total_views
;
3153 $wgTotalEdits = $s->ss_total_edits
;
3154 $wgNumberOfArticles = $s->ss_good_articles
;
3160 * Basicly replacing " > and < with HTML entities ( ", >, <)
3162 * @param string $in Text that might contain HTML tags
3163 * @return string Escaped string
3165 function wfEscapeHTMLTagsOnly( $in ) {
3167 array( '"', '>', '<' ),
3168 array( '"', '>', '<' ),