784b4a8021f76f11cde56ee7fe176496b362164d
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
);
186 # Clean up special characters, only run once, next-to-last before doBlockLevels
190 # french spaces, last one Guillemet-left
191 # only if there is something before the space
192 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
193 # french spaces, Guillemet-right
194 '/(\\302\\253) /' => '\\1 ',
195 '/<hr *>/i' => '<hr />',
196 '/<br *>/i' => '<br />',
197 '/<center *>/i' => '<div class="center">',
198 '/<\\/center *>/i' => '</div>',
200 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
201 $text = Sanitizer
::normalizeCharReferences( $text );
204 # french spaces, last one Guillemet-left
205 '/ (\\?|:|;|!|\\302\\273)/' => ' \\1',
206 # french spaces, Guillemet-right
207 '/(\\302\\253) /' => '\\1 ',
208 '/<center *>/i' => '<div class="center">',
209 '/<\\/center *>/i' => '</div>'
211 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
214 $text = $this->doBlockLevels( $text, $linestart );
216 $this->replaceLinkHolders( $text );
217 $text = $wgContLang->convert($text);
218 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
219 $text = $this->unstripNoWiki( $text, $this->mStripState
);
221 $text = Parser
::tidy($text);
224 $this->mOutput
->setText( $text );
225 wfProfileOut( $fname );
226 return $this->mOutput
;
230 * Get a random string
235 function getRandomString() {
236 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
240 * Replaces all occurrences of <$tag>content</$tag> in the text
241 * with a random marker and returns the new text. the output parameter
242 * $content will be an associative array filled with data on the form
243 * $unique_marker => content.
245 * If $content is already set, the additional entries will be appended
246 * If $tag is set to STRIP_COMMENTS, the function will extract
247 * <!-- HTML comments -->
252 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
253 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
260 while ( '' != $text ) {
261 if($tag==STRIP_COMMENTS
) {
262 $p = preg_split( '/<!--/', $text, 2 );
264 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
267 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
270 if($tag==STRIP_COMMENTS
) {
271 $q = preg_split( '/-->/i', $p[1], 2 );
273 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
275 $marker = $rnd . sprintf('%08X', $n++
);
276 $content[$marker] = $q[0];
277 $stripped .= $marker;
285 * Strips and renders nowiki, pre, math, hiero
286 * If $render is set, performs necessary rendering operations on plugins
287 * Returns the text, and fills an array with data needed in unstrip()
288 * If the $state is already a valid strip state, it adds to the state
290 * @param bool $stripcomments when set, HTML comments <!-- like this -->
291 * will be stripped in addition to other tags. This is important
292 * for section editing, where these comments cause confusion when
293 * counting the sections in the wikisource
297 function strip( $text, &$state, $stripcomments = false ) {
298 $render = ($this->mOutputType
== OT_HTML
);
299 $html_content = array();
300 $nowiki_content = array();
301 $math_content = array();
302 $pre_content = array();
303 $comment_content = array();
304 $ext_content = array();
305 $gallery_content = array();
307 # Replace any instances of the placeholders
308 $uniq_prefix = UNIQ_PREFIX
;
309 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
312 global $wgRawHtml, $wgWhitelistEdit;
313 if( $wgRawHtml && $wgWhitelistEdit ) {
314 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
315 foreach( $html_content as $marker => $content ) {
317 # Raw and unchecked for validity.
318 $html_content[$marker] = $content;
320 $html_content[$marker] = '<html>'.$content.'</html>';
326 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
327 foreach( $nowiki_content as $marker => $content ) {
329 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
331 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
336 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
337 foreach( $math_content as $marker => $content ){
339 if( $this->mOptions
->getUseTeX() ) {
340 $math_content[$marker] = renderMath( $content );
342 $math_content[$marker] = '<math>'.$content.'<math>';
345 $math_content[$marker] = '<math>'.$content.'</math>';
350 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
351 foreach( $pre_content as $marker => $content ){
353 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
355 $pre_content[$marker] = '<pre>'.$content.'</pre>';
360 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
361 foreach( $gallery_content as $marker => $content ) {
362 require_once( 'ImageGallery.php' );
364 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
366 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
372 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
373 foreach( $comment_content as $marker => $content ){
374 $comment_content[$marker] = '<!--'.$content.'-->';
379 foreach ( $this->mTagHooks
as $tag => $callback ) {
380 $ext_contents[$tag] = array();
381 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
382 foreach( $ext_content[$tag] as $marker => $content ) {
384 $ext_content[$tag][$marker] = $callback( $content );
386 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
391 # Merge state with the pre-existing state, if there is one
393 $state['html'] = $state['html'] +
$html_content;
394 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
395 $state['math'] = $state['math'] +
$math_content;
396 $state['pre'] = $state['pre'] +
$pre_content;
397 $state['comment'] = $state['comment'] +
$comment_content;
398 $state['gallery'] = $state['gallery'] +
$gallery_content;
400 foreach( $ext_content as $tag => $array ) {
401 if ( array_key_exists( $tag, $state ) ) {
402 $state[$tag] = $state[$tag] +
$array;
407 'html' => $html_content,
408 'nowiki' => $nowiki_content,
409 'math' => $math_content,
410 'pre' => $pre_content,
411 'comment' => $comment_content,
412 'gallery' => $gallery_content,
419 * restores pre, math, and hiero removed by strip()
421 * always call unstripNoWiki() after this one
424 function unstrip( $text, &$state ) {
425 # Must expand in reverse order, otherwise nested tags will be corrupted
426 $contentDict = end( $state );
427 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
428 if( key($state) != 'nowiki' && key($state) != 'html') {
429 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
430 $text = str_replace( key( $contentDict ), $content, $text );
439 * always call this after unstrip() to preserve the order
443 function unstripNoWiki( $text, &$state ) {
444 # Must expand in reverse order, otherwise nested tags will be corrupted
445 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
446 $text = str_replace( key( $state['nowiki'] ), $content, $text );
451 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
452 $text = str_replace( key( $state['html'] ), $content, $text );
460 * Add an item to the strip state
461 * Returns the unique tag which must be inserted into the stripped text
462 * The tag will be replaced with the original text in unstrip()
466 function insertStripItem( $text, &$state ) {
467 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
476 $state['item'][$rnd] = $text;
481 * Interface with html tidy, used if $wgUseTidy = true.
482 * If tidy isn't able to correct the markup, the original will be
483 * returned in all its glory with a warning comment appended.
485 * Either the external tidy program or the in-process tidy extension
486 * will be used depending on availability. Override the default
487 * $wgTidyInternal setting to disable the internal if it's not working.
489 * @param string $text Hideous HTML input
490 * @return string Corrected HTML output
494 function tidy( $text ) {
495 global $wgTidyInternal;
496 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
497 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
498 '<head><title>test</title></head><body>'.$text.'</body></html>';
499 if( $wgTidyInternal ) {
500 $correctedtext = Parser
::internalTidy( $wrappedtext );
502 $correctedtext = Parser
::externalTidy( $wrappedtext );
504 if( is_null( $correctedtext ) ) {
505 wfDebug( "Tidy error detected!\n" );
506 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
508 return $correctedtext;
512 * Spawn an external HTML tidy process and get corrected markup back from it.
517 function externalTidy( $text ) {
518 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
519 $fname = 'Parser::externalTidy';
520 wfProfileIn( $fname );
525 $descriptorspec = array(
526 0 => array('pipe', 'r'),
527 1 => array('pipe', 'w'),
528 2 => array('file', '/dev/null', 'a')
530 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
531 if (is_resource($process)) {
532 fwrite($pipes[0], $text);
534 while (!feof($pipes[1])) {
535 $cleansource .= fgets($pipes[1], 1024);
538 $return_value = proc_close($process);
541 wfProfileOut( $fname );
543 if( $cleansource == '' && $text != '') {
544 // Some kind of error happened, so we couldn't get the corrected text.
545 // Just give up; we'll use the source text and append a warning.
553 * Use the HTML tidy PECL extension to use the tidy library in-process,
554 * saving the overhead of spawning a new process. Currently written to
555 * the PHP 4.3.x version of the extension, may not work on PHP 5.
557 * 'pear install tidy' should be able to compile the extension module.
562 function internalTidy( $text ) {
564 $fname = 'Parser::internalTidy';
565 wfProfileIn( $fname );
567 tidy_load_config( $wgTidyConf );
568 tidy_set_encoding( 'utf8' );
569 tidy_parse_string( $text );
571 if( tidy_get_status() == 2 ) {
572 // 2 is magic number for fatal error
573 // http://www.php.net/manual/en/function.tidy-get-status.php
576 $cleansource = tidy_get_output();
578 wfProfileOut( $fname );
583 * parse the wiki syntax used to render tables
587 function doTableStuff ( $t ) {
588 $fname = 'Parser::doTableStuff';
589 wfProfileIn( $fname );
591 $t = explode ( "\n" , $t ) ;
592 $td = array () ; # Is currently a td tag open?
593 $ltd = array () ; # Was it TD or TH?
594 $tr = array () ; # Is currently a tr tag open?
595 $ltr = array () ; # tr attributes
596 $indent_level = 0; # indent level of the table
597 foreach ( $t AS $k => $x )
600 $fc = substr ( $x , 0 , 1 ) ;
601 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
602 $indent_level = strlen( $matches[1] );
603 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
604 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
605 array_push ( $td , false ) ;
606 array_push ( $ltd , '' ) ;
607 array_push ( $tr , false ) ;
608 array_push ( $ltr , '' ) ;
610 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
611 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
612 $z = "</table>" . substr ( $x , 2);
613 $l = array_pop ( $ltd ) ;
614 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
615 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
617 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
619 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
620 $x = substr ( $x , 1 ) ;
621 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
623 $l = array_pop ( $ltd ) ;
624 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
625 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
628 array_push ( $tr , false ) ;
629 array_push ( $td , false ) ;
630 array_push ( $ltd , '' ) ;
631 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
633 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
635 if ( '|+' == substr ( $x , 0 , 2 ) ) {
637 $x = substr ( $x , 1 ) ;
639 $after = substr ( $x , 1 ) ;
640 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
641 $after = explode ( '||' , $after ) ;
644 # Loop through each table cell
645 foreach ( $after AS $theline )
650 $tra = array_pop ( $ltr ) ;
651 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
652 array_push ( $tr , true ) ;
653 array_push ( $ltr , '' ) ;
656 $l = array_pop ( $ltd ) ;
657 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
658 if ( $fc == '|' ) $l = 'td' ;
659 else if ( $fc == '!' ) $l = 'th' ;
660 else if ( $fc == '+' ) $l = 'caption' ;
662 array_push ( $ltd , $l ) ;
665 $y = explode ( '|' , $theline , 2 ) ;
666 # Note that a '|' inside an invalid link should not
667 # be mistaken as delimiting cell parameters
668 if ( strpos( $y[0], '[[' ) !== false ) {
669 $y = array ($theline);
671 if ( count ( $y ) == 1 )
672 $y = "{$z}<{$l}>{$y[0]}" ;
673 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
675 array_push ( $td , true ) ;
680 # Closing open td, tr && table
681 while ( count ( $td ) > 0 )
683 if ( array_pop ( $td ) ) $t[] = '</td>' ;
684 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
688 $t = implode ( "\n" , $t ) ;
689 # $t = Sanitizer::removeHTMLtags( $t );
690 wfProfileOut( $fname );
695 * Helper function for parse() that transforms wiki markup into
696 * HTML. Only called for $mOutputType == OT_HTML.
700 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
703 $fname = 'Parser::internalParse';
704 wfProfileIn( $fname );
706 $text = Sanitizer
::removeHTMLtags( $text );
707 $text = $this->replaceVariables( $text, $args );
709 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
711 $text = $this->doHeadings( $text );
712 if($this->mOptions
->getUseDynamicDates()) {
713 $df =& DateFormatter
::getInstance();
714 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
716 $text = $this->doAllQuotes( $text );
717 $text = $this->replaceInternalLinks( $text );
718 $text = $this->replaceExternalLinks( $text );
720 # replaceInternalLinks may sometimes leave behind
721 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
722 $text = str_replace("http-noparse://","http://",$text);
724 $text = $this->doMagicLinks( $text );
725 $text = $this->doTableStuff( $text );
726 $text = $this->formatHeadings( $text, $isMain );
728 wfProfileOut( $fname );
733 * Replace special strings like "ISBN xxx" and "RFC xxx" with
734 * magic external links.
738 function &doMagicLinks( &$text ) {
739 $text = $this->magicISBN( $text );
740 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
741 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
746 * Parse ^^ tokens and return html
750 function doExponent( $text ) {
751 $fname = 'Parser::doExponent';
752 wfProfileIn( $fname );
753 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
754 wfProfileOut( $fname );
759 * Parse headers and return html
763 function doHeadings( $text ) {
764 $fname = 'Parser::doHeadings';
765 wfProfileIn( $fname );
766 for ( $i = 6; $i >= 1; --$i ) {
767 $h = substr( '======', 0, $i );
768 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
769 "<h{$i}>\\1</h{$i}>\\2", $text );
771 wfProfileOut( $fname );
776 * Replace single quotes with HTML markup
778 * @return string the altered text
780 function doAllQuotes( $text ) {
781 $fname = 'Parser::doAllQuotes';
782 wfProfileIn( $fname );
784 $lines = explode( "\n", $text );
785 foreach ( $lines as $line ) {
786 $outtext .= $this->doQuotes ( $line ) . "\n";
788 $outtext = substr($outtext, 0,-1);
789 wfProfileOut( $fname );
794 * Helper function for doAllQuotes()
797 function doQuotes( $text ) {
798 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
799 if ( count( $arr ) == 1 )
803 # First, do some preliminary work. This may shift some apostrophes from
804 # being mark-up to being text. It also counts the number of occurrences
805 # of bold and italics mark-ups.
809 foreach ( $arr as $r )
811 if ( ( $i %
2 ) == 1 )
813 # If there are ever four apostrophes, assume the first is supposed to
814 # be text, and the remaining three constitute mark-up for bold text.
815 if ( strlen( $arr[$i] ) == 4 )
820 # If there are more than 5 apostrophes in a row, assume they're all
821 # text except for the last 5.
822 else if ( strlen( $arr[$i] ) > 5 )
824 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
827 # Count the number of occurrences of bold and italics mark-ups.
828 # We are not counting sequences of five apostrophes.
829 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
830 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
831 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
836 # If there is an odd number of both bold and italics, it is likely
837 # that one of the bold ones was meant to be an apostrophe followed
838 # by italics. Which one we cannot know for certain, but it is more
839 # likely to be one that has a single-letter word before it.
840 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
843 $firstsingleletterword = -1;
844 $firstmultiletterword = -1;
846 foreach ( $arr as $r )
848 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
850 $x1 = substr ($arr[$i-1], -1);
851 $x2 = substr ($arr[$i-1], -2, 1);
853 if ($firstspace == -1) $firstspace = $i;
854 } else if ($x2 == ' ') {
855 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
857 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
863 # If there is a single-letter word, use it!
864 if ($firstsingleletterword > -1)
866 $arr [ $firstsingleletterword ] = "''";
867 $arr [ $firstsingleletterword-1 ] .= "'";
869 # If not, but there's a multi-letter word, use that one.
870 else if ($firstmultiletterword > -1)
872 $arr [ $firstmultiletterword ] = "''";
873 $arr [ $firstmultiletterword-1 ] .= "'";
875 # ... otherwise use the first one that has neither.
876 # (notice that it is possible for all three to be -1 if, for example,
877 # there is only one pentuple-apostrophe in the line)
878 else if ($firstspace > -1)
880 $arr [ $firstspace ] = "''";
881 $arr [ $firstspace-1 ] .= "'";
885 # Now let's actually convert our apostrophic mush to HTML!
894 if ($state == 'both')
901 if (strlen ($r) == 2)
904 { $output .= '</i>'; $state = ''; }
905 else if ($state == 'bi')
906 { $output .= '</i>'; $state = 'b'; }
907 else if ($state == 'ib')
908 { $output .= '</b></i><b>'; $state = 'b'; }
909 else if ($state == 'both')
910 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
911 else # $state can be 'b' or ''
912 { $output .= '<i>'; $state .= 'i'; }
914 else if (strlen ($r) == 3)
917 { $output .= '</b>'; $state = ''; }
918 else if ($state == 'bi')
919 { $output .= '</i></b><i>'; $state = 'i'; }
920 else if ($state == 'ib')
921 { $output .= '</b>'; $state = 'i'; }
922 else if ($state == 'both')
923 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
924 else # $state can be 'i' or ''
925 { $output .= '<b>'; $state .= 'b'; }
927 else if (strlen ($r) == 5)
930 { $output .= '</b><i>'; $state = 'i'; }
931 else if ($state == 'i')
932 { $output .= '</i><b>'; $state = 'b'; }
933 else if ($state == 'bi')
934 { $output .= '</i></b>'; $state = ''; }
935 else if ($state == 'ib')
936 { $output .= '</b></i>'; $state = ''; }
937 else if ($state == 'both')
938 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
939 else # ($state == '')
940 { $buffer = ''; $state = 'both'; }
945 # Now close all remaining tags. Notice that the order is important.
946 if ($state == 'b' ||
$state == 'ib')
948 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
952 if ($state == 'both')
953 $output .= '<b><i>'.$buffer.'</i></b>';
959 * Replace external links
961 * Note: this is all very hackish and the order of execution matters a lot.
962 * Make sure to run maintenance/parserTests.php if you change this code.
966 function replaceExternalLinks( $text ) {
967 $fname = 'Parser::replaceExternalLinks';
968 wfProfileIn( $fname );
970 $sk =& $this->mOptions
->getSkin();
972 $linktrail = $wgContLang->linkTrail();
974 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
976 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
979 while ( $i<count( $bits ) ) {
981 $protocol = $bits[$i++
];
983 $trail = $bits[$i++
];
985 # The characters '<' and '>' (which were escaped by
986 # removeHTMLtags()) should not be included in
987 # URLs, per RFC 2396.
988 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
989 $text = substr($url, $m2[0][1]) . ' ' . $text;
990 $url = substr($url, 0, $m2[0][1]);
993 # If the link text is an image URL, replace it with an <img> tag
994 # This happened by accident in the original parser, but some people used it extensively
995 $img = $this->maybeMakeImageLink( $text );
996 if ( $img !== false ) {
1002 # Set linktype for CSS - if URL==text, link is essentially free
1003 $linktype = ($text == $url) ?
'free' : 'text';
1005 # No link text, e.g. [http://domain.tld/some.link]
1006 if ( $text == '' ) {
1007 # Autonumber if allowed
1008 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1009 $text = '[' . ++
$this->mAutonumber
. ']';
1010 $linktype = 'autonumber';
1012 # Otherwise just use the URL
1013 $text = htmlspecialchars( $url );
1017 # Have link text, e.g. [http://domain.tld/some.link text]s
1019 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1025 # Replace & from obsolete syntax with &.
1026 # All HTML entities will be escaped by makeExternalLink()
1027 # or maybeMakeImageLink()
1028 $url = str_replace( '&', '&', $url );
1030 # Process the trail (i.e. everything after this link up until start of the next link),
1031 # replacing any non-bracketed links
1032 $trail = $this->replaceFreeExternalLinks( $trail );
1034 # Use the encoded URL
1035 # This means that users can paste URLs directly into the text
1036 # Funny characters like ö aren't valid in URLs anyway
1037 # This was changed in August 2004
1038 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1041 wfProfileOut( $fname );
1046 * Replace anything that looks like a URL with a link
1049 function replaceFreeExternalLinks( $text ) {
1050 $fname = 'Parser::replaceFreeExternalLinks';
1051 wfProfileIn( $fname );
1053 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1054 $s = array_shift( $bits );
1057 $sk =& $this->mOptions
->getSkin();
1059 while ( $i < count( $bits ) ){
1060 $protocol = $bits[$i++
];
1061 $remainder = $bits[$i++
];
1063 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1064 # Found some characters after the protocol that look promising
1065 $url = $protocol . $m[1];
1068 # The characters '<' and '>' (which were escaped by
1069 # removeHTMLtags()) should not be included in
1070 # URLs, per RFC 2396.
1071 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1072 $trail = substr($url, $m2[0][1]) . $trail;
1073 $url = substr($url, 0, $m2[0][1]);
1076 # Move trailing punctuation to $trail
1078 # If there is no left bracket, then consider right brackets fair game too
1079 if ( strpos( $url, '(' ) === false ) {
1083 $numSepChars = strspn( strrev( $url ), $sep );
1084 if ( $numSepChars ) {
1085 $trail = substr( $url, -$numSepChars ) . $trail;
1086 $url = substr( $url, 0, -$numSepChars );
1089 # Replace & from obsolete syntax with &.
1090 # All HTML entities will be escaped by makeExternalLink()
1091 # or maybeMakeImageLink()
1092 $url = str_replace( '&', '&', $url );
1094 # Is this an external image?
1095 $text = $this->maybeMakeImageLink( $url );
1096 if ( $text === false ) {
1097 # Not an image, make a link
1098 $text = $sk->makeExternalLink( $url, $url, true, 'free' );
1100 $s .= $text . $trail;
1102 $s .= $protocol . $remainder;
1110 * make an image if it's allowed
1113 function maybeMakeImageLink( $url ) {
1114 $sk =& $this->mOptions
->getSkin();
1116 if ( $this->mOptions
->getAllowExternalImages() ) {
1117 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1119 $text = $sk->makeImage( htmlspecialchars( $url ) );
1126 * Process [[ ]] wikilinks
1130 function replaceInternalLinks( $s ) {
1131 global $wgLang, $wgContLang, $wgLinkCache;
1132 global $wgDisableLangConversion;
1133 static $fname = 'Parser::replaceInternalLinks' ;
1135 wfProfileIn( $fname );
1137 wfProfileIn( $fname.'-setup' );
1139 # the % is needed to support urlencoded titles as well
1140 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1142 $sk =& $this->mOptions
->getSkin();
1143 global $wgUseOldExistenceCheck;
1144 # "Post-parse link colour check" works only on wiki text since it's now
1145 # in Parser. Enable it, then disable it when we're done.
1146 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1148 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1150 #split the entire text string on occurences of [[
1151 $a = explode( '[[', ' ' . $s );
1152 #get the first element (all text up to first [[), and remove the space we added
1153 $s = array_shift( $a );
1154 $s = substr( $s, 1 );
1156 # Match a link having the form [[namespace:link|alternate]]trail
1158 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1159 # Match cases where there is no "]]", which might still be images
1160 static $e1_img = FALSE;
1161 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1162 # Match the end of a line for a word that's not followed by whitespace,
1163 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1164 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1166 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1168 if( is_null( $this->mTitle
) ) {
1169 wfDebugDieBacktrace( 'nooo' );
1171 $nottalk = !$this->mTitle
->isTalkPage();
1173 if ( $useLinkPrefixExtension ) {
1174 if ( preg_match( $e2, $s, $m ) ) {
1175 $first_prefix = $m[2];
1178 $first_prefix = false;
1184 $selflink = $this->mTitle
->getPrefixedText();
1185 wfProfileOut( $fname.'-setup' );
1187 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1188 $useSubpages = $this->areSubpagesAllowed();
1190 # Loop for each link
1191 for ($k = 0; isset( $a[$k] ); $k++
) {
1193 if ( $useLinkPrefixExtension ) {
1194 wfProfileIn( $fname.'-prefixhandling' );
1195 if ( preg_match( $e2, $s, $m ) ) {
1203 $prefix = $first_prefix;
1204 $first_prefix = false;
1206 wfProfileOut( $fname.'-prefixhandling' );
1209 $might_be_img = false;
1211 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1213 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1214 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1215 # the real problem is with the $e1 regex
1217 if (preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1218 $text .= ']'; # so that replaceExternalLinks($text) works later
1221 # fix up urlencoded title texts
1222 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1224 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1225 $might_be_img = true;
1227 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1229 } else { # Invalid form; output directly
1230 $s .= $prefix . '[[' . $line ;
1234 # Don't allow internal links to pages containing
1235 # PROTO: where PROTO is a valid URL protocol; these
1236 # should be external links.
1237 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1238 $s .= $prefix . '[[' . $line ;
1242 # Make subpage if necessary
1243 if( $useSubpages ) {
1244 $link = $this->maybeDoSubpageLink( $m[1], $text );
1249 $noforce = (substr($m[1], 0, 1) != ':');
1251 # Strip off leading ':'
1252 $link = substr($link, 1);
1255 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1257 $s .= $prefix . '[[' . $line;
1261 #check other language variants of the link
1262 #if the article does not exist
1263 if( $checkVariantLink
1264 && $nt->getArticleID() == 0 ) {
1265 $wgContLang->findVariantLink($link, $nt);
1268 $ns = $nt->getNamespace();
1269 $iw = $nt->getInterWiki();
1271 if ($might_be_img) { # if this is actually an invalid link
1272 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1274 while (isset ($a[$k+
1]) ) {
1275 #look at the next 'line' to see if we can close it there
1276 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1277 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1278 # the first ]] closes the inner link, the second the image
1280 $text .= '[[' . $m[1];
1283 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1284 #if there's exactly one ]] that's fine, we'll keep looking
1285 $text .= '[[' . $m[0];
1287 #if $next_line is invalid too, we need look no further
1288 $text .= '[[' . $next_line;
1293 # we couldn't find the end of this imageLink, so output it raw
1294 #but don't ignore what might be perfectly normal links in the text we've examined
1295 $text = $this->replaceInternalLinks($text);
1296 $s .= $prefix . '[[' . $link . '|' . $text;
1297 # note: no $trail, because without an end, there *is* no trail
1300 } else { #it's not an image, so output it raw
1301 $s .= $prefix . '[[' . $link . '|' . $text;
1302 # note: no $trail, because without an end, there *is* no trail
1307 $wasblank = ( '' == $text );
1308 if( $wasblank ) $text = $link;
1311 # Link not escaped by : , create the various objects
1315 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1316 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1317 $s = rtrim($s . "\n");
1318 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1322 if ( $ns == NS_IMAGE
) {
1323 wfProfileIn( "$fname-image" );
1324 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1325 # recursively parse links inside the image caption
1326 # actually, this will parse them in any other parameters, too,
1327 # but it might be hard to fix that, and it doesn't matter ATM
1328 $text = $this->replaceExternalLinks($text);
1329 $text = $this->replaceInternalLinks($text);
1331 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1332 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1333 $wgLinkCache->addImageLinkObj( $nt );
1335 wfProfileOut( "$fname-image" );
1338 wfProfileOut( "$fname-image" );
1342 if ( $ns == NS_CATEGORY
) {
1343 wfProfileIn( "$fname-category" );
1344 $t = $nt->getText();
1345 $s = rtrim($s . "\n"); # bug 87
1347 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1348 $pPLC=$sk->postParseLinkColour();
1349 $sk->postParseLinkColour( false );
1350 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1351 $sk->postParseLinkColour( $pPLC );
1352 $wgLinkCache->resume();
1355 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1356 $sortkey = $this->mTitle
->getText();
1358 $sortkey = $this->mTitle
->getPrefixedText();
1363 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1364 $this->mOutput
->addCategoryLink( $t );
1367 * Strip the whitespace Category links produce, see bug 87
1368 * @todo We might want to use trim($tmp, "\n") here.
1370 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1372 wfProfileOut( "$fname-category" );
1377 if( ( $nt->getPrefixedText() === $selflink ) &&
1378 ( $nt->getFragment() === '' ) ) {
1379 # Self-links are handled specially; generally de-link and change to bold.
1380 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1384 # Special and Media are pseudo-namespaces; no pages actually exist in them
1385 if( $ns == NS_MEDIA
) {
1386 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1387 $wgLinkCache->addImageLinkObj( $nt );
1389 } elseif( $ns == NS_SPECIAL
) {
1390 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1393 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1395 $sk->postParseLinkColour( $saveParseColour );
1396 wfProfileOut( $fname );
1401 * Return true if subpage links should be expanded on this page.
1404 function areSubpagesAllowed() {
1405 # Some namespaces don't allow subpages
1406 global $wgNamespacesWithSubpages;
1407 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1411 * Handle link to subpage if necessary
1412 * @param string $target the source of the link
1413 * @param string &$text the link text, modified as necessary
1414 * @return string the full name of the link
1417 function maybeDoSubpageLink($target, &$text) {
1420 # :Foobar -- override special treatment of prefix (images, language links)
1421 # /Foobar -- convert to CurrentPage/Foobar
1422 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1423 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1424 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1426 $fname = 'Parser::maybeDoSubpageLink';
1427 wfProfileIn( $fname );
1428 $ret = $target; # default return value is no change
1430 # Some namespaces don't allow subpages,
1431 # so only perform processing if subpages are allowed
1432 if( $this->areSubpagesAllowed() ) {
1433 # Look at the first character
1434 if( $target != '' && $target{0} == '/' ) {
1435 # / at end means we don't want the slash to be shown
1436 if( substr( $target, -1, 1 ) == '/' ) {
1437 $target = substr( $target, 1, -1 );
1440 $noslash = substr( $target, 1 );
1443 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1444 if( '' === $text ) {
1446 } # this might be changed for ugliness reasons
1448 # check for .. subpage backlinks
1450 $nodotdot = $target;
1451 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1453 $nodotdot = substr( $nodotdot, 3 );
1455 if($dotdotcount > 0) {
1456 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1457 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1458 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1459 # / at the end means don't show full path
1460 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1461 $nodotdot = substr( $nodotdot, 0, -1 );
1462 if( '' === $text ) {
1466 $nodotdot = trim( $nodotdot );
1467 if( $nodotdot != '' ) {
1468 $ret .= '/' . $nodotdot;
1475 wfProfileOut( $fname );
1480 * Used by doBlockLevels()
1483 /* private */ function closeParagraph() {
1485 if ( '' != $this->mLastSection
) {
1486 $result = '</' . $this->mLastSection
. ">\n";
1488 $this->mInPre
= false;
1489 $this->mLastSection
= '';
1492 # getCommon() returns the length of the longest common substring
1493 # of both arguments, starting at the beginning of both.
1495 /* private */ function getCommon( $st1, $st2 ) {
1496 $fl = strlen( $st1 );
1497 $shorter = strlen( $st2 );
1498 if ( $fl < $shorter ) { $shorter = $fl; }
1500 for ( $i = 0; $i < $shorter; ++
$i ) {
1501 if ( $st1{$i} != $st2{$i} ) { break; }
1505 # These next three functions open, continue, and close the list
1506 # element appropriate to the prefix character passed into them.
1508 /* private */ function openList( $char ) {
1509 $result = $this->closeParagraph();
1511 if ( '*' == $char ) { $result .= '<ul><li>'; }
1512 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1513 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1514 else if ( ';' == $char ) {
1515 $result .= '<dl><dt>';
1516 $this->mDTopen
= true;
1518 else { $result = '<!-- ERR 1 -->'; }
1523 /* private */ function nextItem( $char ) {
1524 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1525 else if ( ':' == $char ||
';' == $char ) {
1527 if ( $this->mDTopen
) { $close = '</dt>'; }
1528 if ( ';' == $char ) {
1529 $this->mDTopen
= true;
1530 return $close . '<dt>';
1532 $this->mDTopen
= false;
1533 return $close . '<dd>';
1536 return '<!-- ERR 2 -->';
1539 /* private */ function closeList( $char ) {
1540 if ( '*' == $char ) { $text = '</li></ul>'; }
1541 else if ( '#' == $char ) { $text = '</li></ol>'; }
1542 else if ( ':' == $char ) {
1543 if ( $this->mDTopen
) {
1544 $this->mDTopen
= false;
1545 $text = '</dt></dl>';
1547 $text = '</dd></dl>';
1550 else { return '<!-- ERR 3 -->'; }
1556 * Make lists from lines starting with ':', '*', '#', etc.
1559 * @return string the lists rendered as HTML
1561 function doBlockLevels( $text, $linestart ) {
1562 $fname = 'Parser::doBlockLevels';
1563 wfProfileIn( $fname );
1565 # Parsing through the text line by line. The main thing
1566 # happening here is handling of block-level elements p, pre,
1567 # and making lists from lines starting with * # : etc.
1569 $textLines = explode( "\n", $text );
1571 $lastPrefix = $output = $lastLine = '';
1572 $this->mDTopen
= $inBlockElem = false;
1574 $paragraphStack = false;
1576 if ( !$linestart ) {
1577 $output .= array_shift( $textLines );
1579 foreach ( $textLines as $oLine ) {
1580 $lastPrefixLength = strlen( $lastPrefix );
1581 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1582 $preOpenMatch = preg_match('/<pre/i', $oLine );
1583 if ( !$this->mInPre
) {
1584 # Multiple prefixes may abut each other for nested lists.
1585 $prefixLength = strspn( $oLine, '*#:;' );
1586 $pref = substr( $oLine, 0, $prefixLength );
1589 $pref2 = str_replace( ';', ':', $pref );
1590 $t = substr( $oLine, $prefixLength );
1591 $this->mInPre
= !empty($preOpenMatch);
1593 # Don't interpret any other prefixes in preformatted text
1595 $pref = $pref2 = '';
1600 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1601 # Same as the last item, so no need to deal with nesting or opening stuff
1602 $output .= $this->nextItem( substr( $pref, -1 ) );
1603 $paragraphStack = false;
1605 if ( substr( $pref, -1 ) == ';') {
1606 # The one nasty exception: definition lists work like this:
1607 # ; title : definition text
1608 # So we check for : in the remainder text to split up the
1609 # title and definition, without b0rking links.
1610 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1612 $output .= $term . $this->nextItem( ':' );
1615 } elseif( $prefixLength ||
$lastPrefixLength ) {
1616 # Either open or close a level...
1617 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1618 $paragraphStack = false;
1620 while( $commonPrefixLength < $lastPrefixLength ) {
1621 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1622 --$lastPrefixLength;
1624 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1625 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1627 while ( $prefixLength > $commonPrefixLength ) {
1628 $char = substr( $pref, $commonPrefixLength, 1 );
1629 $output .= $this->openList( $char );
1631 if ( ';' == $char ) {
1632 # FIXME: This is dupe of code above
1633 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1635 $output .= $term . $this->nextItem( ':' );
1638 ++
$commonPrefixLength;
1640 $lastPrefix = $pref2;
1642 if( 0 == $prefixLength ) {
1643 wfProfileIn( "$fname-paragraph" );
1644 # No prefix (not in list)--go to paragraph mode
1645 $uniq_prefix = UNIQ_PREFIX
;
1646 // XXX: use a stack for nestable elements like span, table and div
1647 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1648 $closematch = preg_match(
1649 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1650 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1651 if ( $openmatch or $closematch ) {
1652 $paragraphStack = false;
1653 $output .= $this->closeParagraph();
1654 if($preOpenMatch and !$preCloseMatch) {
1655 $this->mInPre
= true;
1657 if ( $closematch ) {
1658 $inBlockElem = false;
1660 $inBlockElem = true;
1662 } else if ( !$inBlockElem && !$this->mInPre
) {
1663 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1665 if ($this->mLastSection
!= 'pre') {
1666 $paragraphStack = false;
1667 $output .= $this->closeParagraph().'<pre>';
1668 $this->mLastSection
= 'pre';
1670 $t = substr( $t, 1 );
1673 if ( '' == trim($t) ) {
1674 if ( $paragraphStack ) {
1675 $output .= $paragraphStack.'<br />';
1676 $paragraphStack = false;
1677 $this->mLastSection
= 'p';
1679 if ($this->mLastSection
!= 'p' ) {
1680 $output .= $this->closeParagraph();
1681 $this->mLastSection
= '';
1682 $paragraphStack = '<p>';
1684 $paragraphStack = '</p><p>';
1688 if ( $paragraphStack ) {
1689 $output .= $paragraphStack;
1690 $paragraphStack = false;
1691 $this->mLastSection
= 'p';
1692 } else if ($this->mLastSection
!= 'p') {
1693 $output .= $this->closeParagraph().'<p>';
1694 $this->mLastSection
= 'p';
1699 wfProfileOut( "$fname-paragraph" );
1701 if ($paragraphStack === false) {
1705 while ( $prefixLength ) {
1706 $output .= $this->closeList( $pref2{$prefixLength-1} );
1709 if ( '' != $this->mLastSection
) {
1710 $output .= '</' . $this->mLastSection
. '>';
1711 $this->mLastSection
= '';
1714 wfProfileOut( $fname );
1719 * Split up a string on ':', ignoring any occurences inside
1720 * <a>..</a> or <span>...</span>
1721 * @param string $str the string to split
1722 * @param string &$before set to everything before the ':'
1723 * @param string &$after set to everything after the ':'
1724 * return string the position of the ':', or false if none found
1726 function findColonNoLinks($str, &$before, &$after) {
1727 # I wonder if we should make this count all tags, not just <a>
1728 # and <span>. That would prevent us from matching a ':' that
1729 # comes in the middle of italics other such formatting....
1731 $fname = 'Parser::findColonNoLinks';
1732 wfProfileIn( $fname );
1735 $colon = strpos($str, ':', $pos);
1737 if ($colon !== false) {
1738 $before = substr($str, 0, $colon);
1739 $after = substr($str, $colon +
1);
1741 # Skip any ':' within <a> or <span> pairs
1742 $a = substr_count($before, '<a');
1743 $s = substr_count($before, '<span');
1744 $ca = substr_count($before, '</a>');
1745 $cs = substr_count($before, '</span>');
1747 if ($a <= $ca and $s <= $cs) {
1748 # Tags are balanced before ':'; ok
1753 } while ($colon !== false);
1754 wfProfileOut( $fname );
1759 * Return value of a magic variable (like PAGENAME)
1763 function getVariableValue( $index ) {
1764 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1767 * Some of these require message or data lookups and can be
1768 * expensive to check many times.
1770 static $varCache = array();
1771 if( isset( $varCache[$index] ) ) return $varCache[$index];
1774 case MAG_CURRENTMONTH
:
1775 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1776 case MAG_CURRENTMONTHNAME
:
1777 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1778 case MAG_CURRENTMONTHNAMEGEN
:
1779 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1780 case MAG_CURRENTMONTHABBREV
:
1781 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1782 case MAG_CURRENTDAY
:
1783 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1785 return $this->mTitle
->getText();
1787 return $this->mTitle
->getPartialURL();
1788 case MAG_REVISIONID
:
1789 return $wgArticle->getRevIdFetched();
1791 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1792 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1793 case MAG_CURRENTDAYNAME
:
1794 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1795 case MAG_CURRENTYEAR
:
1796 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1797 case MAG_CURRENTTIME
:
1798 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1799 case MAG_CURRENTWEEK
:
1800 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1801 case MAG_CURRENTDOW
:
1802 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1803 case MAG_NUMBEROFARTICLES
:
1804 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1815 * initialise the magic variables (like CURRENTMONTHNAME)
1819 function initialiseVariables() {
1820 $fname = 'Parser::initialiseVariables';
1821 wfProfileIn( $fname );
1822 global $wgVariableIDs;
1823 $this->mVariables
= array();
1824 foreach ( $wgVariableIDs as $id ) {
1825 $mw =& MagicWord
::get( $id );
1826 $mw->addToArray( $this->mVariables
, $id );
1828 wfProfileOut( $fname );
1832 * Replace magic variables, templates, and template arguments
1833 * with the appropriate text. Templates are substituted recursively,
1834 * taking care to avoid infinite loops.
1836 * Note that the substitution depends on value of $mOutputType:
1837 * OT_WIKI: only {{subst:}} templates
1838 * OT_MSG: only magic variables
1839 * OT_HTML: all templates and magic variables
1841 * @param string $tex The text to transform
1842 * @param array $args Key-value pairs representing template parameters to substitute
1845 function replaceVariables( $text, $args = array() ) {
1846 global $wgLang, $wgScript, $wgArticlePath;
1848 # Prevent too big inclusions
1849 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1853 $fname = 'Parser::replaceVariables';
1854 wfProfileIn( $fname );
1856 $titleChars = Title
::legalChars();
1858 # This function is called recursively. To keep track of arguments we need a stack:
1859 array_push( $this->mArgStack
, $args );
1861 # Variable substitution
1862 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1864 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1865 # Argument substitution
1866 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1868 # Template substitution
1869 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1870 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1872 array_pop( $this->mArgStack
);
1874 wfProfileOut( $fname );
1879 * Replace magic variables
1882 function variableSubstitution( $matches ) {
1883 $fname = 'parser::variableSubstitution';
1884 $varname = $matches[1];
1885 wfProfileIn( $fname );
1886 if ( !$this->mVariables
) {
1887 $this->initialiseVariables();
1890 if ( $this->mOutputType
== OT_WIKI
) {
1891 # Do only magic variables prefixed by SUBST
1892 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1893 if (!$mwSubst->matchStartAndRemove( $varname ))
1895 # Note that if we don't substitute the variable below,
1896 # we don't remove the {{subst:}} magic word, in case
1897 # it is a template rather than a magic variable.
1899 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1900 $id = $this->mVariables
[$varname];
1901 $text = $this->getVariableValue( $id );
1902 $this->mOutput
->mContainsOldMagic
= true;
1904 $text = $matches[0];
1906 wfProfileOut( $fname );
1910 # Split template arguments
1911 function getTemplateArgs( $argsString ) {
1912 if ( $argsString === '' ) {
1916 $args = explode( '|', substr( $argsString, 1 ) );
1918 # If any of the arguments contains a '[[' but no ']]', it needs to be
1919 # merged with the next arg because the '|' character between belongs
1920 # to the link syntax and not the template parameter syntax.
1921 $argc = count($args);
1923 for ( $i = 0; $i < $argc-1; $i++
) {
1924 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1925 $args[$i] .= '|'.$args[$i+
1];
1926 array_splice($args, $i+
1, 1);
1936 * Return the text of a template, after recursively
1937 * replacing any variables or templates within the template.
1939 * @param array $matches The parts of the template
1940 * $matches[1]: the title, i.e. the part before the |
1941 * $matches[2]: the parameters (including a leading |), if any
1942 * @return string the text of the template
1945 function braceSubstitution( $matches ) {
1946 global $wgLinkCache, $wgContLang;
1947 $fname = 'Parser::braceSubstitution';
1948 wfProfileIn( $fname );
1956 # Need to know if the template comes at the start of a line,
1957 # to treat the beginning of the template like the beginning
1958 # of a line for tables and block-level elements.
1959 $linestart = $matches[1];
1961 # $part1 is the bit before the first |, and must contain only title characters
1962 # $args is a list of arguments, starting from index 0, not including $part1
1964 $part1 = $matches[2];
1965 # If the third subpattern matched anything, it will start with |
1967 $args = $this->getTemplateArgs($matches[3]);
1968 $argc = count( $args );
1970 # Don't parse {{{}}} because that's only for template arguments
1971 if ( $linestart === '{' ) {
1972 $text = $matches[0];
1979 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1980 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1981 # One of two possibilities is true:
1982 # 1) Found SUBST but not in the PST phase
1983 # 2) Didn't find SUBST and in the PST phase
1984 # In either case, return without further processing
1985 $text = $matches[0];
1991 # MSG, MSGNW and INT
1994 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1995 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1998 # Remove obsolete MSG:
1999 $mwMsg =& MagicWord
::get( MAG_MSG
);
2000 $mwMsg->matchStartAndRemove( $part1 );
2003 # Check if it is an internal message
2004 $mwInt =& MagicWord
::get( MAG_INT
);
2005 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2006 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2007 $text = $linestart . wfMsgReal( $part1, $args, true );
2015 # Check for NS: (namespace expansion)
2016 $mwNs = MagicWord
::get( MAG_NS
);
2017 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2018 if ( intval( $part1 ) ) {
2019 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2022 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2023 if ( !is_null( $index ) ) {
2024 $text = $linestart . $wgContLang->getNsText( $index );
2031 # LOCALURL and LOCALURLE
2033 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2034 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2036 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2037 $func = 'getLocalURL';
2038 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2039 $func = 'escapeLocalURL';
2044 if ( $func !== '' ) {
2045 $title = Title
::newFromText( $part1 );
2046 if ( !is_null( $title ) ) {
2048 $text = $linestart . $title->$func( $args[0] );
2050 $text = $linestart . $title->$func();
2058 if ( !$found && $argc == 1 ) {
2059 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2060 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2061 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2066 # Template table test
2068 # Did we encounter this template already? If yes, it is in the cache
2069 # and we need to check for loops.
2070 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2073 # Infinite loop test
2074 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2077 $text = $linestart .
2079 '<!-- WARNING: template loop detected -->';
2080 wfDebug( "$fname: template loop broken at '$part1'\n" );
2082 # set $text to cached message.
2083 $text = $linestart . $this->mTemplates
[$part1];
2087 # Load from database
2088 $itcamefromthedatabase = false;
2089 $lastPathLevel = $this->mTemplatePath
;
2092 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2093 if ($subpage !== '') {
2094 $ns = $this->mTitle
->getNamespace();
2096 $title = Title
::newFromText( $part1, $ns );
2097 if ( !is_null( $title ) && !$title->isExternal() ) {
2098 # Check for excessive inclusion
2099 $dbk = $title->getPrefixedDBkey();
2100 if ( $this->incrementIncludeCount( $dbk ) ) {
2101 # This should never be reached.
2102 $article = new Article( $title );
2103 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2104 if ( $articleContent !== false ) {
2106 $text = $linestart . $articleContent;
2107 $itcamefromthedatabase = true;
2111 # If the title is valid but undisplayable, make a link to it
2112 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2113 $text = $linestart . '[['.$title->getPrefixedText().']]';
2117 # Template cache array insertion
2119 $this->mTemplates
[$part1] = $text;
2124 # Recursive parsing, escaping and link table handling
2125 # Only for HTML output
2126 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2127 $text = wfEscapeWikiText( $text );
2128 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2129 # Clean up argument array
2130 $assocArgs = array();
2132 foreach( $args as $arg ) {
2133 $eqpos = strpos( $arg, '=' );
2134 if ( $eqpos === false ) {
2135 $assocArgs[$index++
] = $arg;
2137 $name = trim( substr( $arg, 0, $eqpos ) );
2138 $value = trim( substr( $arg, $eqpos+
1 ) );
2139 if ( $value === false ) {
2142 if ( $name !== false ) {
2143 $assocArgs[$name] = $value;
2148 # Add a new element to the templace recursion path
2149 $this->mTemplatePath
[$part1] = 1;
2151 if( $this->mOutputType
== OT_HTML
) {
2152 $text = $this->strip( $text, $this->mStripState
);
2153 $text = Sanitizer
::removeHTMLtags( $text );
2155 $text = $this->replaceVariables( $text, $assocArgs );
2157 # Resume the link cache and register the inclusion as a link
2158 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2159 $wgLinkCache->addLinkObj( $title );
2162 # If the template begins with a table or block-level
2163 # element, it should be treated as beginning a new line.
2164 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2165 $text = "\n" . $text;
2168 # Prune lower levels off the recursion check path
2169 $this->mTemplatePath
= $lastPathLevel;
2172 wfProfileOut( $fname );
2175 # replace ==section headers==
2176 # XXX this needs to go away once we have a better parser.
2177 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2178 if( !is_null( $title ) )
2179 $encodedname = base64_encode($title->getPrefixedDBkey());
2181 $encodedname = base64_encode("");
2182 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2183 PREG_SPLIT_DELIM_CAPTURE
);
2186 for( $i = 0; $i < count($m); $i +
= 2 ) {
2188 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2190 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2194 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2195 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2196 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2202 # Prune lower levels off the recursion check path
2203 $this->mTemplatePath
= $lastPathLevel;
2206 wfProfileOut( $fname );
2209 wfProfileOut( $fname );
2215 * Triple brace replacement -- used for template arguments
2218 function argSubstitution( $matches ) {
2219 $arg = trim( $matches[1] );
2220 $text = $matches[0];
2221 $inputArgs = end( $this->mArgStack
);
2223 if ( array_key_exists( $arg, $inputArgs ) ) {
2224 $text = $inputArgs[$arg];
2231 * Returns true if the function is allowed to include this entity
2234 function incrementIncludeCount( $dbk ) {
2235 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2236 $this->mIncludeCount
[$dbk] = 0;
2238 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2246 * This function accomplishes several tasks:
2247 * 1) Auto-number headings if that option is enabled
2248 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2249 * 3) Add a Table of contents on the top for users who have enabled the option
2250 * 4) Auto-anchor headings
2252 * It loops through all headlines, collects the necessary data, then splits up the
2253 * string and re-inserts the newly formatted headlines.
2255 * @param string $text
2256 * @param boolean $isMain
2259 function formatHeadings( $text, $isMain=true ) {
2260 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2262 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2264 $forceTocHere = false;
2265 if( !$this->mTitle
->userCanEdit() ) {
2268 $showEditLink = $this->mOptions
->getEditSection();
2271 # Inhibit editsection links if requested in the page
2272 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2273 if( $esw->matchAndRemove( $text ) ) {
2276 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2278 $mw =& MagicWord
::get( MAG_NOTOC
);
2279 if( $mw->matchAndRemove( $text ) ) {
2283 # Get all headlines for numbering them and adding funky stuff like [edit]
2284 # links - this is for later, but we need the number of headlines right now
2285 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2287 # if there are fewer than 4 headlines in the article, do not show TOC
2288 if( $numMatches < 4 ) {
2292 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2293 # override above conditions and always show TOC at that place
2295 $mw =& MagicWord
::get( MAG_TOC
);
2296 if($mw->match( $text ) ) {
2298 $forceTocHere = true;
2300 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2301 # override above conditions and always show TOC above first header
2302 $mw =& MagicWord
::get( MAG_FORCETOC
);
2303 if ($mw->matchAndRemove( $text ) ) {
2308 # Never ever show TOC if no headers
2309 if( $numMatches < 1 ) {
2313 # We need this to perform operations on the HTML
2314 $sk =& $this->mOptions
->getSkin();
2318 $sectionCount = 0; # headlineCount excluding template sections
2320 # Ugh .. the TOC should have neat indentation levels which can be
2321 # passed to the skin functions. These are determined here
2325 $sublevelCount = array();
2326 $levelCount = array();
2333 foreach( $matches[3] as $headline ) {
2335 $templatetitle = '';
2336 $templatesection = 0;
2339 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2341 $templatetitle = base64_decode($mat[1]);
2342 $templatesection = 1 +
(int)base64_decode($mat[2]);
2343 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2347 $prevlevel = $level;
2348 $prevtoclevel = $toclevel;
2350 $level = $matches[1][$headlineCount];
2352 if( $doNumberHeadings ||
$doShowToc ) {
2354 if ( $level > $prevlevel ) {
2355 # Increase TOC level
2357 $sublevelCount[$toclevel] = 0;
2358 $toc .= $sk->tocIndent();
2360 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2361 # Decrease TOC level, find level to jump to
2363 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2364 # Can only go down to level 1
2367 for ($i = $toclevel; $i > 0; $i--) {
2368 if ( $levelCount[$i] == $level ) {
2369 # Found last matching level
2373 elseif ( $levelCount[$i] < $level ) {
2374 # Found first matching level below current level
2381 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2384 # No change in level, end TOC line
2385 $toc .= $sk->tocLineEnd();
2388 $levelCount[$toclevel] = $level;
2390 # count number of headlines for each level
2391 @$sublevelCount[$toclevel]++
;
2393 for( $i = 1; $i <= $toclevel; $i++
) {
2394 if( !empty( $sublevelCount[$i] ) ) {
2398 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2404 # The canonized header is a version of the header text safe to use for links
2405 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2406 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2407 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2409 # Remove link placeholders by the link text.
2410 # <!--LINK number-->
2412 # link text with suffix
2413 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2414 "\$wgLinkHolders['texts'][\$1]",
2415 $canonized_headline );
2416 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2417 "\$wgInterwikiLinkHolders[\$1]",
2418 $canonized_headline );
2421 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2422 $tocline = trim( $canonized_headline );
2423 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2424 $replacearray = array(
2428 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2429 $refer[$headlineCount] = $canonized_headline;
2431 # count how many in assoc. array so we can track dupes in anchors
2432 @$refers[$canonized_headline]++
;
2433 $refcount[$headlineCount]=$refers[$canonized_headline];
2435 # Don't number the heading if it is the only one (looks silly)
2436 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2437 # the two are different if the line contains a link
2438 $headline=$numbering . ' ' . $headline;
2441 # Create the anchor for linking from the TOC to the section
2442 $anchor = $canonized_headline;
2443 if($refcount[$headlineCount] > 1 ) {
2444 $anchor .= '_' . $refcount[$headlineCount];
2446 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2447 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2449 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2450 if ( empty( $head[$headlineCount] ) ) {
2451 $head[$headlineCount] = '';
2454 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2456 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2459 # give headline the correct <h#> tag
2460 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2468 $toclines = $headlineCount;
2469 $toc .= $sk->tocUnindent( $toclevel - 1 );
2470 $toc = $sk->tocList( $toc );
2473 # split up and insert constructed headlines
2475 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2478 foreach( $blocks as $block ) {
2479 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2480 # This is the [edit] link that appears for the top block of text when
2481 # section editing is enabled
2483 # Disabled because it broke block formatting
2484 # For example, a bullet point in the top line
2485 # $full .= $sk->editSectionLink(0);
2488 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2489 # Top anchor now in skin
2493 if( !empty( $head[$i] ) ) {
2499 $mw =& MagicWord
::get( MAG_TOC
);
2500 return $mw->replace( $toc, $full );
2507 * Return an HTML link for the "ISBN 123456" text
2510 function magicISBN( $text ) {
2512 $fname = 'Parser::magicISBN';
2513 wfProfileIn( $fname );
2515 $a = split( 'ISBN ', ' '.$text );
2516 if ( count ( $a ) < 2 ) {
2517 wfProfileOut( $fname );
2520 $text = substr( array_shift( $a ), 1);
2521 $valid = '0123456789-Xx';
2523 foreach ( $a as $x ) {
2524 $isbn = $blank = '' ;
2525 while ( ' ' == $x{0} ) {
2527 $x = substr( $x, 1 );
2529 if ( $x == '' ) { # blank isbn
2530 $text .= "ISBN $blank";
2533 while ( strstr( $valid, $x{0} ) != false ) {
2535 $x = substr( $x, 1 );
2537 $num = str_replace( '-', '', $isbn );
2538 $num = str_replace( ' ', '', $num );
2539 $num = str_replace( 'x', 'X', $num );
2542 $text .= "ISBN $blank$x";
2544 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2545 $text .= '<a href="' .
2546 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2547 "\" class=\"internal\">ISBN $isbn</a>";
2551 wfProfileOut( $fname );
2556 * Return an HTML link for the "RFC 1234" text
2559 * @param string $text Text to be processed
2560 * @param string $keyword Magic keyword to use (default RFC)
2561 * @param string $urlmsg Interface message to use (default rfcurl)
2564 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2567 $valid = '0123456789';
2570 $a = split( $keyword, ' '.$text );
2571 if ( count ( $a ) < 2 ) {
2574 $text = substr( array_shift( $a ), 1);
2576 /* Check if keyword is preceed by [[.
2577 * This test is made here cause of the array_shift above
2578 * that prevent the test to be done in the foreach.
2580 if ( substr( $text, -2 ) == '[[' ) {
2584 foreach ( $a as $x ) {
2585 /* token might be empty if we have RFC RFC 1234 */
2593 /** remove and save whitespaces in $blank */
2594 while ( $x{0} == ' ' ) {
2596 $x = substr( $x, 1 );
2599 /** remove and save the rfc number in $id */
2600 while ( strstr( $valid, $x{0} ) != false ) {
2602 $x = substr( $x, 1 );
2606 /* call back stripped spaces*/
2607 $text .= $keyword.$blank.$x;
2608 } elseif( $internal ) {
2610 $text .= $keyword.$id.$x;
2612 /* build the external link*/
2613 $url = wfMsg( $urlmsg, $id);
2614 $sk =& $this->mOptions
->getSkin();
2615 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2616 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2619 /* Check if the next RFC keyword is preceed by [[ */
2620 $internal = ( substr($x,-2) == '[[' );
2626 * Transform wiki markup when saving a page by doing \r\n -> \n
2627 * conversion, substitting signatures, {{subst:}} templates, etc.
2629 * @param string $text the text to transform
2630 * @param Title &$title the Title object for the current article
2631 * @param User &$user the User object describing the current user
2632 * @param ParserOptions $options parsing options
2633 * @param bool $clearState whether to clear the parser state first
2634 * @return string the altered wiki markup
2637 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2638 $this->mOptions
= $options;
2639 $this->mTitle
=& $title;
2640 $this->mOutputType
= OT_WIKI
;
2642 if ( $clearState ) {
2643 $this->clearState();
2646 $stripState = false;
2650 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2651 $text = $this->strip( $text, $stripState, false );
2652 $text = $this->pstPass2( $text, $user );
2653 $text = $this->unstrip( $text, $stripState );
2654 $text = $this->unstripNoWiki( $text, $stripState );
2659 * Pre-save transform helper function
2662 function pstPass2( $text, &$user ) {
2663 global $wgLang, $wgContLang, $wgLocaltimezone;
2665 # Variable replacement
2666 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2667 $text = $this->replaceVariables( $text );
2671 $n = $user->getName();
2672 $k = $user->getOption( 'nickname' );
2673 if ( '' == $k ) { $k = $n; }
2674 if ( isset( $wgLocaltimezone ) ) {
2675 $oldtz = getenv( 'TZ' );
2676 putenv( 'TZ='.$wgLocaltimezone );
2679 /* Note: This is the timestamp saved as hardcoded wikitext to
2680 * the database, we use $wgContLang here in order to give
2681 * everyone the same signiture and use the default one rather
2682 * than the one selected in each users preferences.
2684 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2685 ' (' . date( 'T' ) . ')';
2686 if ( isset( $wgLocaltimezone ) ) {
2687 putenv( 'TZ='.$oldtzs );
2690 if( $user->getOption( 'fancysig' ) ) {
2693 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2695 $text = preg_replace( '/~~~~~/', $d, $text );
2696 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2697 $text = preg_replace( '/~~~/', $sigText, $text );
2699 # Context links: [[|name]] and [[name (context)|]]
2701 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2702 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2703 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2704 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2706 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2707 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2708 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2709 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2711 $t = $this->mTitle
->getText();
2712 if ( preg_match( $conpat, $t, $m ) ) {
2715 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2716 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2717 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2719 if ( '' == $context ) {
2720 $text = preg_replace( $p2, '[[\\1]]', $text );
2722 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2725 # Trim trailing whitespace
2726 # MAG_END (__END__) tag allows for trailing
2727 # whitespace to be deliberately included
2728 $text = rtrim( $text );
2729 $mw =& MagicWord
::get( MAG_END
);
2730 $mw->matchAndRemove( $text );
2736 * Set up some variables which are usually set up in parse()
2737 * so that an external function can call some class members with confidence
2740 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2741 $this->mTitle
=& $title;
2742 $this->mOptions
= $options;
2743 $this->mOutputType
= $outputType;
2744 if ( $clearState ) {
2745 $this->clearState();
2750 * Transform a MediaWiki message by replacing magic variables.
2752 * @param string $text the text to transform
2753 * @param ParserOptions $options options
2754 * @return string the text with variables substituted
2757 function transformMsg( $text, $options ) {
2759 static $executing = false;
2761 # Guard against infinite recursion
2767 $this->mTitle
= $wgTitle;
2768 $this->mOptions
= $options;
2769 $this->mOutputType
= OT_MSG
;
2770 $this->clearState();
2771 $text = $this->replaceVariables( $text );
2778 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2779 * Callback will be called with the text within
2780 * Transform and return the text within
2783 function setHook( $tag, $callback ) {
2784 $oldVal = @$this->mTagHooks
[$tag];
2785 $this->mTagHooks
[$tag] = $callback;
2790 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2791 * Placeholders created in Skin::makeLinkObj()
2792 * Returns an array of links found, indexed by PDBK:
2796 * $options is a bit field, RLH_FOR_UPDATE to select for update
2798 function replaceLinkHolders( &$text, $options = 0 ) {
2799 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2800 global $wgInterwikiLinkHolders;
2801 global $outputReplace;
2803 if ( $wgUseOldExistenceCheck ) {
2807 $fname = 'Parser::replaceLinkHolders';
2808 wfProfileIn( $fname );
2813 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2814 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2815 wfProfileIn( $fname.'-check' );
2816 $dbr =& wfGetDB( DB_SLAVE
);
2817 $page = $dbr->tableName( 'page' );
2818 $sk = $wgUser->getSkin();
2819 $threshold = $wgUser->getOption('stubthreshold');
2822 asort( $wgLinkHolders['namespaces'] );
2826 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2828 $title = $wgLinkHolders['titles'][$key];
2830 # Skip invalid entries.
2831 # Result will be ugly, but prevents crash.
2832 if ( is_null( $title ) ) {
2835 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2837 # Check if it's in the link cache already
2838 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2839 $colours[$pdbk] = 1;
2840 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2841 $colours[$pdbk] = 0;
2843 # Not in the link cache, add it to the query
2844 if ( !isset( $current ) ) {
2846 $query = "SELECT page_id, page_namespace, page_title";
2847 if ( $threshold > 0 ) {
2848 $query .= ', page_len, page_is_redirect';
2850 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2851 } elseif ( $current != $val ) {
2853 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2858 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2863 if ( $options & RLH_FOR_UPDATE
) {
2864 $query .= ' FOR UPDATE';
2867 $res = $dbr->query( $query, $fname );
2869 # Fetch data and form into an associative array
2870 # non-existent = broken
2873 while ( $s = $dbr->fetchObject($res) ) {
2874 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2875 $pdbk = $title->getPrefixedDBkey();
2876 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2878 if ( $threshold > 0 ) {
2879 $size = $s->page_len
;
2880 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2881 $colours[$pdbk] = 1;
2883 $colours[$pdbk] = 2;
2886 $colours[$pdbk] = 1;
2890 wfProfileOut( $fname.'-check' );
2892 # Construct search and replace arrays
2893 wfProfileIn( $fname.'-construct' );
2894 $outputReplace = array();
2895 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2896 $pdbk = $pdbks[$key];
2897 $searchkey = '<!--LINK '.$key.'-->';
2898 $title = $wgLinkHolders['titles'][$key];
2899 if ( empty( $colours[$pdbk] ) ) {
2900 $wgLinkCache->addBadLink( $pdbk );
2901 $colours[$pdbk] = 0;
2902 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2903 $wgLinkHolders['texts'][$key],
2904 $wgLinkHolders['queries'][$key] );
2905 } elseif ( $colours[$pdbk] == 1 ) {
2906 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2907 $wgLinkHolders['texts'][$key],
2908 $wgLinkHolders['queries'][$key] );
2909 } elseif ( $colours[$pdbk] == 2 ) {
2910 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2911 $wgLinkHolders['texts'][$key],
2912 $wgLinkHolders['queries'][$key] );
2915 wfProfileOut( $fname.'-construct' );
2918 wfProfileIn( $fname.'-replace' );
2920 $text = preg_replace_callback(
2921 '/(<!--LINK .*?-->)/',
2922 "outputReplaceMatches",
2924 wfProfileOut( $fname.'-replace' );
2927 if ( !empty( $wgInterwikiLinkHolders ) ) {
2928 wfProfileIn( $fname.'-interwiki' );
2929 $outputReplace = $wgInterwikiLinkHolders;
2930 $text = preg_replace_callback(
2931 '/<!--IWLINK (.*?)-->/',
2932 "outputReplaceMatches",
2934 wfProfileOut( $fname.'-interwiki' );
2937 wfProfileOut( $fname );
2942 * Renders an image gallery from a text with one line per image.
2943 * text labels may be given by using |-style alternative text. E.g.
2944 * Image:one.jpg|The number "1"
2945 * Image:tree.jpg|A tree
2946 * given as text will return the HTML of a gallery with two images,
2947 * labeled 'The number "1"' and
2950 function renderImageGallery( $text ) {
2952 global $wgUser, $wgParser, $wgTitle;
2953 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2955 global $wgLinkCache;
2956 $ig = new ImageGallery();
2957 $ig->setShowBytes( false );
2958 $ig->setShowFilename( false );
2959 $lines = explode( "\n", $text );
2961 foreach ( $lines as $line ) {
2962 # match lines like these:
2963 # Image:someimage.jpg|This is some image
2964 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2966 if ( count( $matches ) == 0 ) {
2969 $nt = Title
::newFromURL( $matches[1] );
2970 if( is_null( $nt ) ) {
2971 # Bogus title. Ignore these so we don't bomb out later.
2974 if ( isset( $matches[3] ) ) {
2975 $label = $matches[3];
2980 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
2981 $html = $html->mText
;
2983 $ig->add( new Image( $nt ), $html );
2984 $wgLinkCache->addImageLinkObj( $nt );
2986 return $ig->toHTML();
2992 * @package MediaWiki
2996 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2997 var $mCacheTime; # Used in ParserCache
2998 var $mVersion; # Compatibility check
2999 var $mTitleText; # title text of the chosen language variant
3001 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3002 $containsOldMagic = false, $titletext = '' )
3004 $this->mText
= $text;
3005 $this->mLanguageLinks
= $languageLinks;
3006 $this->mCategoryLinks
= $categoryLinks;
3007 $this->mContainsOldMagic
= $containsOldMagic;
3008 $this->mCacheTime
= '';
3009 $this->mVersion
= MW_PARSER_VERSION
;
3010 $this->mTitleText
= $titletext;
3013 function getText() { return $this->mText
; }
3014 function getLanguageLinks() { return $this->mLanguageLinks
; }
3015 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3016 function getCacheTime() { return $this->mCacheTime
; }
3017 function getTitleText() { return $this->mTitleText
; }
3018 function containsOldMagic() { return $this->mContainsOldMagic
; }
3019 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3020 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3021 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3022 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3023 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3024 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3026 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3028 function merge( $other ) {
3029 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3030 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3031 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3035 * Return true if this cached output object predates the global or
3036 * per-article cache invalidation timestamps, or if it comes from
3037 * an incompatible older version.
3039 * @param string $touched the affected article's last touched timestamp
3043 function expired( $touched ) {
3044 global $wgCacheEpoch;
3045 return $this->getCacheTime() <= $touched ||
3046 $this->getCacheTime() <= $wgCacheEpoch ||
3047 !isset( $this->mVersion
) ||
3048 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3053 * Set options of the Parser
3055 * @package MediaWiki
3059 # All variables are private
3060 var $mUseTeX; # Use texvc to expand <math> tags
3061 var $mUseDynamicDates; # Use DateFormatter to format dates
3062 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3063 var $mAllowExternalImages; # Allow external images inline
3064 var $mSkin; # Reference to the preferred skin
3065 var $mDateFormat; # Date format index
3066 var $mEditSection; # Create "edit section" links
3067 var $mNumberHeadings; # Automatically number headings
3069 function getUseTeX() { return $this->mUseTeX
; }
3070 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3071 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3072 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3073 function getSkin() { return $this->mSkin
; }
3074 function getDateFormat() { return $this->mDateFormat
; }
3075 function getEditSection() { return $this->mEditSection
; }
3076 function getNumberHeadings() { return $this->mNumberHeadings
; }
3078 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3079 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3080 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3081 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3082 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3083 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3084 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3086 function setSkin( &$x ) { $this->mSkin
=& $x; }
3089 * Get parser options
3092 function newFromUser( &$user ) {
3093 $popts = new ParserOptions
;
3094 $popts->initialiseFromUser( $user );
3098 /** Get user options */
3099 function initialiseFromUser( &$userInput ) {
3100 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3101 $fname = 'ParserOptions::initialiseFromUser';
3102 wfProfileIn( $fname );
3103 if ( !$userInput ) {
3105 $user->setLoaded( true );
3107 $user =& $userInput;
3110 $this->mUseTeX
= $wgUseTeX;
3111 $this->mUseDynamicDates
= $wgUseDynamicDates;
3112 $this->mInterwikiMagic
= $wgInterwikiMagic;
3113 $this->mAllowExternalImages
= $wgAllowExternalImages;
3114 wfProfileIn( $fname.'-skin' );
3115 $this->mSkin
=& $user->getSkin();
3116 wfProfileOut( $fname.'-skin' );
3117 $this->mDateFormat
= $user->getOption( 'date' );
3118 $this->mEditSection
= $user->getOption( 'editsection' );
3119 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3120 wfProfileOut( $fname );
3125 * Callback function used by Parser::replaceLinkHolders()
3126 * to substitute link placeholders.
3128 function &outputReplaceMatches( $matches ) {
3129 global $outputReplace;
3130 return $outputReplace[$matches[1]];
3134 * Return the total number of articles
3136 function wfNumberOfArticles() {
3137 global $wgNumberOfArticles;
3140 return $wgNumberOfArticles;
3144 * Get various statistics from the database
3147 function wfLoadSiteStats() {
3148 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3149 $fname = 'wfLoadSiteStats';
3151 if ( -1 != $wgNumberOfArticles ) return;
3152 $dbr =& wfGetDB( DB_SLAVE
);
3153 $s = $dbr->selectRow( 'site_stats',
3154 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3155 array( 'ss_row_id' => 1 ), $fname
3158 if ( $s === false ) {
3161 $wgTotalViews = $s->ss_total_views
;
3162 $wgTotalEdits = $s->ss_total_edits
;
3163 $wgNumberOfArticles = $s->ss_good_articles
;
3169 * Basicly replacing " > and < with HTML entities ( ", >, <)
3171 * @param string $in Text that might contain HTML tags
3172 * @return string Escaped string
3174 function wfEscapeHTMLTagsOnly( $in ) {
3176 array( '"', '>', '<' ),
3177 array( '"', '>', '<' ),