3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.5.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgLinkCache
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mOptions, $mTitle, $mOutputType,
105 $mTemplates, // cache of already loaded templates, avoids
106 // multiple SQL queries for the same string
107 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
108 // in this path. Used for loop detection.
110 var $mIWTransData = array();
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;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 wfRunHooks( 'ParserClearState', array( &$this ) );
159 * First pass--just handle <nowiki> sections, pass the rest off
160 * to internalParse() which does all the real work.
163 * @param string $text Text we want to parse
164 * @param Title &$title A title object
165 * @param array $options
166 * @param boolean $linestart
167 * @param boolean $clearState
168 * @param int $revid number to pass in {{REVISIONID}}
169 * @return ParserOutput a ParserOutput
171 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
172 global $wgUseTidy, $wgContLang;
173 $fname = 'Parser::parse';
174 wfProfileIn( $fname );
180 $this->mOptions
= $options;
181 $this->mTitle
=& $title;
182 $this->mRevisionId
= $revid;
183 $this->mOutputType
= OT_HTML
;
185 $this->mStripState
= NULL;
187 //$text = $this->strip( $text, $this->mStripState );
188 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
189 $x =& $this->mStripState
;
191 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
192 $text = $this->strip( $text, $x );
193 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
195 # Hook to suspend the parser in this state
196 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) )
199 $text = $this->internalParse( $text );
201 $text = $this->unstrip( $text, $this->mStripState
);
203 # Clean up special characters, only run once, next-to-last before doBlockLevels
205 # french spaces, last one Guillemet-left
206 # only if there is something before the space
207 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
208 # french spaces, Guillemet-right
209 '/(\\302\\253) /' => '\\1 ',
210 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
212 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
215 $text = $this->doBlockLevels( $text, $linestart );
217 $this->replaceLinkHolders( $text );
219 # the position of the convert() call should not be changed. it
220 # assumes that the links are all replaces and the only thing left
221 # is the <nowiki> mark.
222 $text = $wgContLang->convert($text);
223 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
225 $text = $this->unstripNoWiki( $text, $this->mStripState
);
227 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
229 $text = Sanitizer
::normalizeCharReferences( $text );
232 $text = Parser
::tidy($text);
235 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
237 $this->mOutput
->setText( $text );
238 wfProfileOut( $fname );
239 return $this->mOutput
;
243 * Get a random string
248 function getRandomString() {
249 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
253 * Replaces all occurrences of <$tag>content</$tag> in the text
254 * with a random marker and returns the new text. the output parameter
255 * $content will be an associative array filled with data on the form
256 * $unique_marker => content.
258 * If $content is already set, the additional entries will be appended
259 * If $tag is set to STRIP_COMMENTS, the function will extract
260 * <!-- HTML comments -->
265 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
266 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
281 if( $tag == STRIP_COMMENTS
) {
282 $start = '/<!--()()/';
285 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
286 $end = "/<\\/$tag\\s*>/i";
289 while ( '' != $text ) {
290 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
292 if( count( $p ) < 4 ) {
299 $marker = $rnd . sprintf('%08X', $n++
);
300 $stripped .= $marker;
302 $tags[$marker] = "<$tag$attributes$empty>";
303 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
305 if ( $empty === '/' ) {
306 // Empty element tag, <tag />
307 $content[$marker] = null;
310 $q = preg_split( $end, $inside, 2 );
311 $content[$marker] = $q[0];
312 if( count( $q ) < 2 ) {
313 # No end tag -- let it run out to the end of the text.
324 * Wrapper function for extractTagsAndParams
325 * for cases where $tags and $params isn't needed
326 * i.e. where tags will never have params, like <nowiki>
331 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
332 $dummy_tags = array();
333 $dummy_params = array();
335 return Parser
::extractTagsAndParams( $tag, $text, $content,
336 $dummy_tags, $dummy_params, $uniq_prefix );
340 * Strips and renders nowiki, pre, math, hiero
341 * If $render is set, performs necessary rendering operations on plugins
342 * Returns the text, and fills an array with data needed in unstrip()
343 * If the $state is already a valid strip state, it adds to the state
345 * @param bool $stripcomments when set, HTML comments <!-- like this -->
346 * will be stripped in addition to other tags. This is important
347 * for section editing, where these comments cause confusion when
348 * counting the sections in the wikisource
352 function strip( $text, &$state, $stripcomments = false ) {
353 $render = ($this->mOutputType
== OT_HTML
);
354 $html_content = array();
355 $nowiki_content = array();
356 $math_content = array();
357 $pre_content = array();
358 $comment_content = array();
359 $ext_content = array();
361 $ext_params = array();
362 $gallery_content = array();
364 # Replace any instances of the placeholders
365 $uniq_prefix = $this->mUniqPrefix
;
366 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
371 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
372 foreach( $html_content as $marker => $content ) {
374 # Raw and unchecked for validity.
375 $html_content[$marker] = $content;
377 $html_content[$marker] = '<html>'.$content.'</html>';
383 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
384 foreach( $nowiki_content as $marker => $content ) {
386 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
388 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
393 if( $this->mOptions
->getUseTeX() ) {
394 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
395 foreach( $math_content as $marker => $content ){
397 $math_content[$marker] = renderMath( $content );
399 $math_content[$marker] = '<math>'.$content.'</math>';
405 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
406 foreach( $pre_content as $marker => $content ){
408 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
410 $pre_content[$marker] = '<pre>'.$content.'</pre>';
415 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
416 foreach( $gallery_content as $marker => $content ) {
417 require_once( 'ImageGallery.php' );
419 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
421 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
427 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
428 foreach( $comment_content as $marker => $content ){
429 $comment_content[$marker] = '<!--'.$content.'-->';
434 foreach ( $this->mTagHooks
as $tag => $callback ) {
435 $ext_content[$tag] = array();
436 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
437 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
438 foreach( $ext_content[$tag] as $marker => $content ) {
439 $full_tag = $ext_tags[$tag][$marker];
440 $params = $ext_params[$tag][$marker];
442 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
444 if ( is_null( $content ) ) {
446 $ext_content[$tag][$marker] = $full_tag;
448 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
454 # Merge state with the pre-existing state, if there is one
456 $state['html'] = $state['html'] +
$html_content;
457 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
458 $state['math'] = $state['math'] +
$math_content;
459 $state['pre'] = $state['pre'] +
$pre_content;
460 $state['comment'] = $state['comment'] +
$comment_content;
461 $state['gallery'] = $state['gallery'] +
$gallery_content;
463 foreach( $ext_content as $tag => $array ) {
464 if ( array_key_exists( $tag, $state ) ) {
465 $state[$tag] = $state[$tag] +
$array;
470 'html' => $html_content,
471 'nowiki' => $nowiki_content,
472 'math' => $math_content,
473 'pre' => $pre_content,
474 'comment' => $comment_content,
475 'gallery' => $gallery_content,
482 * restores pre, math, and hiero removed by strip()
484 * always call unstripNoWiki() after this one
487 function unstrip( $text, &$state ) {
488 if ( !is_array( $state ) ) {
492 # Must expand in reverse order, otherwise nested tags will be corrupted
493 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
494 if( $tag != 'nowiki' && $tag != 'html' ) {
495 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
496 $text = str_replace( $uniq, $content, $text );
505 * always call this after unstrip() to preserve the order
509 function unstripNoWiki( $text, &$state ) {
510 if ( !is_array( $state ) ) {
514 # Must expand in reverse order, otherwise nested tags will be corrupted
515 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
516 $text = str_replace( key( $state['nowiki'] ), $content, $text );
521 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
522 $text = str_replace( key( $state['html'] ), $content, $text );
530 * Add an item to the strip state
531 * Returns the unique tag which must be inserted into the stripped text
532 * The tag will be replaced with the original text in unstrip()
536 function insertStripItem( $text, &$state ) {
537 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
544 'comment' => array(),
545 'gallery' => array(),
548 $state['item'][$rnd] = $text;
553 * Interface with html tidy, used if $wgUseTidy = true.
554 * If tidy isn't able to correct the markup, the original will be
555 * returned in all its glory with a warning comment appended.
557 * Either the external tidy program or the in-process tidy extension
558 * will be used depending on availability. Override the default
559 * $wgTidyInternal setting to disable the internal if it's not working.
561 * @param string $text Hideous HTML input
562 * @return string Corrected HTML output
566 function tidy( $text ) {
567 global $wgTidyInternal;
568 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
569 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
570 '<head><title>test</title></head><body>'.$text.'</body></html>';
571 if( $wgTidyInternal ) {
572 $correctedtext = Parser
::internalTidy( $wrappedtext );
574 $correctedtext = Parser
::externalTidy( $wrappedtext );
576 if( is_null( $correctedtext ) ) {
577 wfDebug( "Tidy error detected!\n" );
578 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
580 return $correctedtext;
584 * Spawn an external HTML tidy process and get corrected markup back from it.
589 function externalTidy( $text ) {
590 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
591 $fname = 'Parser::externalTidy';
592 wfProfileIn( $fname );
597 $descriptorspec = array(
598 0 => array('pipe', 'r'),
599 1 => array('pipe', 'w'),
600 2 => array('file', '/dev/null', 'a')
603 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
604 if (is_resource($process)) {
605 fwrite($pipes[0], $text);
607 while (!feof($pipes[1])) {
608 $cleansource .= fgets($pipes[1], 1024);
611 proc_close($process);
614 wfProfileOut( $fname );
616 if( $cleansource == '' && $text != '') {
617 // Some kind of error happened, so we couldn't get the corrected text.
618 // Just give up; we'll use the source text and append a warning.
626 * Use the HTML tidy PECL extension to use the tidy library in-process,
627 * saving the overhead of spawning a new process. Currently written to
628 * the PHP 4.3.x version of the extension, may not work on PHP 5.
630 * 'pear install tidy' should be able to compile the extension module.
635 function internalTidy( $text ) {
637 $fname = 'Parser::internalTidy';
638 wfProfileIn( $fname );
640 tidy_load_config( $wgTidyConf );
641 tidy_set_encoding( 'utf8' );
642 tidy_parse_string( $text );
644 if( tidy_get_status() == 2 ) {
645 // 2 is magic number for fatal error
646 // http://www.php.net/manual/en/function.tidy-get-status.php
649 $cleansource = tidy_get_output();
651 wfProfileOut( $fname );
656 * parse the wiki syntax used to render tables
660 function doTableStuff ( $t ) {
661 $fname = 'Parser::doTableStuff';
662 wfProfileIn( $fname );
664 $t = explode ( "\n" , $t ) ;
665 $td = array () ; # Is currently a td tag open?
666 $ltd = array () ; # Was it TD or TH?
667 $tr = array () ; # Is currently a tr tag open?
668 $ltr = array () ; # tr attributes
669 $indent_level = 0; # indent level of the table
670 foreach ( $t AS $k => $x )
673 $fc = substr ( $x , 0 , 1 ) ;
674 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
675 $indent_level = strlen( $matches[1] );
677 $attributes = $this->unstripForHTML( $matches[2] );
679 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
680 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
681 array_push ( $td , false ) ;
682 array_push ( $ltd , '' ) ;
683 array_push ( $tr , false ) ;
684 array_push ( $ltr , '' ) ;
686 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
687 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
688 $z = "</table>" . substr ( $x , 2);
689 $l = array_pop ( $ltd ) ;
690 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
691 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
693 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
695 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
696 $x = substr ( $x , 1 ) ;
697 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
699 $l = array_pop ( $ltd ) ;
700 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
701 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
704 array_push ( $tr , false ) ;
705 array_push ( $td , false ) ;
706 array_push ( $ltd , '' ) ;
707 $attributes = $this->unstripForHTML( $x );
708 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
710 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
712 if ( '|+' == substr ( $x , 0 , 2 ) ) {
714 $x = substr ( $x , 1 ) ;
716 $after = substr ( $x , 1 ) ;
717 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
718 $after = explode ( '||' , $after ) ;
721 # Loop through each table cell
722 foreach ( $after AS $theline )
727 $tra = array_pop ( $ltr ) ;
728 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
729 array_push ( $tr , true ) ;
730 array_push ( $ltr , '' ) ;
733 $l = array_pop ( $ltd ) ;
734 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
735 if ( $fc == '|' ) $l = 'td' ;
736 else if ( $fc == '!' ) $l = 'th' ;
737 else if ( $fc == '+' ) $l = 'caption' ;
739 array_push ( $ltd , $l ) ;
742 $y = explode ( '|' , $theline , 2 ) ;
743 # Note that a '|' inside an invalid link should not
744 # be mistaken as delimiting cell parameters
745 if ( strpos( $y[0], '[[' ) !== false ) {
746 $y = array ($theline);
748 if ( count ( $y ) == 1 )
749 $y = "{$z}<{$l}>{$y[0]}" ;
751 $attributes = $this->unstripForHTML( $y[0] );
752 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
755 array_push ( $td , true ) ;
760 # Closing open td, tr && table
761 while ( count ( $td ) > 0 )
763 if ( array_pop ( $td ) ) $t[] = '</td>' ;
764 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
768 $t = implode ( "\n" , $t ) ;
769 wfProfileOut( $fname );
774 * Helper function for parse() that transforms wiki markup into
775 * HTML. Only called for $mOutputType == OT_HTML.
779 function internalParse( $text ) {
783 $fname = 'Parser::internalParse';
784 wfProfileIn( $fname );
786 # Remove <noinclude> tags and <includeonly> sections
787 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
788 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
789 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
791 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
792 $text = $this->replaceVariables( $text, $args );
794 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
796 $text = $this->doHeadings( $text );
797 if($this->mOptions
->getUseDynamicDates()) {
798 $df =& DateFormatter
::getInstance();
799 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
801 $text = $this->doAllQuotes( $text );
802 $text = $this->replaceInternalLinks( $text );
803 $text = $this->replaceExternalLinks( $text );
805 # replaceInternalLinks may sometimes leave behind
806 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
807 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
809 $text = $this->doMagicLinks( $text );
810 $text = $this->doTableStuff( $text );
811 $text = $this->formatHeadings( $text, $isMain );
813 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
814 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
816 wfProfileOut( $fname );
820 function scarySubstitution($matches) {
821 # return "[[".$matches[0]."]]";
822 return $this->mIWTransData
[(int)$matches[0]];
826 * Replace special strings like "ISBN xxx" and "RFC xxx" with
827 * magic external links.
831 function &doMagicLinks( &$text ) {
832 $text = $this->magicISBN( $text );
833 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
834 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
839 * Parse headers and return html
843 function doHeadings( $text ) {
844 $fname = 'Parser::doHeadings';
845 wfProfileIn( $fname );
846 for ( $i = 6; $i >= 1; --$i ) {
847 $h = str_repeat( '=', $i );
848 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
849 "<h{$i}>\\1</h{$i}>\\2", $text );
851 wfProfileOut( $fname );
856 * Replace single quotes with HTML markup
858 * @return string the altered text
860 function doAllQuotes( $text ) {
861 $fname = 'Parser::doAllQuotes';
862 wfProfileIn( $fname );
864 $lines = explode( "\n", $text );
865 foreach ( $lines as $line ) {
866 $outtext .= $this->doQuotes ( $line ) . "\n";
868 $outtext = substr($outtext, 0,-1);
869 wfProfileOut( $fname );
874 * Helper function for doAllQuotes()
877 function doQuotes( $text ) {
878 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
879 if ( count( $arr ) == 1 )
883 # First, do some preliminary work. This may shift some apostrophes from
884 # being mark-up to being text. It also counts the number of occurrences
885 # of bold and italics mark-ups.
889 foreach ( $arr as $r )
891 if ( ( $i %
2 ) == 1 )
893 # If there are ever four apostrophes, assume the first is supposed to
894 # be text, and the remaining three constitute mark-up for bold text.
895 if ( strlen( $arr[$i] ) == 4 )
900 # If there are more than 5 apostrophes in a row, assume they're all
901 # text except for the last 5.
902 else if ( strlen( $arr[$i] ) > 5 )
904 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
907 # Count the number of occurrences of bold and italics mark-ups.
908 # We are not counting sequences of five apostrophes.
909 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
910 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
911 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
916 # If there is an odd number of both bold and italics, it is likely
917 # that one of the bold ones was meant to be an apostrophe followed
918 # by italics. Which one we cannot know for certain, but it is more
919 # likely to be one that has a single-letter word before it.
920 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
923 $firstsingleletterword = -1;
924 $firstmultiletterword = -1;
926 foreach ( $arr as $r )
928 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
930 $x1 = substr ($arr[$i-1], -1);
931 $x2 = substr ($arr[$i-1], -2, 1);
933 if ($firstspace == -1) $firstspace = $i;
934 } else if ($x2 == ' ') {
935 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
937 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
943 # If there is a single-letter word, use it!
944 if ($firstsingleletterword > -1)
946 $arr [ $firstsingleletterword ] = "''";
947 $arr [ $firstsingleletterword-1 ] .= "'";
949 # If not, but there's a multi-letter word, use that one.
950 else if ($firstmultiletterword > -1)
952 $arr [ $firstmultiletterword ] = "''";
953 $arr [ $firstmultiletterword-1 ] .= "'";
955 # ... otherwise use the first one that has neither.
956 # (notice that it is possible for all three to be -1 if, for example,
957 # there is only one pentuple-apostrophe in the line)
958 else if ($firstspace > -1)
960 $arr [ $firstspace ] = "''";
961 $arr [ $firstspace-1 ] .= "'";
965 # Now let's actually convert our apostrophic mush to HTML!
974 if ($state == 'both')
981 if (strlen ($r) == 2)
984 { $output .= '</i>'; $state = ''; }
985 else if ($state == 'bi')
986 { $output .= '</i>'; $state = 'b'; }
987 else if ($state == 'ib')
988 { $output .= '</b></i><b>'; $state = 'b'; }
989 else if ($state == 'both')
990 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
991 else # $state can be 'b' or ''
992 { $output .= '<i>'; $state .= 'i'; }
994 else if (strlen ($r) == 3)
997 { $output .= '</b>'; $state = ''; }
998 else if ($state == 'bi')
999 { $output .= '</i></b><i>'; $state = 'i'; }
1000 else if ($state == 'ib')
1001 { $output .= '</b>'; $state = 'i'; }
1002 else if ($state == 'both')
1003 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1004 else # $state can be 'i' or ''
1005 { $output .= '<b>'; $state .= 'b'; }
1007 else if (strlen ($r) == 5)
1010 { $output .= '</b><i>'; $state = 'i'; }
1011 else if ($state == 'i')
1012 { $output .= '</i><b>'; $state = 'b'; }
1013 else if ($state == 'bi')
1014 { $output .= '</i></b>'; $state = ''; }
1015 else if ($state == 'ib')
1016 { $output .= '</b></i>'; $state = ''; }
1017 else if ($state == 'both')
1018 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1019 else # ($state == '')
1020 { $buffer = ''; $state = 'both'; }
1025 # Now close all remaining tags. Notice that the order is important.
1026 if ($state == 'b' ||
$state == 'ib')
1028 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1032 if ($state == 'both')
1033 $output .= '<b><i>'.$buffer.'</i></b>';
1039 * Replace external links
1041 * Note: this is all very hackish and the order of execution matters a lot.
1042 * Make sure to run maintenance/parserTests.php if you change this code.
1046 function replaceExternalLinks( $text ) {
1048 $fname = 'Parser::replaceExternalLinks';
1049 wfProfileIn( $fname );
1051 $sk =& $this->mOptions
->getSkin();
1053 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1055 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1058 while ( $i<count( $bits ) ) {
1060 $protocol = $bits[$i++
];
1061 $text = $bits[$i++
];
1062 $trail = $bits[$i++
];
1064 # The characters '<' and '>' (which were escaped by
1065 # removeHTMLtags()) should not be included in
1066 # URLs, per RFC 2396.
1067 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1068 $text = substr($url, $m2[0][1]) . ' ' . $text;
1069 $url = substr($url, 0, $m2[0][1]);
1072 # If the link text is an image URL, replace it with an <img> tag
1073 # This happened by accident in the original parser, but some people used it extensively
1074 $img = $this->maybeMakeExternalImage( $text );
1075 if ( $img !== false ) {
1081 # Set linktype for CSS - if URL==text, link is essentially free
1082 $linktype = ($text == $url) ?
'free' : 'text';
1084 # No link text, e.g. [http://domain.tld/some.link]
1085 if ( $text == '' ) {
1086 # Autonumber if allowed
1087 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1088 $text = '[' . ++
$this->mAutonumber
. ']';
1089 $linktype = 'autonumber';
1091 # Otherwise just use the URL
1092 $text = htmlspecialchars( $url );
1096 # Have link text, e.g. [http://domain.tld/some.link text]s
1098 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1101 $text = $wgContLang->markNoConversion($text);
1103 # Replace & from obsolete syntax with &.
1104 # All HTML entities will be escaped by makeExternalLink()
1105 # or maybeMakeExternalImage()
1106 $url = str_replace( '&', '&', $url );
1108 # Process the trail (i.e. everything after this link up until start of the next link),
1109 # replacing any non-bracketed links
1110 $trail = $this->replaceFreeExternalLinks( $trail );
1113 # Use the encoded URL
1114 # This means that users can paste URLs directly into the text
1115 # Funny characters like ö aren't valid in URLs anyway
1116 # This was changed in August 2004
1117 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1120 wfProfileOut( $fname );
1125 * Replace anything that looks like a URL with a link
1128 function replaceFreeExternalLinks( $text ) {
1130 $fname = 'Parser::replaceFreeExternalLinks';
1131 wfProfileIn( $fname );
1133 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1134 $s = array_shift( $bits );
1137 $sk =& $this->mOptions
->getSkin();
1139 while ( $i < count( $bits ) ){
1140 $protocol = $bits[$i++
];
1141 $remainder = $bits[$i++
];
1143 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1144 # Found some characters after the protocol that look promising
1145 $url = $protocol . $m[1];
1148 # The characters '<' and '>' (which were escaped by
1149 # removeHTMLtags()) should not be included in
1150 # URLs, per RFC 2396.
1151 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1152 $trail = substr($url, $m2[0][1]) . $trail;
1153 $url = substr($url, 0, $m2[0][1]);
1156 # Move trailing punctuation to $trail
1158 # If there is no left bracket, then consider right brackets fair game too
1159 if ( strpos( $url, '(' ) === false ) {
1163 $numSepChars = strspn( strrev( $url ), $sep );
1164 if ( $numSepChars ) {
1165 $trail = substr( $url, -$numSepChars ) . $trail;
1166 $url = substr( $url, 0, -$numSepChars );
1169 # Replace & from obsolete syntax with &.
1170 # All HTML entities will be escaped by makeExternalLink()
1171 # or maybeMakeExternalImage()
1172 $url = str_replace( '&', '&', $url );
1174 # Is this an external image?
1175 $text = $this->maybeMakeExternalImage( $url );
1176 if ( $text === false ) {
1177 # Not an image, make a link
1178 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1180 $s .= $text . $trail;
1182 $s .= $protocol . $remainder;
1185 wfProfileOut( $fname );
1190 * make an image if it's allowed, either through the global
1191 * option or through the exception
1194 function maybeMakeExternalImage( $url ) {
1195 $sk =& $this->mOptions
->getSkin();
1196 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1197 $imagesexception = !empty($imagesfrom);
1199 if ( $this->mOptions
->getAllowExternalImages()
1200 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1201 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1203 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1210 * Process [[ ]] wikilinks
1214 function replaceInternalLinks( $s ) {
1215 global $wgContLang, $wgLinkCache;
1216 static $fname = 'Parser::replaceInternalLinks' ;
1218 wfProfileIn( $fname );
1220 wfProfileIn( $fname.'-setup' );
1222 # the % is needed to support urlencoded titles as well
1223 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1225 $sk =& $this->mOptions
->getSkin();
1227 #split the entire text string on occurences of [[
1228 $a = explode( '[[', ' ' . $s );
1229 #get the first element (all text up to first [[), and remove the space we added
1230 $s = array_shift( $a );
1231 $s = substr( $s, 1 );
1233 # Match a link having the form [[namespace:link|alternate]]trail
1235 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1236 # Match cases where there is no "]]", which might still be images
1237 static $e1_img = FALSE;
1238 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1239 # Match the end of a line for a word that's not followed by whitespace,
1240 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1241 $e2 = wfMsgForContent( 'linkprefix' );
1243 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1245 if( is_null( $this->mTitle
) ) {
1246 wfDebugDieBacktrace( 'nooo' );
1248 $nottalk = !$this->mTitle
->isTalkPage();
1250 if ( $useLinkPrefixExtension ) {
1251 if ( preg_match( $e2, $s, $m ) ) {
1252 $first_prefix = $m[2];
1254 $first_prefix = false;
1260 $selflink = $this->mTitle
->getPrefixedText();
1261 wfProfileOut( $fname.'-setup' );
1263 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1264 $useSubpages = $this->areSubpagesAllowed();
1266 # Loop for each link
1267 for ($k = 0; isset( $a[$k] ); $k++
) {
1269 if ( $useLinkPrefixExtension ) {
1270 wfProfileIn( $fname.'-prefixhandling' );
1271 if ( preg_match( $e2, $s, $m ) ) {
1279 $prefix = $first_prefix;
1280 $first_prefix = false;
1282 wfProfileOut( $fname.'-prefixhandling' );
1285 $might_be_img = false;
1287 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1289 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1290 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1291 # the real problem is with the $e1 regex
1294 # Still some problems for cases where the ] is meant to be outside punctuation,
1295 # and no image is in sight. See bug 2095.
1297 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1298 $text .= ']'; # so that replaceExternalLinks($text) works later
1301 # fix up urlencoded title texts
1302 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1304 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1305 $might_be_img = true;
1307 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1309 } else { # Invalid form; output directly
1310 $s .= $prefix . '[[' . $line ;
1314 # Don't allow internal links to pages containing
1315 # PROTO: where PROTO is a valid URL protocol; these
1316 # should be external links.
1317 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1318 $s .= $prefix . '[[' . $line ;
1322 # Make subpage if necessary
1323 if( $useSubpages ) {
1324 $link = $this->maybeDoSubpageLink( $m[1], $text );
1329 $noforce = (substr($m[1], 0, 1) != ':');
1331 # Strip off leading ':'
1332 $link = substr($link, 1);
1335 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1337 $s .= $prefix . '[[' . $line;
1341 #check other language variants of the link
1342 #if the article does not exist
1343 if( $checkVariantLink
1344 && $nt->getArticleID() == 0 ) {
1345 $wgContLang->findVariantLink($link, $nt);
1348 $ns = $nt->getNamespace();
1349 $iw = $nt->getInterWiki();
1351 if ($might_be_img) { # if this is actually an invalid link
1352 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1354 while (isset ($a[$k+
1]) ) {
1355 #look at the next 'line' to see if we can close it there
1356 $spliced = array_splice( $a, $k +
1, 1 );
1357 $next_line = array_shift( $spliced );
1358 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1359 # the first ]] closes the inner link, the second the image
1361 $text .= '[[' . $m[1];
1364 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1365 #if there's exactly one ]] that's fine, we'll keep looking
1366 $text .= '[[' . $m[0];
1368 #if $next_line is invalid too, we need look no further
1369 $text .= '[[' . $next_line;
1374 # we couldn't find the end of this imageLink, so output it raw
1375 #but don't ignore what might be perfectly normal links in the text we've examined
1376 $text = $this->replaceInternalLinks($text);
1377 $s .= $prefix . '[[' . $link . '|' . $text;
1378 # note: no $trail, because without an end, there *is* no trail
1381 } else { #it's not an image, so output it raw
1382 $s .= $prefix . '[[' . $link . '|' . $text;
1383 # note: no $trail, because without an end, there *is* no trail
1388 $wasblank = ( '' == $text );
1389 if( $wasblank ) $text = $link;
1392 # Link not escaped by : , create the various objects
1396 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1397 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1398 $s = rtrim($s . "\n");
1399 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1403 if ( $ns == NS_IMAGE
) {
1404 wfProfileIn( "$fname-image" );
1405 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1406 # recursively parse links inside the image caption
1407 # actually, this will parse them in any other parameters, too,
1408 # but it might be hard to fix that, and it doesn't matter ATM
1409 $text = $this->replaceExternalLinks($text);
1410 $text = $this->replaceInternalLinks($text);
1412 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1413 $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', "{$this->mUniqPrefix}NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1414 $wgLinkCache->addImageLinkObj( $nt );
1416 wfProfileOut( "$fname-image" );
1419 wfProfileOut( "$fname-image" );
1423 if ( $ns == NS_CATEGORY
) {
1424 wfProfileIn( "$fname-category" );
1425 $t = $wgContLang->convertHtml( $nt->getText() );
1426 $s = rtrim($s . "\n"); # bug 87
1428 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1429 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1430 $wgLinkCache->resume();
1433 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1434 $sortkey = $this->mTitle
->getText();
1436 $sortkey = $this->mTitle
->getPrefixedText();
1441 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1442 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1443 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1444 $this->mOutput
->addCategoryLink( $t );
1447 * Strip the whitespace Category links produce, see bug 87
1448 * @todo We might want to use trim($tmp, "\n") here.
1450 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1452 wfProfileOut( "$fname-category" );
1457 if( ( $nt->getPrefixedText() === $selflink ) &&
1458 ( $nt->getFragment() === '' ) ) {
1459 # Self-links are handled specially; generally de-link and change to bold.
1460 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1464 # Special and Media are pseudo-namespaces; no pages actually exist in them
1465 if( $ns == NS_MEDIA
) {
1466 $link = $sk->makeMediaLinkObj( $nt, $text );
1467 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1468 $s .= $prefix . str_replace( 'http://', "http{$this->mUniqPrefix}NOPARSE://", $link ) . $trail;
1469 $wgLinkCache->addImageLinkObj( $nt );
1471 } elseif( $ns == NS_SPECIAL
) {
1472 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1474 } elseif( $ns == NS_IMAGE
) {
1475 $img = Image
::newFromTitle( $nt );
1476 if( $img->exists() ) {
1477 // Force a blue link if the file exists; may be a remote
1478 // upload on the shared repository, and we want to see its
1479 // auto-generated page.
1480 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1484 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1486 wfProfileOut( $fname );
1491 * Make a link placeholder. The text returned can be later resolved to a real link with
1492 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1493 * parsing of interwiki links, and secondly to allow all extistence checks and
1494 * article length checks (for stub links) to be bundled into a single query.
1497 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1498 if ( ! is_object($nt) ) {
1500 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1502 # Separate the link trail from the rest of the link
1503 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1505 if ( $nt->isExternal() ) {
1506 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1507 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1508 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1510 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1511 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1512 $this->mLinkHolders
['queries'][] = $query;
1513 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1514 $this->mLinkHolders
['titles'][] = $nt;
1516 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1523 * Return true if subpage links should be expanded on this page.
1526 function areSubpagesAllowed() {
1527 # Some namespaces don't allow subpages
1528 global $wgNamespacesWithSubpages;
1529 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1533 * Handle link to subpage if necessary
1534 * @param string $target the source of the link
1535 * @param string &$text the link text, modified as necessary
1536 * @return string the full name of the link
1539 function maybeDoSubpageLink($target, &$text) {
1542 # :Foobar -- override special treatment of prefix (images, language links)
1543 # /Foobar -- convert to CurrentPage/Foobar
1544 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1545 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1546 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1548 $fname = 'Parser::maybeDoSubpageLink';
1549 wfProfileIn( $fname );
1550 $ret = $target; # default return value is no change
1552 # Some namespaces don't allow subpages,
1553 # so only perform processing if subpages are allowed
1554 if( $this->areSubpagesAllowed() ) {
1555 # Look at the first character
1556 if( $target != '' && $target{0} == '/' ) {
1557 # / at end means we don't want the slash to be shown
1558 if( substr( $target, -1, 1 ) == '/' ) {
1559 $target = substr( $target, 1, -1 );
1562 $noslash = substr( $target, 1 );
1565 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1566 if( '' === $text ) {
1568 } # this might be changed for ugliness reasons
1570 # check for .. subpage backlinks
1572 $nodotdot = $target;
1573 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1575 $nodotdot = substr( $nodotdot, 3 );
1577 if($dotdotcount > 0) {
1578 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1579 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1580 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1581 # / at the end means don't show full path
1582 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1583 $nodotdot = substr( $nodotdot, 0, -1 );
1584 if( '' === $text ) {
1588 $nodotdot = trim( $nodotdot );
1589 if( $nodotdot != '' ) {
1590 $ret .= '/' . $nodotdot;
1597 wfProfileOut( $fname );
1602 * Used by doBlockLevels()
1605 /* private */ function closeParagraph() {
1607 if ( '' != $this->mLastSection
) {
1608 $result = '</' . $this->mLastSection
. ">\n";
1610 $this->mInPre
= false;
1611 $this->mLastSection
= '';
1614 # getCommon() returns the length of the longest common substring
1615 # of both arguments, starting at the beginning of both.
1617 /* private */ function getCommon( $st1, $st2 ) {
1618 $fl = strlen( $st1 );
1619 $shorter = strlen( $st2 );
1620 if ( $fl < $shorter ) { $shorter = $fl; }
1622 for ( $i = 0; $i < $shorter; ++
$i ) {
1623 if ( $st1{$i} != $st2{$i} ) { break; }
1627 # These next three functions open, continue, and close the list
1628 # element appropriate to the prefix character passed into them.
1630 /* private */ function openList( $char ) {
1631 $result = $this->closeParagraph();
1633 if ( '*' == $char ) { $result .= '<ul><li>'; }
1634 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1635 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1636 else if ( ';' == $char ) {
1637 $result .= '<dl><dt>';
1638 $this->mDTopen
= true;
1640 else { $result = '<!-- ERR 1 -->'; }
1645 /* private */ function nextItem( $char ) {
1646 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1647 else if ( ':' == $char ||
';' == $char ) {
1649 if ( $this->mDTopen
) { $close = '</dt>'; }
1650 if ( ';' == $char ) {
1651 $this->mDTopen
= true;
1652 return $close . '<dt>';
1654 $this->mDTopen
= false;
1655 return $close . '<dd>';
1658 return '<!-- ERR 2 -->';
1661 /* private */ function closeList( $char ) {
1662 if ( '*' == $char ) { $text = '</li></ul>'; }
1663 else if ( '#' == $char ) { $text = '</li></ol>'; }
1664 else if ( ':' == $char ) {
1665 if ( $this->mDTopen
) {
1666 $this->mDTopen
= false;
1667 $text = '</dt></dl>';
1669 $text = '</dd></dl>';
1672 else { return '<!-- ERR 3 -->'; }
1678 * Make lists from lines starting with ':', '*', '#', etc.
1681 * @return string the lists rendered as HTML
1683 function doBlockLevels( $text, $linestart ) {
1684 $fname = 'Parser::doBlockLevels';
1685 wfProfileIn( $fname );
1687 # Parsing through the text line by line. The main thing
1688 # happening here is handling of block-level elements p, pre,
1689 # and making lists from lines starting with * # : etc.
1691 $textLines = explode( "\n", $text );
1693 $lastPrefix = $output = '';
1694 $this->mDTopen
= $inBlockElem = false;
1696 $paragraphStack = false;
1698 if ( !$linestart ) {
1699 $output .= array_shift( $textLines );
1701 foreach ( $textLines as $oLine ) {
1702 $lastPrefixLength = strlen( $lastPrefix );
1703 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1704 $preOpenMatch = preg_match('/<pre/i', $oLine );
1705 if ( !$this->mInPre
) {
1706 # Multiple prefixes may abut each other for nested lists.
1707 $prefixLength = strspn( $oLine, '*#:;' );
1708 $pref = substr( $oLine, 0, $prefixLength );
1711 $pref2 = str_replace( ';', ':', $pref );
1712 $t = substr( $oLine, $prefixLength );
1713 $this->mInPre
= !empty($preOpenMatch);
1715 # Don't interpret any other prefixes in preformatted text
1717 $pref = $pref2 = '';
1722 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1723 # Same as the last item, so no need to deal with nesting or opening stuff
1724 $output .= $this->nextItem( substr( $pref, -1 ) );
1725 $paragraphStack = false;
1727 if ( substr( $pref, -1 ) == ';') {
1728 # The one nasty exception: definition lists work like this:
1729 # ; title : definition text
1730 # So we check for : in the remainder text to split up the
1731 # title and definition, without b0rking links.
1733 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1735 $output .= $term . $this->nextItem( ':' );
1738 } elseif( $prefixLength ||
$lastPrefixLength ) {
1739 # Either open or close a level...
1740 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1741 $paragraphStack = false;
1743 while( $commonPrefixLength < $lastPrefixLength ) {
1744 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1745 --$lastPrefixLength;
1747 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1748 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1750 while ( $prefixLength > $commonPrefixLength ) {
1751 $char = substr( $pref, $commonPrefixLength, 1 );
1752 $output .= $this->openList( $char );
1754 if ( ';' == $char ) {
1755 # FIXME: This is dupe of code above
1756 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1758 $output .= $term . $this->nextItem( ':' );
1761 ++
$commonPrefixLength;
1763 $lastPrefix = $pref2;
1765 if( 0 == $prefixLength ) {
1766 wfProfileIn( "$fname-paragraph" );
1767 # No prefix (not in list)--go to paragraph mode
1768 // XXX: use a stack for nestable elements like span, table and div
1769 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1770 $closematch = preg_match(
1771 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1772 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1773 if ( $openmatch or $closematch ) {
1774 $paragraphStack = false;
1775 $output .= $this->closeParagraph();
1776 if ( $preOpenMatch and !$preCloseMatch ) {
1777 $this->mInPre
= true;
1779 if ( $closematch ) {
1780 $inBlockElem = false;
1782 $inBlockElem = true;
1784 } else if ( !$inBlockElem && !$this->mInPre
) {
1785 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1787 if ($this->mLastSection
!= 'pre') {
1788 $paragraphStack = false;
1789 $output .= $this->closeParagraph().'<pre>';
1790 $this->mLastSection
= 'pre';
1792 $t = substr( $t, 1 );
1795 if ( '' == trim($t) ) {
1796 if ( $paragraphStack ) {
1797 $output .= $paragraphStack.'<br />';
1798 $paragraphStack = false;
1799 $this->mLastSection
= 'p';
1801 if ($this->mLastSection
!= 'p' ) {
1802 $output .= $this->closeParagraph();
1803 $this->mLastSection
= '';
1804 $paragraphStack = '<p>';
1806 $paragraphStack = '</p><p>';
1810 if ( $paragraphStack ) {
1811 $output .= $paragraphStack;
1812 $paragraphStack = false;
1813 $this->mLastSection
= 'p';
1814 } else if ($this->mLastSection
!= 'p') {
1815 $output .= $this->closeParagraph().'<p>';
1816 $this->mLastSection
= 'p';
1821 wfProfileOut( "$fname-paragraph" );
1823 // somewhere above we forget to get out of pre block (bug 785)
1824 if($preCloseMatch && $this->mInPre
) {
1825 $this->mInPre
= false;
1827 if ($paragraphStack === false) {
1831 while ( $prefixLength ) {
1832 $output .= $this->closeList( $pref2{$prefixLength-1} );
1835 if ( '' != $this->mLastSection
) {
1836 $output .= '</' . $this->mLastSection
. '>';
1837 $this->mLastSection
= '';
1840 wfProfileOut( $fname );
1845 * Split up a string on ':', ignoring any occurences inside
1846 * <a>..</a> or <span>...</span>
1847 * @param string $str the string to split
1848 * @param string &$before set to everything before the ':'
1849 * @param string &$after set to everything after the ':'
1850 * return string the position of the ':', or false if none found
1852 function findColonNoLinks($str, &$before, &$after) {
1853 # I wonder if we should make this count all tags, not just <a>
1854 # and <span>. That would prevent us from matching a ':' that
1855 # comes in the middle of italics other such formatting....
1857 $fname = 'Parser::findColonNoLinks';
1858 wfProfileIn( $fname );
1861 $colon = strpos($str, ':', $pos);
1863 if ($colon !== false) {
1864 $before = substr($str, 0, $colon);
1865 $after = substr($str, $colon +
1);
1867 # Skip any ':' within <a> or <span> pairs
1868 $a = substr_count($before, '<a');
1869 $s = substr_count($before, '<span');
1870 $ca = substr_count($before, '</a>');
1871 $cs = substr_count($before, '</span>');
1873 if ($a <= $ca and $s <= $cs) {
1874 # Tags are balanced before ':'; ok
1879 } while ($colon !== false);
1880 wfProfileOut( $fname );
1885 * Return value of a magic variable (like PAGENAME)
1889 function getVariableValue( $index ) {
1890 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1893 * Some of these require message or data lookups and can be
1894 * expensive to check many times.
1896 static $varCache = array();
1897 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1898 if ( isset( $varCache[$index] ) )
1899 return $varCache[$index];
1902 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1905 case MAG_CURRENTMONTH
:
1906 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1907 case MAG_CURRENTMONTHNAME
:
1908 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1909 case MAG_CURRENTMONTHNAMEGEN
:
1910 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1911 case MAG_CURRENTMONTHABBREV
:
1912 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1913 case MAG_CURRENTDAY
:
1914 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1916 return $this->mTitle
->getText();
1918 return $this->mTitle
->getPartialURL();
1919 case MAG_FULLPAGENAME
:
1920 return $this->mTitle
->getPrefixedText();
1921 case MAG_FULLPAGENAMEE
:
1922 return wfUrlencode( $this->mTitle
->getPrefixedText() );
1923 case MAG_REVISIONID
:
1924 return $this->mRevisionId
;
1926 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
1927 case MAG_NAMESPACEE
:
1928 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
1929 case MAG_CURRENTDAYNAME
:
1930 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
1931 case MAG_CURRENTYEAR
:
1932 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
1933 case MAG_CURRENTTIME
:
1934 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
1935 case MAG_CURRENTWEEK
:
1936 return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
1937 case MAG_CURRENTDOW
:
1938 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
1939 case MAG_NUMBEROFARTICLES
:
1940 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1941 case MAG_NUMBEROFFILES
:
1942 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1947 case MAG_SERVERNAME
:
1948 return $wgServerName;
1949 case MAG_SCRIPTPATH
:
1950 return $wgScriptPath;
1953 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
1961 * initialise the magic variables (like CURRENTMONTHNAME)
1965 function initialiseVariables() {
1966 $fname = 'Parser::initialiseVariables';
1967 wfProfileIn( $fname );
1968 global $wgVariableIDs;
1969 $this->mVariables
= array();
1970 foreach ( $wgVariableIDs as $id ) {
1971 $mw =& MagicWord
::get( $id );
1972 $mw->addToArray( $this->mVariables
, $id );
1974 wfProfileOut( $fname );
1978 * parse any parentheses in format ((title|part|part))
1979 * and call callbacks to get a replacement text for any found piece
1981 * @param string $text The text to parse
1982 * @param array $callbacks rules in form:
1983 * '{' => array( # opening parentheses
1984 * 'end' => '}', # closing parentheses
1985 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1986 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1991 function replace_callback ($text, $callbacks) {
1992 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1993 $lastOpeningBrace = -1; # last not closed parentheses
1995 for ($i = 0; $i < strlen($text); $i++
) {
1996 # check for any opening brace
1999 foreach ($callbacks as $key => $value) {
2000 $pos = strpos ($text, $key, $i);
2001 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2007 if ($lastOpeningBrace >= 0) {
2008 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2010 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2015 $pos = strpos ($text, '|', $i);
2017 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2028 # found openning brace, lets add it to parentheses stack
2029 if (null != $rule) {
2030 $piece = array('brace' => $text[$i],
2031 'braceEnd' => $rule['end'],
2036 # count openning brace characters
2037 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2042 $piece['startAt'] = $i+
1;
2043 $piece['partStart'] = $i+
1;
2045 # we need to add to stack only if openning brace count is enough for any given rule
2046 foreach ($rule['cb'] as $cnt => $fn) {
2047 if ($piece['count'] >= $cnt) {
2048 $lastOpeningBrace ++
;
2049 $openingBraceStack[$lastOpeningBrace] = $piece;
2056 else if ($lastOpeningBrace >= 0) {
2057 # first check if it is a closing brace
2058 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2059 # lets check if it is enough characters for closing brace
2061 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2064 # if there are more closing parentheses than opening ones, we parse less
2065 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2066 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2068 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2070 $matchingCallback = null;
2071 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2072 if ($count >= $cnt && $matchingCount < $cnt) {
2073 $matchingCount = $cnt;
2074 $matchingCallback = $fn;
2078 if ($matchingCount == 0) {
2083 # lets set a title or last part (if '|' was found)
2084 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2085 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2087 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2089 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2090 $pieceEnd = $i +
$matchingCount;
2092 if( is_callable( $matchingCallback ) ) {
2094 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2095 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2096 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2097 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2099 # finally we can call a user callback and replace piece of text
2100 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2101 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2102 $i = $pieceStart +
strlen($replaceWith) - 1;
2105 # null value for callback means that parentheses should be parsed, but not replaced
2106 $i +
= $matchingCount - 1;
2109 # reset last openning parentheses, but keep it in case there are unused characters
2110 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2111 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2112 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2115 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2116 $openingBraceStack[$lastOpeningBrace--] = null;
2118 if ($matchingCount < $piece['count']) {
2119 $piece['count'] -= $matchingCount;
2120 $piece['startAt'] -= $matchingCount;
2121 $piece['partStart'] = $piece['startAt'];
2122 # do we still qualify for any callback with remaining count?
2123 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2124 if ($piece['count'] >= $cnt) {
2125 $lastOpeningBrace ++
;
2126 $openingBraceStack[$lastOpeningBrace] = $piece;
2134 # lets set a title if it is a first separator, or next part otherwise
2135 if ($text[$i] == '|') {
2136 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2137 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2138 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2141 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2143 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2152 * Replace magic variables, templates, and template arguments
2153 * with the appropriate text. Templates are substituted recursively,
2154 * taking care to avoid infinite loops.
2156 * Note that the substitution depends on value of $mOutputType:
2157 * OT_WIKI: only {{subst:}} templates
2158 * OT_MSG: only magic variables
2159 * OT_HTML: all templates and magic variables
2161 * @param string $tex The text to transform
2162 * @param array $args Key-value pairs representing template parameters to substitute
2165 function replaceVariables( $text, $args = array() ) {
2166 # Prevent too big inclusions
2167 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2171 $fname = 'Parser::replaceVariables';
2172 wfProfileIn( $fname );
2174 # This function is called recursively. To keep track of arguments we need a stack:
2175 array_push( $this->mArgStack
, $args );
2177 $braceCallbacks = array();
2178 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2179 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2180 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2182 $callbacks = array();
2183 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2184 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2185 $text = $this->replace_callback ($text, $callbacks);
2187 array_pop( $this->mArgStack
);
2189 wfProfileOut( $fname );
2194 * Replace magic variables
2197 function variableSubstitution( $matches ) {
2198 $fname = 'parser::variableSubstitution';
2199 $varname = $matches[1];
2200 wfProfileIn( $fname );
2201 if ( !$this->mVariables
) {
2202 $this->initialiseVariables();
2205 if ( $this->mOutputType
== OT_WIKI
) {
2206 # Do only magic variables prefixed by SUBST
2207 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2208 if (!$mwSubst->matchStartAndRemove( $varname ))
2210 # Note that if we don't substitute the variable below,
2211 # we don't remove the {{subst:}} magic word, in case
2212 # it is a template rather than a magic variable.
2214 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2215 $id = $this->mVariables
[$varname];
2216 $text = $this->getVariableValue( $id );
2217 $this->mOutput
->mContainsOldMagic
= true;
2219 $text = $matches[0];
2221 wfProfileOut( $fname );
2225 # Split template arguments
2226 function getTemplateArgs( $argsString ) {
2227 if ( $argsString === '' ) {
2231 $args = explode( '|', substr( $argsString, 1 ) );
2233 # If any of the arguments contains a '[[' but no ']]', it needs to be
2234 # merged with the next arg because the '|' character between belongs
2235 # to the link syntax and not the template parameter syntax.
2236 $argc = count($args);
2238 for ( $i = 0; $i < $argc-1; $i++
) {
2239 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2240 $args[$i] .= '|'.$args[$i+
1];
2241 array_splice($args, $i+
1, 1);
2251 * Return the text of a template, after recursively
2252 * replacing any variables or templates within the template.
2254 * @param array $piece The parts of the template
2255 * $piece['text']: matched text
2256 * $piece['title']: the title, i.e. the part before the |
2257 * $piece['parts']: the parameter array
2258 * @return string the text of the template
2261 function braceSubstitution( $piece ) {
2262 global $wgLinkCache, $wgContLang;
2263 $fname = 'Parser::braceSubstitution';
2264 wfProfileIn( $fname );
2274 # $part1 is the bit before the first |, and must contain only title characters
2275 # $args is a list of arguments, starting from index 0, not including $part1
2277 $part1 = $piece['title'];
2278 # If the third subpattern matched anything, it will start with |
2280 if (null == $piece['parts']) {
2281 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2282 if ($replaceWith != $piece['text']) {
2283 $text = $replaceWith;
2289 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2290 $argc = count( $args );
2294 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2295 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2296 # One of two possibilities is true:
2297 # 1) Found SUBST but not in the PST phase
2298 # 2) Didn't find SUBST and in the PST phase
2299 # In either case, return without further processing
2300 $text = $piece['text'];
2306 # MSG, MSGNW and INT
2309 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2310 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2313 # Remove obsolete MSG:
2314 $mwMsg =& MagicWord
::get( MAG_MSG
);
2315 $mwMsg->matchStartAndRemove( $part1 );
2318 # Check if it is an internal message
2319 $mwInt =& MagicWord
::get( MAG_INT
);
2320 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2321 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2322 $text = $linestart . wfMsgReal( $part1, $args, true );
2330 # Check for NS: (namespace expansion)
2331 $mwNs = MagicWord
::get( MAG_NS
);
2332 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2333 if ( intval( $part1 ) ) {
2334 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2337 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2338 if ( !is_null( $index ) ) {
2339 $text = $linestart . $wgContLang->getNsText( $index );
2346 # LCFIRST, UCFIRST, LC and UC
2348 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2349 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2350 $lc =& MagicWord
::get( MAG_LC
);
2351 $uc =& MagicWord
::get( MAG_UC
);
2352 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2353 $text = $linestart . $wgContLang->lcfirst( $part1 );
2355 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2356 $text = $linestart . $wgContLang->ucfirst( $part1 );
2358 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2359 $text = $linestart . $wgContLang->lc( $part1 );
2361 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2362 $text = $linestart . $wgContLang->uc( $part1 );
2367 # LOCALURL and FULLURL
2369 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2370 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2371 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2372 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2375 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2376 $func = 'getLocalURL';
2377 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2378 $func = 'escapeLocalURL';
2379 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2380 $func = 'getFullURL';
2381 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2382 $func = 'escapeFullURL';
2387 if ( $func !== false ) {
2388 $title = Title
::newFromText( $part1 );
2389 if ( !is_null( $title ) ) {
2391 $text = $linestart . $title->$func( $args[0] );
2393 $text = $linestart . $title->$func();
2401 if ( !$found && $argc == 1 ) {
2402 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2403 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2404 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2410 if ( !$found && $argc >= 2 ) {
2411 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2412 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2413 if ($argc==2) {$args[2]=$args[1];}
2414 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2419 # Template table test
2421 # Did we encounter this template already? If yes, it is in the cache
2422 # and we need to check for loops.
2423 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2426 # Infinite loop test
2427 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2430 $text = $linestart .
2431 '{{' . $part1 . '}}' .
2432 '<!-- WARNING: template loop detected -->';
2433 wfDebug( "$fname: template loop broken at '$part1'\n" );
2435 # set $text to cached message.
2436 $text = $linestart . $this->mTemplates
[$part1];
2440 # Load from database
2441 $replaceHeadings = false;
2443 $lastPathLevel = $this->mTemplatePath
;
2446 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2447 if ($subpage !== '') {
2448 $ns = $this->mTitle
->getNamespace();
2450 $title = Title
::newFromText( $part1, $ns );
2453 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2454 if ($interwiki != '' && $title->isTrans()) {
2455 return $this->scarytransclude($title, $interwiki);
2459 if ( !is_null( $title ) && !$title->isExternal() ) {
2460 # Check for excessive inclusion
2461 $dbk = $title->getPrefixedDBkey();
2462 if ( $this->incrementIncludeCount( $dbk ) ) {
2463 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2464 # Capture special page output
2465 $text = SpecialPage
::capturePath( $title );
2466 if ( is_string( $text ) ) {
2470 $this->disableCache();
2473 $article = new Article( $title );
2474 $articleContent = $article->fetchContent(0, false);
2475 if ( $articleContent !== false ) {
2477 $text = $articleContent;
2478 $replaceHeadings = true;
2483 # If the title is valid but undisplayable, make a link to it
2484 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2485 $text = '[['.$title->getPrefixedText().']]';
2489 # Template cache array insertion
2491 $this->mTemplates
[$part1] = $text;
2492 $text = $linestart . $text;
2497 # Recursive parsing, escaping and link table handling
2498 # Only for HTML output
2499 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2500 $text = wfEscapeWikiText( $text );
2501 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2502 # Clean up argument array
2503 $assocArgs = array();
2505 foreach( $args as $arg ) {
2506 $eqpos = strpos( $arg, '=' );
2507 if ( $eqpos === false ) {
2508 $assocArgs[$index++
] = $arg;
2510 $name = trim( substr( $arg, 0, $eqpos ) );
2511 $value = trim( substr( $arg, $eqpos+
1 ) );
2512 if ( $value === false ) {
2515 if ( $name !== false ) {
2516 $assocArgs[$name] = $value;
2521 # Add a new element to the templace recursion path
2522 $this->mTemplatePath
[$part1] = 1;
2524 # If there are any <onlyinclude> tags, only include them
2525 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2526 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2528 foreach ($m[1] as $piece)
2531 # Remove <noinclude> sections and <includeonly> tags
2532 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2533 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2535 if( $this->mOutputType
== OT_HTML
) {
2536 # Strip <nowiki>, <pre>, etc.
2537 $text = $this->strip( $text, $this->mStripState
);
2538 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2540 $text = $this->replaceVariables( $text, $assocArgs );
2542 # Resume the link cache and register the inclusion as a link
2543 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2544 $wgLinkCache->addLinkObj( $title );
2547 # If the template begins with a table or block-level
2548 # element, it should be treated as beginning a new line.
2549 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2550 $text = "\n" . $text;
2553 # Prune lower levels off the recursion check path
2554 $this->mTemplatePath
= $lastPathLevel;
2557 wfProfileOut( $fname );
2558 return $piece['text'];
2561 # Replace raw HTML by a placeholder
2562 # Add a blank line preceding, to prevent it from mucking up
2563 # immediately preceding headings
2564 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2566 # replace ==section headers==
2567 # XXX this needs to go away once we have a better parser.
2568 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2569 if( !is_null( $title ) )
2570 $encodedname = base64_encode($title->getPrefixedDBkey());
2572 $encodedname = base64_encode("");
2573 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2574 PREG_SPLIT_DELIM_CAPTURE
);
2577 for( $i = 0; $i < count($m); $i +
= 2 ) {
2579 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2581 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2585 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2586 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2587 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2595 # Prune lower levels off the recursion check path
2596 $this->mTemplatePath
= $lastPathLevel;
2599 wfProfileOut( $fname );
2600 return $piece['text'];
2602 wfProfileOut( $fname );
2608 * Translude an interwiki link.
2610 function scarytransclude($title, $interwiki) {
2611 global $wgEnableScaryTranscluding;
2613 if (!$wgEnableScaryTranscluding)
2614 return wfMsg('scarytranscludedisabled');
2616 $articlename = "Template:" . $title->getDBkey();
2617 $url = str_replace('$1', urlencode($articlename), $interwiki);
2618 if (strlen($url) > 255)
2619 return wfMsg('scarytranscludetoolong');
2620 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2621 $this->mIWTransData
[] = $text;
2622 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2625 function fetchScaryTemplateMaybeFromCache($url) {
2626 $dbr =& wfGetDB(DB_SLAVE
);
2627 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2628 array('tc_url' => $url));
2630 $time = $obj->tc_time
;
2631 $text = $obj->tc_contents
;
2632 if ($time && $time < (time() +
(60*60))) {
2637 $text = wfGetHTTP($url . '?action=render');
2639 return wfMsg('scarytranscludefailed', $url);
2641 $dbw =& wfGetDB(DB_MASTER
);
2642 $dbw->replace('transcache', array(), array(
2644 'tc_time' => time(),
2645 'tc_contents' => $text));
2651 * Triple brace replacement -- used for template arguments
2654 function argSubstitution( $matches ) {
2655 $arg = trim( $matches['title'] );
2656 $text = $matches['text'];
2657 $inputArgs = end( $this->mArgStack
);
2659 if ( array_key_exists( $arg, $inputArgs ) ) {
2660 $text = $inputArgs[$arg];
2661 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2662 $text = $matches['parts'][0];
2669 * Returns true if the function is allowed to include this entity
2672 function incrementIncludeCount( $dbk ) {
2673 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2674 $this->mIncludeCount
[$dbk] = 0;
2676 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2684 * This function accomplishes several tasks:
2685 * 1) Auto-number headings if that option is enabled
2686 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2687 * 3) Add a Table of contents on the top for users who have enabled the option
2688 * 4) Auto-anchor headings
2690 * It loops through all headlines, collects the necessary data, then splits up the
2691 * string and re-inserts the newly formatted headlines.
2693 * @param string $text
2694 * @param boolean $isMain
2697 function formatHeadings( $text, $isMain=true ) {
2698 global $wgMaxTocLevel, $wgContLang;
2700 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2702 $forceTocHere = false;
2703 if( !$this->mTitle
->userCanEdit() ) {
2706 $showEditLink = $this->mOptions
->getEditSection();
2709 # Inhibit editsection links if requested in the page
2710 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2711 if( $esw->matchAndRemove( $text ) ) {
2714 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2716 $mw =& MagicWord
::get( MAG_NOTOC
);
2717 if( $mw->matchAndRemove( $text ) ) {
2721 # Get all headlines for numbering them and adding funky stuff like [edit]
2722 # links - this is for later, but we need the number of headlines right now
2723 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2725 # if there are fewer than 4 headlines in the article, do not show TOC
2726 if( $numMatches < 4 ) {
2730 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2731 # override above conditions and always show TOC at that place
2733 $mw =& MagicWord
::get( MAG_TOC
);
2734 if($mw->match( $text ) ) {
2736 $forceTocHere = true;
2738 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2739 # override above conditions and always show TOC above first header
2740 $mw =& MagicWord
::get( MAG_FORCETOC
);
2741 if ($mw->matchAndRemove( $text ) ) {
2746 # Never ever show TOC if no headers
2747 if( $numMatches < 1 ) {
2751 # We need this to perform operations on the HTML
2752 $sk =& $this->mOptions
->getSkin();
2756 $sectionCount = 0; # headlineCount excluding template sections
2758 # Ugh .. the TOC should have neat indentation levels which can be
2759 # passed to the skin functions. These are determined here
2763 $sublevelCount = array();
2764 $levelCount = array();
2771 foreach( $matches[3] as $headline ) {
2773 $templatetitle = '';
2774 $templatesection = 0;
2777 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2779 $templatetitle = base64_decode($mat[1]);
2780 $templatesection = 1 +
(int)base64_decode($mat[2]);
2781 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2785 $prevlevel = $level;
2786 $prevtoclevel = $toclevel;
2788 $level = $matches[1][$headlineCount];
2790 if( $doNumberHeadings ||
$doShowToc ) {
2792 if ( $level > $prevlevel ) {
2793 # Increase TOC level
2795 $sublevelCount[$toclevel] = 0;
2796 $toc .= $sk->tocIndent();
2798 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2799 # Decrease TOC level, find level to jump to
2801 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2802 # Can only go down to level 1
2805 for ($i = $toclevel; $i > 0; $i--) {
2806 if ( $levelCount[$i] == $level ) {
2807 # Found last matching level
2811 elseif ( $levelCount[$i] < $level ) {
2812 # Found first matching level below current level
2819 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2822 # No change in level, end TOC line
2823 $toc .= $sk->tocLineEnd();
2826 $levelCount[$toclevel] = $level;
2828 # count number of headlines for each level
2829 @$sublevelCount[$toclevel]++
;
2831 for( $i = 1; $i <= $toclevel; $i++
) {
2832 if( !empty( $sublevelCount[$i] ) ) {
2836 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2842 # The canonized header is a version of the header text safe to use for links
2843 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2844 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2845 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2847 # Remove link placeholders by the link text.
2848 # <!--LINK number-->
2850 # link text with suffix
2851 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2852 "\$this->mLinkHolders['texts'][\$1]",
2853 $canonized_headline );
2854 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2855 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2856 $canonized_headline );
2859 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2860 $tocline = trim( $canonized_headline );
2861 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2862 $replacearray = array(
2866 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2867 $refers[$headlineCount] = $canonized_headline;
2869 # count how many in assoc. array so we can track dupes in anchors
2870 @$refers[$canonized_headline]++
;
2871 $refcount[$headlineCount]=$refers[$canonized_headline];
2873 # Don't number the heading if it is the only one (looks silly)
2874 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2875 # the two are different if the line contains a link
2876 $headline=$numbering . ' ' . $headline;
2879 # Create the anchor for linking from the TOC to the section
2880 $anchor = $canonized_headline;
2881 if($refcount[$headlineCount] > 1 ) {
2882 $anchor .= '_' . $refcount[$headlineCount];
2884 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2885 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2887 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2888 if ( empty( $head[$headlineCount] ) ) {
2889 $head[$headlineCount] = '';
2892 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2894 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2897 # give headline the correct <h#> tag
2898 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2906 $toc .= $sk->tocUnindent( $toclevel - 1 );
2907 $toc = $sk->tocList( $toc );
2910 # split up and insert constructed headlines
2912 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2915 foreach( $blocks as $block ) {
2916 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2917 # This is the [edit] link that appears for the top block of text when
2918 # section editing is enabled
2920 # Disabled because it broke block formatting
2921 # For example, a bullet point in the top line
2922 # $full .= $sk->editSectionLink(0);
2925 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2926 # Top anchor now in skin
2930 if( !empty( $head[$i] ) ) {
2936 $mw =& MagicWord
::get( MAG_TOC
);
2937 return $mw->replace( $toc, $full );
2944 * Return an HTML link for the "ISBN 123456" text
2947 function magicISBN( $text ) {
2948 $fname = 'Parser::magicISBN';
2949 wfProfileIn( $fname );
2951 $a = split( 'ISBN ', ' '.$text );
2952 if ( count ( $a ) < 2 ) {
2953 wfProfileOut( $fname );
2956 $text = substr( array_shift( $a ), 1);
2957 $valid = '0123456789-Xx';
2959 foreach ( $a as $x ) {
2960 $isbn = $blank = '' ;
2961 while ( ' ' == $x{0} ) {
2963 $x = substr( $x, 1 );
2965 if ( $x == '' ) { # blank isbn
2966 $text .= "ISBN $blank";
2969 while ( strstr( $valid, $x{0} ) != false ) {
2971 $x = substr( $x, 1 );
2973 $num = str_replace( '-', '', $isbn );
2974 $num = str_replace( ' ', '', $num );
2975 $num = str_replace( 'x', 'X', $num );
2978 $text .= "ISBN $blank$x";
2980 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2981 $text .= '<a href="' .
2982 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2983 "\" class=\"internal\">ISBN $isbn</a>";
2987 wfProfileOut( $fname );
2992 * Return an HTML link for the "RFC 1234" text
2995 * @param string $text Text to be processed
2996 * @param string $keyword Magic keyword to use (default RFC)
2997 * @param string $urlmsg Interface message to use (default rfcurl)
3000 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3002 $valid = '0123456789';
3005 $a = split( $keyword, ' '.$text );
3006 if ( count ( $a ) < 2 ) {
3009 $text = substr( array_shift( $a ), 1);
3011 /* Check if keyword is preceed by [[.
3012 * This test is made here cause of the array_shift above
3013 * that prevent the test to be done in the foreach.
3015 if ( substr( $text, -2 ) == '[[' ) {
3019 foreach ( $a as $x ) {
3020 /* token might be empty if we have RFC RFC 1234 */
3028 /** remove and save whitespaces in $blank */
3029 while ( $x{0} == ' ' ) {
3031 $x = substr( $x, 1 );
3034 /** remove and save the rfc number in $id */
3035 while ( strstr( $valid, $x{0} ) != false ) {
3037 $x = substr( $x, 1 );
3041 /* call back stripped spaces*/
3042 $text .= $keyword.$blank.$x;
3043 } elseif( $internal ) {
3045 $text .= $keyword.$id.$x;
3047 /* build the external link*/
3048 $url = wfMsg( $urlmsg, $id);
3049 $sk =& $this->mOptions
->getSkin();
3050 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3051 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3054 /* Check if the next RFC keyword is preceed by [[ */
3055 $internal = ( substr($x,-2) == '[[' );
3061 * Transform wiki markup when saving a page by doing \r\n -> \n
3062 * conversion, substitting signatures, {{subst:}} templates, etc.
3064 * @param string $text the text to transform
3065 * @param Title &$title the Title object for the current article
3066 * @param User &$user the User object describing the current user
3067 * @param ParserOptions $options parsing options
3068 * @param bool $clearState whether to clear the parser state first
3069 * @return string the altered wiki markup
3072 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3073 $this->mOptions
= $options;
3074 $this->mTitle
=& $title;
3075 $this->mOutputType
= OT_WIKI
;
3077 if ( $clearState ) {
3078 $this->clearState();
3081 $stripState = false;
3085 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3086 $text = $this->strip( $text, $stripState, true );
3087 $text = $this->pstPass2( $text, $user );
3088 $text = $this->unstrip( $text, $stripState );
3089 $text = $this->unstripNoWiki( $text, $stripState );
3094 * Pre-save transform helper function
3097 function pstPass2( $text, &$user ) {
3098 global $wgContLang, $wgLocaltimezone;
3100 # Variable replacement
3101 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3102 $text = $this->replaceVariables( $text );
3106 $sigText = $this->getUserSig( $user );
3108 /* Note: This is the timestamp saved as hardcoded wikitext to
3109 * the database, we use $wgContLang here in order to give
3110 * everyone the same signiture and use the default one rather
3111 * than the one selected in each users preferences.
3113 if ( isset( $wgLocaltimezone ) ) {
3114 $oldtz = getenv( 'TZ' );
3115 putenv( 'TZ='.$wgLocaltimezone );
3117 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3118 ' (' . date( 'T' ) . ')';
3119 if ( isset( $wgLocaltimezone ) ) {
3120 putenv( 'TZ='.$oldtz );
3123 $text = preg_replace( '/~~~~~/', $d, $text );
3124 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3125 $text = preg_replace( '/~~~/', $sigText, $text );
3127 # Context links: [[|name]] and [[name (context)|]]
3129 global $wgLegalTitleChars;
3130 $tc = "[$wgLegalTitleChars]";
3131 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3133 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3134 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3136 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3137 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3138 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3139 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3141 $t = $this->mTitle
->getText();
3142 if ( preg_match( $conpat, $t, $m ) ) {
3145 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3146 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3147 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3149 if ( '' == $context ) {
3150 $text = preg_replace( $p2, '[[\\1]]', $text );
3152 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3155 # Trim trailing whitespace
3156 # MAG_END (__END__) tag allows for trailing
3157 # whitespace to be deliberately included
3158 $text = rtrim( $text );
3159 $mw =& MagicWord
::get( MAG_END
);
3160 $mw->matchAndRemove( $text );
3166 * Fetch the user's signature text, if any, and normalize to
3167 * validated, ready-to-insert wikitext.
3173 function getUserSig( &$user ) {
3174 $name = $user->getName();
3175 $nick = trim( $user->getOption( 'nickname' ) );
3176 if ( '' == $nick ) {
3180 if( $user->getOption( 'fancysig' ) ) {
3181 // A wikitext signature.
3182 $valid = $this->validateSig( $nick );
3183 if( $valid === false ) {
3184 // Fall back to default sig
3186 wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
3192 // Plain text linking to the user's homepage
3194 $page = $user->getUserPage();
3196 $page->getPrefixedText() .
3198 wfEscapeWikIText( $nick ) .
3203 * We want to enforce two rules on wikitext sigs here:
3204 * 1) Expand any templates at save time (forced subst:)
3205 * 2) Check for unbalanced XML tags, and reject if so.
3207 * @param string $text
3208 * @return mixed An expanded string, or false if invalid.
3210 * @todo Run brace substitutions
3211 * @todo ?? Check for unbalanced '' and ''' quotes, etc
3213 function validateSig( $text ) {
3214 if( wfIsWellFormedXmlFragment( $text ) ) {
3222 * Set up some variables which are usually set up in parse()
3223 * so that an external function can call some class members with confidence
3226 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3227 $this->mTitle
=& $title;
3228 $this->mOptions
= $options;
3229 $this->mOutputType
= $outputType;
3230 if ( $clearState ) {
3231 $this->clearState();
3236 * Transform a MediaWiki message by replacing magic variables.
3238 * @param string $text the text to transform
3239 * @param ParserOptions $options options
3240 * @return string the text with variables substituted
3243 function transformMsg( $text, $options ) {
3245 static $executing = false;
3247 # Guard against infinite recursion
3253 $this->mTitle
= $wgTitle;
3254 $this->mOptions
= $options;
3255 $this->mOutputType
= OT_MSG
;
3256 $this->clearState();
3257 $text = $this->replaceVariables( $text );
3264 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3265 * Callback will be called with the text within
3266 * Transform and return the text within
3270 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3271 * @param mixed $callback The callback function (and object) to use for the tag
3273 * @return The old value of the mTagHooks array associated with the hook
3275 function setHook( $tag, $callback ) {
3276 $oldVal = @$this->mTagHooks
[$tag];
3277 $this->mTagHooks
[$tag] = $callback;
3283 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3284 * Placeholders created in Skin::makeLinkObj()
3285 * Returns an array of links found, indexed by PDBK:
3289 * $options is a bit field, RLH_FOR_UPDATE to select for update
3291 function replaceLinkHolders( &$text, $options = 0 ) {
3292 global $wgUser, $wgLinkCache;
3293 global $wgOutputReplace;
3295 $fname = 'Parser::replaceLinkHolders';
3296 wfProfileIn( $fname );
3300 $sk = $this->mOptions
->getSkin();
3302 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3303 wfProfileIn( $fname.'-check' );
3304 $dbr =& wfGetDB( DB_SLAVE
);
3305 $page = $dbr->tableName( 'page' );
3306 $threshold = $wgUser->getOption('stubthreshold');
3309 asort( $this->mLinkHolders
['namespaces'] );
3313 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3315 $title = $this->mLinkHolders
['titles'][$key];
3317 # Skip invalid entries.
3318 # Result will be ugly, but prevents crash.
3319 if ( is_null( $title ) ) {
3322 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3324 # Check if it's in the link cache already
3325 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3326 $colours[$pdbk] = 1;
3327 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3328 $colours[$pdbk] = 0;
3330 # Not in the link cache, add it to the query
3331 if ( !isset( $current ) ) {
3333 $query = "SELECT page_id, page_namespace, page_title";
3334 if ( $threshold > 0 ) {
3335 $query .= ', page_len, page_is_redirect';
3337 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3338 } elseif ( $current != $val ) {
3340 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3345 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3350 if ( $options & RLH_FOR_UPDATE
) {
3351 $query .= ' FOR UPDATE';
3354 $res = $dbr->query( $query, $fname );
3356 # Fetch data and form into an associative array
3357 # non-existent = broken
3360 while ( $s = $dbr->fetchObject($res) ) {
3361 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3362 $pdbk = $title->getPrefixedDBkey();
3363 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3365 if ( $threshold > 0 ) {
3366 $size = $s->page_len
;
3367 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3368 $colours[$pdbk] = 1;
3370 $colours[$pdbk] = 2;
3373 $colours[$pdbk] = 1;
3377 wfProfileOut( $fname.'-check' );
3379 # Construct search and replace arrays
3380 wfProfileIn( $fname.'-construct' );
3381 $wgOutputReplace = array();
3382 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3383 $pdbk = $pdbks[$key];
3384 $searchkey = "<!--LINK $key-->";
3385 $title = $this->mLinkHolders
['titles'][$key];
3386 if ( empty( $colours[$pdbk] ) ) {
3387 $wgLinkCache->addBadLinkObj( $title );
3388 $colours[$pdbk] = 0;
3389 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3390 $this->mLinkHolders
['texts'][$key],
3391 $this->mLinkHolders
['queries'][$key] );
3392 } elseif ( $colours[$pdbk] == 1 ) {
3393 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3394 $this->mLinkHolders
['texts'][$key],
3395 $this->mLinkHolders
['queries'][$key] );
3396 } elseif ( $colours[$pdbk] == 2 ) {
3397 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3398 $this->mLinkHolders
['texts'][$key],
3399 $this->mLinkHolders
['queries'][$key] );
3402 wfProfileOut( $fname.'-construct' );
3405 wfProfileIn( $fname.'-replace' );
3407 $text = preg_replace_callback(
3408 '/(<!--LINK .*?-->)/',
3409 "wfOutputReplaceMatches",
3412 wfProfileOut( $fname.'-replace' );
3415 # Now process interwiki link holders
3416 # This is quite a bit simpler than internal links
3417 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3418 wfProfileIn( $fname.'-interwiki' );
3419 # Make interwiki link HTML
3420 $wgOutputReplace = array();
3421 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3422 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3423 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3426 $text = preg_replace_callback(
3427 '/<!--IWLINK (.*?)-->/',
3428 "wfOutputReplaceMatches",
3430 wfProfileOut( $fname.'-interwiki' );
3433 wfProfileOut( $fname );
3438 * Replace <!--LINK--> link placeholders with plain text of links
3439 * (not HTML-formatted).
3440 * @param string $text
3443 function replaceLinkHoldersText( $text ) {
3444 global $wgUser, $wgLinkCache;
3445 global $wgOutputReplace;
3447 $fname = 'Parser::replaceLinkHoldersText';
3448 wfProfileIn( $fname );
3450 $text = preg_replace_callback(
3451 '/<!--(LINK|IWLINK) (.*?)-->/',
3452 array( &$this, 'replaceLinkHoldersTextCallback' ),
3455 wfProfileOut( $fname );
3460 * @param array $matches
3464 function replaceLinkHoldersTextCallback( $matches ) {
3465 $type = $matches[1];
3467 if( $type == 'LINK' ) {
3468 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3469 return $this->mLinkHolders
['texts'][$key];
3471 } elseif( $type == 'IWLINK' ) {
3472 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3473 return $this->mInterwikiLinkHolders
['texts'][$key];
3480 * Renders an image gallery from a text with one line per image.
3481 * text labels may be given by using |-style alternative text. E.g.
3482 * Image:one.jpg|The number "1"
3483 * Image:tree.jpg|A tree
3484 * given as text will return the HTML of a gallery with two images,
3485 * labeled 'The number "1"' and
3490 function renderImageGallery( $text ) {
3492 global $wgUser, $wgTitle;
3493 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3494 $localParser = new Parser();
3496 global $wgLinkCache;
3497 $ig = new ImageGallery();
3498 $ig->setShowBytes( false );
3499 $ig->setShowFilename( false );
3500 $lines = explode( "\n", $text );
3502 foreach ( $lines as $line ) {
3503 # match lines like these:
3504 # Image:someimage.jpg|This is some image
3505 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3507 if ( count( $matches ) == 0 ) {
3510 $nt = Title
::newFromURL( $matches[1] );
3511 if( is_null( $nt ) ) {
3512 # Bogus title. Ignore these so we don't bomb out later.
3515 if ( isset( $matches[3] ) ) {
3516 $label = $matches[3];
3521 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3522 $html = $html->mText
;
3524 $ig->add( new Image( $nt ), $html );
3525 $wgLinkCache->addImageLinkObj( $nt );
3527 return $ig->toHTML();
3531 * Parse image options text and use it to make an image
3533 function makeImage( &$nt, $options ) {
3534 global $wgContLang, $wgUseImageResize, $wgUser;
3538 # Check if the options text is of the form "options|alt text"
3540 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3541 # * left no resizing, just left align. label is used for alt= only
3542 # * right same, but right aligned
3543 # * none same, but not aligned
3544 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3545 # * center center the image
3546 # * framed Keep original image size, no magnify-button.
3548 $part = explode( '|', $options);
3550 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3551 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3552 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3553 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3554 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3555 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3556 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3557 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3560 $width = $height = $framed = $thumb = false;
3561 $manual_thumb = '' ;
3563 foreach( $part as $key => $val ) {
3564 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3566 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3567 # use manually specified thumbnail
3569 $manual_thumb = $match;
3570 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3571 # remember to set an alignment, don't render immediately
3573 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3574 # remember to set an alignment, don't render immediately
3576 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3577 # remember to set an alignment, don't render immediately
3579 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3580 # remember to set an alignment, don't render immediately
3582 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3583 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3584 # $match is the image width in pixels
3585 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3586 $width = intval( $m[1] );
3587 $height = intval( $m[2] );
3589 $width = intval($match);
3591 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3597 # Strip bad stuff out of the alt text
3598 $alt = $this->replaceLinkHoldersText( $caption );
3599 $alt = Sanitizer
::stripAllTags( $alt );
3601 # Linker does the rest
3602 $sk =& $this->mOptions
->getSkin();
3603 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3607 * Set a flag in the output object indicating that the content is dynamic and
3608 * shouldn't be cached.
3610 function disableCache() {
3611 $this->mOutput
->mCacheTime
= -1;
3615 * Callback from the Sanitizer for expanding items found in HTML attribute
3616 * values, so they can be safely tested and escaped.
3617 * @param string $text
3618 * @param array $args
3622 function attributeStripCallback( &$text, $args ) {
3623 $text = $this->replaceVariables( $text, $args );
3624 $text = $this->unstripForHTML( $text );
3628 function unstripForHTML( $text ) {
3629 $text = $this->unstrip( $text, $this->mStripState
);
3630 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3634 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3635 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3636 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3641 * @package MediaWiki
3645 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3646 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3647 var $mVersion; # Compatibility check
3648 var $mTitleText; # title text of the chosen language variant
3650 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3651 $containsOldMagic = false, $titletext = '' )
3653 $this->mText
= $text;
3654 $this->mLanguageLinks
= $languageLinks;
3655 $this->mCategoryLinks
= $categoryLinks;
3656 $this->mContainsOldMagic
= $containsOldMagic;
3657 $this->mCacheTime
= '';
3658 $this->mVersion
= MW_PARSER_VERSION
;
3659 $this->mTitleText
= $titletext;
3662 function getText() { return $this->mText
; }
3663 function getLanguageLinks() { return $this->mLanguageLinks
; }
3664 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3665 function getCacheTime() { return $this->mCacheTime
; }
3666 function getTitleText() { return $this->mTitleText
; }
3667 function containsOldMagic() { return $this->mContainsOldMagic
; }
3668 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3669 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3670 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3671 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3672 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3673 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3675 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3677 function merge( $other ) {
3678 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3679 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3680 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3684 * Return true if this cached output object predates the global or
3685 * per-article cache invalidation timestamps, or if it comes from
3686 * an incompatible older version.
3688 * @param string $touched the affected article's last touched timestamp
3692 function expired( $touched ) {
3693 global $wgCacheEpoch;
3694 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3695 $this->getCacheTime() < $touched ||
3696 $this->getCacheTime() <= $wgCacheEpoch ||
3697 !isset( $this->mVersion
) ||
3698 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3703 * Set options of the Parser
3705 * @package MediaWiki
3709 # All variables are private
3710 var $mUseTeX; # Use texvc to expand <math> tags
3711 var $mUseDynamicDates; # Use DateFormatter to format dates
3712 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3713 var $mAllowExternalImages; # Allow external images inline
3714 var $mAllowExternalImagesFrom; # If not, any exception?
3715 var $mSkin; # Reference to the preferred skin
3716 var $mDateFormat; # Date format index
3717 var $mEditSection; # Create "edit section" links
3718 var $mNumberHeadings; # Automatically number headings
3719 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3721 function getUseTeX() { return $this->mUseTeX
; }
3722 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3723 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3724 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3725 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3726 function &getSkin() { return $this->mSkin
; }
3727 function getDateFormat() { return $this->mDateFormat
; }
3728 function getEditSection() { return $this->mEditSection
; }
3729 function getNumberHeadings() { return $this->mNumberHeadings
; }
3730 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3733 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3734 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3735 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3736 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3737 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3738 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3739 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3740 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3741 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3743 function setSkin( &$x ) { $this->mSkin
=& $x; }
3745 function ParserOptions() {
3747 $this->initialiseFromUser( $wgUser );
3751 * Get parser options
3754 function newFromUser( &$user ) {
3755 $popts = new ParserOptions
;
3756 $popts->initialiseFromUser( $user );
3760 /** Get user options */
3761 function initialiseFromUser( &$userInput ) {
3762 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3763 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3764 $fname = 'ParserOptions::initialiseFromUser';
3765 wfProfileIn( $fname );
3766 if ( !$userInput ) {
3768 $user->setLoaded( true );
3770 $user =& $userInput;
3773 $this->mUseTeX
= $wgUseTeX;
3774 $this->mUseDynamicDates
= $wgUseDynamicDates;
3775 $this->mInterwikiMagic
= $wgInterwikiMagic;
3776 $this->mAllowExternalImages
= $wgAllowExternalImages;
3777 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3778 wfProfileIn( $fname.'-skin' );
3779 $this->mSkin
=& $user->getSkin();
3780 wfProfileOut( $fname.'-skin' );
3781 $this->mDateFormat
= $user->getOption( 'date' );
3782 $this->mEditSection
= true;
3783 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3784 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3785 wfProfileOut( $fname );
3790 * Callback function used by Parser::replaceLinkHolders()
3791 * to substitute link placeholders.
3793 function &wfOutputReplaceMatches( $matches ) {
3794 global $wgOutputReplace;
3795 return $wgOutputReplace[$matches[1]];
3799 * Return the total number of articles
3801 function wfNumberOfArticles() {
3802 global $wgNumberOfArticles;
3805 return $wgNumberOfArticles;
3809 * Return the number of files
3811 function wfNumberOfFiles() {
3812 $fname = 'Parser::wfNumberOfFiles';
3814 wfProfileIn( $fname );
3815 $dbr =& wfGetDB( DB_SLAVE
);
3816 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3817 wfProfileOut( $fname );
3823 * Get various statistics from the database
3826 function wfLoadSiteStats() {
3827 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3828 $fname = 'wfLoadSiteStats';
3830 if ( -1 != $wgNumberOfArticles ) return;
3831 $dbr =& wfGetDB( DB_SLAVE
);
3832 $s = $dbr->selectRow( 'site_stats',
3833 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3834 array( 'ss_row_id' => 1 ), $fname
3837 if ( $s === false ) {
3840 $wgTotalViews = $s->ss_total_views
;
3841 $wgTotalEdits = $s->ss_total_edits
;
3842 $wgNumberOfArticles = $s->ss_good_articles
;
3848 * Basicly replacing " > and < with HTML entities ( ", >, <)
3850 * @param string $in Text that might contain HTML tags
3851 * @return string Escaped string
3853 function wfEscapeHTMLTagsOnly( $in ) {
3855 array( '"', '>', '<' ),
3856 array( '"', '>', '<' ),