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();
157 * First pass--just handle <nowiki> sections, pass the rest off
158 * to internalParse() which does all the real work.
161 * @param string $text Text we want to parse
162 * @param Title &$title A title object
163 * @param array $options
164 * @param boolean $linestart
165 * @param boolean $clearState
166 * @param int $revid number to pass in {{REVISIONID}}
167 * @return ParserOutput a ParserOutput
169 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
170 global $wgUseTidy, $wgContLang;
171 $fname = 'Parser::parse';
172 wfProfileIn( $fname );
178 $this->mOptions
= $options;
179 $this->mTitle
=& $title;
180 $this->mRevisionId
= $revid;
181 $this->mOutputType
= OT_HTML
;
183 $this->mStripState
= NULL;
185 //$text = $this->strip( $text, $this->mStripState );
186 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
187 $x =& $this->mStripState
;
189 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
190 $text = $this->strip( $text, $x );
191 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
193 # Hook to suspend the parser in this state
194 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) )
197 $text = $this->internalParse( $text );
199 $text = $this->unstrip( $text, $this->mStripState
);
201 # Clean up special characters, only run once, next-to-last before doBlockLevels
203 # french spaces, last one Guillemet-left
204 # only if there is something before the space
205 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
206 # french spaces, Guillemet-right
207 '/(\\302\\253) /' => '\\1 ',
208 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
210 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
213 $text = $this->doBlockLevels( $text, $linestart );
215 $this->replaceLinkHolders( $text );
217 # the position of the convert() call should not be changed. it
218 # assumes that the links are all replaces and the only thing left
219 # is the <nowiki> mark.
220 $text = $wgContLang->convert($text);
221 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
223 $text = $this->unstripNoWiki( $text, $this->mStripState
);
225 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
227 $text = Sanitizer
::normalizeCharReferences( $text );
230 $text = Parser
::tidy($text);
233 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
235 $this->mOutput
->setText( $text );
236 wfProfileOut( $fname );
237 return $this->mOutput
;
241 * Get a random string
246 function getRandomString() {
247 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
251 * Replaces all occurrences of <$tag>content</$tag> in the text
252 * with a random marker and returns the new text. the output parameter
253 * $content will be an associative array filled with data on the form
254 * $unique_marker => content.
256 * If $content is already set, the additional entries will be appended
257 * If $tag is set to STRIP_COMMENTS, the function will extract
258 * <!-- HTML comments -->
263 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
264 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
279 if( $tag == STRIP_COMMENTS
) {
280 $start = '/<!--()()/';
283 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
284 $end = "/<\\/$tag\\s*>/i";
287 while ( '' != $text ) {
288 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
290 if( count( $p ) < 4 ) {
297 $marker = $rnd . sprintf('%08X', $n++
);
298 $stripped .= $marker;
300 $tags[$marker] = "<$tag$attributes$empty>";
301 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
303 if ( $empty === '/' ) {
304 // Empty element tag, <tag />
305 $content[$marker] = null;
308 $q = preg_split( $end, $inside, 2 );
309 $content[$marker] = $q[0];
310 if( count( $q ) < 2 ) {
311 # No end tag -- let it run out to the end of the text.
322 * Wrapper function for extractTagsAndParams
323 * for cases where $tags and $params isn't needed
324 * i.e. where tags will never have params, like <nowiki>
329 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
330 $dummy_tags = array();
331 $dummy_params = array();
333 return Parser
::extractTagsAndParams( $tag, $text, $content,
334 $dummy_tags, $dummy_params, $uniq_prefix );
338 * Strips and renders nowiki, pre, math, hiero
339 * If $render is set, performs necessary rendering operations on plugins
340 * Returns the text, and fills an array with data needed in unstrip()
341 * If the $state is already a valid strip state, it adds to the state
343 * @param bool $stripcomments when set, HTML comments <!-- like this -->
344 * will be stripped in addition to other tags. This is important
345 * for section editing, where these comments cause confusion when
346 * counting the sections in the wikisource
350 function strip( $text, &$state, $stripcomments = false ) {
351 $render = ($this->mOutputType
== OT_HTML
);
352 $html_content = array();
353 $nowiki_content = array();
354 $math_content = array();
355 $pre_content = array();
356 $comment_content = array();
357 $ext_content = array();
359 $ext_params = array();
360 $gallery_content = array();
362 # Replace any instances of the placeholders
363 $uniq_prefix = $this->mUniqPrefix
;
364 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
369 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
370 foreach( $html_content as $marker => $content ) {
372 # Raw and unchecked for validity.
373 $html_content[$marker] = $content;
375 $html_content[$marker] = '<html>'.$content.'</html>';
381 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
382 foreach( $nowiki_content as $marker => $content ) {
384 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
386 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
391 if( $this->mOptions
->getUseTeX() ) {
392 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
393 foreach( $math_content as $marker => $content ){
395 $math_content[$marker] = renderMath( $content );
397 $math_content[$marker] = '<math>'.$content.'</math>';
403 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
404 foreach( $pre_content as $marker => $content ){
406 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
408 $pre_content[$marker] = '<pre>'.$content.'</pre>';
413 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
414 foreach( $gallery_content as $marker => $content ) {
415 require_once( 'ImageGallery.php' );
417 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
419 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
425 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
426 foreach( $comment_content as $marker => $content ){
427 $comment_content[$marker] = '<!--'.$content.'-->';
432 foreach ( $this->mTagHooks
as $tag => $callback ) {
433 $ext_content[$tag] = array();
434 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
435 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
436 foreach( $ext_content[$tag] as $marker => $content ) {
437 $full_tag = $ext_tags[$tag][$marker];
438 $params = $ext_params[$tag][$marker];
440 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
442 if ( is_null( $content ) ) {
444 $ext_content[$tag][$marker] = $full_tag;
446 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
452 # Merge state with the pre-existing state, if there is one
454 $state['html'] = $state['html'] +
$html_content;
455 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
456 $state['math'] = $state['math'] +
$math_content;
457 $state['pre'] = $state['pre'] +
$pre_content;
458 $state['comment'] = $state['comment'] +
$comment_content;
459 $state['gallery'] = $state['gallery'] +
$gallery_content;
461 foreach( $ext_content as $tag => $array ) {
462 if ( array_key_exists( $tag, $state ) ) {
463 $state[$tag] = $state[$tag] +
$array;
468 'html' => $html_content,
469 'nowiki' => $nowiki_content,
470 'math' => $math_content,
471 'pre' => $pre_content,
472 'comment' => $comment_content,
473 'gallery' => $gallery_content,
480 * restores pre, math, and hiero removed by strip()
482 * always call unstripNoWiki() after this one
485 function unstrip( $text, &$state ) {
486 if ( !is_array( $state ) ) {
490 # Must expand in reverse order, otherwise nested tags will be corrupted
491 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
492 if( $tag != 'nowiki' && $tag != 'html' ) {
493 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
494 $text = str_replace( $uniq, $content, $text );
503 * always call this after unstrip() to preserve the order
507 function unstripNoWiki( $text, &$state ) {
508 if ( !is_array( $state ) ) {
512 # Must expand in reverse order, otherwise nested tags will be corrupted
513 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
514 $text = str_replace( key( $state['nowiki'] ), $content, $text );
519 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
520 $text = str_replace( key( $state['html'] ), $content, $text );
528 * Add an item to the strip state
529 * Returns the unique tag which must be inserted into the stripped text
530 * The tag will be replaced with the original text in unstrip()
534 function insertStripItem( $text, &$state ) {
535 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
542 'comment' => array(),
543 'gallery' => array(),
546 $state['item'][$rnd] = $text;
551 * Interface with html tidy, used if $wgUseTidy = true.
552 * If tidy isn't able to correct the markup, the original will be
553 * returned in all its glory with a warning comment appended.
555 * Either the external tidy program or the in-process tidy extension
556 * will be used depending on availability. Override the default
557 * $wgTidyInternal setting to disable the internal if it's not working.
559 * @param string $text Hideous HTML input
560 * @return string Corrected HTML output
564 function tidy( $text ) {
565 global $wgTidyInternal;
566 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
567 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
568 '<head><title>test</title></head><body>'.$text.'</body></html>';
569 if( $wgTidyInternal ) {
570 $correctedtext = Parser
::internalTidy( $wrappedtext );
572 $correctedtext = Parser
::externalTidy( $wrappedtext );
574 if( is_null( $correctedtext ) ) {
575 wfDebug( "Tidy error detected!\n" );
576 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
578 return $correctedtext;
582 * Spawn an external HTML tidy process and get corrected markup back from it.
587 function externalTidy( $text ) {
588 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
589 $fname = 'Parser::externalTidy';
590 wfProfileIn( $fname );
595 $descriptorspec = array(
596 0 => array('pipe', 'r'),
597 1 => array('pipe', 'w'),
598 2 => array('file', '/dev/null', 'a')
601 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
602 if (is_resource($process)) {
603 fwrite($pipes[0], $text);
605 while (!feof($pipes[1])) {
606 $cleansource .= fgets($pipes[1], 1024);
609 proc_close($process);
612 wfProfileOut( $fname );
614 if( $cleansource == '' && $text != '') {
615 // Some kind of error happened, so we couldn't get the corrected text.
616 // Just give up; we'll use the source text and append a warning.
624 * Use the HTML tidy PECL extension to use the tidy library in-process,
625 * saving the overhead of spawning a new process. Currently written to
626 * the PHP 4.3.x version of the extension, may not work on PHP 5.
628 * 'pear install tidy' should be able to compile the extension module.
633 function internalTidy( $text ) {
635 $fname = 'Parser::internalTidy';
636 wfProfileIn( $fname );
638 tidy_load_config( $wgTidyConf );
639 tidy_set_encoding( 'utf8' );
640 tidy_parse_string( $text );
642 if( tidy_get_status() == 2 ) {
643 // 2 is magic number for fatal error
644 // http://www.php.net/manual/en/function.tidy-get-status.php
647 $cleansource = tidy_get_output();
649 wfProfileOut( $fname );
654 * parse the wiki syntax used to render tables
658 function doTableStuff ( $t ) {
659 $fname = 'Parser::doTableStuff';
660 wfProfileIn( $fname );
662 $t = explode ( "\n" , $t ) ;
663 $td = array () ; # Is currently a td tag open?
664 $ltd = array () ; # Was it TD or TH?
665 $tr = array () ; # Is currently a tr tag open?
666 $ltr = array () ; # tr attributes
667 $indent_level = 0; # indent level of the table
668 foreach ( $t AS $k => $x )
671 $fc = substr ( $x , 0 , 1 ) ;
672 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
673 $indent_level = strlen( $matches[1] );
675 $attributes = $this->unstripForHTML( $matches[2] );
677 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
678 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
679 array_push ( $td , false ) ;
680 array_push ( $ltd , '' ) ;
681 array_push ( $tr , false ) ;
682 array_push ( $ltr , '' ) ;
684 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
685 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
686 $z = "</table>" . substr ( $x , 2);
687 $l = array_pop ( $ltd ) ;
688 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
689 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
691 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
693 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
694 $x = substr ( $x , 1 ) ;
695 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
697 $l = array_pop ( $ltd ) ;
698 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
699 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
702 array_push ( $tr , false ) ;
703 array_push ( $td , false ) ;
704 array_push ( $ltd , '' ) ;
705 $attributes = $this->unstripForHTML( $x );
706 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
708 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
710 if ( '|+' == substr ( $x , 0 , 2 ) ) {
712 $x = substr ( $x , 1 ) ;
714 $after = substr ( $x , 1 ) ;
715 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
716 $after = explode ( '||' , $after ) ;
719 # Loop through each table cell
720 foreach ( $after AS $theline )
725 $tra = array_pop ( $ltr ) ;
726 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
727 array_push ( $tr , true ) ;
728 array_push ( $ltr , '' ) ;
731 $l = array_pop ( $ltd ) ;
732 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
733 if ( $fc == '|' ) $l = 'td' ;
734 else if ( $fc == '!' ) $l = 'th' ;
735 else if ( $fc == '+' ) $l = 'caption' ;
737 array_push ( $ltd , $l ) ;
740 $y = explode ( '|' , $theline , 2 ) ;
741 # Note that a '|' inside an invalid link should not
742 # be mistaken as delimiting cell parameters
743 if ( strpos( $y[0], '[[' ) !== false ) {
744 $y = array ($theline);
746 if ( count ( $y ) == 1 )
747 $y = "{$z}<{$l}>{$y[0]}" ;
749 $attributes = $this->unstripForHTML( $y[0] );
750 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
753 array_push ( $td , true ) ;
758 # Closing open td, tr && table
759 while ( count ( $td ) > 0 )
761 if ( array_pop ( $td ) ) $t[] = '</td>' ;
762 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
766 $t = implode ( "\n" , $t ) ;
767 wfProfileOut( $fname );
772 * Helper function for parse() that transforms wiki markup into
773 * HTML. Only called for $mOutputType == OT_HTML.
777 function internalParse( $text ) {
781 $fname = 'Parser::internalParse';
782 wfProfileIn( $fname );
784 # Remove <noinclude> tags and <includeonly> sections
785 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
786 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
787 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
789 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
790 $text = $this->replaceVariables( $text, $args );
792 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
794 $text = $this->doHeadings( $text );
795 if($this->mOptions
->getUseDynamicDates()) {
796 $df =& DateFormatter
::getInstance();
797 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
799 $text = $this->doAllQuotes( $text );
800 $text = $this->replaceInternalLinks( $text );
801 $text = $this->replaceExternalLinks( $text );
803 # replaceInternalLinks may sometimes leave behind
804 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
805 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
807 $text = $this->doMagicLinks( $text );
808 $text = $this->doTableStuff( $text );
809 $text = $this->formatHeadings( $text, $isMain );
811 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
812 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
814 wfProfileOut( $fname );
818 function scarySubstitution($matches) {
819 # return "[[".$matches[0]."]]";
820 return $this->mIWTransData
[(int)$matches[0]];
824 * Replace special strings like "ISBN xxx" and "RFC xxx" with
825 * magic external links.
829 function &doMagicLinks( &$text ) {
830 $text = $this->magicISBN( $text );
831 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
832 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
837 * Parse headers and return html
841 function doHeadings( $text ) {
842 $fname = 'Parser::doHeadings';
843 wfProfileIn( $fname );
844 for ( $i = 6; $i >= 1; --$i ) {
845 $h = str_repeat( '=', $i );
846 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
847 "<h{$i}>\\1</h{$i}>\\2", $text );
849 wfProfileOut( $fname );
854 * Replace single quotes with HTML markup
856 * @return string the altered text
858 function doAllQuotes( $text ) {
859 $fname = 'Parser::doAllQuotes';
860 wfProfileIn( $fname );
862 $lines = explode( "\n", $text );
863 foreach ( $lines as $line ) {
864 $outtext .= $this->doQuotes ( $line ) . "\n";
866 $outtext = substr($outtext, 0,-1);
867 wfProfileOut( $fname );
872 * Helper function for doAllQuotes()
875 function doQuotes( $text ) {
876 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
877 if ( count( $arr ) == 1 )
881 # First, do some preliminary work. This may shift some apostrophes from
882 # being mark-up to being text. It also counts the number of occurrences
883 # of bold and italics mark-ups.
887 foreach ( $arr as $r )
889 if ( ( $i %
2 ) == 1 )
891 # If there are ever four apostrophes, assume the first is supposed to
892 # be text, and the remaining three constitute mark-up for bold text.
893 if ( strlen( $arr[$i] ) == 4 )
898 # If there are more than 5 apostrophes in a row, assume they're all
899 # text except for the last 5.
900 else if ( strlen( $arr[$i] ) > 5 )
902 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
905 # Count the number of occurrences of bold and italics mark-ups.
906 # We are not counting sequences of five apostrophes.
907 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
908 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
909 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
914 # If there is an odd number of both bold and italics, it is likely
915 # that one of the bold ones was meant to be an apostrophe followed
916 # by italics. Which one we cannot know for certain, but it is more
917 # likely to be one that has a single-letter word before it.
918 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
921 $firstsingleletterword = -1;
922 $firstmultiletterword = -1;
924 foreach ( $arr as $r )
926 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
928 $x1 = substr ($arr[$i-1], -1);
929 $x2 = substr ($arr[$i-1], -2, 1);
931 if ($firstspace == -1) $firstspace = $i;
932 } else if ($x2 == ' ') {
933 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
935 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
941 # If there is a single-letter word, use it!
942 if ($firstsingleletterword > -1)
944 $arr [ $firstsingleletterword ] = "''";
945 $arr [ $firstsingleletterword-1 ] .= "'";
947 # If not, but there's a multi-letter word, use that one.
948 else if ($firstmultiletterword > -1)
950 $arr [ $firstmultiletterword ] = "''";
951 $arr [ $firstmultiletterword-1 ] .= "'";
953 # ... otherwise use the first one that has neither.
954 # (notice that it is possible for all three to be -1 if, for example,
955 # there is only one pentuple-apostrophe in the line)
956 else if ($firstspace > -1)
958 $arr [ $firstspace ] = "''";
959 $arr [ $firstspace-1 ] .= "'";
963 # Now let's actually convert our apostrophic mush to HTML!
972 if ($state == 'both')
979 if (strlen ($r) == 2)
982 { $output .= '</i>'; $state = ''; }
983 else if ($state == 'bi')
984 { $output .= '</i>'; $state = 'b'; }
985 else if ($state == 'ib')
986 { $output .= '</b></i><b>'; $state = 'b'; }
987 else if ($state == 'both')
988 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
989 else # $state can be 'b' or ''
990 { $output .= '<i>'; $state .= 'i'; }
992 else if (strlen ($r) == 3)
995 { $output .= '</b>'; $state = ''; }
996 else if ($state == 'bi')
997 { $output .= '</i></b><i>'; $state = 'i'; }
998 else if ($state == 'ib')
999 { $output .= '</b>'; $state = 'i'; }
1000 else if ($state == 'both')
1001 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1002 else # $state can be 'i' or ''
1003 { $output .= '<b>'; $state .= 'b'; }
1005 else if (strlen ($r) == 5)
1008 { $output .= '</b><i>'; $state = 'i'; }
1009 else if ($state == 'i')
1010 { $output .= '</i><b>'; $state = 'b'; }
1011 else if ($state == 'bi')
1012 { $output .= '</i></b>'; $state = ''; }
1013 else if ($state == 'ib')
1014 { $output .= '</b></i>'; $state = ''; }
1015 else if ($state == 'both')
1016 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1017 else # ($state == '')
1018 { $buffer = ''; $state = 'both'; }
1023 # Now close all remaining tags. Notice that the order is important.
1024 if ($state == 'b' ||
$state == 'ib')
1026 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1030 if ($state == 'both')
1031 $output .= '<b><i>'.$buffer.'</i></b>';
1037 * Replace external links
1039 * Note: this is all very hackish and the order of execution matters a lot.
1040 * Make sure to run maintenance/parserTests.php if you change this code.
1044 function replaceExternalLinks( $text ) {
1046 $fname = 'Parser::replaceExternalLinks';
1047 wfProfileIn( $fname );
1049 $sk =& $this->mOptions
->getSkin();
1051 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1053 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1056 while ( $i<count( $bits ) ) {
1058 $protocol = $bits[$i++
];
1059 $text = $bits[$i++
];
1060 $trail = $bits[$i++
];
1062 # The characters '<' and '>' (which were escaped by
1063 # removeHTMLtags()) should not be included in
1064 # URLs, per RFC 2396.
1065 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1066 $text = substr($url, $m2[0][1]) . ' ' . $text;
1067 $url = substr($url, 0, $m2[0][1]);
1070 # If the link text is an image URL, replace it with an <img> tag
1071 # This happened by accident in the original parser, but some people used it extensively
1072 $img = $this->maybeMakeExternalImage( $text );
1073 if ( $img !== false ) {
1079 # Set linktype for CSS - if URL==text, link is essentially free
1080 $linktype = ($text == $url) ?
'free' : 'text';
1082 # No link text, e.g. [http://domain.tld/some.link]
1083 if ( $text == '' ) {
1084 # Autonumber if allowed
1085 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1086 $text = '[' . ++
$this->mAutonumber
. ']';
1087 $linktype = 'autonumber';
1089 # Otherwise just use the URL
1090 $text = htmlspecialchars( $url );
1094 # Have link text, e.g. [http://domain.tld/some.link text]s
1096 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1099 $text = $wgContLang->markNoConversion($text);
1101 # Replace & from obsolete syntax with &.
1102 # All HTML entities will be escaped by makeExternalLink()
1103 # or maybeMakeExternalImage()
1104 $url = str_replace( '&', '&', $url );
1106 # Process the trail (i.e. everything after this link up until start of the next link),
1107 # replacing any non-bracketed links
1108 $trail = $this->replaceFreeExternalLinks( $trail );
1111 # Use the encoded URL
1112 # This means that users can paste URLs directly into the text
1113 # Funny characters like ö aren't valid in URLs anyway
1114 # This was changed in August 2004
1115 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1118 wfProfileOut( $fname );
1123 * Replace anything that looks like a URL with a link
1126 function replaceFreeExternalLinks( $text ) {
1128 $fname = 'Parser::replaceFreeExternalLinks';
1129 wfProfileIn( $fname );
1131 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1132 $s = array_shift( $bits );
1135 $sk =& $this->mOptions
->getSkin();
1137 while ( $i < count( $bits ) ){
1138 $protocol = $bits[$i++
];
1139 $remainder = $bits[$i++
];
1141 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1142 # Found some characters after the protocol that look promising
1143 $url = $protocol . $m[1];
1146 # The characters '<' and '>' (which were escaped by
1147 # removeHTMLtags()) should not be included in
1148 # URLs, per RFC 2396.
1149 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1150 $trail = substr($url, $m2[0][1]) . $trail;
1151 $url = substr($url, 0, $m2[0][1]);
1154 # Move trailing punctuation to $trail
1156 # If there is no left bracket, then consider right brackets fair game too
1157 if ( strpos( $url, '(' ) === false ) {
1161 $numSepChars = strspn( strrev( $url ), $sep );
1162 if ( $numSepChars ) {
1163 $trail = substr( $url, -$numSepChars ) . $trail;
1164 $url = substr( $url, 0, -$numSepChars );
1167 # Replace & from obsolete syntax with &.
1168 # All HTML entities will be escaped by makeExternalLink()
1169 # or maybeMakeExternalImage()
1170 $url = str_replace( '&', '&', $url );
1172 # Is this an external image?
1173 $text = $this->maybeMakeExternalImage( $url );
1174 if ( $text === false ) {
1175 # Not an image, make a link
1176 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1178 $s .= $text . $trail;
1180 $s .= $protocol . $remainder;
1183 wfProfileOut( $fname );
1188 * make an image if it's allowed, either through the global
1189 * option or through the exception
1192 function maybeMakeExternalImage( $url ) {
1193 $sk =& $this->mOptions
->getSkin();
1194 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1195 $imagesexception = !empty($imagesfrom);
1197 if ( $this->mOptions
->getAllowExternalImages()
1198 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1199 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1201 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1208 * Process [[ ]] wikilinks
1212 function replaceInternalLinks( $s ) {
1213 global $wgContLang, $wgLinkCache;
1214 static $fname = 'Parser::replaceInternalLinks' ;
1216 wfProfileIn( $fname );
1218 wfProfileIn( $fname.'-setup' );
1220 # the % is needed to support urlencoded titles as well
1221 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1223 $sk =& $this->mOptions
->getSkin();
1225 #split the entire text string on occurences of [[
1226 $a = explode( '[[', ' ' . $s );
1227 #get the first element (all text up to first [[), and remove the space we added
1228 $s = array_shift( $a );
1229 $s = substr( $s, 1 );
1231 # Match a link having the form [[namespace:link|alternate]]trail
1233 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1234 # Match cases where there is no "]]", which might still be images
1235 static $e1_img = FALSE;
1236 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1237 # Match the end of a line for a word that's not followed by whitespace,
1238 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1239 $e2 = wfMsgForContent( 'linkprefix' );
1241 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1243 if( is_null( $this->mTitle
) ) {
1244 wfDebugDieBacktrace( 'nooo' );
1246 $nottalk = !$this->mTitle
->isTalkPage();
1248 if ( $useLinkPrefixExtension ) {
1249 if ( preg_match( $e2, $s, $m ) ) {
1250 $first_prefix = $m[2];
1252 $first_prefix = false;
1258 $selflink = $this->mTitle
->getPrefixedText();
1259 wfProfileOut( $fname.'-setup' );
1261 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1262 $useSubpages = $this->areSubpagesAllowed();
1264 # Loop for each link
1265 for ($k = 0; isset( $a[$k] ); $k++
) {
1267 if ( $useLinkPrefixExtension ) {
1268 wfProfileIn( $fname.'-prefixhandling' );
1269 if ( preg_match( $e2, $s, $m ) ) {
1277 $prefix = $first_prefix;
1278 $first_prefix = false;
1280 wfProfileOut( $fname.'-prefixhandling' );
1283 $might_be_img = false;
1285 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1287 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1288 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1289 # the real problem is with the $e1 regex
1292 # Still some problems for cases where the ] is meant to be outside punctuation,
1293 # and no image is in sight. See bug 2095.
1295 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1296 $text .= ']'; # so that replaceExternalLinks($text) works later
1299 # fix up urlencoded title texts
1300 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1302 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1303 $might_be_img = true;
1305 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1307 } else { # Invalid form; output directly
1308 $s .= $prefix . '[[' . $line ;
1312 # Don't allow internal links to pages containing
1313 # PROTO: where PROTO is a valid URL protocol; these
1314 # should be external links.
1315 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1316 $s .= $prefix . '[[' . $line ;
1320 # Make subpage if necessary
1321 if( $useSubpages ) {
1322 $link = $this->maybeDoSubpageLink( $m[1], $text );
1327 $noforce = (substr($m[1], 0, 1) != ':');
1329 # Strip off leading ':'
1330 $link = substr($link, 1);
1333 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1335 $s .= $prefix . '[[' . $line;
1339 #check other language variants of the link
1340 #if the article does not exist
1341 if( $checkVariantLink
1342 && $nt->getArticleID() == 0 ) {
1343 $wgContLang->findVariantLink($link, $nt);
1346 $ns = $nt->getNamespace();
1347 $iw = $nt->getInterWiki();
1349 if ($might_be_img) { # if this is actually an invalid link
1350 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1352 while (isset ($a[$k+
1]) ) {
1353 #look at the next 'line' to see if we can close it there
1354 $spliced = array_splice( $a, $k +
1, 1 );
1355 $next_line = array_shift( $spliced );
1356 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1357 # the first ]] closes the inner link, the second the image
1359 $text .= '[[' . $m[1];
1362 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1363 #if there's exactly one ]] that's fine, we'll keep looking
1364 $text .= '[[' . $m[0];
1366 #if $next_line is invalid too, we need look no further
1367 $text .= '[[' . $next_line;
1372 # we couldn't find the end of this imageLink, so output it raw
1373 #but don't ignore what might be perfectly normal links in the text we've examined
1374 $text = $this->replaceInternalLinks($text);
1375 $s .= $prefix . '[[' . $link . '|' . $text;
1376 # note: no $trail, because without an end, there *is* no trail
1379 } else { #it's not an image, so output it raw
1380 $s .= $prefix . '[[' . $link . '|' . $text;
1381 # note: no $trail, because without an end, there *is* no trail
1386 $wasblank = ( '' == $text );
1387 if( $wasblank ) $text = $link;
1390 # Link not escaped by : , create the various objects
1394 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1395 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1396 $s = rtrim($s . "\n");
1397 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1401 if ( $ns == NS_IMAGE
) {
1402 wfProfileIn( "$fname-image" );
1403 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1404 # recursively parse links inside the image caption
1405 # actually, this will parse them in any other parameters, too,
1406 # but it might be hard to fix that, and it doesn't matter ATM
1407 $text = $this->replaceExternalLinks($text);
1408 $text = $this->replaceInternalLinks($text);
1410 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1411 $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', "{$this->mUniqPrefix}NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1412 $wgLinkCache->addImageLinkObj( $nt );
1414 wfProfileOut( "$fname-image" );
1417 wfProfileOut( "$fname-image" );
1421 if ( $ns == NS_CATEGORY
) {
1422 wfProfileIn( "$fname-category" );
1423 $t = $wgContLang->convertHtml( $nt->getText() );
1424 $s = rtrim($s . "\n"); # bug 87
1426 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1427 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1428 $wgLinkCache->resume();
1431 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1432 $sortkey = $this->mTitle
->getText();
1434 $sortkey = $this->mTitle
->getPrefixedText();
1439 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1440 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1441 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1442 $this->mOutput
->addCategoryLink( $t );
1445 * Strip the whitespace Category links produce, see bug 87
1446 * @todo We might want to use trim($tmp, "\n") here.
1448 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1450 wfProfileOut( "$fname-category" );
1455 if( ( $nt->getPrefixedText() === $selflink ) &&
1456 ( $nt->getFragment() === '' ) ) {
1457 # Self-links are handled specially; generally de-link and change to bold.
1458 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1462 # Special and Media are pseudo-namespaces; no pages actually exist in them
1463 if( $ns == NS_MEDIA
) {
1464 $link = $sk->makeMediaLinkObj( $nt, $text );
1465 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1466 $s .= $prefix . str_replace( 'http://', "http{$this->mUniqPrefix}NOPARSE://", $link ) . $trail;
1467 $wgLinkCache->addImageLinkObj( $nt );
1469 } elseif( $ns == NS_SPECIAL
) {
1470 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1472 } elseif( $ns == NS_IMAGE
) {
1473 $img = Image
::newFromTitle( $nt );
1474 if( $img->exists() ) {
1475 // Force a blue link if the file exists; may be a remote
1476 // upload on the shared repository, and we want to see its
1477 // auto-generated page.
1478 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1482 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1484 wfProfileOut( $fname );
1489 * Make a link placeholder. The text returned can be later resolved to a real link with
1490 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1491 * parsing of interwiki links, and secondly to allow all extistence checks and
1492 * article length checks (for stub links) to be bundled into a single query.
1495 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1496 if ( ! is_object($nt) ) {
1498 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1500 # Separate the link trail from the rest of the link
1501 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1503 if ( $nt->isExternal() ) {
1504 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1505 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1506 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1508 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1509 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1510 $this->mLinkHolders
['queries'][] = $query;
1511 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1512 $this->mLinkHolders
['titles'][] = $nt;
1514 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1521 * Return true if subpage links should be expanded on this page.
1524 function areSubpagesAllowed() {
1525 # Some namespaces don't allow subpages
1526 global $wgNamespacesWithSubpages;
1527 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1531 * Handle link to subpage if necessary
1532 * @param string $target the source of the link
1533 * @param string &$text the link text, modified as necessary
1534 * @return string the full name of the link
1537 function maybeDoSubpageLink($target, &$text) {
1540 # :Foobar -- override special treatment of prefix (images, language links)
1541 # /Foobar -- convert to CurrentPage/Foobar
1542 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1543 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1544 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1546 $fname = 'Parser::maybeDoSubpageLink';
1547 wfProfileIn( $fname );
1548 $ret = $target; # default return value is no change
1550 # Some namespaces don't allow subpages,
1551 # so only perform processing if subpages are allowed
1552 if( $this->areSubpagesAllowed() ) {
1553 # Look at the first character
1554 if( $target != '' && $target{0} == '/' ) {
1555 # / at end means we don't want the slash to be shown
1556 if( substr( $target, -1, 1 ) == '/' ) {
1557 $target = substr( $target, 1, -1 );
1560 $noslash = substr( $target, 1 );
1563 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1564 if( '' === $text ) {
1566 } # this might be changed for ugliness reasons
1568 # check for .. subpage backlinks
1570 $nodotdot = $target;
1571 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1573 $nodotdot = substr( $nodotdot, 3 );
1575 if($dotdotcount > 0) {
1576 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1577 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1578 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1579 # / at the end means don't show full path
1580 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1581 $nodotdot = substr( $nodotdot, 0, -1 );
1582 if( '' === $text ) {
1586 $nodotdot = trim( $nodotdot );
1587 if( $nodotdot != '' ) {
1588 $ret .= '/' . $nodotdot;
1595 wfProfileOut( $fname );
1600 * Used by doBlockLevels()
1603 /* private */ function closeParagraph() {
1605 if ( '' != $this->mLastSection
) {
1606 $result = '</' . $this->mLastSection
. ">\n";
1608 $this->mInPre
= false;
1609 $this->mLastSection
= '';
1612 # getCommon() returns the length of the longest common substring
1613 # of both arguments, starting at the beginning of both.
1615 /* private */ function getCommon( $st1, $st2 ) {
1616 $fl = strlen( $st1 );
1617 $shorter = strlen( $st2 );
1618 if ( $fl < $shorter ) { $shorter = $fl; }
1620 for ( $i = 0; $i < $shorter; ++
$i ) {
1621 if ( $st1{$i} != $st2{$i} ) { break; }
1625 # These next three functions open, continue, and close the list
1626 # element appropriate to the prefix character passed into them.
1628 /* private */ function openList( $char ) {
1629 $result = $this->closeParagraph();
1631 if ( '*' == $char ) { $result .= '<ul><li>'; }
1632 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1633 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1634 else if ( ';' == $char ) {
1635 $result .= '<dl><dt>';
1636 $this->mDTopen
= true;
1638 else { $result = '<!-- ERR 1 -->'; }
1643 /* private */ function nextItem( $char ) {
1644 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1645 else if ( ':' == $char ||
';' == $char ) {
1647 if ( $this->mDTopen
) { $close = '</dt>'; }
1648 if ( ';' == $char ) {
1649 $this->mDTopen
= true;
1650 return $close . '<dt>';
1652 $this->mDTopen
= false;
1653 return $close . '<dd>';
1656 return '<!-- ERR 2 -->';
1659 /* private */ function closeList( $char ) {
1660 if ( '*' == $char ) { $text = '</li></ul>'; }
1661 else if ( '#' == $char ) { $text = '</li></ol>'; }
1662 else if ( ':' == $char ) {
1663 if ( $this->mDTopen
) {
1664 $this->mDTopen
= false;
1665 $text = '</dt></dl>';
1667 $text = '</dd></dl>';
1670 else { return '<!-- ERR 3 -->'; }
1676 * Make lists from lines starting with ':', '*', '#', etc.
1679 * @return string the lists rendered as HTML
1681 function doBlockLevels( $text, $linestart ) {
1682 $fname = 'Parser::doBlockLevels';
1683 wfProfileIn( $fname );
1685 # Parsing through the text line by line. The main thing
1686 # happening here is handling of block-level elements p, pre,
1687 # and making lists from lines starting with * # : etc.
1689 $textLines = explode( "\n", $text );
1691 $lastPrefix = $output = '';
1692 $this->mDTopen
= $inBlockElem = false;
1694 $paragraphStack = false;
1696 if ( !$linestart ) {
1697 $output .= array_shift( $textLines );
1699 foreach ( $textLines as $oLine ) {
1700 $lastPrefixLength = strlen( $lastPrefix );
1701 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1702 $preOpenMatch = preg_match('/<pre/i', $oLine );
1703 if ( !$this->mInPre
) {
1704 # Multiple prefixes may abut each other for nested lists.
1705 $prefixLength = strspn( $oLine, '*#:;' );
1706 $pref = substr( $oLine, 0, $prefixLength );
1709 $pref2 = str_replace( ';', ':', $pref );
1710 $t = substr( $oLine, $prefixLength );
1711 $this->mInPre
= !empty($preOpenMatch);
1713 # Don't interpret any other prefixes in preformatted text
1715 $pref = $pref2 = '';
1720 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1721 # Same as the last item, so no need to deal with nesting or opening stuff
1722 $output .= $this->nextItem( substr( $pref, -1 ) );
1723 $paragraphStack = false;
1725 if ( substr( $pref, -1 ) == ';') {
1726 # The one nasty exception: definition lists work like this:
1727 # ; title : definition text
1728 # So we check for : in the remainder text to split up the
1729 # title and definition, without b0rking links.
1731 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1733 $output .= $term . $this->nextItem( ':' );
1736 } elseif( $prefixLength ||
$lastPrefixLength ) {
1737 # Either open or close a level...
1738 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1739 $paragraphStack = false;
1741 while( $commonPrefixLength < $lastPrefixLength ) {
1742 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1743 --$lastPrefixLength;
1745 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1746 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1748 while ( $prefixLength > $commonPrefixLength ) {
1749 $char = substr( $pref, $commonPrefixLength, 1 );
1750 $output .= $this->openList( $char );
1752 if ( ';' == $char ) {
1753 # FIXME: This is dupe of code above
1754 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1756 $output .= $term . $this->nextItem( ':' );
1759 ++
$commonPrefixLength;
1761 $lastPrefix = $pref2;
1763 if( 0 == $prefixLength ) {
1764 wfProfileIn( "$fname-paragraph" );
1765 # No prefix (not in list)--go to paragraph mode
1766 // XXX: use a stack for nestable elements like span, table and div
1767 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1768 $closematch = preg_match(
1769 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1770 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1771 if ( $openmatch or $closematch ) {
1772 $paragraphStack = false;
1773 $output .= $this->closeParagraph();
1774 if ( $preOpenMatch and !$preCloseMatch ) {
1775 $this->mInPre
= true;
1777 if ( $closematch ) {
1778 $inBlockElem = false;
1780 $inBlockElem = true;
1782 } else if ( !$inBlockElem && !$this->mInPre
) {
1783 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1785 if ($this->mLastSection
!= 'pre') {
1786 $paragraphStack = false;
1787 $output .= $this->closeParagraph().'<pre>';
1788 $this->mLastSection
= 'pre';
1790 $t = substr( $t, 1 );
1793 if ( '' == trim($t) ) {
1794 if ( $paragraphStack ) {
1795 $output .= $paragraphStack.'<br />';
1796 $paragraphStack = false;
1797 $this->mLastSection
= 'p';
1799 if ($this->mLastSection
!= 'p' ) {
1800 $output .= $this->closeParagraph();
1801 $this->mLastSection
= '';
1802 $paragraphStack = '<p>';
1804 $paragraphStack = '</p><p>';
1808 if ( $paragraphStack ) {
1809 $output .= $paragraphStack;
1810 $paragraphStack = false;
1811 $this->mLastSection
= 'p';
1812 } else if ($this->mLastSection
!= 'p') {
1813 $output .= $this->closeParagraph().'<p>';
1814 $this->mLastSection
= 'p';
1819 wfProfileOut( "$fname-paragraph" );
1821 // somewhere above we forget to get out of pre block (bug 785)
1822 if($preCloseMatch && $this->mInPre
) {
1823 $this->mInPre
= false;
1825 if ($paragraphStack === false) {
1829 while ( $prefixLength ) {
1830 $output .= $this->closeList( $pref2{$prefixLength-1} );
1833 if ( '' != $this->mLastSection
) {
1834 $output .= '</' . $this->mLastSection
. '>';
1835 $this->mLastSection
= '';
1838 wfProfileOut( $fname );
1843 * Split up a string on ':', ignoring any occurences inside
1844 * <a>..</a> or <span>...</span>
1845 * @param string $str the string to split
1846 * @param string &$before set to everything before the ':'
1847 * @param string &$after set to everything after the ':'
1848 * return string the position of the ':', or false if none found
1850 function findColonNoLinks($str, &$before, &$after) {
1851 # I wonder if we should make this count all tags, not just <a>
1852 # and <span>. That would prevent us from matching a ':' that
1853 # comes in the middle of italics other such formatting....
1855 $fname = 'Parser::findColonNoLinks';
1856 wfProfileIn( $fname );
1859 $colon = strpos($str, ':', $pos);
1861 if ($colon !== false) {
1862 $before = substr($str, 0, $colon);
1863 $after = substr($str, $colon +
1);
1865 # Skip any ':' within <a> or <span> pairs
1866 $a = substr_count($before, '<a');
1867 $s = substr_count($before, '<span');
1868 $ca = substr_count($before, '</a>');
1869 $cs = substr_count($before, '</span>');
1871 if ($a <= $ca and $s <= $cs) {
1872 # Tags are balanced before ':'; ok
1877 } while ($colon !== false);
1878 wfProfileOut( $fname );
1883 * Return value of a magic variable (like PAGENAME)
1887 function getVariableValue( $index ) {
1888 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1891 * Some of these require message or data lookups and can be
1892 * expensive to check many times.
1894 static $varCache = array();
1895 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1896 if ( isset( $varCache[$index] ) )
1897 return $varCache[$index];
1900 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1903 case MAG_CURRENTMONTH
:
1904 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1905 case MAG_CURRENTMONTHNAME
:
1906 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1907 case MAG_CURRENTMONTHNAMEGEN
:
1908 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1909 case MAG_CURRENTMONTHABBREV
:
1910 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1911 case MAG_CURRENTDAY
:
1912 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1914 return $this->mTitle
->getText();
1916 return $this->mTitle
->getPartialURL();
1917 case MAG_FULLPAGENAME
:
1918 return $this->mTitle
->getPrefixedText();
1919 case MAG_FULLPAGENAMEE
:
1920 return wfUrlencode( $this->mTitle
->getPrefixedText() );
1921 case MAG_REVISIONID
:
1922 return $this->mRevisionId
;
1924 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
1925 case MAG_NAMESPACEE
:
1926 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
1927 case MAG_CURRENTDAYNAME
:
1928 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
1929 case MAG_CURRENTYEAR
:
1930 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
1931 case MAG_CURRENTTIME
:
1932 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
1933 case MAG_CURRENTWEEK
:
1934 return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
1935 case MAG_CURRENTDOW
:
1936 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
1937 case MAG_NUMBEROFARTICLES
:
1938 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1939 case MAG_NUMBEROFFILES
:
1940 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1945 case MAG_SERVERNAME
:
1946 return $wgServerName;
1947 case MAG_SCRIPTPATH
:
1948 return $wgScriptPath;
1951 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
1959 * initialise the magic variables (like CURRENTMONTHNAME)
1963 function initialiseVariables() {
1964 $fname = 'Parser::initialiseVariables';
1965 wfProfileIn( $fname );
1966 global $wgVariableIDs;
1967 $this->mVariables
= array();
1968 foreach ( $wgVariableIDs as $id ) {
1969 $mw =& MagicWord
::get( $id );
1970 $mw->addToArray( $this->mVariables
, $id );
1972 wfProfileOut( $fname );
1976 * parse any parentheses in format ((title|part|part))
1977 * and call callbacks to get a replacement text for any found piece
1979 * @param string $text The text to parse
1980 * @param array $callbacks rules in form:
1981 * '{' => array( # opening parentheses
1982 * 'end' => '}', # closing parentheses
1983 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1984 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1989 function replace_callback ($text, $callbacks) {
1990 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1991 $lastOpeningBrace = -1; # last not closed parentheses
1993 for ($i = 0; $i < strlen($text); $i++
) {
1994 # check for any opening brace
1997 foreach ($callbacks as $key => $value) {
1998 $pos = strpos ($text, $key, $i);
1999 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2005 if ($lastOpeningBrace >= 0) {
2006 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2008 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2013 $pos = strpos ($text, '|', $i);
2015 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2026 # found openning brace, lets add it to parentheses stack
2027 if (null != $rule) {
2028 $piece = array('brace' => $text[$i],
2029 'braceEnd' => $rule['end'],
2034 # count openning brace characters
2035 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2040 $piece['startAt'] = $i+
1;
2041 $piece['partStart'] = $i+
1;
2043 # we need to add to stack only if openning brace count is enough for any given rule
2044 foreach ($rule['cb'] as $cnt => $fn) {
2045 if ($piece['count'] >= $cnt) {
2046 $lastOpeningBrace ++
;
2047 $openingBraceStack[$lastOpeningBrace] = $piece;
2054 else if ($lastOpeningBrace >= 0) {
2055 # first check if it is a closing brace
2056 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2057 # lets check if it is enough characters for closing brace
2059 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2062 # if there are more closing parentheses than opening ones, we parse less
2063 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2064 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2066 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2068 $matchingCallback = null;
2069 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2070 if ($count >= $cnt && $matchingCount < $cnt) {
2071 $matchingCount = $cnt;
2072 $matchingCallback = $fn;
2076 if ($matchingCount == 0) {
2081 # lets set a title or last part (if '|' was found)
2082 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2083 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2085 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2087 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2088 $pieceEnd = $i +
$matchingCount;
2090 if( is_callable( $matchingCallback ) ) {
2092 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2093 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2094 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2095 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2097 # finally we can call a user callback and replace piece of text
2098 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2099 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2100 $i = $pieceStart +
strlen($replaceWith) - 1;
2103 # null value for callback means that parentheses should be parsed, but not replaced
2104 $i +
= $matchingCount - 1;
2107 # reset last openning parentheses, but keep it in case there are unused characters
2108 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2109 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2110 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2113 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2114 $openingBraceStack[$lastOpeningBrace--] = null;
2116 if ($matchingCount < $piece['count']) {
2117 $piece['count'] -= $matchingCount;
2118 $piece['startAt'] -= $matchingCount;
2119 $piece['partStart'] = $piece['startAt'];
2120 # do we still qualify for any callback with remaining count?
2121 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2122 if ($piece['count'] >= $cnt) {
2123 $lastOpeningBrace ++
;
2124 $openingBraceStack[$lastOpeningBrace] = $piece;
2132 # lets set a title if it is a first separator, or next part otherwise
2133 if ($text[$i] == '|') {
2134 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2135 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2136 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2139 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2141 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2150 * Replace magic variables, templates, and template arguments
2151 * with the appropriate text. Templates are substituted recursively,
2152 * taking care to avoid infinite loops.
2154 * Note that the substitution depends on value of $mOutputType:
2155 * OT_WIKI: only {{subst:}} templates
2156 * OT_MSG: only magic variables
2157 * OT_HTML: all templates and magic variables
2159 * @param string $tex The text to transform
2160 * @param array $args Key-value pairs representing template parameters to substitute
2163 function replaceVariables( $text, $args = array() ) {
2164 # Prevent too big inclusions
2165 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2169 $fname = 'Parser::replaceVariables';
2170 wfProfileIn( $fname );
2172 # This function is called recursively. To keep track of arguments we need a stack:
2173 array_push( $this->mArgStack
, $args );
2175 $braceCallbacks = array();
2176 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2177 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2178 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2180 $callbacks = array();
2181 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2182 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2183 $text = $this->replace_callback ($text, $callbacks);
2185 array_pop( $this->mArgStack
);
2187 wfProfileOut( $fname );
2192 * Replace magic variables
2195 function variableSubstitution( $matches ) {
2196 $fname = 'parser::variableSubstitution';
2197 $varname = $matches[1];
2198 wfProfileIn( $fname );
2199 if ( !$this->mVariables
) {
2200 $this->initialiseVariables();
2203 if ( $this->mOutputType
== OT_WIKI
) {
2204 # Do only magic variables prefixed by SUBST
2205 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2206 if (!$mwSubst->matchStartAndRemove( $varname ))
2208 # Note that if we don't substitute the variable below,
2209 # we don't remove the {{subst:}} magic word, in case
2210 # it is a template rather than a magic variable.
2212 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2213 $id = $this->mVariables
[$varname];
2214 $text = $this->getVariableValue( $id );
2215 $this->mOutput
->mContainsOldMagic
= true;
2217 $text = $matches[0];
2219 wfProfileOut( $fname );
2223 # Split template arguments
2224 function getTemplateArgs( $argsString ) {
2225 if ( $argsString === '' ) {
2229 $args = explode( '|', substr( $argsString, 1 ) );
2231 # If any of the arguments contains a '[[' but no ']]', it needs to be
2232 # merged with the next arg because the '|' character between belongs
2233 # to the link syntax and not the template parameter syntax.
2234 $argc = count($args);
2236 for ( $i = 0; $i < $argc-1; $i++
) {
2237 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2238 $args[$i] .= '|'.$args[$i+
1];
2239 array_splice($args, $i+
1, 1);
2249 * Return the text of a template, after recursively
2250 * replacing any variables or templates within the template.
2252 * @param array $piece The parts of the template
2253 * $piece['text']: matched text
2254 * $piece['title']: the title, i.e. the part before the |
2255 * $piece['parts']: the parameter array
2256 * @return string the text of the template
2259 function braceSubstitution( $piece ) {
2260 global $wgLinkCache, $wgContLang;
2261 $fname = 'Parser::braceSubstitution';
2262 wfProfileIn( $fname );
2272 # $part1 is the bit before the first |, and must contain only title characters
2273 # $args is a list of arguments, starting from index 0, not including $part1
2275 $part1 = $piece['title'];
2276 # If the third subpattern matched anything, it will start with |
2278 if (null == $piece['parts']) {
2279 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2280 if ($replaceWith != $piece['text']) {
2281 $text = $replaceWith;
2287 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2288 $argc = count( $args );
2292 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2293 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2294 # One of two possibilities is true:
2295 # 1) Found SUBST but not in the PST phase
2296 # 2) Didn't find SUBST and in the PST phase
2297 # In either case, return without further processing
2298 $text = $piece['text'];
2304 # MSG, MSGNW and INT
2307 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2308 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2311 # Remove obsolete MSG:
2312 $mwMsg =& MagicWord
::get( MAG_MSG
);
2313 $mwMsg->matchStartAndRemove( $part1 );
2316 # Check if it is an internal message
2317 $mwInt =& MagicWord
::get( MAG_INT
);
2318 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2319 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2320 $text = $linestart . wfMsgReal( $part1, $args, true );
2328 # Check for NS: (namespace expansion)
2329 $mwNs = MagicWord
::get( MAG_NS
);
2330 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2331 if ( intval( $part1 ) ) {
2332 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2335 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2336 if ( !is_null( $index ) ) {
2337 $text = $linestart . $wgContLang->getNsText( $index );
2344 # LCFIRST, UCFIRST, LC and UC
2346 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2347 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2348 $lc =& MagicWord
::get( MAG_LC
);
2349 $uc =& MagicWord
::get( MAG_UC
);
2350 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2351 $text = $linestart . $wgContLang->lcfirst( $part1 );
2353 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2354 $text = $linestart . $wgContLang->ucfirst( $part1 );
2356 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2357 $text = $linestart . $wgContLang->lc( $part1 );
2359 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2360 $text = $linestart . $wgContLang->uc( $part1 );
2365 # LOCALURL and FULLURL
2367 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2368 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2369 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2370 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2373 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2374 $func = 'getLocalURL';
2375 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2376 $func = 'escapeLocalURL';
2377 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2378 $func = 'getFullURL';
2379 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2380 $func = 'escapeFullURL';
2385 if ( $func !== false ) {
2386 $title = Title
::newFromText( $part1 );
2387 if ( !is_null( $title ) ) {
2389 $text = $linestart . $title->$func( $args[0] );
2391 $text = $linestart . $title->$func();
2399 if ( !$found && $argc == 1 ) {
2400 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2401 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2402 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2408 if ( !$found && $argc >= 2 ) {
2409 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2410 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2411 if ($argc==2) {$args[2]=$args[1];}
2412 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2417 # Template table test
2419 # Did we encounter this template already? If yes, it is in the cache
2420 # and we need to check for loops.
2421 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2424 # Infinite loop test
2425 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2428 $text = $linestart .
2429 '{{' . $part1 . '}}' .
2430 '<!-- WARNING: template loop detected -->';
2431 wfDebug( "$fname: template loop broken at '$part1'\n" );
2433 # set $text to cached message.
2434 $text = $linestart . $this->mTemplates
[$part1];
2438 # Load from database
2439 $replaceHeadings = false;
2441 $lastPathLevel = $this->mTemplatePath
;
2444 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2445 if ($subpage !== '') {
2446 $ns = $this->mTitle
->getNamespace();
2448 $title = Title
::newFromText( $part1, $ns );
2451 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2452 if ($interwiki != '' && $title->isTrans()) {
2453 return $this->scarytransclude($title, $interwiki);
2457 if ( !is_null( $title ) && !$title->isExternal() ) {
2458 # Check for excessive inclusion
2459 $dbk = $title->getPrefixedDBkey();
2460 if ( $this->incrementIncludeCount( $dbk ) ) {
2461 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2462 # Capture special page output
2463 $text = SpecialPage
::capturePath( $title );
2464 if ( is_string( $text ) ) {
2468 $this->disableCache();
2471 $article = new Article( $title );
2472 $articleContent = $article->fetchContent(0, false);
2473 if ( $articleContent !== false ) {
2475 $text = $articleContent;
2476 $replaceHeadings = true;
2481 # If the title is valid but undisplayable, make a link to it
2482 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2483 $text = '[['.$title->getPrefixedText().']]';
2487 # Template cache array insertion
2489 $this->mTemplates
[$part1] = $text;
2490 $text = $linestart . $text;
2495 # Recursive parsing, escaping and link table handling
2496 # Only for HTML output
2497 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2498 $text = wfEscapeWikiText( $text );
2499 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2500 # Clean up argument array
2501 $assocArgs = array();
2503 foreach( $args as $arg ) {
2504 $eqpos = strpos( $arg, '=' );
2505 if ( $eqpos === false ) {
2506 $assocArgs[$index++
] = $arg;
2508 $name = trim( substr( $arg, 0, $eqpos ) );
2509 $value = trim( substr( $arg, $eqpos+
1 ) );
2510 if ( $value === false ) {
2513 if ( $name !== false ) {
2514 $assocArgs[$name] = $value;
2519 # Add a new element to the templace recursion path
2520 $this->mTemplatePath
[$part1] = 1;
2522 # If there are any <onlyinclude> tags, only include them
2523 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2524 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2526 foreach ($m[1] as $piece)
2529 # Remove <noinclude> sections and <includeonly> tags
2530 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2531 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2533 if( $this->mOutputType
== OT_HTML
) {
2534 # Strip <nowiki>, <pre>, etc.
2535 $text = $this->strip( $text, $this->mStripState
);
2536 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2538 $text = $this->replaceVariables( $text, $assocArgs );
2540 # Resume the link cache and register the inclusion as a link
2541 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2542 $wgLinkCache->addLinkObj( $title );
2545 # If the template begins with a table or block-level
2546 # element, it should be treated as beginning a new line.
2547 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2548 $text = "\n" . $text;
2551 # Prune lower levels off the recursion check path
2552 $this->mTemplatePath
= $lastPathLevel;
2555 wfProfileOut( $fname );
2556 return $piece['text'];
2559 # Replace raw HTML by a placeholder
2560 # Add a blank line preceding, to prevent it from mucking up
2561 # immediately preceding headings
2562 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2564 # replace ==section headers==
2565 # XXX this needs to go away once we have a better parser.
2566 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2567 if( !is_null( $title ) )
2568 $encodedname = base64_encode($title->getPrefixedDBkey());
2570 $encodedname = base64_encode("");
2571 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2572 PREG_SPLIT_DELIM_CAPTURE
);
2575 for( $i = 0; $i < count($m); $i +
= 2 ) {
2577 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2579 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2583 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2584 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2585 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2593 # Prune lower levels off the recursion check path
2594 $this->mTemplatePath
= $lastPathLevel;
2597 wfProfileOut( $fname );
2598 return $piece['text'];
2600 wfProfileOut( $fname );
2606 * Translude an interwiki link.
2608 function scarytransclude($title, $interwiki) {
2609 global $wgEnableScaryTranscluding;
2611 if (!$wgEnableScaryTranscluding)
2612 return wfMsg('scarytranscludedisabled');
2614 $articlename = "Template:" . $title->getDBkey();
2615 $url = str_replace('$1', urlencode($articlename), $interwiki);
2616 if (strlen($url) > 255)
2617 return wfMsg('scarytranscludetoolong');
2618 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2619 $this->mIWTransData
[] = $text;
2620 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2623 function fetchScaryTemplateMaybeFromCache($url) {
2624 $dbr =& wfGetDB(DB_SLAVE
);
2625 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2626 array('tc_url' => $url));
2628 $time = $obj->tc_time
;
2629 $text = $obj->tc_contents
;
2630 if ($time && $time < (time() +
(60*60))) {
2635 $text = wfGetHTTP($url . '?action=render');
2637 return wfMsg('scarytranscludefailed', $url);
2639 $dbw =& wfGetDB(DB_MASTER
);
2640 $dbw->replace('transcache', array(), array(
2642 'tc_time' => time(),
2643 'tc_contents' => $text));
2649 * Triple brace replacement -- used for template arguments
2652 function argSubstitution( $matches ) {
2653 $arg = trim( $matches['title'] );
2654 $text = $matches['text'];
2655 $inputArgs = end( $this->mArgStack
);
2657 if ( array_key_exists( $arg, $inputArgs ) ) {
2658 $text = $inputArgs[$arg];
2659 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2660 $text = $matches['parts'][0];
2667 * Returns true if the function is allowed to include this entity
2670 function incrementIncludeCount( $dbk ) {
2671 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2672 $this->mIncludeCount
[$dbk] = 0;
2674 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2682 * This function accomplishes several tasks:
2683 * 1) Auto-number headings if that option is enabled
2684 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2685 * 3) Add a Table of contents on the top for users who have enabled the option
2686 * 4) Auto-anchor headings
2688 * It loops through all headlines, collects the necessary data, then splits up the
2689 * string and re-inserts the newly formatted headlines.
2691 * @param string $text
2692 * @param boolean $isMain
2695 function formatHeadings( $text, $isMain=true ) {
2696 global $wgMaxTocLevel, $wgContLang;
2698 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2700 $forceTocHere = false;
2701 if( !$this->mTitle
->userCanEdit() ) {
2704 $showEditLink = $this->mOptions
->getEditSection();
2707 # Inhibit editsection links if requested in the page
2708 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2709 if( $esw->matchAndRemove( $text ) ) {
2712 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2714 $mw =& MagicWord
::get( MAG_NOTOC
);
2715 if( $mw->matchAndRemove( $text ) ) {
2719 # Get all headlines for numbering them and adding funky stuff like [edit]
2720 # links - this is for later, but we need the number of headlines right now
2721 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2723 # if there are fewer than 4 headlines in the article, do not show TOC
2724 if( $numMatches < 4 ) {
2728 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2729 # override above conditions and always show TOC at that place
2731 $mw =& MagicWord
::get( MAG_TOC
);
2732 if($mw->match( $text ) ) {
2734 $forceTocHere = true;
2736 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2737 # override above conditions and always show TOC above first header
2738 $mw =& MagicWord
::get( MAG_FORCETOC
);
2739 if ($mw->matchAndRemove( $text ) ) {
2744 # Never ever show TOC if no headers
2745 if( $numMatches < 1 ) {
2749 # We need this to perform operations on the HTML
2750 $sk =& $this->mOptions
->getSkin();
2754 $sectionCount = 0; # headlineCount excluding template sections
2756 # Ugh .. the TOC should have neat indentation levels which can be
2757 # passed to the skin functions. These are determined here
2761 $sublevelCount = array();
2762 $levelCount = array();
2769 foreach( $matches[3] as $headline ) {
2771 $templatetitle = '';
2772 $templatesection = 0;
2775 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2777 $templatetitle = base64_decode($mat[1]);
2778 $templatesection = 1 +
(int)base64_decode($mat[2]);
2779 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2783 $prevlevel = $level;
2784 $prevtoclevel = $toclevel;
2786 $level = $matches[1][$headlineCount];
2788 if( $doNumberHeadings ||
$doShowToc ) {
2790 if ( $level > $prevlevel ) {
2791 # Increase TOC level
2793 $sublevelCount[$toclevel] = 0;
2794 $toc .= $sk->tocIndent();
2796 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2797 # Decrease TOC level, find level to jump to
2799 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2800 # Can only go down to level 1
2803 for ($i = $toclevel; $i > 0; $i--) {
2804 if ( $levelCount[$i] == $level ) {
2805 # Found last matching level
2809 elseif ( $levelCount[$i] < $level ) {
2810 # Found first matching level below current level
2817 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2820 # No change in level, end TOC line
2821 $toc .= $sk->tocLineEnd();
2824 $levelCount[$toclevel] = $level;
2826 # count number of headlines for each level
2827 @$sublevelCount[$toclevel]++
;
2829 for( $i = 1; $i <= $toclevel; $i++
) {
2830 if( !empty( $sublevelCount[$i] ) ) {
2834 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2840 # The canonized header is a version of the header text safe to use for links
2841 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2842 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2843 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2845 # Remove link placeholders by the link text.
2846 # <!--LINK number-->
2848 # link text with suffix
2849 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2850 "\$this->mLinkHolders['texts'][\$1]",
2851 $canonized_headline );
2852 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2853 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2854 $canonized_headline );
2857 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2858 $tocline = trim( $canonized_headline );
2859 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2860 $replacearray = array(
2864 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2865 $refers[$headlineCount] = $canonized_headline;
2867 # count how many in assoc. array so we can track dupes in anchors
2868 @$refers[$canonized_headline]++
;
2869 $refcount[$headlineCount]=$refers[$canonized_headline];
2871 # Don't number the heading if it is the only one (looks silly)
2872 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2873 # the two are different if the line contains a link
2874 $headline=$numbering . ' ' . $headline;
2877 # Create the anchor for linking from the TOC to the section
2878 $anchor = $canonized_headline;
2879 if($refcount[$headlineCount] > 1 ) {
2880 $anchor .= '_' . $refcount[$headlineCount];
2882 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2883 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2885 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2886 if ( empty( $head[$headlineCount] ) ) {
2887 $head[$headlineCount] = '';
2890 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2892 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2895 # give headline the correct <h#> tag
2896 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2904 $toc .= $sk->tocUnindent( $toclevel - 1 );
2905 $toc = $sk->tocList( $toc );
2908 # split up and insert constructed headlines
2910 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2913 foreach( $blocks as $block ) {
2914 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2915 # This is the [edit] link that appears for the top block of text when
2916 # section editing is enabled
2918 # Disabled because it broke block formatting
2919 # For example, a bullet point in the top line
2920 # $full .= $sk->editSectionLink(0);
2923 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2924 # Top anchor now in skin
2928 if( !empty( $head[$i] ) ) {
2934 $mw =& MagicWord
::get( MAG_TOC
);
2935 return $mw->replace( $toc, $full );
2942 * Return an HTML link for the "ISBN 123456" text
2945 function magicISBN( $text ) {
2946 $fname = 'Parser::magicISBN';
2947 wfProfileIn( $fname );
2949 $a = split( 'ISBN ', ' '.$text );
2950 if ( count ( $a ) < 2 ) {
2951 wfProfileOut( $fname );
2954 $text = substr( array_shift( $a ), 1);
2955 $valid = '0123456789-Xx';
2957 foreach ( $a as $x ) {
2958 $isbn = $blank = '' ;
2959 while ( ' ' == $x{0} ) {
2961 $x = substr( $x, 1 );
2963 if ( $x == '' ) { # blank isbn
2964 $text .= "ISBN $blank";
2967 while ( strstr( $valid, $x{0} ) != false ) {
2969 $x = substr( $x, 1 );
2971 $num = str_replace( '-', '', $isbn );
2972 $num = str_replace( ' ', '', $num );
2973 $num = str_replace( 'x', 'X', $num );
2976 $text .= "ISBN $blank$x";
2978 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2979 $text .= '<a href="' .
2980 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2981 "\" class=\"internal\">ISBN $isbn</a>";
2985 wfProfileOut( $fname );
2990 * Return an HTML link for the "RFC 1234" text
2993 * @param string $text Text to be processed
2994 * @param string $keyword Magic keyword to use (default RFC)
2995 * @param string $urlmsg Interface message to use (default rfcurl)
2998 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3000 $valid = '0123456789';
3003 $a = split( $keyword, ' '.$text );
3004 if ( count ( $a ) < 2 ) {
3007 $text = substr( array_shift( $a ), 1);
3009 /* Check if keyword is preceed by [[.
3010 * This test is made here cause of the array_shift above
3011 * that prevent the test to be done in the foreach.
3013 if ( substr( $text, -2 ) == '[[' ) {
3017 foreach ( $a as $x ) {
3018 /* token might be empty if we have RFC RFC 1234 */
3026 /** remove and save whitespaces in $blank */
3027 while ( $x{0} == ' ' ) {
3029 $x = substr( $x, 1 );
3032 /** remove and save the rfc number in $id */
3033 while ( strstr( $valid, $x{0} ) != false ) {
3035 $x = substr( $x, 1 );
3039 /* call back stripped spaces*/
3040 $text .= $keyword.$blank.$x;
3041 } elseif( $internal ) {
3043 $text .= $keyword.$id.$x;
3045 /* build the external link*/
3046 $url = wfMsg( $urlmsg, $id);
3047 $sk =& $this->mOptions
->getSkin();
3048 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3049 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3052 /* Check if the next RFC keyword is preceed by [[ */
3053 $internal = ( substr($x,-2) == '[[' );
3059 * Transform wiki markup when saving a page by doing \r\n -> \n
3060 * conversion, substitting signatures, {{subst:}} templates, etc.
3062 * @param string $text the text to transform
3063 * @param Title &$title the Title object for the current article
3064 * @param User &$user the User object describing the current user
3065 * @param ParserOptions $options parsing options
3066 * @param bool $clearState whether to clear the parser state first
3067 * @return string the altered wiki markup
3070 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3071 $this->mOptions
= $options;
3072 $this->mTitle
=& $title;
3073 $this->mOutputType
= OT_WIKI
;
3075 if ( $clearState ) {
3076 $this->clearState();
3079 $stripState = false;
3083 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3084 $text = $this->strip( $text, $stripState, true );
3085 $text = $this->pstPass2( $text, $user );
3086 $text = $this->unstrip( $text, $stripState );
3087 $text = $this->unstripNoWiki( $text, $stripState );
3092 * Pre-save transform helper function
3095 function pstPass2( $text, &$user ) {
3096 global $wgContLang, $wgLocaltimezone;
3098 # Variable replacement
3099 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3100 $text = $this->replaceVariables( $text );
3104 $sigText = $this->getUserSig( $user );
3106 /* Note: This is the timestamp saved as hardcoded wikitext to
3107 * the database, we use $wgContLang here in order to give
3108 * everyone the same signiture and use the default one rather
3109 * than the one selected in each users preferences.
3111 if ( isset( $wgLocaltimezone ) ) {
3112 $oldtz = getenv( 'TZ' );
3113 putenv( 'TZ='.$wgLocaltimezone );
3115 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3116 ' (' . date( 'T' ) . ')';
3117 if ( isset( $wgLocaltimezone ) ) {
3118 putenv( 'TZ='.$oldtz );
3121 $text = preg_replace( '/~~~~~/', $d, $text );
3122 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3123 $text = preg_replace( '/~~~/', $sigText, $text );
3125 # Context links: [[|name]] and [[name (context)|]]
3127 global $wgLegalTitleChars;
3128 $tc = "[$wgLegalTitleChars]";
3129 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3131 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3132 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3134 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3135 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3136 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3137 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3139 $t = $this->mTitle
->getText();
3140 if ( preg_match( $conpat, $t, $m ) ) {
3143 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3144 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3145 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3147 if ( '' == $context ) {
3148 $text = preg_replace( $p2, '[[\\1]]', $text );
3150 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3153 # Trim trailing whitespace
3154 # MAG_END (__END__) tag allows for trailing
3155 # whitespace to be deliberately included
3156 $text = rtrim( $text );
3157 $mw =& MagicWord
::get( MAG_END
);
3158 $mw->matchAndRemove( $text );
3164 * Fetch the user's signature text, if any, and normalize to
3165 * validated, ready-to-insert wikitext.
3171 function getUserSig( &$user ) {
3172 $name = $user->getName();
3173 $nick = trim( $user->getOption( 'nickname' ) );
3174 if ( '' == $nick ) {
3178 if( $user->getOption( 'fancysig' ) ) {
3179 // A wikitext signature.
3180 $valid = $this->validateSig( $nick );
3181 if( $valid === false ) {
3182 // Fall back to default sig
3184 wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
3190 // Plain text linking to the user's homepage
3192 $page = $user->getUserPage();
3194 $page->getPrefixedText() .
3196 wfEscapeWikIText( $nick ) .
3201 * We want to enforce two rules on wikitext sigs here:
3202 * 1) Expand any templates at save time (forced subst:)
3203 * 2) Check for unbalanced XML tags, and reject if so.
3205 * @param string $text
3206 * @return mixed An expanded string, or false if invalid.
3208 * @todo Run brace substitutions
3209 * @todo ?? Check for unbalanced '' and ''' quotes, etc
3211 function validateSig( $text ) {
3212 if( wfIsWellFormedXmlFragment( $text ) ) {
3220 * Set up some variables which are usually set up in parse()
3221 * so that an external function can call some class members with confidence
3224 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3225 $this->mTitle
=& $title;
3226 $this->mOptions
= $options;
3227 $this->mOutputType
= $outputType;
3228 if ( $clearState ) {
3229 $this->clearState();
3234 * Transform a MediaWiki message by replacing magic variables.
3236 * @param string $text the text to transform
3237 * @param ParserOptions $options options
3238 * @return string the text with variables substituted
3241 function transformMsg( $text, $options ) {
3243 static $executing = false;
3245 # Guard against infinite recursion
3251 $this->mTitle
= $wgTitle;
3252 $this->mOptions
= $options;
3253 $this->mOutputType
= OT_MSG
;
3254 $this->clearState();
3255 $text = $this->replaceVariables( $text );
3262 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3263 * Callback will be called with the text within
3264 * Transform and return the text within
3268 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3269 * @param mixed $callback The callback function (and object) to use for the tag
3271 * @return The old value of the mTagHooks array associated with the hook
3273 function setHook( $tag, $callback ) {
3274 $oldVal = @$this->mTagHooks
[$tag];
3275 $this->mTagHooks
[$tag] = $callback;
3281 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3282 * Placeholders created in Skin::makeLinkObj()
3283 * Returns an array of links found, indexed by PDBK:
3287 * $options is a bit field, RLH_FOR_UPDATE to select for update
3289 function replaceLinkHolders( &$text, $options = 0 ) {
3290 global $wgUser, $wgLinkCache;
3291 global $wgOutputReplace;
3293 $fname = 'Parser::replaceLinkHolders';
3294 wfProfileIn( $fname );
3298 $sk = $this->mOptions
->getSkin();
3300 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3301 wfProfileIn( $fname.'-check' );
3302 $dbr =& wfGetDB( DB_SLAVE
);
3303 $page = $dbr->tableName( 'page' );
3304 $threshold = $wgUser->getOption('stubthreshold');
3307 asort( $this->mLinkHolders
['namespaces'] );
3311 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3313 $title = $this->mLinkHolders
['titles'][$key];
3315 # Skip invalid entries.
3316 # Result will be ugly, but prevents crash.
3317 if ( is_null( $title ) ) {
3320 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3322 # Check if it's in the link cache already
3323 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3324 $colours[$pdbk] = 1;
3325 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3326 $colours[$pdbk] = 0;
3328 # Not in the link cache, add it to the query
3329 if ( !isset( $current ) ) {
3331 $query = "SELECT page_id, page_namespace, page_title";
3332 if ( $threshold > 0 ) {
3333 $query .= ', page_len, page_is_redirect';
3335 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3336 } elseif ( $current != $val ) {
3338 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3343 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3348 if ( $options & RLH_FOR_UPDATE
) {
3349 $query .= ' FOR UPDATE';
3352 $res = $dbr->query( $query, $fname );
3354 # Fetch data and form into an associative array
3355 # non-existent = broken
3358 while ( $s = $dbr->fetchObject($res) ) {
3359 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3360 $pdbk = $title->getPrefixedDBkey();
3361 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3363 if ( $threshold > 0 ) {
3364 $size = $s->page_len
;
3365 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3366 $colours[$pdbk] = 1;
3368 $colours[$pdbk] = 2;
3371 $colours[$pdbk] = 1;
3375 wfProfileOut( $fname.'-check' );
3377 # Construct search and replace arrays
3378 wfProfileIn( $fname.'-construct' );
3379 $wgOutputReplace = array();
3380 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3381 $pdbk = $pdbks[$key];
3382 $searchkey = "<!--LINK $key-->";
3383 $title = $this->mLinkHolders
['titles'][$key];
3384 if ( empty( $colours[$pdbk] ) ) {
3385 $wgLinkCache->addBadLinkObj( $title );
3386 $colours[$pdbk] = 0;
3387 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3388 $this->mLinkHolders
['texts'][$key],
3389 $this->mLinkHolders
['queries'][$key] );
3390 } elseif ( $colours[$pdbk] == 1 ) {
3391 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3392 $this->mLinkHolders
['texts'][$key],
3393 $this->mLinkHolders
['queries'][$key] );
3394 } elseif ( $colours[$pdbk] == 2 ) {
3395 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3396 $this->mLinkHolders
['texts'][$key],
3397 $this->mLinkHolders
['queries'][$key] );
3400 wfProfileOut( $fname.'-construct' );
3403 wfProfileIn( $fname.'-replace' );
3405 $text = preg_replace_callback(
3406 '/(<!--LINK .*?-->)/',
3407 "wfOutputReplaceMatches",
3410 wfProfileOut( $fname.'-replace' );
3413 # Now process interwiki link holders
3414 # This is quite a bit simpler than internal links
3415 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3416 wfProfileIn( $fname.'-interwiki' );
3417 # Make interwiki link HTML
3418 $wgOutputReplace = array();
3419 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3420 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3421 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3424 $text = preg_replace_callback(
3425 '/<!--IWLINK (.*?)-->/',
3426 "wfOutputReplaceMatches",
3428 wfProfileOut( $fname.'-interwiki' );
3431 wfProfileOut( $fname );
3436 * Replace <!--LINK--> link placeholders with plain text of links
3437 * (not HTML-formatted).
3438 * @param string $text
3441 function replaceLinkHoldersText( $text ) {
3442 global $wgUser, $wgLinkCache;
3443 global $wgOutputReplace;
3445 $fname = 'Parser::replaceLinkHoldersText';
3446 wfProfileIn( $fname );
3448 $text = preg_replace_callback(
3449 '/<!--(LINK|IWLINK) (.*?)-->/',
3450 array( &$this, 'replaceLinkHoldersTextCallback' ),
3453 wfProfileOut( $fname );
3458 * @param array $matches
3462 function replaceLinkHoldersTextCallback( $matches ) {
3463 $type = $matches[1];
3465 if( $type == 'LINK' ) {
3466 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3467 return $this->mLinkHolders
['texts'][$key];
3469 } elseif( $type == 'IWLINK' ) {
3470 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3471 return $this->mInterwikiLinkHolders
['texts'][$key];
3478 * Renders an image gallery from a text with one line per image.
3479 * text labels may be given by using |-style alternative text. E.g.
3480 * Image:one.jpg|The number "1"
3481 * Image:tree.jpg|A tree
3482 * given as text will return the HTML of a gallery with two images,
3483 * labeled 'The number "1"' and
3488 function renderImageGallery( $text ) {
3490 global $wgUser, $wgTitle;
3491 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3492 $localParser = new Parser();
3494 global $wgLinkCache;
3495 $ig = new ImageGallery();
3496 $ig->setShowBytes( false );
3497 $ig->setShowFilename( false );
3498 $lines = explode( "\n", $text );
3500 foreach ( $lines as $line ) {
3501 # match lines like these:
3502 # Image:someimage.jpg|This is some image
3503 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3505 if ( count( $matches ) == 0 ) {
3508 $nt = Title
::newFromURL( $matches[1] );
3509 if( is_null( $nt ) ) {
3510 # Bogus title. Ignore these so we don't bomb out later.
3513 if ( isset( $matches[3] ) ) {
3514 $label = $matches[3];
3519 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3520 $html = $html->mText
;
3522 $ig->add( new Image( $nt ), $html );
3523 $wgLinkCache->addImageLinkObj( $nt );
3525 return $ig->toHTML();
3529 * Parse image options text and use it to make an image
3531 function makeImage( &$nt, $options ) {
3532 global $wgContLang, $wgUseImageResize, $wgUser;
3536 # Check if the options text is of the form "options|alt text"
3538 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3539 # * left no resizing, just left align. label is used for alt= only
3540 # * right same, but right aligned
3541 # * none same, but not aligned
3542 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3543 # * center center the image
3544 # * framed Keep original image size, no magnify-button.
3546 $part = explode( '|', $options);
3548 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3549 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3550 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3551 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3552 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3553 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3554 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3555 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3558 $width = $height = $framed = $thumb = false;
3559 $manual_thumb = '' ;
3561 foreach( $part as $key => $val ) {
3562 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3564 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3565 # use manually specified thumbnail
3567 $manual_thumb = $match;
3568 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3569 # remember to set an alignment, don't render immediately
3571 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3572 # remember to set an alignment, don't render immediately
3574 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3575 # remember to set an alignment, don't render immediately
3577 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3578 # remember to set an alignment, don't render immediately
3580 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3581 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3582 # $match is the image width in pixels
3583 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3584 $width = intval( $m[1] );
3585 $height = intval( $m[2] );
3587 $width = intval($match);
3589 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3595 # Strip bad stuff out of the alt text
3596 $alt = $this->replaceLinkHoldersText( $caption );
3597 $alt = Sanitizer
::stripAllTags( $alt );
3599 # Linker does the rest
3600 $sk =& $this->mOptions
->getSkin();
3601 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3605 * Set a flag in the output object indicating that the content is dynamic and
3606 * shouldn't be cached.
3608 function disableCache() {
3609 $this->mOutput
->mCacheTime
= -1;
3613 * Callback from the Sanitizer for expanding items found in HTML attribute
3614 * values, so they can be safely tested and escaped.
3615 * @param string $text
3616 * @param array $args
3620 function attributeStripCallback( &$text, $args ) {
3621 $text = $this->replaceVariables( $text, $args );
3622 $text = $this->unstripForHTML( $text );
3626 function unstripForHTML( $text ) {
3627 $text = $this->unstrip( $text, $this->mStripState
);
3628 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3632 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3633 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3634 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3639 * @package MediaWiki
3643 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3644 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3645 var $mVersion; # Compatibility check
3646 var $mTitleText; # title text of the chosen language variant
3648 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3649 $containsOldMagic = false, $titletext = '' )
3651 $this->mText
= $text;
3652 $this->mLanguageLinks
= $languageLinks;
3653 $this->mCategoryLinks
= $categoryLinks;
3654 $this->mContainsOldMagic
= $containsOldMagic;
3655 $this->mCacheTime
= '';
3656 $this->mVersion
= MW_PARSER_VERSION
;
3657 $this->mTitleText
= $titletext;
3660 function getText() { return $this->mText
; }
3661 function getLanguageLinks() { return $this->mLanguageLinks
; }
3662 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3663 function getCacheTime() { return $this->mCacheTime
; }
3664 function getTitleText() { return $this->mTitleText
; }
3665 function containsOldMagic() { return $this->mContainsOldMagic
; }
3666 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3667 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3668 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3669 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3670 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3671 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3673 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3675 function merge( $other ) {
3676 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3677 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3678 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3682 * Return true if this cached output object predates the global or
3683 * per-article cache invalidation timestamps, or if it comes from
3684 * an incompatible older version.
3686 * @param string $touched the affected article's last touched timestamp
3690 function expired( $touched ) {
3691 global $wgCacheEpoch;
3692 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3693 $this->getCacheTime() < $touched ||
3694 $this->getCacheTime() <= $wgCacheEpoch ||
3695 !isset( $this->mVersion
) ||
3696 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3701 * Set options of the Parser
3703 * @package MediaWiki
3707 # All variables are private
3708 var $mUseTeX; # Use texvc to expand <math> tags
3709 var $mUseDynamicDates; # Use DateFormatter to format dates
3710 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3711 var $mAllowExternalImages; # Allow external images inline
3712 var $mAllowExternalImagesFrom; # If not, any exception?
3713 var $mSkin; # Reference to the preferred skin
3714 var $mDateFormat; # Date format index
3715 var $mEditSection; # Create "edit section" links
3716 var $mNumberHeadings; # Automatically number headings
3717 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3719 function getUseTeX() { return $this->mUseTeX
; }
3720 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3721 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3722 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3723 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3724 function &getSkin() { return $this->mSkin
; }
3725 function getDateFormat() { return $this->mDateFormat
; }
3726 function getEditSection() { return $this->mEditSection
; }
3727 function getNumberHeadings() { return $this->mNumberHeadings
; }
3728 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3731 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3732 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3733 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3734 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3735 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3736 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3737 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3738 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3739 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3741 function setSkin( &$x ) { $this->mSkin
=& $x; }
3743 function ParserOptions() {
3745 $this->initialiseFromUser( $wgUser );
3749 * Get parser options
3752 function newFromUser( &$user ) {
3753 $popts = new ParserOptions
;
3754 $popts->initialiseFromUser( $user );
3758 /** Get user options */
3759 function initialiseFromUser( &$userInput ) {
3760 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3761 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3762 $fname = 'ParserOptions::initialiseFromUser';
3763 wfProfileIn( $fname );
3764 if ( !$userInput ) {
3766 $user->setLoaded( true );
3768 $user =& $userInput;
3771 $this->mUseTeX
= $wgUseTeX;
3772 $this->mUseDynamicDates
= $wgUseDynamicDates;
3773 $this->mInterwikiMagic
= $wgInterwikiMagic;
3774 $this->mAllowExternalImages
= $wgAllowExternalImages;
3775 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3776 wfProfileIn( $fname.'-skin' );
3777 $this->mSkin
=& $user->getSkin();
3778 wfProfileOut( $fname.'-skin' );
3779 $this->mDateFormat
= $user->getOption( 'date' );
3780 $this->mEditSection
= true;
3781 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3782 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3783 wfProfileOut( $fname );
3788 * Callback function used by Parser::replaceLinkHolders()
3789 * to substitute link placeholders.
3791 function &wfOutputReplaceMatches( $matches ) {
3792 global $wgOutputReplace;
3793 return $wgOutputReplace[$matches[1]];
3797 * Return the total number of articles
3799 function wfNumberOfArticles() {
3800 global $wgNumberOfArticles;
3803 return $wgNumberOfArticles;
3807 * Return the number of files
3809 function wfNumberOfFiles() {
3810 $fname = 'Parser::wfNumberOfFiles';
3812 wfProfileIn( $fname );
3813 $dbr =& wfGetDB( DB_SLAVE
);
3814 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3815 wfProfileOut( $fname );
3821 * Get various statistics from the database
3824 function wfLoadSiteStats() {
3825 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3826 $fname = 'wfLoadSiteStats';
3828 if ( -1 != $wgNumberOfArticles ) return;
3829 $dbr =& wfGetDB( DB_SLAVE
);
3830 $s = $dbr->selectRow( 'site_stats',
3831 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3832 array( 'ss_row_id' => 1 ), $fname
3835 if ( $s === false ) {
3838 $wgTotalViews = $s->ss_total_views
;
3839 $wgTotalEdits = $s->ss_total_edits
;
3840 $wgNumberOfArticles = $s->ss_good_articles
;
3846 * Basicly replacing " > and < with HTML entities ( ", >, <)
3848 * @param string $in Text that might contain HTML tags
3849 * @return string Escaped string
3851 function wfEscapeHTMLTagsOnly( $in ) {
3853 array( '"', '>', '<' ),
3854 array( '"', '>', '<' ),