3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.5.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgLinkCache
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mOptions, $mTitle, $mOutputType,
105 $mTemplates, // cache of already loaded templates, avoids
106 // multiple SQL queries for the same string
107 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
108 // in this path. Used for loop detection.
110 var $mIWTransData = array();
120 $this->mTemplates
= array();
121 $this->mTemplatePath
= array();
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 wfRunHooks( 'ParserClearState', array( &$this ) );
159 * First pass--just handle <nowiki> sections, pass the rest off
160 * to internalParse() which does all the real work.
163 * @param string $text Text we want to parse
164 * @param Title &$title A title object
165 * @param array $options
166 * @param boolean $linestart
167 * @param boolean $clearState
168 * @param int $revid number to pass in {{REVISIONID}}
169 * @return ParserOutput a ParserOutput
171 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
172 global $wgUseTidy, $wgContLang;
173 $fname = 'Parser::parse';
174 wfProfileIn( $fname );
180 $this->mOptions
= $options;
181 $this->mTitle
=& $title;
182 $this->mRevisionId
= $revid;
183 $this->mOutputType
= OT_HTML
;
185 $this->mStripState
= NULL;
187 //$text = $this->strip( $text, $this->mStripState );
188 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
189 $x =& $this->mStripState
;
191 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
192 $text = $this->strip( $text, $x );
193 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
195 # Hook to suspend the parser in this state
196 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) )
199 $text = $this->internalParse( $text );
201 $text = $this->unstrip( $text, $this->mStripState
);
203 # Clean up special characters, only run once, next-to-last before doBlockLevels
205 # french spaces, last one Guillemet-left
206 # only if there is something before the space
207 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
208 # french spaces, Guillemet-right
209 '/(\\302\\253) /' => '\\1 ',
210 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
212 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
215 $text = $this->doBlockLevels( $text, $linestart );
217 $this->replaceLinkHolders( $text );
219 # the position of the convert() call should not be changed. it
220 # assumes that the links are all replaces and the only thing left
221 # is the <nowiki> mark.
222 $text = $wgContLang->convert($text);
223 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
225 $text = $this->unstripNoWiki( $text, $this->mStripState
);
227 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
229 $text = Sanitizer
::normalizeCharReferences( $text );
232 $text = Parser
::tidy($text);
235 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
237 $this->mOutput
->setText( $text );
238 wfProfileOut( $fname );
239 return $this->mOutput
;
243 * Get a random string
248 function getRandomString() {
249 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
253 * Replaces all occurrences of <$tag>content</$tag> in the text
254 * with a random marker and returns the new text. the output parameter
255 * $content will be an associative array filled with data on the form
256 * $unique_marker => content.
258 * If $content is already set, the additional entries will be appended
259 * If $tag is set to STRIP_COMMENTS, the function will extract
260 * <!-- HTML comments -->
265 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
266 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
281 if( $tag == STRIP_COMMENTS
) {
282 $start = '/<!--()()/';
285 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
286 $end = "/<\\/$tag\\s*>/i";
289 while ( '' != $text ) {
290 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
292 if( count( $p ) < 4 ) {
299 $marker = $rnd . sprintf('%08X', $n++
);
300 $stripped .= $marker;
302 $tags[$marker] = "<$tag$attributes$empty>";
303 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
305 if ( $empty === '/' ) {
306 // Empty element tag, <tag />
307 $content[$marker] = null;
310 $q = preg_split( $end, $inside, 2 );
311 $content[$marker] = $q[0];
312 if( count( $q ) < 2 ) {
313 # No end tag -- let it run out to the end of the text.
324 * Wrapper function for extractTagsAndParams
325 * for cases where $tags and $params isn't needed
326 * i.e. where tags will never have params, like <nowiki>
331 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
332 $dummy_tags = array();
333 $dummy_params = array();
335 return Parser
::extractTagsAndParams( $tag, $text, $content,
336 $dummy_tags, $dummy_params, $uniq_prefix );
340 * Strips and renders nowiki, pre, math, hiero
341 * If $render is set, performs necessary rendering operations on plugins
342 * Returns the text, and fills an array with data needed in unstrip()
343 * If the $state is already a valid strip state, it adds to the state
345 * @param bool $stripcomments when set, HTML comments <!-- like this -->
346 * will be stripped in addition to other tags. This is important
347 * for section editing, where these comments cause confusion when
348 * counting the sections in the wikisource
352 function strip( $text, &$state, $stripcomments = false ) {
353 $render = ($this->mOutputType
== OT_HTML
);
354 $html_content = array();
355 $nowiki_content = array();
356 $math_content = array();
357 $pre_content = array();
358 $comment_content = array();
359 $ext_content = array();
361 $ext_params = array();
362 $gallery_content = array();
364 # Replace any instances of the placeholders
365 $uniq_prefix = $this->mUniqPrefix
;
366 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
371 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
372 foreach( $html_content as $marker => $content ) {
374 # Raw and unchecked for validity.
375 $html_content[$marker] = $content;
377 $html_content[$marker] = '<html>'.$content.'</html>';
383 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
384 foreach( $nowiki_content as $marker => $content ) {
386 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
388 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
393 if( $this->mOptions
->getUseTeX() ) {
394 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
395 foreach( $math_content as $marker => $content ){
397 $math_content[$marker] = renderMath( $content );
399 $math_content[$marker] = '<math>'.$content.'</math>';
405 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
406 foreach( $pre_content as $marker => $content ){
408 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
410 $pre_content[$marker] = '<pre>'.$content.'</pre>';
415 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
416 foreach( $gallery_content as $marker => $content ) {
417 require_once( 'ImageGallery.php' );
419 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
421 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
427 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
428 foreach( $comment_content as $marker => $content ){
429 $comment_content[$marker] = '<!--'.$content.'-->';
434 foreach ( $this->mTagHooks
as $tag => $callback ) {
435 $ext_content[$tag] = array();
436 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
437 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
438 foreach( $ext_content[$tag] as $marker => $content ) {
439 $full_tag = $ext_tags[$tag][$marker];
440 $params = $ext_params[$tag][$marker];
442 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
444 if ( is_null( $content ) ) {
446 $ext_content[$tag][$marker] = $full_tag;
448 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
454 # Merge state with the pre-existing state, if there is one
456 $state['html'] = $state['html'] +
$html_content;
457 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
458 $state['math'] = $state['math'] +
$math_content;
459 $state['pre'] = $state['pre'] +
$pre_content;
460 $state['comment'] = $state['comment'] +
$comment_content;
461 $state['gallery'] = $state['gallery'] +
$gallery_content;
463 foreach( $ext_content as $tag => $array ) {
464 if ( array_key_exists( $tag, $state ) ) {
465 $state[$tag] = $state[$tag] +
$array;
470 'html' => $html_content,
471 'nowiki' => $nowiki_content,
472 'math' => $math_content,
473 'pre' => $pre_content,
474 'comment' => $comment_content,
475 'gallery' => $gallery_content,
482 * restores pre, math, and hiero removed by strip()
484 * always call unstripNoWiki() after this one
487 function unstrip( $text, &$state ) {
488 if ( !is_array( $state ) ) {
492 # Must expand in reverse order, otherwise nested tags will be corrupted
493 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
494 if( $tag != 'nowiki' && $tag != 'html' ) {
495 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
496 $text = str_replace( $uniq, $content, $text );
505 * always call this after unstrip() to preserve the order
509 function unstripNoWiki( $text, &$state ) {
510 if ( !is_array( $state ) ) {
514 # Must expand in reverse order, otherwise nested tags will be corrupted
515 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
516 $text = str_replace( key( $state['nowiki'] ), $content, $text );
521 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
522 $text = str_replace( key( $state['html'] ), $content, $text );
530 * Add an item to the strip state
531 * Returns the unique tag which must be inserted into the stripped text
532 * The tag will be replaced with the original text in unstrip()
536 function insertStripItem( $text, &$state ) {
537 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
544 'comment' => array(),
545 'gallery' => array(),
548 $state['item'][$rnd] = $text;
553 * Interface with html tidy, used if $wgUseTidy = true.
554 * If tidy isn't able to correct the markup, the original will be
555 * returned in all its glory with a warning comment appended.
557 * Either the external tidy program or the in-process tidy extension
558 * will be used depending on availability. Override the default
559 * $wgTidyInternal setting to disable the internal if it's not working.
561 * @param string $text Hideous HTML input
562 * @return string Corrected HTML output
566 function tidy( $text ) {
567 global $wgTidyInternal;
568 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
569 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
570 '<head><title>test</title></head><body>'.$text.'</body></html>';
571 if( $wgTidyInternal ) {
572 $correctedtext = Parser
::internalTidy( $wrappedtext );
574 $correctedtext = Parser
::externalTidy( $wrappedtext );
576 if( is_null( $correctedtext ) ) {
577 wfDebug( "Tidy error detected!\n" );
578 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
580 return $correctedtext;
584 * Spawn an external HTML tidy process and get corrected markup back from it.
589 function externalTidy( $text ) {
590 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
591 $fname = 'Parser::externalTidy';
592 wfProfileIn( $fname );
597 $descriptorspec = array(
598 0 => array('pipe', 'r'),
599 1 => array('pipe', 'w'),
600 2 => array('file', '/dev/null', 'a')
603 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
604 if (is_resource($process)) {
605 fwrite($pipes[0], $text);
607 while (!feof($pipes[1])) {
608 $cleansource .= fgets($pipes[1], 1024);
611 proc_close($process);
614 wfProfileOut( $fname );
616 if( $cleansource == '' && $text != '') {
617 // Some kind of error happened, so we couldn't get the corrected text.
618 // Just give up; we'll use the source text and append a warning.
626 * Use the HTML tidy PECL extension to use the tidy library in-process,
627 * saving the overhead of spawning a new process. Currently written to
628 * the PHP 4.3.x version of the extension, may not work on PHP 5.
630 * 'pear install tidy' should be able to compile the extension module.
635 function internalTidy( $text ) {
637 $fname = 'Parser::internalTidy';
638 wfProfileIn( $fname );
640 tidy_load_config( $wgTidyConf );
641 tidy_set_encoding( 'utf8' );
642 tidy_parse_string( $text );
644 if( tidy_get_status() == 2 ) {
645 // 2 is magic number for fatal error
646 // http://www.php.net/manual/en/function.tidy-get-status.php
649 $cleansource = tidy_get_output();
651 wfProfileOut( $fname );
656 * parse the wiki syntax used to render tables
660 function doTableStuff ( $t ) {
661 $fname = 'Parser::doTableStuff';
662 wfProfileIn( $fname );
664 $t = explode ( "\n" , $t ) ;
665 $td = array () ; # Is currently a td tag open?
666 $ltd = array () ; # Was it TD or TH?
667 $tr = array () ; # Is currently a tr tag open?
668 $ltr = array () ; # tr attributes
669 $indent_level = 0; # indent level of the table
670 foreach ( $t AS $k => $x )
673 $fc = substr ( $x , 0 , 1 ) ;
674 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
675 $indent_level = strlen( $matches[1] );
677 $attributes = $this->unstripForHTML( $matches[2] );
679 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
680 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
681 array_push ( $td , false ) ;
682 array_push ( $ltd , '' ) ;
683 array_push ( $tr , false ) ;
684 array_push ( $ltr , '' ) ;
686 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
687 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
688 $z = "</table>" . substr ( $x , 2);
689 $l = array_pop ( $ltd ) ;
690 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
691 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
693 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
695 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
696 $x = substr ( $x , 1 ) ;
697 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
699 $l = array_pop ( $ltd ) ;
700 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
701 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
704 array_push ( $tr , false ) ;
705 array_push ( $td , false ) ;
706 array_push ( $ltd , '' ) ;
707 $attributes = $this->unstripForHTML( $x );
708 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
710 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
712 if ( '|+' == substr ( $x , 0 , 2 ) ) {
714 $x = substr ( $x , 1 ) ;
716 $after = substr ( $x , 1 ) ;
717 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
718 $after = explode ( '||' , $after ) ;
721 # Loop through each table cell
722 foreach ( $after AS $theline )
727 $tra = array_pop ( $ltr ) ;
728 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
729 array_push ( $tr , true ) ;
730 array_push ( $ltr , '' ) ;
733 $l = array_pop ( $ltd ) ;
734 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
735 if ( $fc == '|' ) $l = 'td' ;
736 else if ( $fc == '!' ) $l = 'th' ;
737 else if ( $fc == '+' ) $l = 'caption' ;
739 array_push ( $ltd , $l ) ;
742 $y = explode ( '|' , $theline , 2 ) ;
743 # Note that a '|' inside an invalid link should not
744 # be mistaken as delimiting cell parameters
745 if ( strpos( $y[0], '[[' ) !== false ) {
746 $y = array ($theline);
748 if ( count ( $y ) == 1 )
749 $y = "{$z}<{$l}>{$y[0]}" ;
751 $attributes = $this->unstripForHTML( $y[0] );
752 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
755 array_push ( $td , true ) ;
760 # Closing open td, tr && table
761 while ( count ( $td ) > 0 )
763 if ( array_pop ( $td ) ) $t[] = '</td>' ;
764 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
768 $t = implode ( "\n" , $t ) ;
769 wfProfileOut( $fname );
774 * Helper function for parse() that transforms wiki markup into
775 * HTML. Only called for $mOutputType == OT_HTML.
779 function internalParse( $text ) {
783 $fname = 'Parser::internalParse';
784 wfProfileIn( $fname );
786 # Remove <noinclude> tags and <includeonly> sections
787 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
788 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
789 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
791 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
792 $text = $this->replaceVariables( $text, $args );
794 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
796 $text = $this->doHeadings( $text );
797 if($this->mOptions
->getUseDynamicDates()) {
798 $df =& DateFormatter
::getInstance();
799 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
801 $text = $this->doAllQuotes( $text );
802 $text = $this->replaceInternalLinks( $text );
803 $text = $this->replaceExternalLinks( $text );
805 # replaceInternalLinks may sometimes leave behind
806 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
807 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
809 $text = $this->doMagicLinks( $text );
810 $text = $this->doTableStuff( $text );
811 $text = $this->formatHeadings( $text, $isMain );
813 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
814 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
816 wfProfileOut( $fname );
820 function scarySubstitution($matches) {
821 # return "[[".$matches[0]."]]";
822 return $this->mIWTransData
[(int)$matches[0]];
826 * Replace special strings like "ISBN xxx" and "RFC xxx" with
827 * magic external links.
831 function &doMagicLinks( &$text ) {
832 $text = $this->magicISBN( $text );
833 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
834 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
839 * Parse headers and return html
843 function doHeadings( $text ) {
844 $fname = 'Parser::doHeadings';
845 wfProfileIn( $fname );
846 for ( $i = 6; $i >= 1; --$i ) {
847 $h = str_repeat( '=', $i );
848 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
849 "<h{$i}>\\1</h{$i}>\\2", $text );
851 wfProfileOut( $fname );
856 * Replace single quotes with HTML markup
858 * @return string the altered text
860 function doAllQuotes( $text ) {
861 $fname = 'Parser::doAllQuotes';
862 wfProfileIn( $fname );
864 $lines = explode( "\n", $text );
865 foreach ( $lines as $line ) {
866 $outtext .= $this->doQuotes ( $line ) . "\n";
868 $outtext = substr($outtext, 0,-1);
869 wfProfileOut( $fname );
874 * Helper function for doAllQuotes()
877 function doQuotes( $text ) {
878 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
879 if ( count( $arr ) == 1 )
883 # First, do some preliminary work. This may shift some apostrophes from
884 # being mark-up to being text. It also counts the number of occurrences
885 # of bold and italics mark-ups.
889 foreach ( $arr as $r )
891 if ( ( $i %
2 ) == 1 )
893 # If there are ever four apostrophes, assume the first is supposed to
894 # be text, and the remaining three constitute mark-up for bold text.
895 if ( strlen( $arr[$i] ) == 4 )
900 # If there are more than 5 apostrophes in a row, assume they're all
901 # text except for the last 5.
902 else if ( strlen( $arr[$i] ) > 5 )
904 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
907 # Count the number of occurrences of bold and italics mark-ups.
908 # We are not counting sequences of five apostrophes.
909 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
910 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
911 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
916 # If there is an odd number of both bold and italics, it is likely
917 # that one of the bold ones was meant to be an apostrophe followed
918 # by italics. Which one we cannot know for certain, but it is more
919 # likely to be one that has a single-letter word before it.
920 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
923 $firstsingleletterword = -1;
924 $firstmultiletterword = -1;
926 foreach ( $arr as $r )
928 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
930 $x1 = substr ($arr[$i-1], -1);
931 $x2 = substr ($arr[$i-1], -2, 1);
933 if ($firstspace == -1) $firstspace = $i;
934 } else if ($x2 == ' ') {
935 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
937 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
943 # If there is a single-letter word, use it!
944 if ($firstsingleletterword > -1)
946 $arr [ $firstsingleletterword ] = "''";
947 $arr [ $firstsingleletterword-1 ] .= "'";
949 # If not, but there's a multi-letter word, use that one.
950 else if ($firstmultiletterword > -1)
952 $arr [ $firstmultiletterword ] = "''";
953 $arr [ $firstmultiletterword-1 ] .= "'";
955 # ... otherwise use the first one that has neither.
956 # (notice that it is possible for all three to be -1 if, for example,
957 # there is only one pentuple-apostrophe in the line)
958 else if ($firstspace > -1)
960 $arr [ $firstspace ] = "''";
961 $arr [ $firstspace-1 ] .= "'";
965 # Now let's actually convert our apostrophic mush to HTML!
974 if ($state == 'both')
981 if (strlen ($r) == 2)
984 { $output .= '</i>'; $state = ''; }
985 else if ($state == 'bi')
986 { $output .= '</i>'; $state = 'b'; }
987 else if ($state == 'ib')
988 { $output .= '</b></i><b>'; $state = 'b'; }
989 else if ($state == 'both')
990 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
991 else # $state can be 'b' or ''
992 { $output .= '<i>'; $state .= 'i'; }
994 else if (strlen ($r) == 3)
997 { $output .= '</b>'; $state = ''; }
998 else if ($state == 'bi')
999 { $output .= '</i></b><i>'; $state = 'i'; }
1000 else if ($state == 'ib')
1001 { $output .= '</b>'; $state = 'i'; }
1002 else if ($state == 'both')
1003 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1004 else # $state can be 'i' or ''
1005 { $output .= '<b>'; $state .= 'b'; }
1007 else if (strlen ($r) == 5)
1010 { $output .= '</b><i>'; $state = 'i'; }
1011 else if ($state == 'i')
1012 { $output .= '</i><b>'; $state = 'b'; }
1013 else if ($state == 'bi')
1014 { $output .= '</i></b>'; $state = ''; }
1015 else if ($state == 'ib')
1016 { $output .= '</b></i>'; $state = ''; }
1017 else if ($state == 'both')
1018 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1019 else # ($state == '')
1020 { $buffer = ''; $state = 'both'; }
1025 # Now close all remaining tags. Notice that the order is important.
1026 if ($state == 'b' ||
$state == 'ib')
1028 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1032 if ($state == 'both')
1033 $output .= '<b><i>'.$buffer.'</i></b>';
1039 * Replace external links
1041 * Note: this is all very hackish and the order of execution matters a lot.
1042 * Make sure to run maintenance/parserTests.php if you change this code.
1046 function replaceExternalLinks( $text ) {
1048 $fname = 'Parser::replaceExternalLinks';
1049 wfProfileIn( $fname );
1051 $sk =& $this->mOptions
->getSkin();
1053 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1055 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1058 while ( $i<count( $bits ) ) {
1060 $protocol = $bits[$i++
];
1061 $text = $bits[$i++
];
1062 $trail = $bits[$i++
];
1064 # The characters '<' and '>' (which were escaped by
1065 # removeHTMLtags()) should not be included in
1066 # URLs, per RFC 2396.
1067 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1068 $text = substr($url, $m2[0][1]) . ' ' . $text;
1069 $url = substr($url, 0, $m2[0][1]);
1072 # If the link text is an image URL, replace it with an <img> tag
1073 # This happened by accident in the original parser, but some people used it extensively
1074 $img = $this->maybeMakeExternalImage( $text );
1075 if ( $img !== false ) {
1081 # Set linktype for CSS - if URL==text, link is essentially free
1082 $linktype = ($text == $url) ?
'free' : 'text';
1084 # No link text, e.g. [http://domain.tld/some.link]
1085 if ( $text == '' ) {
1086 # Autonumber if allowed
1087 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1088 $text = '[' . ++
$this->mAutonumber
. ']';
1089 $linktype = 'autonumber';
1091 # Otherwise just use the URL
1092 $text = htmlspecialchars( $url );
1096 # Have link text, e.g. [http://domain.tld/some.link text]s
1098 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1101 $text = $wgContLang->markNoConversion($text);
1103 # Replace & from obsolete syntax with &.
1104 # All HTML entities will be escaped by makeExternalLink()
1105 # or maybeMakeExternalImage()
1106 $url = str_replace( '&', '&', $url );
1108 # Process the trail (i.e. everything after this link up until start of the next link),
1109 # replacing any non-bracketed links
1110 $trail = $this->replaceFreeExternalLinks( $trail );
1113 # Use the encoded URL
1114 # This means that users can paste URLs directly into the text
1115 # Funny characters like ö aren't valid in URLs anyway
1116 # This was changed in August 2004
1117 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1120 wfProfileOut( $fname );
1125 * Replace anything that looks like a URL with a link
1128 function replaceFreeExternalLinks( $text ) {
1130 $fname = 'Parser::replaceFreeExternalLinks';
1131 wfProfileIn( $fname );
1133 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1134 $s = array_shift( $bits );
1137 $sk =& $this->mOptions
->getSkin();
1139 while ( $i < count( $bits ) ){
1140 $protocol = $bits[$i++
];
1141 $remainder = $bits[$i++
];
1143 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1144 # Found some characters after the protocol that look promising
1145 $url = $protocol . $m[1];
1148 # The characters '<' and '>' (which were escaped by
1149 # removeHTMLtags()) should not be included in
1150 # URLs, per RFC 2396.
1151 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1152 $trail = substr($url, $m2[0][1]) . $trail;
1153 $url = substr($url, 0, $m2[0][1]);
1156 # Move trailing punctuation to $trail
1158 # If there is no left bracket, then consider right brackets fair game too
1159 if ( strpos( $url, '(' ) === false ) {
1163 $numSepChars = strspn( strrev( $url ), $sep );
1164 if ( $numSepChars ) {
1165 $trail = substr( $url, -$numSepChars ) . $trail;
1166 $url = substr( $url, 0, -$numSepChars );
1169 # Replace & from obsolete syntax with &.
1170 # All HTML entities will be escaped by makeExternalLink()
1171 # or maybeMakeExternalImage()
1172 $url = str_replace( '&', '&', $url );
1174 # Is this an external image?
1175 $text = $this->maybeMakeExternalImage( $url );
1176 if ( $text === false ) {
1177 # Not an image, make a link
1178 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1180 $s .= $text . $trail;
1182 $s .= $protocol . $remainder;
1185 wfProfileOut( $fname );
1190 * make an image if it's allowed, either through the global
1191 * option or through the exception
1194 function maybeMakeExternalImage( $url ) {
1195 $sk =& $this->mOptions
->getSkin();
1196 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1197 $imagesexception = !empty($imagesfrom);
1199 if ( $this->mOptions
->getAllowExternalImages()
1200 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1201 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1203 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1210 * Process [[ ]] wikilinks
1214 function replaceInternalLinks( $s ) {
1215 global $wgContLang, $wgLinkCache;
1216 static $fname = 'Parser::replaceInternalLinks' ;
1218 wfProfileIn( $fname );
1220 wfProfileIn( $fname.'-setup' );
1222 # the % is needed to support urlencoded titles as well
1223 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1225 $sk =& $this->mOptions
->getSkin();
1227 #split the entire text string on occurences of [[
1228 $a = explode( '[[', ' ' . $s );
1229 #get the first element (all text up to first [[), and remove the space we added
1230 $s = array_shift( $a );
1231 $s = substr( $s, 1 );
1233 # Match a link having the form [[namespace:link|alternate]]trail
1235 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1236 # Match cases where there is no "]]", which might still be images
1237 static $e1_img = FALSE;
1238 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1239 # Match the end of a line for a word that's not followed by whitespace,
1240 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1241 $e2 = wfMsgForContent( 'linkprefix' );
1243 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1245 if( is_null( $this->mTitle
) ) {
1246 wfDebugDieBacktrace( 'nooo' );
1248 $nottalk = !$this->mTitle
->isTalkPage();
1250 if ( $useLinkPrefixExtension ) {
1251 if ( preg_match( $e2, $s, $m ) ) {
1252 $first_prefix = $m[2];
1254 $first_prefix = false;
1260 $selflink = $this->mTitle
->getPrefixedText();
1261 wfProfileOut( $fname.'-setup' );
1263 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1264 $useSubpages = $this->areSubpagesAllowed();
1266 # Loop for each link
1267 for ($k = 0; isset( $a[$k] ); $k++
) {
1269 if ( $useLinkPrefixExtension ) {
1270 wfProfileIn( $fname.'-prefixhandling' );
1271 if ( preg_match( $e2, $s, $m ) ) {
1279 $prefix = $first_prefix;
1280 $first_prefix = false;
1282 wfProfileOut( $fname.'-prefixhandling' );
1285 $might_be_img = false;
1287 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1289 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1290 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1291 # the real problem is with the $e1 regex
1294 # Still some problems for cases where the ] is meant to be outside punctuation,
1295 # and no image is in sight. See bug 2095.
1297 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1298 $text .= ']'; # so that replaceExternalLinks($text) works later
1301 # fix up urlencoded title texts
1302 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1304 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1305 $might_be_img = true;
1307 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1309 } else { # Invalid form; output directly
1310 $s .= $prefix . '[[' . $line ;
1314 # Don't allow internal links to pages containing
1315 # PROTO: where PROTO is a valid URL protocol; these
1316 # should be external links.
1317 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1318 $s .= $prefix . '[[' . $line ;
1322 # Make subpage if necessary
1323 if( $useSubpages ) {
1324 $link = $this->maybeDoSubpageLink( $m[1], $text );
1329 $noforce = (substr($m[1], 0, 1) != ':');
1331 # Strip off leading ':'
1332 $link = substr($link, 1);
1335 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1337 $s .= $prefix . '[[' . $line;
1341 #check other language variants of the link
1342 #if the article does not exist
1343 if( $checkVariantLink
1344 && $nt->getArticleID() == 0 ) {
1345 $wgContLang->findVariantLink($link, $nt);
1348 $ns = $nt->getNamespace();
1349 $iw = $nt->getInterWiki();
1351 if ($might_be_img) { # if this is actually an invalid link
1352 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1354 while (isset ($a[$k+
1]) ) {
1355 #look at the next 'line' to see if we can close it there
1356 $spliced = array_splice( $a, $k +
1, 1 );
1357 $next_line = array_shift( $spliced );
1358 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1359 # the first ]] closes the inner link, the second the image
1361 $text .= '[[' . $m[1];
1364 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1365 #if there's exactly one ]] that's fine, we'll keep looking
1366 $text .= '[[' . $m[0];
1368 #if $next_line is invalid too, we need look no further
1369 $text .= '[[' . $next_line;
1374 # we couldn't find the end of this imageLink, so output it raw
1375 #but don't ignore what might be perfectly normal links in the text we've examined
1376 $text = $this->replaceInternalLinks($text);
1377 $s .= $prefix . '[[' . $link . '|' . $text;
1378 # note: no $trail, because without an end, there *is* no trail
1381 } else { #it's not an image, so output it raw
1382 $s .= $prefix . '[[' . $link . '|' . $text;
1383 # note: no $trail, because without an end, there *is* no trail
1388 $wasblank = ( '' == $text );
1389 if( $wasblank ) $text = $link;
1392 # Link not escaped by : , create the various objects
1396 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1397 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1398 $s = rtrim($s . "\n");
1399 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1403 if ( $ns == NS_IMAGE
) {
1404 wfProfileIn( "$fname-image" );
1405 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1406 # recursively parse links inside the image caption
1407 # actually, this will parse them in any other parameters, too,
1408 # but it might be hard to fix that, and it doesn't matter ATM
1409 $text = $this->replaceExternalLinks($text);
1410 $text = $this->replaceInternalLinks($text);
1412 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1413 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1414 $wgLinkCache->addImageLinkObj( $nt );
1416 wfProfileOut( "$fname-image" );
1419 wfProfileOut( "$fname-image" );
1423 if ( $ns == NS_CATEGORY
) {
1424 wfProfileIn( "$fname-category" );
1425 $t = $wgContLang->convertHtml( $nt->getText() );
1426 $s = rtrim($s . "\n"); # bug 87
1428 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1429 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1430 $wgLinkCache->resume();
1433 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1434 $sortkey = $this->mTitle
->getText();
1436 $sortkey = $this->mTitle
->getPrefixedText();
1441 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1442 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1443 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1444 $this->mOutput
->addCategoryLink( $t );
1447 * Strip the whitespace Category links produce, see bug 87
1448 * @todo We might want to use trim($tmp, "\n") here.
1450 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1452 wfProfileOut( "$fname-category" );
1457 if( ( $nt->getPrefixedText() === $selflink ) &&
1458 ( $nt->getFragment() === '' ) ) {
1459 # Self-links are handled specially; generally de-link and change to bold.
1460 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1464 # Special and Media are pseudo-namespaces; no pages actually exist in them
1465 if( $ns == NS_MEDIA
) {
1466 $link = $sk->makeMediaLinkObj( $nt, $text );
1467 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1468 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1469 $wgLinkCache->addImageLinkObj( $nt );
1471 } elseif( $ns == NS_SPECIAL
) {
1472 $s .= $prefix . $this->armorLinks( $sk->makeKnownLinkObj( $nt, $text, '', $trail ) );
1474 } elseif( $ns == NS_IMAGE
) {
1475 $img = Image
::newFromTitle( $nt );
1476 if( $img->exists() ) {
1477 // Force a blue link if the file exists; may be a remote
1478 // upload on the shared repository, and we want to see its
1479 // auto-generated page.
1480 $s .= $prefix . $this->armorLinks( $sk->makeKnownLinkObj( $nt, $text, '', $trail ) );
1484 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1486 wfProfileOut( $fname );
1491 * Make a link placeholder. The text returned can be later resolved to a real link with
1492 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1493 * parsing of interwiki links, and secondly to allow all extistence checks and
1494 * article length checks (for stub links) to be bundled into a single query.
1497 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1498 if ( ! is_object($nt) ) {
1500 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1502 # Separate the link trail from the rest of the link
1503 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1505 if ( $nt->isExternal() ) {
1506 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1507 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1508 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1510 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1511 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1512 $this->mLinkHolders
['queries'][] = $query;
1513 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1514 $this->mLinkHolders
['titles'][] = $nt;
1516 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1523 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1524 * going to go through further parsing steps before inline URL expansion.
1526 * In particular this is important when using action=render, which causes
1527 * full URLs to be included.
1529 * Oh man I hate our multi-layer parser!
1531 * @param string more-or-less HTML
1532 * @return string less-or-more HTML with NOPARSE bits
1534 function armorLinks( $text ) {
1535 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1536 "{$this->mUniqPrefix}NOPARSE$1", $text );
1540 * Return true if subpage links should be expanded on this page.
1543 function areSubpagesAllowed() {
1544 # Some namespaces don't allow subpages
1545 global $wgNamespacesWithSubpages;
1546 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1550 * Handle link to subpage if necessary
1551 * @param string $target the source of the link
1552 * @param string &$text the link text, modified as necessary
1553 * @return string the full name of the link
1556 function maybeDoSubpageLink($target, &$text) {
1559 # :Foobar -- override special treatment of prefix (images, language links)
1560 # /Foobar -- convert to CurrentPage/Foobar
1561 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1562 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1563 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1565 $fname = 'Parser::maybeDoSubpageLink';
1566 wfProfileIn( $fname );
1567 $ret = $target; # default return value is no change
1569 # Some namespaces don't allow subpages,
1570 # so only perform processing if subpages are allowed
1571 if( $this->areSubpagesAllowed() ) {
1572 # Look at the first character
1573 if( $target != '' && $target{0} == '/' ) {
1574 # / at end means we don't want the slash to be shown
1575 if( substr( $target, -1, 1 ) == '/' ) {
1576 $target = substr( $target, 1, -1 );
1579 $noslash = substr( $target, 1 );
1582 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1583 if( '' === $text ) {
1585 } # this might be changed for ugliness reasons
1587 # check for .. subpage backlinks
1589 $nodotdot = $target;
1590 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1592 $nodotdot = substr( $nodotdot, 3 );
1594 if($dotdotcount > 0) {
1595 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1596 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1597 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1598 # / at the end means don't show full path
1599 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1600 $nodotdot = substr( $nodotdot, 0, -1 );
1601 if( '' === $text ) {
1605 $nodotdot = trim( $nodotdot );
1606 if( $nodotdot != '' ) {
1607 $ret .= '/' . $nodotdot;
1614 wfProfileOut( $fname );
1619 * Used by doBlockLevels()
1622 /* private */ function closeParagraph() {
1624 if ( '' != $this->mLastSection
) {
1625 $result = '</' . $this->mLastSection
. ">\n";
1627 $this->mInPre
= false;
1628 $this->mLastSection
= '';
1631 # getCommon() returns the length of the longest common substring
1632 # of both arguments, starting at the beginning of both.
1634 /* private */ function getCommon( $st1, $st2 ) {
1635 $fl = strlen( $st1 );
1636 $shorter = strlen( $st2 );
1637 if ( $fl < $shorter ) { $shorter = $fl; }
1639 for ( $i = 0; $i < $shorter; ++
$i ) {
1640 if ( $st1{$i} != $st2{$i} ) { break; }
1644 # These next three functions open, continue, and close the list
1645 # element appropriate to the prefix character passed into them.
1647 /* private */ function openList( $char ) {
1648 $result = $this->closeParagraph();
1650 if ( '*' == $char ) { $result .= '<ul><li>'; }
1651 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1652 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1653 else if ( ';' == $char ) {
1654 $result .= '<dl><dt>';
1655 $this->mDTopen
= true;
1657 else { $result = '<!-- ERR 1 -->'; }
1662 /* private */ function nextItem( $char ) {
1663 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1664 else if ( ':' == $char ||
';' == $char ) {
1666 if ( $this->mDTopen
) { $close = '</dt>'; }
1667 if ( ';' == $char ) {
1668 $this->mDTopen
= true;
1669 return $close . '<dt>';
1671 $this->mDTopen
= false;
1672 return $close . '<dd>';
1675 return '<!-- ERR 2 -->';
1678 /* private */ function closeList( $char ) {
1679 if ( '*' == $char ) { $text = '</li></ul>'; }
1680 else if ( '#' == $char ) { $text = '</li></ol>'; }
1681 else if ( ':' == $char ) {
1682 if ( $this->mDTopen
) {
1683 $this->mDTopen
= false;
1684 $text = '</dt></dl>';
1686 $text = '</dd></dl>';
1689 else { return '<!-- ERR 3 -->'; }
1695 * Make lists from lines starting with ':', '*', '#', etc.
1698 * @return string the lists rendered as HTML
1700 function doBlockLevels( $text, $linestart ) {
1701 $fname = 'Parser::doBlockLevels';
1702 wfProfileIn( $fname );
1704 # Parsing through the text line by line. The main thing
1705 # happening here is handling of block-level elements p, pre,
1706 # and making lists from lines starting with * # : etc.
1708 $textLines = explode( "\n", $text );
1710 $lastPrefix = $output = '';
1711 $this->mDTopen
= $inBlockElem = false;
1713 $paragraphStack = false;
1715 if ( !$linestart ) {
1716 $output .= array_shift( $textLines );
1718 foreach ( $textLines as $oLine ) {
1719 $lastPrefixLength = strlen( $lastPrefix );
1720 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1721 $preOpenMatch = preg_match('/<pre/i', $oLine );
1722 if ( !$this->mInPre
) {
1723 # Multiple prefixes may abut each other for nested lists.
1724 $prefixLength = strspn( $oLine, '*#:;' );
1725 $pref = substr( $oLine, 0, $prefixLength );
1728 $pref2 = str_replace( ';', ':', $pref );
1729 $t = substr( $oLine, $prefixLength );
1730 $this->mInPre
= !empty($preOpenMatch);
1732 # Don't interpret any other prefixes in preformatted text
1734 $pref = $pref2 = '';
1739 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1740 # Same as the last item, so no need to deal with nesting or opening stuff
1741 $output .= $this->nextItem( substr( $pref, -1 ) );
1742 $paragraphStack = false;
1744 if ( substr( $pref, -1 ) == ';') {
1745 # The one nasty exception: definition lists work like this:
1746 # ; title : definition text
1747 # So we check for : in the remainder text to split up the
1748 # title and definition, without b0rking links.
1750 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1752 $output .= $term . $this->nextItem( ':' );
1755 } elseif( $prefixLength ||
$lastPrefixLength ) {
1756 # Either open or close a level...
1757 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1758 $paragraphStack = false;
1760 while( $commonPrefixLength < $lastPrefixLength ) {
1761 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1762 --$lastPrefixLength;
1764 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1765 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1767 while ( $prefixLength > $commonPrefixLength ) {
1768 $char = substr( $pref, $commonPrefixLength, 1 );
1769 $output .= $this->openList( $char );
1771 if ( ';' == $char ) {
1772 # FIXME: This is dupe of code above
1773 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1775 $output .= $term . $this->nextItem( ':' );
1778 ++
$commonPrefixLength;
1780 $lastPrefix = $pref2;
1782 if( 0 == $prefixLength ) {
1783 wfProfileIn( "$fname-paragraph" );
1784 # No prefix (not in list)--go to paragraph mode
1785 // XXX: use a stack for nestable elements like span, table and div
1786 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1787 $closematch = preg_match(
1788 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1789 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1790 if ( $openmatch or $closematch ) {
1791 $paragraphStack = false;
1792 $output .= $this->closeParagraph();
1793 if ( $preOpenMatch and !$preCloseMatch ) {
1794 $this->mInPre
= true;
1796 if ( $closematch ) {
1797 $inBlockElem = false;
1799 $inBlockElem = true;
1801 } else if ( !$inBlockElem && !$this->mInPre
) {
1802 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1804 if ($this->mLastSection
!= 'pre') {
1805 $paragraphStack = false;
1806 $output .= $this->closeParagraph().'<pre>';
1807 $this->mLastSection
= 'pre';
1809 $t = substr( $t, 1 );
1812 if ( '' == trim($t) ) {
1813 if ( $paragraphStack ) {
1814 $output .= $paragraphStack.'<br />';
1815 $paragraphStack = false;
1816 $this->mLastSection
= 'p';
1818 if ($this->mLastSection
!= 'p' ) {
1819 $output .= $this->closeParagraph();
1820 $this->mLastSection
= '';
1821 $paragraphStack = '<p>';
1823 $paragraphStack = '</p><p>';
1827 if ( $paragraphStack ) {
1828 $output .= $paragraphStack;
1829 $paragraphStack = false;
1830 $this->mLastSection
= 'p';
1831 } else if ($this->mLastSection
!= 'p') {
1832 $output .= $this->closeParagraph().'<p>';
1833 $this->mLastSection
= 'p';
1838 wfProfileOut( "$fname-paragraph" );
1840 // somewhere above we forget to get out of pre block (bug 785)
1841 if($preCloseMatch && $this->mInPre
) {
1842 $this->mInPre
= false;
1844 if ($paragraphStack === false) {
1848 while ( $prefixLength ) {
1849 $output .= $this->closeList( $pref2{$prefixLength-1} );
1852 if ( '' != $this->mLastSection
) {
1853 $output .= '</' . $this->mLastSection
. '>';
1854 $this->mLastSection
= '';
1857 wfProfileOut( $fname );
1862 * Split up a string on ':', ignoring any occurences inside
1863 * <a>..</a> or <span>...</span>
1864 * @param string $str the string to split
1865 * @param string &$before set to everything before the ':'
1866 * @param string &$after set to everything after the ':'
1867 * return string the position of the ':', or false if none found
1869 function findColonNoLinks($str, &$before, &$after) {
1870 # I wonder if we should make this count all tags, not just <a>
1871 # and <span>. That would prevent us from matching a ':' that
1872 # comes in the middle of italics other such formatting....
1874 $fname = 'Parser::findColonNoLinks';
1875 wfProfileIn( $fname );
1878 $colon = strpos($str, ':', $pos);
1880 if ($colon !== false) {
1881 $before = substr($str, 0, $colon);
1882 $after = substr($str, $colon +
1);
1884 # Skip any ':' within <a> or <span> pairs
1885 $a = substr_count($before, '<a');
1886 $s = substr_count($before, '<span');
1887 $ca = substr_count($before, '</a>');
1888 $cs = substr_count($before, '</span>');
1890 if ($a <= $ca and $s <= $cs) {
1891 # Tags are balanced before ':'; ok
1896 } while ($colon !== false);
1897 wfProfileOut( $fname );
1902 * Return value of a magic variable (like PAGENAME)
1906 function getVariableValue( $index ) {
1907 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1910 * Some of these require message or data lookups and can be
1911 * expensive to check many times.
1913 static $varCache = array();
1914 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1915 if ( isset( $varCache[$index] ) )
1916 return $varCache[$index];
1919 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1922 case MAG_CURRENTMONTH
:
1923 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1924 case MAG_CURRENTMONTHNAME
:
1925 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1926 case MAG_CURRENTMONTHNAMEGEN
:
1927 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1928 case MAG_CURRENTMONTHABBREV
:
1929 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1930 case MAG_CURRENTDAY
:
1931 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1933 return $this->mTitle
->getText();
1935 return $this->mTitle
->getPartialURL();
1936 case MAG_FULLPAGENAME
:
1937 return $this->mTitle
->getPrefixedText();
1938 case MAG_FULLPAGENAMEE
:
1939 return wfUrlencode( $this->mTitle
->getPrefixedText() );
1940 case MAG_REVISIONID
:
1941 return $this->mRevisionId
;
1943 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
1944 case MAG_NAMESPACEE
:
1945 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
1946 case MAG_CURRENTDAYNAME
:
1947 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
1948 case MAG_CURRENTYEAR
:
1949 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
1950 case MAG_CURRENTTIME
:
1951 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
1952 case MAG_CURRENTWEEK
:
1953 return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
1954 case MAG_CURRENTDOW
:
1955 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
1956 case MAG_NUMBEROFARTICLES
:
1957 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1958 case MAG_NUMBEROFFILES
:
1959 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1964 case MAG_SERVERNAME
:
1965 return $wgServerName;
1966 case MAG_SCRIPTPATH
:
1967 return $wgScriptPath;
1970 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
1978 * initialise the magic variables (like CURRENTMONTHNAME)
1982 function initialiseVariables() {
1983 $fname = 'Parser::initialiseVariables';
1984 wfProfileIn( $fname );
1985 global $wgVariableIDs;
1986 $this->mVariables
= array();
1987 foreach ( $wgVariableIDs as $id ) {
1988 $mw =& MagicWord
::get( $id );
1989 $mw->addToArray( $this->mVariables
, $id );
1991 wfProfileOut( $fname );
1995 * parse any parentheses in format ((title|part|part))
1996 * and call callbacks to get a replacement text for any found piece
1998 * @param string $text The text to parse
1999 * @param array $callbacks rules in form:
2000 * '{' => array( # opening parentheses
2001 * 'end' => '}', # closing parentheses
2002 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2003 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2008 function replace_callback ($text, $callbacks) {
2009 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2010 $lastOpeningBrace = -1; # last not closed parentheses
2012 for ($i = 0; $i < strlen($text); $i++
) {
2013 # check for any opening brace
2016 foreach ($callbacks as $key => $value) {
2017 $pos = strpos ($text, $key, $i);
2018 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2024 if ($lastOpeningBrace >= 0) {
2025 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2027 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2032 $pos = strpos ($text, '|', $i);
2034 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2045 # found openning brace, lets add it to parentheses stack
2046 if (null != $rule) {
2047 $piece = array('brace' => $text[$i],
2048 'braceEnd' => $rule['end'],
2053 # count openning brace characters
2054 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2059 $piece['startAt'] = $i+
1;
2060 $piece['partStart'] = $i+
1;
2062 # we need to add to stack only if openning brace count is enough for any given rule
2063 foreach ($rule['cb'] as $cnt => $fn) {
2064 if ($piece['count'] >= $cnt) {
2065 $lastOpeningBrace ++
;
2066 $openingBraceStack[$lastOpeningBrace] = $piece;
2073 else if ($lastOpeningBrace >= 0) {
2074 # first check if it is a closing brace
2075 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2076 # lets check if it is enough characters for closing brace
2078 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2081 # if there are more closing parentheses than opening ones, we parse less
2082 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2083 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2085 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2087 $matchingCallback = null;
2088 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2089 if ($count >= $cnt && $matchingCount < $cnt) {
2090 $matchingCount = $cnt;
2091 $matchingCallback = $fn;
2095 if ($matchingCount == 0) {
2100 # lets set a title or last part (if '|' was found)
2101 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2102 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2104 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2106 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2107 $pieceEnd = $i +
$matchingCount;
2109 if( is_callable( $matchingCallback ) ) {
2111 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2112 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2113 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2114 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2116 # finally we can call a user callback and replace piece of text
2117 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2118 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2119 $i = $pieceStart +
strlen($replaceWith) - 1;
2122 # null value for callback means that parentheses should be parsed, but not replaced
2123 $i +
= $matchingCount - 1;
2126 # reset last openning parentheses, but keep it in case there are unused characters
2127 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2128 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2129 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2132 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2133 $openingBraceStack[$lastOpeningBrace--] = null;
2135 if ($matchingCount < $piece['count']) {
2136 $piece['count'] -= $matchingCount;
2137 $piece['startAt'] -= $matchingCount;
2138 $piece['partStart'] = $piece['startAt'];
2139 # do we still qualify for any callback with remaining count?
2140 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2141 if ($piece['count'] >= $cnt) {
2142 $lastOpeningBrace ++
;
2143 $openingBraceStack[$lastOpeningBrace] = $piece;
2151 # lets set a title if it is a first separator, or next part otherwise
2152 if ($text[$i] == '|') {
2153 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2154 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2155 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2158 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2160 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2169 * Replace magic variables, templates, and template arguments
2170 * with the appropriate text. Templates are substituted recursively,
2171 * taking care to avoid infinite loops.
2173 * Note that the substitution depends on value of $mOutputType:
2174 * OT_WIKI: only {{subst:}} templates
2175 * OT_MSG: only magic variables
2176 * OT_HTML: all templates and magic variables
2178 * @param string $tex The text to transform
2179 * @param array $args Key-value pairs representing template parameters to substitute
2182 function replaceVariables( $text, $args = array() ) {
2183 # Prevent too big inclusions
2184 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2188 $fname = 'Parser::replaceVariables';
2189 wfProfileIn( $fname );
2191 # This function is called recursively. To keep track of arguments we need a stack:
2192 array_push( $this->mArgStack
, $args );
2194 $braceCallbacks = array();
2195 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2196 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2197 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2199 $callbacks = array();
2200 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2201 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2202 $text = $this->replace_callback ($text, $callbacks);
2204 array_pop( $this->mArgStack
);
2206 wfProfileOut( $fname );
2211 * Replace magic variables
2214 function variableSubstitution( $matches ) {
2215 $fname = 'Parser::variableSubstitution';
2216 $varname = $matches[1];
2217 wfProfileIn( $fname );
2218 if ( !$this->mVariables
) {
2219 $this->initialiseVariables();
2222 if ( $this->mOutputType
== OT_WIKI
) {
2223 # Do only magic variables prefixed by SUBST
2224 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2225 if (!$mwSubst->matchStartAndRemove( $varname ))
2227 # Note that if we don't substitute the variable below,
2228 # we don't remove the {{subst:}} magic word, in case
2229 # it is a template rather than a magic variable.
2231 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2232 $id = $this->mVariables
[$varname];
2233 $text = $this->getVariableValue( $id );
2234 $this->mOutput
->mContainsOldMagic
= true;
2236 $text = $matches[0];
2238 wfProfileOut( $fname );
2242 # Split template arguments
2243 function getTemplateArgs( $argsString ) {
2244 if ( $argsString === '' ) {
2248 $args = explode( '|', substr( $argsString, 1 ) );
2250 # If any of the arguments contains a '[[' but no ']]', it needs to be
2251 # merged with the next arg because the '|' character between belongs
2252 # to the link syntax and not the template parameter syntax.
2253 $argc = count($args);
2255 for ( $i = 0; $i < $argc-1; $i++
) {
2256 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2257 $args[$i] .= '|'.$args[$i+
1];
2258 array_splice($args, $i+
1, 1);
2268 * Return the text of a template, after recursively
2269 * replacing any variables or templates within the template.
2271 * @param array $piece The parts of the template
2272 * $piece['text']: matched text
2273 * $piece['title']: the title, i.e. the part before the |
2274 * $piece['parts']: the parameter array
2275 * @return string the text of the template
2278 function braceSubstitution( $piece ) {
2279 global $wgLinkCache, $wgContLang;
2280 $fname = 'Parser::braceSubstitution';
2281 wfProfileIn( $fname );
2291 # $part1 is the bit before the first |, and must contain only title characters
2292 # $args is a list of arguments, starting from index 0, not including $part1
2294 $part1 = $piece['title'];
2295 # If the third subpattern matched anything, it will start with |
2297 if (null == $piece['parts']) {
2298 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2299 if ($replaceWith != $piece['text']) {
2300 $text = $replaceWith;
2306 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2307 $argc = count( $args );
2311 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2312 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2313 # One of two possibilities is true:
2314 # 1) Found SUBST but not in the PST phase
2315 # 2) Didn't find SUBST and in the PST phase
2316 # In either case, return without further processing
2317 $text = $piece['text'];
2323 # MSG, MSGNW and INT
2326 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2327 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2330 # Remove obsolete MSG:
2331 $mwMsg =& MagicWord
::get( MAG_MSG
);
2332 $mwMsg->matchStartAndRemove( $part1 );
2335 # Check if it is an internal message
2336 $mwInt =& MagicWord
::get( MAG_INT
);
2337 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2338 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2339 $text = $linestart . wfMsgReal( $part1, $args, true );
2347 # Check for NS: (namespace expansion)
2348 $mwNs = MagicWord
::get( MAG_NS
);
2349 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2350 if ( intval( $part1 ) ) {
2351 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2354 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2355 if ( !is_null( $index ) ) {
2356 $text = $linestart . $wgContLang->getNsText( $index );
2363 # LCFIRST, UCFIRST, LC and UC
2365 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2366 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2367 $lc =& MagicWord
::get( MAG_LC
);
2368 $uc =& MagicWord
::get( MAG_UC
);
2369 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2370 $text = $linestart . $wgContLang->lcfirst( $part1 );
2372 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2373 $text = $linestart . $wgContLang->ucfirst( $part1 );
2375 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2376 $text = $linestart . $wgContLang->lc( $part1 );
2378 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2379 $text = $linestart . $wgContLang->uc( $part1 );
2384 # LOCALURL and FULLURL
2386 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2387 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2388 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2389 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2392 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2393 $func = 'getLocalURL';
2394 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2395 $func = 'escapeLocalURL';
2396 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2397 $func = 'getFullURL';
2398 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2399 $func = 'escapeFullURL';
2404 if ( $func !== false ) {
2405 $title = Title
::newFromText( $part1 );
2406 if ( !is_null( $title ) ) {
2408 $text = $linestart . $title->$func( $args[0] );
2410 $text = $linestart . $title->$func();
2418 if ( !$found && $argc == 1 ) {
2419 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2420 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2421 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2427 if ( !$found && $argc >= 2 ) {
2428 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2429 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2430 if ($argc==2) {$args[2]=$args[1];}
2431 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2436 # Template table test
2438 # Did we encounter this template already? If yes, it is in the cache
2439 # and we need to check for loops.
2440 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2443 # Infinite loop test
2444 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2447 $text = $linestart .
2448 '{{' . $part1 . '}}' .
2449 '<!-- WARNING: template loop detected -->';
2450 wfDebug( "$fname: template loop broken at '$part1'\n" );
2452 # set $text to cached message.
2453 $text = $linestart . $this->mTemplates
[$part1];
2457 # Load from database
2458 $replaceHeadings = false;
2460 $lastPathLevel = $this->mTemplatePath
;
2463 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2464 if ($subpage !== '') {
2465 $ns = $this->mTitle
->getNamespace();
2467 $title = Title
::newFromText( $part1, $ns );
2470 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2471 if ($interwiki != '' && $title->isTrans()) {
2472 return $this->scarytransclude($title, $interwiki);
2476 if ( !is_null( $title ) && !$title->isExternal() ) {
2477 # Check for excessive inclusion
2478 $dbk = $title->getPrefixedDBkey();
2479 if ( $this->incrementIncludeCount( $dbk ) ) {
2480 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2481 # Capture special page output
2482 $text = SpecialPage
::capturePath( $title );
2483 if ( is_string( $text ) ) {
2487 $this->disableCache();
2490 $article = new Article( $title );
2491 $articleContent = $article->fetchContent(0, false);
2492 if ( $articleContent !== false ) {
2494 $text = $articleContent;
2495 $replaceHeadings = true;
2500 # If the title is valid but undisplayable, make a link to it
2501 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2502 $text = '[['.$title->getPrefixedText().']]';
2506 # Template cache array insertion
2508 $this->mTemplates
[$part1] = $text;
2509 $text = $linestart . $text;
2514 # Recursive parsing, escaping and link table handling
2515 # Only for HTML output
2516 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2517 $text = wfEscapeWikiText( $text );
2518 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2519 # Clean up argument array
2520 $assocArgs = array();
2522 foreach( $args as $arg ) {
2523 $eqpos = strpos( $arg, '=' );
2524 if ( $eqpos === false ) {
2525 $assocArgs[$index++
] = $arg;
2527 $name = trim( substr( $arg, 0, $eqpos ) );
2528 $value = trim( substr( $arg, $eqpos+
1 ) );
2529 if ( $value === false ) {
2532 if ( $name !== false ) {
2533 $assocArgs[$name] = $value;
2538 # Add a new element to the templace recursion path
2539 $this->mTemplatePath
[$part1] = 1;
2541 # If there are any <onlyinclude> tags, only include them
2542 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2543 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2545 foreach ($m[1] as $piece)
2548 # Remove <noinclude> sections and <includeonly> tags
2549 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2550 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2552 if( $this->mOutputType
== OT_HTML
) {
2553 # Strip <nowiki>, <pre>, etc.
2554 $text = $this->strip( $text, $this->mStripState
);
2555 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2557 $text = $this->replaceVariables( $text, $assocArgs );
2559 # Resume the link cache and register the inclusion as a link
2560 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2561 $wgLinkCache->addLinkObj( $title );
2564 # If the template begins with a table or block-level
2565 # element, it should be treated as beginning a new line.
2566 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2567 $text = "\n" . $text;
2570 # Prune lower levels off the recursion check path
2571 $this->mTemplatePath
= $lastPathLevel;
2574 wfProfileOut( $fname );
2575 return $piece['text'];
2578 # Replace raw HTML by a placeholder
2579 # Add a blank line preceding, to prevent it from mucking up
2580 # immediately preceding headings
2581 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2583 # replace ==section headers==
2584 # XXX this needs to go away once we have a better parser.
2585 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2586 if( !is_null( $title ) )
2587 $encodedname = base64_encode($title->getPrefixedDBkey());
2589 $encodedname = base64_encode("");
2590 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2591 PREG_SPLIT_DELIM_CAPTURE
);
2594 for( $i = 0; $i < count($m); $i +
= 2 ) {
2596 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2598 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2602 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2603 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2604 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2612 # Prune lower levels off the recursion check path
2613 $this->mTemplatePath
= $lastPathLevel;
2616 wfProfileOut( $fname );
2617 return $piece['text'];
2619 wfProfileOut( $fname );
2625 * Translude an interwiki link.
2627 function scarytransclude($title, $interwiki) {
2628 global $wgEnableScaryTranscluding;
2630 if (!$wgEnableScaryTranscluding)
2631 return wfMsg('scarytranscludedisabled');
2633 $articlename = "Template:" . $title->getDBkey();
2634 $url = str_replace('$1', urlencode($articlename), $interwiki);
2635 if (strlen($url) > 255)
2636 return wfMsg('scarytranscludetoolong');
2637 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2638 $this->mIWTransData
[] = $text;
2639 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2642 function fetchScaryTemplateMaybeFromCache($url) {
2643 $dbr =& wfGetDB(DB_SLAVE
);
2644 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2645 array('tc_url' => $url));
2647 $time = $obj->tc_time
;
2648 $text = $obj->tc_contents
;
2649 if ($time && $time < (time() +
(60*60))) {
2654 $text = wfGetHTTP($url . '?action=render');
2656 return wfMsg('scarytranscludefailed', $url);
2658 $dbw =& wfGetDB(DB_MASTER
);
2659 $dbw->replace('transcache', array(), array(
2661 'tc_time' => time(),
2662 'tc_contents' => $text));
2668 * Triple brace replacement -- used for template arguments
2671 function argSubstitution( $matches ) {
2672 $arg = trim( $matches['title'] );
2673 $text = $matches['text'];
2674 $inputArgs = end( $this->mArgStack
);
2676 if ( array_key_exists( $arg, $inputArgs ) ) {
2677 $text = $inputArgs[$arg];
2678 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2679 $text = $matches['parts'][0];
2686 * Returns true if the function is allowed to include this entity
2689 function incrementIncludeCount( $dbk ) {
2690 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2691 $this->mIncludeCount
[$dbk] = 0;
2693 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2701 * This function accomplishes several tasks:
2702 * 1) Auto-number headings if that option is enabled
2703 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2704 * 3) Add a Table of contents on the top for users who have enabled the option
2705 * 4) Auto-anchor headings
2707 * It loops through all headlines, collects the necessary data, then splits up the
2708 * string and re-inserts the newly formatted headlines.
2710 * @param string $text
2711 * @param boolean $isMain
2714 function formatHeadings( $text, $isMain=true ) {
2715 global $wgMaxTocLevel, $wgContLang;
2717 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2719 $forceTocHere = false;
2720 if( !$this->mTitle
->userCanEdit() ) {
2723 $showEditLink = $this->mOptions
->getEditSection();
2726 # Inhibit editsection links if requested in the page
2727 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2728 if( $esw->matchAndRemove( $text ) ) {
2731 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2733 $mw =& MagicWord
::get( MAG_NOTOC
);
2734 if( $mw->matchAndRemove( $text ) ) {
2738 # Get all headlines for numbering them and adding funky stuff like [edit]
2739 # links - this is for later, but we need the number of headlines right now
2740 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2742 # if there are fewer than 4 headlines in the article, do not show TOC
2743 if( $numMatches < 4 ) {
2747 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2748 # override above conditions and always show TOC at that place
2750 $mw =& MagicWord
::get( MAG_TOC
);
2751 if($mw->match( $text ) ) {
2753 $forceTocHere = true;
2755 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2756 # override above conditions and always show TOC above first header
2757 $mw =& MagicWord
::get( MAG_FORCETOC
);
2758 if ($mw->matchAndRemove( $text ) ) {
2763 # Never ever show TOC if no headers
2764 if( $numMatches < 1 ) {
2768 # We need this to perform operations on the HTML
2769 $sk =& $this->mOptions
->getSkin();
2773 $sectionCount = 0; # headlineCount excluding template sections
2775 # Ugh .. the TOC should have neat indentation levels which can be
2776 # passed to the skin functions. These are determined here
2780 $sublevelCount = array();
2781 $levelCount = array();
2788 foreach( $matches[3] as $headline ) {
2790 $templatetitle = '';
2791 $templatesection = 0;
2794 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2796 $templatetitle = base64_decode($mat[1]);
2797 $templatesection = 1 +
(int)base64_decode($mat[2]);
2798 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2802 $prevlevel = $level;
2803 $prevtoclevel = $toclevel;
2805 $level = $matches[1][$headlineCount];
2807 if( $doNumberHeadings ||
$doShowToc ) {
2809 if ( $level > $prevlevel ) {
2810 # Increase TOC level
2812 $sublevelCount[$toclevel] = 0;
2813 $toc .= $sk->tocIndent();
2815 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2816 # Decrease TOC level, find level to jump to
2818 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2819 # Can only go down to level 1
2822 for ($i = $toclevel; $i > 0; $i--) {
2823 if ( $levelCount[$i] == $level ) {
2824 # Found last matching level
2828 elseif ( $levelCount[$i] < $level ) {
2829 # Found first matching level below current level
2836 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2839 # No change in level, end TOC line
2840 $toc .= $sk->tocLineEnd();
2843 $levelCount[$toclevel] = $level;
2845 # count number of headlines for each level
2846 @$sublevelCount[$toclevel]++
;
2848 for( $i = 1; $i <= $toclevel; $i++
) {
2849 if( !empty( $sublevelCount[$i] ) ) {
2853 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2859 # The canonized header is a version of the header text safe to use for links
2860 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2861 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2862 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2864 # Remove link placeholders by the link text.
2865 # <!--LINK number-->
2867 # link text with suffix
2868 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2869 "\$this->mLinkHolders['texts'][\$1]",
2870 $canonized_headline );
2871 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2872 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2873 $canonized_headline );
2876 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2877 $tocline = trim( $canonized_headline );
2878 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2879 $replacearray = array(
2883 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2884 $refers[$headlineCount] = $canonized_headline;
2886 # count how many in assoc. array so we can track dupes in anchors
2887 @$refers[$canonized_headline]++
;
2888 $refcount[$headlineCount]=$refers[$canonized_headline];
2890 # Don't number the heading if it is the only one (looks silly)
2891 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2892 # the two are different if the line contains a link
2893 $headline=$numbering . ' ' . $headline;
2896 # Create the anchor for linking from the TOC to the section
2897 $anchor = $canonized_headline;
2898 if($refcount[$headlineCount] > 1 ) {
2899 $anchor .= '_' . $refcount[$headlineCount];
2901 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2902 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2904 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2905 if ( empty( $head[$headlineCount] ) ) {
2906 $head[$headlineCount] = '';
2909 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2911 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2914 # give headline the correct <h#> tag
2915 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2923 $toc .= $sk->tocUnindent( $toclevel - 1 );
2924 $toc = $sk->tocList( $toc );
2927 # split up and insert constructed headlines
2929 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2932 foreach( $blocks as $block ) {
2933 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2934 # This is the [edit] link that appears for the top block of text when
2935 # section editing is enabled
2937 # Disabled because it broke block formatting
2938 # For example, a bullet point in the top line
2939 # $full .= $sk->editSectionLink(0);
2942 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2943 # Top anchor now in skin
2947 if( !empty( $head[$i] ) ) {
2953 $mw =& MagicWord
::get( MAG_TOC
);
2954 return $mw->replace( $toc, $full );
2961 * Return an HTML link for the "ISBN 123456" text
2964 function magicISBN( $text ) {
2965 $fname = 'Parser::magicISBN';
2966 wfProfileIn( $fname );
2968 $a = split( 'ISBN ', ' '.$text );
2969 if ( count ( $a ) < 2 ) {
2970 wfProfileOut( $fname );
2973 $text = substr( array_shift( $a ), 1);
2974 $valid = '0123456789-Xx';
2976 foreach ( $a as $x ) {
2977 $isbn = $blank = '' ;
2978 while ( ' ' == $x{0} ) {
2980 $x = substr( $x, 1 );
2982 if ( $x == '' ) { # blank isbn
2983 $text .= "ISBN $blank";
2986 while ( strstr( $valid, $x{0} ) != false ) {
2988 $x = substr( $x, 1 );
2990 $num = str_replace( '-', '', $isbn );
2991 $num = str_replace( ' ', '', $num );
2992 $num = str_replace( 'x', 'X', $num );
2995 $text .= "ISBN $blank$x";
2997 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2998 $text .= '<a href="' .
2999 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3000 "\" class=\"internal\">ISBN $isbn</a>";
3004 wfProfileOut( $fname );
3009 * Return an HTML link for the "RFC 1234" text
3012 * @param string $text Text to be processed
3013 * @param string $keyword Magic keyword to use (default RFC)
3014 * @param string $urlmsg Interface message to use (default rfcurl)
3017 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3019 $valid = '0123456789';
3022 $a = split( $keyword, ' '.$text );
3023 if ( count ( $a ) < 2 ) {
3026 $text = substr( array_shift( $a ), 1);
3028 /* Check if keyword is preceed by [[.
3029 * This test is made here cause of the array_shift above
3030 * that prevent the test to be done in the foreach.
3032 if ( substr( $text, -2 ) == '[[' ) {
3036 foreach ( $a as $x ) {
3037 /* token might be empty if we have RFC RFC 1234 */
3045 /** remove and save whitespaces in $blank */
3046 while ( $x{0} == ' ' ) {
3048 $x = substr( $x, 1 );
3051 /** remove and save the rfc number in $id */
3052 while ( strstr( $valid, $x{0} ) != false ) {
3054 $x = substr( $x, 1 );
3058 /* call back stripped spaces*/
3059 $text .= $keyword.$blank.$x;
3060 } elseif( $internal ) {
3062 $text .= $keyword.$id.$x;
3064 /* build the external link*/
3065 $url = wfMsg( $urlmsg, $id);
3066 $sk =& $this->mOptions
->getSkin();
3067 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3068 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3071 /* Check if the next RFC keyword is preceed by [[ */
3072 $internal = ( substr($x,-2) == '[[' );
3078 * Transform wiki markup when saving a page by doing \r\n -> \n
3079 * conversion, substitting signatures, {{subst:}} templates, etc.
3081 * @param string $text the text to transform
3082 * @param Title &$title the Title object for the current article
3083 * @param User &$user the User object describing the current user
3084 * @param ParserOptions $options parsing options
3085 * @param bool $clearState whether to clear the parser state first
3086 * @return string the altered wiki markup
3089 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3090 $this->mOptions
= $options;
3091 $this->mTitle
=& $title;
3092 $this->mOutputType
= OT_WIKI
;
3094 if ( $clearState ) {
3095 $this->clearState();
3098 $stripState = false;
3102 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3103 $text = $this->strip( $text, $stripState, true );
3104 $text = $this->pstPass2( $text, $user );
3105 $text = $this->unstrip( $text, $stripState );
3106 $text = $this->unstripNoWiki( $text, $stripState );
3111 * Pre-save transform helper function
3114 function pstPass2( $text, &$user ) {
3115 global $wgContLang, $wgLocaltimezone;
3117 # Variable replacement
3118 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3119 $text = $this->replaceVariables( $text );
3123 $sigText = $this->getUserSig( $user );
3125 /* Note: This is the timestamp saved as hardcoded wikitext to
3126 * the database, we use $wgContLang here in order to give
3127 * everyone the same signiture and use the default one rather
3128 * than the one selected in each users preferences.
3130 if ( isset( $wgLocaltimezone ) ) {
3131 $oldtz = getenv( 'TZ' );
3132 putenv( 'TZ='.$wgLocaltimezone );
3134 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3135 ' (' . date( 'T' ) . ')';
3136 if ( isset( $wgLocaltimezone ) ) {
3137 putenv( 'TZ='.$oldtz );
3140 $text = preg_replace( '/~~~~~/', $d, $text );
3141 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3142 $text = preg_replace( '/~~~/', $sigText, $text );
3144 # Context links: [[|name]] and [[name (context)|]]
3146 global $wgLegalTitleChars;
3147 $tc = "[$wgLegalTitleChars]";
3148 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3150 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3151 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3153 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3154 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3155 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3156 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3158 $t = $this->mTitle
->getText();
3159 if ( preg_match( $conpat, $t, $m ) ) {
3162 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3163 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3164 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3166 if ( '' == $context ) {
3167 $text = preg_replace( $p2, '[[\\1]]', $text );
3169 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3172 # Trim trailing whitespace
3173 # MAG_END (__END__) tag allows for trailing
3174 # whitespace to be deliberately included
3175 $text = rtrim( $text );
3176 $mw =& MagicWord
::get( MAG_END
);
3177 $mw->matchAndRemove( $text );
3183 * Fetch the user's signature text, if any, and normalize to
3184 * validated, ready-to-insert wikitext.
3190 function getUserSig( &$user ) {
3191 $name = $user->getName();
3192 $nick = trim( $user->getOption( 'nickname' ) );
3193 if ( '' == $nick ) {
3197 if( $user->getOption( 'fancysig' ) ) {
3198 // A wikitext signature.
3199 $valid = $this->validateSig( $nick );
3200 if( $valid === false ) {
3201 // Fall back to default sig
3203 wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
3209 // Plain text linking to the user's homepage
3211 $page = $user->getUserPage();
3213 $page->getPrefixedText() .
3215 wfEscapeWikIText( $nick ) .
3220 * We want to enforce two rules on wikitext sigs here:
3221 * 1) Expand any templates at save time (forced subst:)
3222 * 2) Check for unbalanced XML tags, and reject if so.
3224 * @param string $text
3225 * @return mixed An expanded string, or false if invalid.
3227 * @todo Run brace substitutions
3228 * @todo ?? Check for unbalanced '' and ''' quotes, etc
3230 function validateSig( $text ) {
3231 if( wfIsWellFormedXmlFragment( $text ) ) {
3239 * Set up some variables which are usually set up in parse()
3240 * so that an external function can call some class members with confidence
3243 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3244 $this->mTitle
=& $title;
3245 $this->mOptions
= $options;
3246 $this->mOutputType
= $outputType;
3247 if ( $clearState ) {
3248 $this->clearState();
3253 * Transform a MediaWiki message by replacing magic variables.
3255 * @param string $text the text to transform
3256 * @param ParserOptions $options options
3257 * @return string the text with variables substituted
3260 function transformMsg( $text, $options ) {
3262 static $executing = false;
3264 # Guard against infinite recursion
3270 $this->mTitle
= $wgTitle;
3271 $this->mOptions
= $options;
3272 $this->mOutputType
= OT_MSG
;
3273 $this->clearState();
3274 $text = $this->replaceVariables( $text );
3281 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3282 * Callback will be called with the text within
3283 * Transform and return the text within
3287 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3288 * @param mixed $callback The callback function (and object) to use for the tag
3290 * @return The old value of the mTagHooks array associated with the hook
3292 function setHook( $tag, $callback ) {
3293 $oldVal = @$this->mTagHooks
[$tag];
3294 $this->mTagHooks
[$tag] = $callback;
3300 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3301 * Placeholders created in Skin::makeLinkObj()
3302 * Returns an array of links found, indexed by PDBK:
3306 * $options is a bit field, RLH_FOR_UPDATE to select for update
3308 function replaceLinkHolders( &$text, $options = 0 ) {
3309 global $wgUser, $wgLinkCache;
3310 global $wgOutputReplace;
3312 $fname = 'Parser::replaceLinkHolders';
3313 wfProfileIn( $fname );
3317 $sk = $this->mOptions
->getSkin();
3319 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3320 wfProfileIn( $fname.'-check' );
3321 $dbr =& wfGetDB( DB_SLAVE
);
3322 $page = $dbr->tableName( 'page' );
3323 $threshold = $wgUser->getOption('stubthreshold');
3326 asort( $this->mLinkHolders
['namespaces'] );
3330 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3332 $title = $this->mLinkHolders
['titles'][$key];
3334 # Skip invalid entries.
3335 # Result will be ugly, but prevents crash.
3336 if ( is_null( $title ) ) {
3339 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3341 # Check if it's in the link cache already
3342 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3343 $colours[$pdbk] = 1;
3344 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3345 $colours[$pdbk] = 0;
3347 # Not in the link cache, add it to the query
3348 if ( !isset( $current ) ) {
3350 $query = "SELECT page_id, page_namespace, page_title";
3351 if ( $threshold > 0 ) {
3352 $query .= ', page_len, page_is_redirect';
3354 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3355 } elseif ( $current != $val ) {
3357 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3362 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3367 if ( $options & RLH_FOR_UPDATE
) {
3368 $query .= ' FOR UPDATE';
3371 $res = $dbr->query( $query, $fname );
3373 # Fetch data and form into an associative array
3374 # non-existent = broken
3377 while ( $s = $dbr->fetchObject($res) ) {
3378 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3379 $pdbk = $title->getPrefixedDBkey();
3380 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3382 if ( $threshold > 0 ) {
3383 $size = $s->page_len
;
3384 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3385 $colours[$pdbk] = 1;
3387 $colours[$pdbk] = 2;
3390 $colours[$pdbk] = 1;
3394 wfProfileOut( $fname.'-check' );
3396 # Construct search and replace arrays
3397 wfProfileIn( $fname.'-construct' );
3398 $wgOutputReplace = array();
3399 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3400 $pdbk = $pdbks[$key];
3401 $searchkey = "<!--LINK $key-->";
3402 $title = $this->mLinkHolders
['titles'][$key];
3403 if ( empty( $colours[$pdbk] ) ) {
3404 $wgLinkCache->addBadLinkObj( $title );
3405 $colours[$pdbk] = 0;
3406 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3407 $this->mLinkHolders
['texts'][$key],
3408 $this->mLinkHolders
['queries'][$key] );
3409 } elseif ( $colours[$pdbk] == 1 ) {
3410 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3411 $this->mLinkHolders
['texts'][$key],
3412 $this->mLinkHolders
['queries'][$key] );
3413 } elseif ( $colours[$pdbk] == 2 ) {
3414 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3415 $this->mLinkHolders
['texts'][$key],
3416 $this->mLinkHolders
['queries'][$key] );
3419 wfProfileOut( $fname.'-construct' );
3422 wfProfileIn( $fname.'-replace' );
3424 $text = preg_replace_callback(
3425 '/(<!--LINK .*?-->)/',
3426 "wfOutputReplaceMatches",
3429 wfProfileOut( $fname.'-replace' );
3432 # Now process interwiki link holders
3433 # This is quite a bit simpler than internal links
3434 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3435 wfProfileIn( $fname.'-interwiki' );
3436 # Make interwiki link HTML
3437 $wgOutputReplace = array();
3438 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3439 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3440 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3443 $text = preg_replace_callback(
3444 '/<!--IWLINK (.*?)-->/',
3445 "wfOutputReplaceMatches",
3447 wfProfileOut( $fname.'-interwiki' );
3450 wfProfileOut( $fname );
3455 * Replace <!--LINK--> link placeholders with plain text of links
3456 * (not HTML-formatted).
3457 * @param string $text
3460 function replaceLinkHoldersText( $text ) {
3461 global $wgUser, $wgLinkCache;
3462 global $wgOutputReplace;
3464 $fname = 'Parser::replaceLinkHoldersText';
3465 wfProfileIn( $fname );
3467 $text = preg_replace_callback(
3468 '/<!--(LINK|IWLINK) (.*?)-->/',
3469 array( &$this, 'replaceLinkHoldersTextCallback' ),
3472 wfProfileOut( $fname );
3477 * @param array $matches
3481 function replaceLinkHoldersTextCallback( $matches ) {
3482 $type = $matches[1];
3484 if( $type == 'LINK' ) {
3485 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3486 return $this->mLinkHolders
['texts'][$key];
3488 } elseif( $type == 'IWLINK' ) {
3489 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3490 return $this->mInterwikiLinkHolders
['texts'][$key];
3497 * Renders an image gallery from a text with one line per image.
3498 * text labels may be given by using |-style alternative text. E.g.
3499 * Image:one.jpg|The number "1"
3500 * Image:tree.jpg|A tree
3501 * given as text will return the HTML of a gallery with two images,
3502 * labeled 'The number "1"' and
3507 function renderImageGallery( $text ) {
3509 global $wgUser, $wgTitle;
3510 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3511 $localParser = new Parser();
3513 global $wgLinkCache;
3514 $ig = new ImageGallery();
3515 $ig->setShowBytes( false );
3516 $ig->setShowFilename( false );
3517 $lines = explode( "\n", $text );
3519 foreach ( $lines as $line ) {
3520 # match lines like these:
3521 # Image:someimage.jpg|This is some image
3522 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3524 if ( count( $matches ) == 0 ) {
3527 $nt = Title
::newFromURL( $matches[1] );
3528 if( is_null( $nt ) ) {
3529 # Bogus title. Ignore these so we don't bomb out later.
3532 if ( isset( $matches[3] ) ) {
3533 $label = $matches[3];
3538 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3539 $html = $html->mText
;
3541 $ig->add( new Image( $nt ), $html );
3542 $wgLinkCache->addImageLinkObj( $nt );
3544 return $ig->toHTML();
3548 * Parse image options text and use it to make an image
3550 function makeImage( &$nt, $options ) {
3551 global $wgContLang, $wgUseImageResize, $wgUser;
3555 # Check if the options text is of the form "options|alt text"
3557 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3558 # * left no resizing, just left align. label is used for alt= only
3559 # * right same, but right aligned
3560 # * none same, but not aligned
3561 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3562 # * center center the image
3563 # * framed Keep original image size, no magnify-button.
3565 $part = explode( '|', $options);
3567 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3568 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3569 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3570 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3571 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3572 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3573 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3574 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3577 $width = $height = $framed = $thumb = false;
3578 $manual_thumb = '' ;
3580 foreach( $part as $key => $val ) {
3581 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3583 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3584 # use manually specified thumbnail
3586 $manual_thumb = $match;
3587 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3588 # remember to set an alignment, don't render immediately
3590 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3591 # remember to set an alignment, don't render immediately
3593 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3594 # remember to set an alignment, don't render immediately
3596 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3597 # remember to set an alignment, don't render immediately
3599 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3600 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3601 # $match is the image width in pixels
3602 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3603 $width = intval( $m[1] );
3604 $height = intval( $m[2] );
3606 $width = intval($match);
3608 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3614 # Strip bad stuff out of the alt text
3615 $alt = $this->replaceLinkHoldersText( $caption );
3616 $alt = Sanitizer
::stripAllTags( $alt );
3618 # Linker does the rest
3619 $sk =& $this->mOptions
->getSkin();
3620 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3624 * Set a flag in the output object indicating that the content is dynamic and
3625 * shouldn't be cached.
3627 function disableCache() {
3628 $this->mOutput
->mCacheTime
= -1;
3632 * Callback from the Sanitizer for expanding items found in HTML attribute
3633 * values, so they can be safely tested and escaped.
3634 * @param string $text
3635 * @param array $args
3639 function attributeStripCallback( &$text, $args ) {
3640 $text = $this->replaceVariables( $text, $args );
3641 $text = $this->unstripForHTML( $text );
3645 function unstripForHTML( $text ) {
3646 $text = $this->unstrip( $text, $this->mStripState
);
3647 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3651 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3652 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3653 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3658 * @package MediaWiki
3662 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3663 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3664 var $mVersion; # Compatibility check
3665 var $mTitleText; # title text of the chosen language variant
3667 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3668 $containsOldMagic = false, $titletext = '' )
3670 $this->mText
= $text;
3671 $this->mLanguageLinks
= $languageLinks;
3672 $this->mCategoryLinks
= $categoryLinks;
3673 $this->mContainsOldMagic
= $containsOldMagic;
3674 $this->mCacheTime
= '';
3675 $this->mVersion
= MW_PARSER_VERSION
;
3676 $this->mTitleText
= $titletext;
3679 function getText() { return $this->mText
; }
3680 function getLanguageLinks() { return $this->mLanguageLinks
; }
3681 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3682 function getCacheTime() { return $this->mCacheTime
; }
3683 function getTitleText() { return $this->mTitleText
; }
3684 function containsOldMagic() { return $this->mContainsOldMagic
; }
3685 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3686 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3687 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3688 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3689 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3690 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3692 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3694 function merge( $other ) {
3695 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3696 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3697 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3701 * Return true if this cached output object predates the global or
3702 * per-article cache invalidation timestamps, or if it comes from
3703 * an incompatible older version.
3705 * @param string $touched the affected article's last touched timestamp
3709 function expired( $touched ) {
3710 global $wgCacheEpoch;
3711 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3712 $this->getCacheTime() < $touched ||
3713 $this->getCacheTime() <= $wgCacheEpoch ||
3714 !isset( $this->mVersion
) ||
3715 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3720 * Set options of the Parser
3722 * @package MediaWiki
3726 # All variables are private
3727 var $mUseTeX; # Use texvc to expand <math> tags
3728 var $mUseDynamicDates; # Use DateFormatter to format dates
3729 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3730 var $mAllowExternalImages; # Allow external images inline
3731 var $mAllowExternalImagesFrom; # If not, any exception?
3732 var $mSkin; # Reference to the preferred skin
3733 var $mDateFormat; # Date format index
3734 var $mEditSection; # Create "edit section" links
3735 var $mNumberHeadings; # Automatically number headings
3736 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3738 function getUseTeX() { return $this->mUseTeX
; }
3739 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3740 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3741 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3742 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3743 function &getSkin() { return $this->mSkin
; }
3744 function getDateFormat() { return $this->mDateFormat
; }
3745 function getEditSection() { return $this->mEditSection
; }
3746 function getNumberHeadings() { return $this->mNumberHeadings
; }
3747 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3750 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3751 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3752 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3753 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3754 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3755 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3756 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3757 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3758 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3760 function setSkin( &$x ) { $this->mSkin
=& $x; }
3762 function ParserOptions() {
3764 $this->initialiseFromUser( $wgUser );
3768 * Get parser options
3771 function newFromUser( &$user ) {
3772 $popts = new ParserOptions
;
3773 $popts->initialiseFromUser( $user );
3777 /** Get user options */
3778 function initialiseFromUser( &$userInput ) {
3779 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3780 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3781 $fname = 'ParserOptions::initialiseFromUser';
3782 wfProfileIn( $fname );
3783 if ( !$userInput ) {
3785 $user->setLoaded( true );
3787 $user =& $userInput;
3790 $this->mUseTeX
= $wgUseTeX;
3791 $this->mUseDynamicDates
= $wgUseDynamicDates;
3792 $this->mInterwikiMagic
= $wgInterwikiMagic;
3793 $this->mAllowExternalImages
= $wgAllowExternalImages;
3794 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3795 wfProfileIn( $fname.'-skin' );
3796 $this->mSkin
=& $user->getSkin();
3797 wfProfileOut( $fname.'-skin' );
3798 $this->mDateFormat
= $user->getOption( 'date' );
3799 $this->mEditSection
= true;
3800 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3801 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3802 wfProfileOut( $fname );
3807 * Callback function used by Parser::replaceLinkHolders()
3808 * to substitute link placeholders.
3810 function &wfOutputReplaceMatches( $matches ) {
3811 global $wgOutputReplace;
3812 return $wgOutputReplace[$matches[1]];
3816 * Return the total number of articles
3818 function wfNumberOfArticles() {
3819 global $wgNumberOfArticles;
3822 return $wgNumberOfArticles;
3826 * Return the number of files
3828 function wfNumberOfFiles() {
3829 $fname = 'Parser::wfNumberOfFiles';
3831 wfProfileIn( $fname );
3832 $dbr =& wfGetDB( DB_SLAVE
);
3833 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3834 wfProfileOut( $fname );
3840 * Get various statistics from the database
3843 function wfLoadSiteStats() {
3844 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3845 $fname = 'wfLoadSiteStats';
3847 if ( -1 != $wgNumberOfArticles ) return;
3848 $dbr =& wfGetDB( DB_SLAVE
);
3849 $s = $dbr->selectRow( 'site_stats',
3850 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3851 array( 'ss_row_id' => 1 ), $fname
3854 if ( $s === false ) {
3857 $wgTotalViews = $s->ss_total_views
;
3858 $wgTotalEdits = $s->ss_total_edits
;
3859 $wgNumberOfArticles = $s->ss_good_articles
;
3865 * Basicly replacing " > and < with HTML entities ( ", >, <)
3867 * @param string $in Text that might contain HTML tags
3868 * @return string Escaped string
3870 function wfEscapeHTMLTagsOnly( $in ) {
3872 array( '"', '>', '<' ),
3873 array( '"', '>', '<' ),