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 # prefix for escaping, used in two functions at least
47 define( 'UNIQ_PREFIX', 'NaodW29');
49 # Constants needed for external link processing
50 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone, $wgAllowSpecialInclusion*
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
113 var $mIWTransData = array();
123 $this->mTemplates
= array();
124 $this->mTemplatePath
= array();
125 $this->mTagHooks
= array();
134 function clearState() {
135 $this->mOutput
= new ParserOutput
;
136 $this->mAutonumber
= 0;
137 $this->mLastSection
= '';
138 $this->mDTopen
= false;
139 $this->mVariables
= false;
140 $this->mIncludeCount
= array();
141 $this->mStripState
= array();
142 $this->mArgStack
= array();
143 $this->mInPre
= false;
144 $this->mInterwikiLinkHolders
= array(
148 $this->mLinkHolders
= array(
149 'namespaces' => array(),
151 'queries' => array(),
155 $this->mRevisionId
= null;
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 $text = $this->internalParse( $text );
197 $text = $this->unstrip( $text, $this->mStripState
);
199 # Clean up special characters, only run once, next-to-last before doBlockLevels
201 # french spaces, last one Guillemet-left
202 # only if there is something before the space
203 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
204 # french spaces, Guillemet-right
205 '/(\\302\\253) /' => '\\1 ',
206 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
208 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
211 $text = $this->doBlockLevels( $text, $linestart );
213 $this->replaceLinkHolders( $text );
215 # the position of the convert() call should not be changed. it
216 # assumes that the links are all replaces and the only thing left
217 # is the <nowiki> mark.
218 $text = $wgContLang->convert($text);
219 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
221 $text = $this->unstripNoWiki( $text, $this->mStripState
);
223 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
225 $text = Sanitizer
::normalizeCharReferences( $text );
228 $text = Parser
::tidy($text);
231 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
233 $this->mOutput
->setText( $text );
234 wfProfileOut( $fname );
235 return $this->mOutput
;
239 * Get a random string
244 function getRandomString() {
245 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
249 * Replaces all occurrences of <$tag>content</$tag> in the text
250 * with a random marker and returns the new text. the output parameter
251 * $content will be an associative array filled with data on the form
252 * $unique_marker => content.
254 * If $content is already set, the additional entries will be appended
255 * If $tag is set to STRIP_COMMENTS, the function will extract
256 * <!-- HTML comments -->
261 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
262 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
277 if( $tag == STRIP_COMMENTS
) {
278 $start = '/<!--()()/';
281 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
282 $end = "/<\\/$tag\\s*>/i";
285 while ( '' != $text ) {
286 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
288 if( count( $p ) < 4 ) {
295 $marker = $rnd . sprintf('%08X', $n++
);
296 $stripped .= $marker;
298 $tags[$marker] = "<$tag$attributes$empty>";
299 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
301 if ( $empty === '/' ) {
302 // Empty element tag, <tag />
303 $content[$marker] = null;
306 $q = preg_split( $end, $inside, 2 );
307 $content[$marker] = $q[0];
308 if( count( $q ) < 2 ) {
309 # No end tag -- let it run out to the end of the text.
320 * Wrapper function for extractTagsAndParams
321 * for cases where $tags and $params isn't needed
322 * i.e. where tags will never have params, like <nowiki>
327 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
328 $dummy_tags = array();
329 $dummy_params = array();
331 return Parser
::extractTagsAndParams( $tag, $text, $content,
332 $dummy_tags, $dummy_params, $uniq_prefix );
336 * Strips and renders nowiki, pre, math, hiero
337 * If $render is set, performs necessary rendering operations on plugins
338 * Returns the text, and fills an array with data needed in unstrip()
339 * If the $state is already a valid strip state, it adds to the state
341 * @param bool $stripcomments when set, HTML comments <!-- like this -->
342 * will be stripped in addition to other tags. This is important
343 * for section editing, where these comments cause confusion when
344 * counting the sections in the wikisource
348 function strip( $text, &$state, $stripcomments = false ) {
349 $render = ($this->mOutputType
== OT_HTML
);
350 $html_content = array();
351 $nowiki_content = array();
352 $math_content = array();
353 $pre_content = array();
354 $comment_content = array();
355 $ext_content = array();
357 $ext_params = array();
358 $gallery_content = array();
360 # Replace any instances of the placeholders
361 $uniq_prefix = UNIQ_PREFIX
;
362 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
367 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
368 foreach( $html_content as $marker => $content ) {
370 # Raw and unchecked for validity.
371 $html_content[$marker] = $content;
373 $html_content[$marker] = '<html>'.$content.'</html>';
379 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
380 foreach( $nowiki_content as $marker => $content ) {
382 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
384 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
389 if( $this->mOptions
->getUseTeX() ) {
390 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
391 foreach( $math_content as $marker => $content ){
393 $math_content[$marker] = renderMath( $content );
395 $math_content[$marker] = '<math>'.$content.'</math>';
401 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
402 foreach( $pre_content as $marker => $content ){
404 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
406 $pre_content[$marker] = '<pre>'.$content.'</pre>';
411 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
412 foreach( $gallery_content as $marker => $content ) {
413 require_once( 'ImageGallery.php' );
415 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
417 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
423 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
424 foreach( $comment_content as $marker => $content ){
425 $comment_content[$marker] = '<!--'.$content.'-->';
430 foreach ( $this->mTagHooks
as $tag => $callback ) {
431 $ext_content[$tag] = array();
432 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
433 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
434 foreach( $ext_content[$tag] as $marker => $content ) {
435 $full_tag = $ext_tags[$tag][$marker];
436 $params = $ext_params[$tag][$marker];
438 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
440 if ( is_null( $content ) ) {
442 $ext_content[$tag][$marker] = $full_tag;
444 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
450 # Merge state with the pre-existing state, if there is one
452 $state['html'] = $state['html'] +
$html_content;
453 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
454 $state['math'] = $state['math'] +
$math_content;
455 $state['pre'] = $state['pre'] +
$pre_content;
456 $state['comment'] = $state['comment'] +
$comment_content;
457 $state['gallery'] = $state['gallery'] +
$gallery_content;
459 foreach( $ext_content as $tag => $array ) {
460 if ( array_key_exists( $tag, $state ) ) {
461 $state[$tag] = $state[$tag] +
$array;
466 'html' => $html_content,
467 'nowiki' => $nowiki_content,
468 'math' => $math_content,
469 'pre' => $pre_content,
470 'comment' => $comment_content,
471 'gallery' => $gallery_content,
478 * restores pre, math, and hiero removed by strip()
480 * always call unstripNoWiki() after this one
483 function unstrip( $text, &$state ) {
484 if ( !is_array( $state ) ) {
488 # Must expand in reverse order, otherwise nested tags will be corrupted
489 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
490 if( $tag != 'nowiki' && $tag != 'html' ) {
491 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
492 $text = str_replace( $uniq, $content, $text );
501 * always call this after unstrip() to preserve the order
505 function unstripNoWiki( $text, &$state ) {
506 if ( !is_array( $state ) ) {
510 # Must expand in reverse order, otherwise nested tags will be corrupted
511 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
512 $text = str_replace( key( $state['nowiki'] ), $content, $text );
517 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
518 $text = str_replace( key( $state['html'] ), $content, $text );
526 * Add an item to the strip state
527 * Returns the unique tag which must be inserted into the stripped text
528 * The tag will be replaced with the original text in unstrip()
532 function insertStripItem( $text, &$state ) {
533 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
540 'comment' => array(),
541 'gallery' => array(),
544 $state['item'][$rnd] = $text;
549 * Interface with html tidy, used if $wgUseTidy = true.
550 * If tidy isn't able to correct the markup, the original will be
551 * returned in all its glory with a warning comment appended.
553 * Either the external tidy program or the in-process tidy extension
554 * will be used depending on availability. Override the default
555 * $wgTidyInternal setting to disable the internal if it's not working.
557 * @param string $text Hideous HTML input
558 * @return string Corrected HTML output
562 function tidy( $text ) {
563 global $wgTidyInternal;
564 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
565 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
566 '<head><title>test</title></head><body>'.$text.'</body></html>';
567 if( $wgTidyInternal ) {
568 $correctedtext = Parser
::internalTidy( $wrappedtext );
570 $correctedtext = Parser
::externalTidy( $wrappedtext );
572 if( is_null( $correctedtext ) ) {
573 wfDebug( "Tidy error detected!\n" );
574 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
576 return $correctedtext;
580 * Spawn an external HTML tidy process and get corrected markup back from it.
585 function externalTidy( $text ) {
586 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
587 $fname = 'Parser::externalTidy';
588 wfProfileIn( $fname );
593 $descriptorspec = array(
594 0 => array('pipe', 'r'),
595 1 => array('pipe', 'w'),
596 2 => array('file', '/dev/null', 'a')
599 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
600 if (is_resource($process)) {
601 fwrite($pipes[0], $text);
603 while (!feof($pipes[1])) {
604 $cleansource .= fgets($pipes[1], 1024);
607 proc_close($process);
610 wfProfileOut( $fname );
612 if( $cleansource == '' && $text != '') {
613 // Some kind of error happened, so we couldn't get the corrected text.
614 // Just give up; we'll use the source text and append a warning.
622 * Use the HTML tidy PECL extension to use the tidy library in-process,
623 * saving the overhead of spawning a new process. Currently written to
624 * the PHP 4.3.x version of the extension, may not work on PHP 5.
626 * 'pear install tidy' should be able to compile the extension module.
631 function internalTidy( $text ) {
633 $fname = 'Parser::internalTidy';
634 wfProfileIn( $fname );
636 tidy_load_config( $wgTidyConf );
637 tidy_set_encoding( 'utf8' );
638 tidy_parse_string( $text );
640 if( tidy_get_status() == 2 ) {
641 // 2 is magic number for fatal error
642 // http://www.php.net/manual/en/function.tidy-get-status.php
645 $cleansource = tidy_get_output();
647 wfProfileOut( $fname );
652 * parse the wiki syntax used to render tables
656 function doTableStuff ( $t ) {
657 $fname = 'Parser::doTableStuff';
658 wfProfileIn( $fname );
660 $t = explode ( "\n" , $t ) ;
661 $td = array () ; # Is currently a td tag open?
662 $ltd = array () ; # Was it TD or TH?
663 $tr = array () ; # Is currently a tr tag open?
664 $ltr = array () ; # tr attributes
665 $indent_level = 0; # indent level of the table
666 foreach ( $t AS $k => $x )
669 $fc = substr ( $x , 0 , 1 ) ;
670 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
671 $indent_level = strlen( $matches[1] );
673 $attributes = $this->unstripForHTML( $matches[2] );
675 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
676 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
677 array_push ( $td , false ) ;
678 array_push ( $ltd , '' ) ;
679 array_push ( $tr , false ) ;
680 array_push ( $ltr , '' ) ;
682 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
683 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
684 $z = "</table>" . substr ( $x , 2);
685 $l = array_pop ( $ltd ) ;
686 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
687 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
689 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
691 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
692 $x = substr ( $x , 1 ) ;
693 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
695 $l = array_pop ( $ltd ) ;
696 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
697 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
700 array_push ( $tr , false ) ;
701 array_push ( $td , false ) ;
702 array_push ( $ltd , '' ) ;
703 $attributes = $this->unstripForHTML( $x );
704 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
706 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
708 if ( '|+' == substr ( $x , 0 , 2 ) ) {
710 $x = substr ( $x , 1 ) ;
712 $after = substr ( $x , 1 ) ;
713 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
714 $after = explode ( '||' , $after ) ;
717 # Loop through each table cell
718 foreach ( $after AS $theline )
723 $tra = array_pop ( $ltr ) ;
724 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
725 array_push ( $tr , true ) ;
726 array_push ( $ltr , '' ) ;
729 $l = array_pop ( $ltd ) ;
730 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
731 if ( $fc == '|' ) $l = 'td' ;
732 else if ( $fc == '!' ) $l = 'th' ;
733 else if ( $fc == '+' ) $l = 'caption' ;
735 array_push ( $ltd , $l ) ;
738 $y = explode ( '|' , $theline , 2 ) ;
739 # Note that a '|' inside an invalid link should not
740 # be mistaken as delimiting cell parameters
741 if ( strpos( $y[0], '[[' ) !== false ) {
742 $y = array ($theline);
744 if ( count ( $y ) == 1 )
745 $y = "{$z}<{$l}>{$y[0]}" ;
747 $attributes = $this->unstripForHTML( $y[0] );
748 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
751 array_push ( $td , true ) ;
756 # Closing open td, tr && table
757 while ( count ( $td ) > 0 )
759 if ( array_pop ( $td ) ) $t[] = '</td>' ;
760 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
764 $t = implode ( "\n" , $t ) ;
765 wfProfileOut( $fname );
770 * Helper function for parse() that transforms wiki markup into
771 * HTML. Only called for $mOutputType == OT_HTML.
775 function internalParse( $text ) {
779 $fname = 'Parser::internalParse';
780 wfProfileIn( $fname );
782 # Remove <noinclude> tags and <includeonly> sections
783 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
784 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
785 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
787 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
788 $text = $this->replaceVariables( $text, $args );
790 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
792 $text = $this->doHeadings( $text );
793 if($this->mOptions
->getUseDynamicDates()) {
794 $df =& DateFormatter
::getInstance();
795 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
797 $text = $this->doAllQuotes( $text );
798 $text = $this->replaceInternalLinks( $text );
799 $text = $this->replaceExternalLinks( $text );
801 # replaceInternalLinks may sometimes leave behind
802 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
803 $text = str_replace(UNIQ_PREFIX
."NOPARSE", "", $text);
805 $text = $this->doMagicLinks( $text );
806 $text = $this->doTableStuff( $text );
807 $text = $this->formatHeadings( $text, $isMain );
809 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
810 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
812 wfProfileOut( $fname );
816 function scarySubstitution($matches) {
817 # return "[[".$matches[0]."]]";
818 return $this->mIWTransData
[(int)$matches[0]];
822 * Replace special strings like "ISBN xxx" and "RFC xxx" with
823 * magic external links.
827 function &doMagicLinks( &$text ) {
828 $text = $this->magicISBN( $text );
829 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
830 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
835 * Parse headers and return html
839 function doHeadings( $text ) {
840 $fname = 'Parser::doHeadings';
841 wfProfileIn( $fname );
842 for ( $i = 6; $i >= 1; --$i ) {
843 $h = str_repeat( '=', $i );
844 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
845 "<h{$i}>\\1</h{$i}>\\2", $text );
847 wfProfileOut( $fname );
852 * Replace single quotes with HTML markup
854 * @return string the altered text
856 function doAllQuotes( $text ) {
857 $fname = 'Parser::doAllQuotes';
858 wfProfileIn( $fname );
860 $lines = explode( "\n", $text );
861 foreach ( $lines as $line ) {
862 $outtext .= $this->doQuotes ( $line ) . "\n";
864 $outtext = substr($outtext, 0,-1);
865 wfProfileOut( $fname );
870 * Helper function for doAllQuotes()
873 function doQuotes( $text ) {
874 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
875 if ( count( $arr ) == 1 )
879 # First, do some preliminary work. This may shift some apostrophes from
880 # being mark-up to being text. It also counts the number of occurrences
881 # of bold and italics mark-ups.
885 foreach ( $arr as $r )
887 if ( ( $i %
2 ) == 1 )
889 # If there are ever four apostrophes, assume the first is supposed to
890 # be text, and the remaining three constitute mark-up for bold text.
891 if ( strlen( $arr[$i] ) == 4 )
896 # If there are more than 5 apostrophes in a row, assume they're all
897 # text except for the last 5.
898 else if ( strlen( $arr[$i] ) > 5 )
900 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
903 # Count the number of occurrences of bold and italics mark-ups.
904 # We are not counting sequences of five apostrophes.
905 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
906 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
907 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
912 # If there is an odd number of both bold and italics, it is likely
913 # that one of the bold ones was meant to be an apostrophe followed
914 # by italics. Which one we cannot know for certain, but it is more
915 # likely to be one that has a single-letter word before it.
916 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
919 $firstsingleletterword = -1;
920 $firstmultiletterword = -1;
922 foreach ( $arr as $r )
924 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
926 $x1 = substr ($arr[$i-1], -1);
927 $x2 = substr ($arr[$i-1], -2, 1);
929 if ($firstspace == -1) $firstspace = $i;
930 } else if ($x2 == ' ') {
931 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
933 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
939 # If there is a single-letter word, use it!
940 if ($firstsingleletterword > -1)
942 $arr [ $firstsingleletterword ] = "''";
943 $arr [ $firstsingleletterword-1 ] .= "'";
945 # If not, but there's a multi-letter word, use that one.
946 else if ($firstmultiletterword > -1)
948 $arr [ $firstmultiletterword ] = "''";
949 $arr [ $firstmultiletterword-1 ] .= "'";
951 # ... otherwise use the first one that has neither.
952 # (notice that it is possible for all three to be -1 if, for example,
953 # there is only one pentuple-apostrophe in the line)
954 else if ($firstspace > -1)
956 $arr [ $firstspace ] = "''";
957 $arr [ $firstspace-1 ] .= "'";
961 # Now let's actually convert our apostrophic mush to HTML!
970 if ($state == 'both')
977 if (strlen ($r) == 2)
980 { $output .= '</i>'; $state = ''; }
981 else if ($state == 'bi')
982 { $output .= '</i>'; $state = 'b'; }
983 else if ($state == 'ib')
984 { $output .= '</b></i><b>'; $state = 'b'; }
985 else if ($state == 'both')
986 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
987 else # $state can be 'b' or ''
988 { $output .= '<i>'; $state .= 'i'; }
990 else if (strlen ($r) == 3)
993 { $output .= '</b>'; $state = ''; }
994 else if ($state == 'bi')
995 { $output .= '</i></b><i>'; $state = 'i'; }
996 else if ($state == 'ib')
997 { $output .= '</b>'; $state = 'i'; }
998 else if ($state == 'both')
999 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1000 else # $state can be 'i' or ''
1001 { $output .= '<b>'; $state .= 'b'; }
1003 else if (strlen ($r) == 5)
1006 { $output .= '</b><i>'; $state = 'i'; }
1007 else if ($state == 'i')
1008 { $output .= '</i><b>'; $state = 'b'; }
1009 else if ($state == 'bi')
1010 { $output .= '</i></b>'; $state = ''; }
1011 else if ($state == 'ib')
1012 { $output .= '</b></i>'; $state = ''; }
1013 else if ($state == 'both')
1014 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1015 else # ($state == '')
1016 { $buffer = ''; $state = 'both'; }
1021 # Now close all remaining tags. Notice that the order is important.
1022 if ($state == 'b' ||
$state == 'ib')
1024 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1028 if ($state == 'both')
1029 $output .= '<b><i>'.$buffer.'</i></b>';
1035 * Replace external links
1037 * Note: this is all very hackish and the order of execution matters a lot.
1038 * Make sure to run maintenance/parserTests.php if you change this code.
1042 function replaceExternalLinks( $text ) {
1044 $fname = 'Parser::replaceExternalLinks';
1045 wfProfileIn( $fname );
1047 $sk =& $this->mOptions
->getSkin();
1049 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1051 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1054 while ( $i<count( $bits ) ) {
1056 $protocol = $bits[$i++
];
1057 $text = $bits[$i++
];
1058 $trail = $bits[$i++
];
1060 # The characters '<' and '>' (which were escaped by
1061 # removeHTMLtags()) should not be included in
1062 # URLs, per RFC 2396.
1063 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1064 $text = substr($url, $m2[0][1]) . ' ' . $text;
1065 $url = substr($url, 0, $m2[0][1]);
1068 # If the link text is an image URL, replace it with an <img> tag
1069 # This happened by accident in the original parser, but some people used it extensively
1070 $img = $this->maybeMakeExternalImage( $text );
1071 if ( $img !== false ) {
1077 # Set linktype for CSS - if URL==text, link is essentially free
1078 $linktype = ($text == $url) ?
'free' : 'text';
1080 # No link text, e.g. [http://domain.tld/some.link]
1081 if ( $text == '' ) {
1082 # Autonumber if allowed
1083 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1084 $text = '[' . ++
$this->mAutonumber
. ']';
1085 $linktype = 'autonumber';
1087 # Otherwise just use the URL
1088 $text = htmlspecialchars( $url );
1092 # Have link text, e.g. [http://domain.tld/some.link text]s
1094 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1097 $text = $wgContLang->markNoConversion($text);
1099 # Replace & from obsolete syntax with &.
1100 # All HTML entities will be escaped by makeExternalLink()
1101 # or maybeMakeExternalImage()
1102 $url = str_replace( '&', '&', $url );
1104 # Process the trail (i.e. everything after this link up until start of the next link),
1105 # replacing any non-bracketed links
1106 $trail = $this->replaceFreeExternalLinks( $trail );
1109 # Use the encoded URL
1110 # This means that users can paste URLs directly into the text
1111 # Funny characters like ö aren't valid in URLs anyway
1112 # This was changed in August 2004
1113 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1116 wfProfileOut( $fname );
1121 * Replace anything that looks like a URL with a link
1124 function replaceFreeExternalLinks( $text ) {
1126 $fname = 'Parser::replaceFreeExternalLinks';
1127 wfProfileIn( $fname );
1129 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1130 $s = array_shift( $bits );
1133 $sk =& $this->mOptions
->getSkin();
1135 while ( $i < count( $bits ) ){
1136 $protocol = $bits[$i++
];
1137 $remainder = $bits[$i++
];
1139 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1140 # Found some characters after the protocol that look promising
1141 $url = $protocol . $m[1];
1144 # The characters '<' and '>' (which were escaped by
1145 # removeHTMLtags()) should not be included in
1146 # URLs, per RFC 2396.
1147 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1148 $trail = substr($url, $m2[0][1]) . $trail;
1149 $url = substr($url, 0, $m2[0][1]);
1152 # Move trailing punctuation to $trail
1154 # If there is no left bracket, then consider right brackets fair game too
1155 if ( strpos( $url, '(' ) === false ) {
1159 $numSepChars = strspn( strrev( $url ), $sep );
1160 if ( $numSepChars ) {
1161 $trail = substr( $url, -$numSepChars ) . $trail;
1162 $url = substr( $url, 0, -$numSepChars );
1165 # Replace & from obsolete syntax with &.
1166 # All HTML entities will be escaped by makeExternalLink()
1167 # or maybeMakeExternalImage()
1168 $url = str_replace( '&', '&', $url );
1170 # Is this an external image?
1171 $text = $this->maybeMakeExternalImage( $url );
1172 if ( $text === false ) {
1173 # Not an image, make a link
1174 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1176 $s .= $text . $trail;
1178 $s .= $protocol . $remainder;
1181 wfProfileOut( $fname );
1186 * make an image if it's allowed, either through the global
1187 * option or through the exception
1190 function maybeMakeExternalImage( $url ) {
1191 $sk =& $this->mOptions
->getSkin();
1192 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1193 $imagesexception = !empty($imagesfrom);
1195 if ( $this->mOptions
->getAllowExternalImages()
1196 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1197 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1199 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1206 * Process [[ ]] wikilinks
1210 function replaceInternalLinks( $s ) {
1211 global $wgContLang, $wgLinkCache;
1212 static $fname = 'Parser::replaceInternalLinks' ;
1214 wfProfileIn( $fname );
1216 wfProfileIn( $fname.'-setup' );
1218 # the % is needed to support urlencoded titles as well
1219 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1221 $sk =& $this->mOptions
->getSkin();
1223 #split the entire text string on occurences of [[
1224 $a = explode( '[[', ' ' . $s );
1225 #get the first element (all text up to first [[), and remove the space we added
1226 $s = array_shift( $a );
1227 $s = substr( $s, 1 );
1229 # Match a link having the form [[namespace:link|alternate]]trail
1231 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1232 # Match cases where there is no "]]", which might still be images
1233 static $e1_img = FALSE;
1234 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1235 # Match the end of a line for a word that's not followed by whitespace,
1236 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1237 $e2 = wfMsgForContent( 'linkprefix' );
1239 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1241 if( is_null( $this->mTitle
) ) {
1242 wfDebugDieBacktrace( 'nooo' );
1244 $nottalk = !$this->mTitle
->isTalkPage();
1246 if ( $useLinkPrefixExtension ) {
1247 if ( preg_match( $e2, $s, $m ) ) {
1248 $first_prefix = $m[2];
1250 $first_prefix = false;
1256 $selflink = $this->mTitle
->getPrefixedText();
1257 wfProfileOut( $fname.'-setup' );
1259 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1260 $useSubpages = $this->areSubpagesAllowed();
1262 # Loop for each link
1263 for ($k = 0; isset( $a[$k] ); $k++
) {
1265 if ( $useLinkPrefixExtension ) {
1266 wfProfileIn( $fname.'-prefixhandling' );
1267 if ( preg_match( $e2, $s, $m ) ) {
1275 $prefix = $first_prefix;
1276 $first_prefix = false;
1278 wfProfileOut( $fname.'-prefixhandling' );
1281 $might_be_img = false;
1283 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1285 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1286 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1287 # the real problem is with the $e1 regex
1290 # Still some problems for cases where the ] is meant to be outside punctuation,
1291 # and no image is in sight. See bug 2095.
1293 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1294 $text .= ']'; # so that replaceExternalLinks($text) works later
1297 # fix up urlencoded title texts
1298 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1300 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1301 $might_be_img = true;
1303 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1305 } else { # Invalid form; output directly
1306 $s .= $prefix . '[[' . $line ;
1310 # Don't allow internal links to pages containing
1311 # PROTO: where PROTO is a valid URL protocol; these
1312 # should be external links.
1313 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1314 $s .= $prefix . '[[' . $line ;
1318 # Make subpage if necessary
1319 if( $useSubpages ) {
1320 $link = $this->maybeDoSubpageLink( $m[1], $text );
1325 $noforce = (substr($m[1], 0, 1) != ':');
1327 # Strip off leading ':'
1328 $link = substr($link, 1);
1331 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1333 $s .= $prefix . '[[' . $line;
1337 #check other language variants of the link
1338 #if the article does not exist
1339 if( $checkVariantLink
1340 && $nt->getArticleID() == 0 ) {
1341 $wgContLang->findVariantLink($link, $nt);
1344 $ns = $nt->getNamespace();
1345 $iw = $nt->getInterWiki();
1347 if ($might_be_img) { # if this is actually an invalid link
1348 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1350 while (isset ($a[$k+
1]) ) {
1351 #look at the next 'line' to see if we can close it there
1352 $spliced = array_splice( $a, $k +
1, 1 );
1353 $next_line = array_shift( $spliced );
1354 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1355 # the first ]] closes the inner link, the second the image
1357 $text .= '[[' . $m[1];
1360 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1361 #if there's exactly one ]] that's fine, we'll keep looking
1362 $text .= '[[' . $m[0];
1364 #if $next_line is invalid too, we need look no further
1365 $text .= '[[' . $next_line;
1370 # we couldn't find the end of this imageLink, so output it raw
1371 #but don't ignore what might be perfectly normal links in the text we've examined
1372 $text = $this->replaceInternalLinks($text);
1373 $s .= $prefix . '[[' . $link . '|' . $text;
1374 # note: no $trail, because without an end, there *is* no trail
1377 } else { #it's not an image, so output it raw
1378 $s .= $prefix . '[[' . $link . '|' . $text;
1379 # note: no $trail, because without an end, there *is* no trail
1384 $wasblank = ( '' == $text );
1385 if( $wasblank ) $text = $link;
1388 # Link not escaped by : , create the various objects
1392 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1393 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1394 $s = rtrim($s . "\n");
1395 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1399 if ( $ns == NS_IMAGE
) {
1400 wfProfileIn( "$fname-image" );
1401 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1402 # recursively parse links inside the image caption
1403 # actually, this will parse them in any other parameters, too,
1404 # but it might be hard to fix that, and it doesn't matter ATM
1405 $text = $this->replaceExternalLinks($text);
1406 $text = $this->replaceInternalLinks($text);
1408 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1409 $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1410 $wgLinkCache->addImageLinkObj( $nt );
1412 wfProfileOut( "$fname-image" );
1415 wfProfileOut( "$fname-image" );
1419 if ( $ns == NS_CATEGORY
) {
1420 wfProfileIn( "$fname-category" );
1421 $t = $wgContLang->convertHtml( $nt->getText() );
1422 $s = rtrim($s . "\n"); # bug 87
1424 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1425 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1426 $wgLinkCache->resume();
1429 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1430 $sortkey = $this->mTitle
->getText();
1432 $sortkey = $this->mTitle
->getPrefixedText();
1437 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1438 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1439 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1440 $this->mOutput
->addCategoryLink( $t );
1443 * Strip the whitespace Category links produce, see bug 87
1444 * @todo We might want to use trim($tmp, "\n") here.
1446 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1448 wfProfileOut( "$fname-category" );
1453 if( ( $nt->getPrefixedText() === $selflink ) &&
1454 ( $nt->getFragment() === '' ) ) {
1455 # Self-links are handled specially; generally de-link and change to bold.
1456 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1460 # Special and Media are pseudo-namespaces; no pages actually exist in them
1461 if( $ns == NS_MEDIA
) {
1462 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1463 $wgLinkCache->addImageLinkObj( $nt );
1465 } elseif( $ns == NS_SPECIAL
) {
1466 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1468 } elseif( $ns == NS_IMAGE
) {
1469 $img = Image
::newFromTitle( $nt );
1470 if( $img->exists() ) {
1471 // Force a blue link if the file exists; may be a remote
1472 // upload on the shared repository, and we want to see its
1473 // auto-generated page.
1474 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1478 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1480 wfProfileOut( $fname );
1485 * Make a link placeholder. The text returned can be later resolved to a real link with
1486 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1487 * parsing of interwiki links, and secondly to allow all extistence checks and
1488 * article length checks (for stub links) to be bundled into a single query.
1491 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1492 if ( ! is_object($nt) ) {
1494 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1496 # Separate the link trail from the rest of the link
1497 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1499 if ( $nt->isExternal() ) {
1500 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1501 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1502 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1504 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1505 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1506 $this->mLinkHolders
['queries'][] = $query;
1507 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1508 $this->mLinkHolders
['titles'][] = $nt;
1510 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1517 * Return true if subpage links should be expanded on this page.
1520 function areSubpagesAllowed() {
1521 # Some namespaces don't allow subpages
1522 global $wgNamespacesWithSubpages;
1523 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1527 * Handle link to subpage if necessary
1528 * @param string $target the source of the link
1529 * @param string &$text the link text, modified as necessary
1530 * @return string the full name of the link
1533 function maybeDoSubpageLink($target, &$text) {
1536 # :Foobar -- override special treatment of prefix (images, language links)
1537 # /Foobar -- convert to CurrentPage/Foobar
1538 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1539 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1540 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1542 $fname = 'Parser::maybeDoSubpageLink';
1543 wfProfileIn( $fname );
1544 $ret = $target; # default return value is no change
1546 # Some namespaces don't allow subpages,
1547 # so only perform processing if subpages are allowed
1548 if( $this->areSubpagesAllowed() ) {
1549 # Look at the first character
1550 if( $target != '' && $target{0} == '/' ) {
1551 # / at end means we don't want the slash to be shown
1552 if( substr( $target, -1, 1 ) == '/' ) {
1553 $target = substr( $target, 1, -1 );
1556 $noslash = substr( $target, 1 );
1559 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1560 if( '' === $text ) {
1562 } # this might be changed for ugliness reasons
1564 # check for .. subpage backlinks
1566 $nodotdot = $target;
1567 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1569 $nodotdot = substr( $nodotdot, 3 );
1571 if($dotdotcount > 0) {
1572 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1573 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1574 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1575 # / at the end means don't show full path
1576 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1577 $nodotdot = substr( $nodotdot, 0, -1 );
1578 if( '' === $text ) {
1582 $nodotdot = trim( $nodotdot );
1583 if( $nodotdot != '' ) {
1584 $ret .= '/' . $nodotdot;
1591 wfProfileOut( $fname );
1596 * Used by doBlockLevels()
1599 /* private */ function closeParagraph() {
1601 if ( '' != $this->mLastSection
) {
1602 $result = '</' . $this->mLastSection
. ">\n";
1604 $this->mInPre
= false;
1605 $this->mLastSection
= '';
1608 # getCommon() returns the length of the longest common substring
1609 # of both arguments, starting at the beginning of both.
1611 /* private */ function getCommon( $st1, $st2 ) {
1612 $fl = strlen( $st1 );
1613 $shorter = strlen( $st2 );
1614 if ( $fl < $shorter ) { $shorter = $fl; }
1616 for ( $i = 0; $i < $shorter; ++
$i ) {
1617 if ( $st1{$i} != $st2{$i} ) { break; }
1621 # These next three functions open, continue, and close the list
1622 # element appropriate to the prefix character passed into them.
1624 /* private */ function openList( $char ) {
1625 $result = $this->closeParagraph();
1627 if ( '*' == $char ) { $result .= '<ul><li>'; }
1628 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1629 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1630 else if ( ';' == $char ) {
1631 $result .= '<dl><dt>';
1632 $this->mDTopen
= true;
1634 else { $result = '<!-- ERR 1 -->'; }
1639 /* private */ function nextItem( $char ) {
1640 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1641 else if ( ':' == $char ||
';' == $char ) {
1643 if ( $this->mDTopen
) { $close = '</dt>'; }
1644 if ( ';' == $char ) {
1645 $this->mDTopen
= true;
1646 return $close . '<dt>';
1648 $this->mDTopen
= false;
1649 return $close . '<dd>';
1652 return '<!-- ERR 2 -->';
1655 /* private */ function closeList( $char ) {
1656 if ( '*' == $char ) { $text = '</li></ul>'; }
1657 else if ( '#' == $char ) { $text = '</li></ol>'; }
1658 else if ( ':' == $char ) {
1659 if ( $this->mDTopen
) {
1660 $this->mDTopen
= false;
1661 $text = '</dt></dl>';
1663 $text = '</dd></dl>';
1666 else { return '<!-- ERR 3 -->'; }
1672 * Make lists from lines starting with ':', '*', '#', etc.
1675 * @return string the lists rendered as HTML
1677 function doBlockLevels( $text, $linestart ) {
1678 $fname = 'Parser::doBlockLevels';
1679 wfProfileIn( $fname );
1681 # Parsing through the text line by line. The main thing
1682 # happening here is handling of block-level elements p, pre,
1683 # and making lists from lines starting with * # : etc.
1685 $textLines = explode( "\n", $text );
1687 $lastPrefix = $output = '';
1688 $this->mDTopen
= $inBlockElem = false;
1690 $paragraphStack = false;
1692 if ( !$linestart ) {
1693 $output .= array_shift( $textLines );
1695 foreach ( $textLines as $oLine ) {
1696 $lastPrefixLength = strlen( $lastPrefix );
1697 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1698 $preOpenMatch = preg_match('/<pre/i', $oLine );
1699 if ( !$this->mInPre
) {
1700 # Multiple prefixes may abut each other for nested lists.
1701 $prefixLength = strspn( $oLine, '*#:;' );
1702 $pref = substr( $oLine, 0, $prefixLength );
1705 $pref2 = str_replace( ';', ':', $pref );
1706 $t = substr( $oLine, $prefixLength );
1707 $this->mInPre
= !empty($preOpenMatch);
1709 # Don't interpret any other prefixes in preformatted text
1711 $pref = $pref2 = '';
1716 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1717 # Same as the last item, so no need to deal with nesting or opening stuff
1718 $output .= $this->nextItem( substr( $pref, -1 ) );
1719 $paragraphStack = false;
1721 if ( substr( $pref, -1 ) == ';') {
1722 # The one nasty exception: definition lists work like this:
1723 # ; title : definition text
1724 # So we check for : in the remainder text to split up the
1725 # title and definition, without b0rking links.
1727 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1729 $output .= $term . $this->nextItem( ':' );
1732 } elseif( $prefixLength ||
$lastPrefixLength ) {
1733 # Either open or close a level...
1734 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1735 $paragraphStack = false;
1737 while( $commonPrefixLength < $lastPrefixLength ) {
1738 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1739 --$lastPrefixLength;
1741 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1742 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1744 while ( $prefixLength > $commonPrefixLength ) {
1745 $char = substr( $pref, $commonPrefixLength, 1 );
1746 $output .= $this->openList( $char );
1748 if ( ';' == $char ) {
1749 # FIXME: This is dupe of code above
1750 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1752 $output .= $term . $this->nextItem( ':' );
1755 ++
$commonPrefixLength;
1757 $lastPrefix = $pref2;
1759 if( 0 == $prefixLength ) {
1760 wfProfileIn( "$fname-paragraph" );
1761 # No prefix (not in list)--go to paragraph mode
1762 $uniq_prefix = UNIQ_PREFIX
;
1763 // XXX: use a stack for nestable elements like span, table and div
1764 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1765 $closematch = preg_match(
1766 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1767 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1768 if ( $openmatch or $closematch ) {
1769 $paragraphStack = false;
1770 $output .= $this->closeParagraph();
1771 if ( $preOpenMatch and !$preCloseMatch ) {
1772 $this->mInPre
= true;
1774 if ( $closematch ) {
1775 $inBlockElem = false;
1777 $inBlockElem = true;
1779 } else if ( !$inBlockElem && !$this->mInPre
) {
1780 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1782 if ($this->mLastSection
!= 'pre') {
1783 $paragraphStack = false;
1784 $output .= $this->closeParagraph().'<pre>';
1785 $this->mLastSection
= 'pre';
1787 $t = substr( $t, 1 );
1790 if ( '' == trim($t) ) {
1791 if ( $paragraphStack ) {
1792 $output .= $paragraphStack.'<br />';
1793 $paragraphStack = false;
1794 $this->mLastSection
= 'p';
1796 if ($this->mLastSection
!= 'p' ) {
1797 $output .= $this->closeParagraph();
1798 $this->mLastSection
= '';
1799 $paragraphStack = '<p>';
1801 $paragraphStack = '</p><p>';
1805 if ( $paragraphStack ) {
1806 $output .= $paragraphStack;
1807 $paragraphStack = false;
1808 $this->mLastSection
= 'p';
1809 } else if ($this->mLastSection
!= 'p') {
1810 $output .= $this->closeParagraph().'<p>';
1811 $this->mLastSection
= 'p';
1816 wfProfileOut( "$fname-paragraph" );
1818 // somewhere above we forget to get out of pre block (bug 785)
1819 if($preCloseMatch && $this->mInPre
) {
1820 $this->mInPre
= false;
1822 if ($paragraphStack === false) {
1826 while ( $prefixLength ) {
1827 $output .= $this->closeList( $pref2{$prefixLength-1} );
1830 if ( '' != $this->mLastSection
) {
1831 $output .= '</' . $this->mLastSection
. '>';
1832 $this->mLastSection
= '';
1835 wfProfileOut( $fname );
1840 * Split up a string on ':', ignoring any occurences inside
1841 * <a>..</a> or <span>...</span>
1842 * @param string $str the string to split
1843 * @param string &$before set to everything before the ':'
1844 * @param string &$after set to everything after the ':'
1845 * return string the position of the ':', or false if none found
1847 function findColonNoLinks($str, &$before, &$after) {
1848 # I wonder if we should make this count all tags, not just <a>
1849 # and <span>. That would prevent us from matching a ':' that
1850 # comes in the middle of italics other such formatting....
1852 $fname = 'Parser::findColonNoLinks';
1853 wfProfileIn( $fname );
1856 $colon = strpos($str, ':', $pos);
1858 if ($colon !== false) {
1859 $before = substr($str, 0, $colon);
1860 $after = substr($str, $colon +
1);
1862 # Skip any ':' within <a> or <span> pairs
1863 $a = substr_count($before, '<a');
1864 $s = substr_count($before, '<span');
1865 $ca = substr_count($before, '</a>');
1866 $cs = substr_count($before, '</span>');
1868 if ($a <= $ca and $s <= $cs) {
1869 # Tags are balanced before ':'; ok
1874 } while ($colon !== false);
1875 wfProfileOut( $fname );
1880 * Return value of a magic variable (like PAGENAME)
1884 function getVariableValue( $index ) {
1885 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1888 * Some of these require message or data lookups and can be
1889 * expensive to check many times.
1891 static $varCache = array();
1892 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1893 if ( isset( $varCache[$index] ) )
1894 return $varCache[$index];
1897 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1900 case MAG_CURRENTMONTH
:
1901 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1902 case MAG_CURRENTMONTHNAME
:
1903 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1904 case MAG_CURRENTMONTHNAMEGEN
:
1905 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1906 case MAG_CURRENTMONTHABBREV
:
1907 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1908 case MAG_CURRENTDAY
:
1909 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1911 return $this->mTitle
->getText();
1913 return $this->mTitle
->getPartialURL();
1914 case MAG_FULLPAGENAME
:
1915 return $this->mTitle
->getPrefixedText();
1916 case MAG_FULLPAGENAMEE
:
1917 return wfUrlencode( $this->mTitle
->getPrefixedText() );
1918 case MAG_REVISIONID
:
1919 return $this->mRevisionId
;
1921 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
1922 case MAG_NAMESPACEE
:
1923 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
1924 case MAG_CURRENTDAYNAME
:
1925 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
1926 case MAG_CURRENTYEAR
:
1927 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
1928 case MAG_CURRENTTIME
:
1929 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
1930 case MAG_CURRENTWEEK
:
1931 return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
1932 case MAG_CURRENTDOW
:
1933 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
1934 case MAG_NUMBEROFARTICLES
:
1935 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1936 case MAG_NUMBEROFFILES
:
1937 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1942 case MAG_SERVERNAME
:
1943 return $wgServerName;
1944 case MAG_SCRIPTPATH
:
1945 return $wgScriptPath;
1948 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
1956 * initialise the magic variables (like CURRENTMONTHNAME)
1960 function initialiseVariables() {
1961 $fname = 'Parser::initialiseVariables';
1962 wfProfileIn( $fname );
1963 global $wgVariableIDs;
1964 $this->mVariables
= array();
1965 foreach ( $wgVariableIDs as $id ) {
1966 $mw =& MagicWord
::get( $id );
1967 $mw->addToArray( $this->mVariables
, $id );
1969 wfProfileOut( $fname );
1973 * parse any parentheses in format ((title|part|part))
1974 * and call callbacks to get a replacement text for any found piece
1976 * @param string $text The text to parse
1977 * @param array $callbacks rules in form:
1978 * '{' => array( # opening parentheses
1979 * 'end' => '}', # closing parentheses
1980 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1981 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1986 function replace_callback ($text, $callbacks) {
1987 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1988 $lastOpeningBrace = -1; # last not closed parentheses
1990 for ($i = 0; $i < strlen($text); $i++
) {
1991 # check for any opening brace
1994 foreach ($callbacks as $key => $value) {
1995 $pos = strpos ($text, $key, $i);
1996 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2002 if ($lastOpeningBrace >= 0) {
2003 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2005 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2010 $pos = strpos ($text, '|', $i);
2012 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2023 # found openning brace, lets add it to parentheses stack
2024 if (null != $rule) {
2025 $piece = array('brace' => $text[$i],
2026 'braceEnd' => $rule['end'],
2031 # count openning brace characters
2032 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2037 $piece['startAt'] = $i+
1;
2038 $piece['partStart'] = $i+
1;
2040 # we need to add to stack only if openning brace count is enough for any given rule
2041 foreach ($rule['cb'] as $cnt => $fn) {
2042 if ($piece['count'] >= $cnt) {
2043 $lastOpeningBrace ++
;
2044 $openingBraceStack[$lastOpeningBrace] = $piece;
2051 else if ($lastOpeningBrace >= 0) {
2052 # first check if it is a closing brace
2053 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2054 # lets check if it is enough characters for closing brace
2056 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2059 # if there are more closing parentheses than opening ones, we parse less
2060 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2061 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2063 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2065 $matchingCallback = null;
2066 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2067 if ($count >= $cnt && $matchingCount < $cnt) {
2068 $matchingCount = $cnt;
2069 $matchingCallback = $fn;
2073 if ($matchingCount == 0) {
2078 # lets set a title or last part (if '|' was found)
2079 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2080 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2082 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2084 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2085 $pieceEnd = $i +
$matchingCount;
2087 if( is_callable( $matchingCallback ) ) {
2089 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2090 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2091 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2092 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2094 # finally we can call a user callback and replace piece of text
2095 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2096 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2097 $i = $pieceStart +
strlen($replaceWith) - 1;
2100 # null value for callback means that parentheses should be parsed, but not replaced
2101 $i +
= $matchingCount - 1;
2104 # reset last openning parentheses, but keep it in case there are unused characters
2105 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2106 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2107 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2110 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2111 $openingBraceStack[$lastOpeningBrace--] = null;
2113 if ($matchingCount < $piece['count']) {
2114 $piece['count'] -= $matchingCount;
2115 $piece['startAt'] -= $matchingCount;
2116 $piece['partStart'] = $piece['startAt'];
2117 # do we still qualify for any callback with remaining count?
2118 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2119 if ($piece['count'] >= $cnt) {
2120 $lastOpeningBrace ++
;
2121 $openingBraceStack[$lastOpeningBrace] = $piece;
2129 # lets set a title if it is a first separator, or next part otherwise
2130 if ($text[$i] == '|') {
2131 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2132 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2133 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2136 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2138 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2147 * Replace magic variables, templates, and template arguments
2148 * with the appropriate text. Templates are substituted recursively,
2149 * taking care to avoid infinite loops.
2151 * Note that the substitution depends on value of $mOutputType:
2152 * OT_WIKI: only {{subst:}} templates
2153 * OT_MSG: only magic variables
2154 * OT_HTML: all templates and magic variables
2156 * @param string $tex The text to transform
2157 * @param array $args Key-value pairs representing template parameters to substitute
2160 function replaceVariables( $text, $args = array() ) {
2161 # Prevent too big inclusions
2162 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2166 $fname = 'Parser::replaceVariables';
2167 wfProfileIn( $fname );
2169 # This function is called recursively. To keep track of arguments we need a stack:
2170 array_push( $this->mArgStack
, $args );
2172 $braceCallbacks = array();
2173 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2174 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2175 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2177 $callbacks = array();
2178 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2179 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2180 $text = $this->replace_callback ($text, $callbacks);
2182 array_pop( $this->mArgStack
);
2184 wfProfileOut( $fname );
2189 * Replace magic variables
2192 function variableSubstitution( $matches ) {
2193 $fname = 'parser::variableSubstitution';
2194 $varname = $matches[1];
2195 wfProfileIn( $fname );
2196 if ( !$this->mVariables
) {
2197 $this->initialiseVariables();
2200 if ( $this->mOutputType
== OT_WIKI
) {
2201 # Do only magic variables prefixed by SUBST
2202 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2203 if (!$mwSubst->matchStartAndRemove( $varname ))
2205 # Note that if we don't substitute the variable below,
2206 # we don't remove the {{subst:}} magic word, in case
2207 # it is a template rather than a magic variable.
2209 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2210 $id = $this->mVariables
[$varname];
2211 $text = $this->getVariableValue( $id );
2212 $this->mOutput
->mContainsOldMagic
= true;
2214 $text = $matches[0];
2216 wfProfileOut( $fname );
2220 # Split template arguments
2221 function getTemplateArgs( $argsString ) {
2222 if ( $argsString === '' ) {
2226 $args = explode( '|', substr( $argsString, 1 ) );
2228 # If any of the arguments contains a '[[' but no ']]', it needs to be
2229 # merged with the next arg because the '|' character between belongs
2230 # to the link syntax and not the template parameter syntax.
2231 $argc = count($args);
2233 for ( $i = 0; $i < $argc-1; $i++
) {
2234 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2235 $args[$i] .= '|'.$args[$i+
1];
2236 array_splice($args, $i+
1, 1);
2246 * Return the text of a template, after recursively
2247 * replacing any variables or templates within the template.
2249 * @param array $piece The parts of the template
2250 * $piece['text']: matched text
2251 * $piece['title']: the title, i.e. the part before the |
2252 * $piece['parts']: the parameter array
2253 * @return string the text of the template
2256 function braceSubstitution( $piece ) {
2257 global $wgLinkCache, $wgContLang;
2258 $fname = 'Parser::braceSubstitution';
2259 wfProfileIn( $fname );
2269 # $part1 is the bit before the first |, and must contain only title characters
2270 # $args is a list of arguments, starting from index 0, not including $part1
2272 $part1 = $piece['title'];
2273 # If the third subpattern matched anything, it will start with |
2275 if (null == $piece['parts']) {
2276 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2277 if ($replaceWith != $piece['text']) {
2278 $text = $replaceWith;
2284 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2285 $argc = count( $args );
2289 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2290 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2291 # One of two possibilities is true:
2292 # 1) Found SUBST but not in the PST phase
2293 # 2) Didn't find SUBST and in the PST phase
2294 # In either case, return without further processing
2295 $text = $piece['text'];
2301 # MSG, MSGNW and INT
2304 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2305 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2308 # Remove obsolete MSG:
2309 $mwMsg =& MagicWord
::get( MAG_MSG
);
2310 $mwMsg->matchStartAndRemove( $part1 );
2313 # Check if it is an internal message
2314 $mwInt =& MagicWord
::get( MAG_INT
);
2315 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2316 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2317 $text = $linestart . wfMsgReal( $part1, $args, true );
2325 # Check for NS: (namespace expansion)
2326 $mwNs = MagicWord
::get( MAG_NS
);
2327 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2328 if ( intval( $part1 ) ) {
2329 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2332 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2333 if ( !is_null( $index ) ) {
2334 $text = $linestart . $wgContLang->getNsText( $index );
2341 # LCFIRST, UCFIRST, LC and UC
2343 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2344 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2345 $lc =& MagicWord
::get( MAG_LC
);
2346 $uc =& MagicWord
::get( MAG_UC
);
2347 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2348 $text = $linestart . $wgContLang->lcfirst( $part1 );
2350 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2351 $text = $linestart . $wgContLang->ucfirst( $part1 );
2353 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2354 $text = $linestart . $wgContLang->lc( $part1 );
2356 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2357 $text = $linestart . $wgContLang->uc( $part1 );
2362 # LOCALURL and FULLURL
2364 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2365 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2366 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2367 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2370 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2371 $func = 'getLocalURL';
2372 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2373 $func = 'escapeLocalURL';
2374 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2375 $func = 'getFullURL';
2376 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2377 $func = 'escapeFullURL';
2382 if ( $func !== false ) {
2383 $title = Title
::newFromText( $part1 );
2384 if ( !is_null( $title ) ) {
2386 $text = $linestart . $title->$func( $args[0] );
2388 $text = $linestart . $title->$func();
2396 if ( !$found && $argc == 1 ) {
2397 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2398 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2399 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2405 if ( !$found && $argc >= 2 ) {
2406 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2407 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2408 if ($argc==2) {$args[2]=$args[1];}
2409 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2414 # Template table test
2416 # Did we encounter this template already? If yes, it is in the cache
2417 # and we need to check for loops.
2418 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2421 # Infinite loop test
2422 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2425 $text = $linestart .
2426 '{{' . $part1 . '}}' .
2427 '<!-- WARNING: template loop detected -->';
2428 wfDebug( "$fname: template loop broken at '$part1'\n" );
2430 # set $text to cached message.
2431 $text = $linestart . $this->mTemplates
[$part1];
2435 # Load from database
2436 $replaceHeadings = false;
2438 $lastPathLevel = $this->mTemplatePath
;
2441 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2442 if ($subpage !== '') {
2443 $ns = $this->mTitle
->getNamespace();
2445 $title = Title
::newFromText( $part1, $ns );
2448 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2449 if ($interwiki != '' && $title->isTrans()) {
2450 return $this->scarytransclude($title, $interwiki);
2454 if ( !is_null( $title ) && !$title->isExternal() ) {
2455 # Check for excessive inclusion
2456 $dbk = $title->getPrefixedDBkey();
2457 if ( $this->incrementIncludeCount( $dbk ) ) {
2458 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2459 # Capture special page output
2460 $text = SpecialPage
::capturePath( $title );
2461 if ( is_string( $text ) ) {
2465 $this->disableCache();
2468 $article = new Article( $title );
2469 $articleContent = $article->fetchContent(0, false);
2470 if ( $articleContent !== false ) {
2472 $text = $articleContent;
2473 $replaceHeadings = true;
2478 # If the title is valid but undisplayable, make a link to it
2479 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2480 $text = '[['.$title->getPrefixedText().']]';
2484 # Template cache array insertion
2486 $this->mTemplates
[$part1] = $text;
2487 $text = $linestart . $text;
2492 # Recursive parsing, escaping and link table handling
2493 # Only for HTML output
2494 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2495 $text = wfEscapeWikiText( $text );
2496 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2497 # Clean up argument array
2498 $assocArgs = array();
2500 foreach( $args as $arg ) {
2501 $eqpos = strpos( $arg, '=' );
2502 if ( $eqpos === false ) {
2503 $assocArgs[$index++
] = $arg;
2505 $name = trim( substr( $arg, 0, $eqpos ) );
2506 $value = trim( substr( $arg, $eqpos+
1 ) );
2507 if ( $value === false ) {
2510 if ( $name !== false ) {
2511 $assocArgs[$name] = $value;
2516 # Add a new element to the templace recursion path
2517 $this->mTemplatePath
[$part1] = 1;
2519 # If there are any <onlyinclude> tags, only include them
2520 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2521 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2523 foreach ($m[1] as $piece)
2526 # Remove <noinclude> sections and <includeonly> tags
2527 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2528 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2530 if( $this->mOutputType
== OT_HTML
) {
2531 # Strip <nowiki>, <pre>, etc.
2532 $text = $this->strip( $text, $this->mStripState
);
2533 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2535 $text = $this->replaceVariables( $text, $assocArgs );
2537 # Resume the link cache and register the inclusion as a link
2538 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2539 $wgLinkCache->addLinkObj( $title );
2542 # If the template begins with a table or block-level
2543 # element, it should be treated as beginning a new line.
2544 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2545 $text = "\n" . $text;
2548 # Prune lower levels off the recursion check path
2549 $this->mTemplatePath
= $lastPathLevel;
2552 wfProfileOut( $fname );
2553 return $piece['text'];
2556 # Replace raw HTML by a placeholder
2557 # Add a blank line preceding, to prevent it from mucking up
2558 # immediately preceding headings
2559 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2561 # replace ==section headers==
2562 # XXX this needs to go away once we have a better parser.
2563 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2564 if( !is_null( $title ) )
2565 $encodedname = base64_encode($title->getPrefixedDBkey());
2567 $encodedname = base64_encode("");
2568 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2569 PREG_SPLIT_DELIM_CAPTURE
);
2572 for( $i = 0; $i < count($m); $i +
= 2 ) {
2574 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2576 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2580 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2581 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2582 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2590 # Prune lower levels off the recursion check path
2591 $this->mTemplatePath
= $lastPathLevel;
2594 wfProfileOut( $fname );
2595 return $piece['text'];
2597 wfProfileOut( $fname );
2603 * Translude an interwiki link.
2605 function scarytransclude($title, $interwiki) {
2606 global $wgEnableScaryTranscluding;
2608 if (!$wgEnableScaryTranscluding)
2609 return wfMsg('scarytranscludedisabled');
2611 $articlename = "Template:" . $title->getDBkey();
2612 $url = str_replace('$1', urlencode($articlename), $interwiki);
2613 if (strlen($url) > 255)
2614 return wfMsg('scarytranscludetoolong');
2615 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2616 $this->mIWTransData
[] = $text;
2617 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2620 function fetchScaryTemplateMaybeFromCache($url) {
2621 $dbr =& wfGetDB(DB_SLAVE
);
2622 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2623 array('tc_url' => $url));
2625 $time = $obj->tc_time
;
2626 $text = $obj->tc_contents
;
2627 if ($time && $time < (time() +
(60*60))) {
2632 $text = wfGetHTTP($url . '?action=render');
2634 return wfMsg('scarytranscludefailed', $url);
2636 $dbw =& wfGetDB(DB_MASTER
);
2637 $dbw->replace('transcache', array(), array(
2639 'tc_time' => time(),
2640 'tc_contents' => $text));
2646 * Triple brace replacement -- used for template arguments
2649 function argSubstitution( $matches ) {
2650 $arg = trim( $matches['title'] );
2651 $text = $matches['text'];
2652 $inputArgs = end( $this->mArgStack
);
2654 if ( array_key_exists( $arg, $inputArgs ) ) {
2655 $text = $inputArgs[$arg];
2656 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2657 $text = $matches['parts'][0];
2664 * Returns true if the function is allowed to include this entity
2667 function incrementIncludeCount( $dbk ) {
2668 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2669 $this->mIncludeCount
[$dbk] = 0;
2671 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2679 * This function accomplishes several tasks:
2680 * 1) Auto-number headings if that option is enabled
2681 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2682 * 3) Add a Table of contents on the top for users who have enabled the option
2683 * 4) Auto-anchor headings
2685 * It loops through all headlines, collects the necessary data, then splits up the
2686 * string and re-inserts the newly formatted headlines.
2688 * @param string $text
2689 * @param boolean $isMain
2692 function formatHeadings( $text, $isMain=true ) {
2693 global $wgMaxTocLevel, $wgContLang;
2695 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2697 $forceTocHere = false;
2698 if( !$this->mTitle
->userCanEdit() ) {
2701 $showEditLink = $this->mOptions
->getEditSection();
2704 # Inhibit editsection links if requested in the page
2705 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2706 if( $esw->matchAndRemove( $text ) ) {
2709 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2711 $mw =& MagicWord
::get( MAG_NOTOC
);
2712 if( $mw->matchAndRemove( $text ) ) {
2716 # Get all headlines for numbering them and adding funky stuff like [edit]
2717 # links - this is for later, but we need the number of headlines right now
2718 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2720 # if there are fewer than 4 headlines in the article, do not show TOC
2721 if( $numMatches < 4 ) {
2725 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2726 # override above conditions and always show TOC at that place
2728 $mw =& MagicWord
::get( MAG_TOC
);
2729 if($mw->match( $text ) ) {
2731 $forceTocHere = true;
2733 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2734 # override above conditions and always show TOC above first header
2735 $mw =& MagicWord
::get( MAG_FORCETOC
);
2736 if ($mw->matchAndRemove( $text ) ) {
2741 # Never ever show TOC if no headers
2742 if( $numMatches < 1 ) {
2746 # We need this to perform operations on the HTML
2747 $sk =& $this->mOptions
->getSkin();
2751 $sectionCount = 0; # headlineCount excluding template sections
2753 # Ugh .. the TOC should have neat indentation levels which can be
2754 # passed to the skin functions. These are determined here
2758 $sublevelCount = array();
2759 $levelCount = array();
2766 foreach( $matches[3] as $headline ) {
2768 $templatetitle = '';
2769 $templatesection = 0;
2772 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2774 $templatetitle = base64_decode($mat[1]);
2775 $templatesection = 1 +
(int)base64_decode($mat[2]);
2776 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2780 $prevlevel = $level;
2781 $prevtoclevel = $toclevel;
2783 $level = $matches[1][$headlineCount];
2785 if( $doNumberHeadings ||
$doShowToc ) {
2787 if ( $level > $prevlevel ) {
2788 # Increase TOC level
2790 $sublevelCount[$toclevel] = 0;
2791 $toc .= $sk->tocIndent();
2793 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2794 # Decrease TOC level, find level to jump to
2796 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2797 # Can only go down to level 1
2800 for ($i = $toclevel; $i > 0; $i--) {
2801 if ( $levelCount[$i] == $level ) {
2802 # Found last matching level
2806 elseif ( $levelCount[$i] < $level ) {
2807 # Found first matching level below current level
2814 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2817 # No change in level, end TOC line
2818 $toc .= $sk->tocLineEnd();
2821 $levelCount[$toclevel] = $level;
2823 # count number of headlines for each level
2824 @$sublevelCount[$toclevel]++
;
2826 for( $i = 1; $i <= $toclevel; $i++
) {
2827 if( !empty( $sublevelCount[$i] ) ) {
2831 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2837 # The canonized header is a version of the header text safe to use for links
2838 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2839 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2840 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2842 # Remove link placeholders by the link text.
2843 # <!--LINK number-->
2845 # link text with suffix
2846 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2847 "\$this->mLinkHolders['texts'][\$1]",
2848 $canonized_headline );
2849 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2850 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2851 $canonized_headline );
2854 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2855 $tocline = trim( $canonized_headline );
2856 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2857 $replacearray = array(
2861 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2862 $refers[$headlineCount] = $canonized_headline;
2864 # count how many in assoc. array so we can track dupes in anchors
2865 @$refers[$canonized_headline]++
;
2866 $refcount[$headlineCount]=$refers[$canonized_headline];
2868 # Don't number the heading if it is the only one (looks silly)
2869 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2870 # the two are different if the line contains a link
2871 $headline=$numbering . ' ' . $headline;
2874 # Create the anchor for linking from the TOC to the section
2875 $anchor = $canonized_headline;
2876 if($refcount[$headlineCount] > 1 ) {
2877 $anchor .= '_' . $refcount[$headlineCount];
2879 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2880 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2882 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2883 if ( empty( $head[$headlineCount] ) ) {
2884 $head[$headlineCount] = '';
2887 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2889 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2892 # give headline the correct <h#> tag
2893 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2901 $toc .= $sk->tocUnindent( $toclevel - 1 );
2902 $toc = $sk->tocList( $toc );
2905 # split up and insert constructed headlines
2907 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2910 foreach( $blocks as $block ) {
2911 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2912 # This is the [edit] link that appears for the top block of text when
2913 # section editing is enabled
2915 # Disabled because it broke block formatting
2916 # For example, a bullet point in the top line
2917 # $full .= $sk->editSectionLink(0);
2920 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2921 # Top anchor now in skin
2925 if( !empty( $head[$i] ) ) {
2931 $mw =& MagicWord
::get( MAG_TOC
);
2932 return $mw->replace( $toc, $full );
2939 * Return an HTML link for the "ISBN 123456" text
2942 function magicISBN( $text ) {
2943 $fname = 'Parser::magicISBN';
2944 wfProfileIn( $fname );
2946 $a = split( 'ISBN ', ' '.$text );
2947 if ( count ( $a ) < 2 ) {
2948 wfProfileOut( $fname );
2951 $text = substr( array_shift( $a ), 1);
2952 $valid = '0123456789-Xx';
2954 foreach ( $a as $x ) {
2955 $isbn = $blank = '' ;
2956 while ( ' ' == $x{0} ) {
2958 $x = substr( $x, 1 );
2960 if ( $x == '' ) { # blank isbn
2961 $text .= "ISBN $blank";
2964 while ( strstr( $valid, $x{0} ) != false ) {
2966 $x = substr( $x, 1 );
2968 $num = str_replace( '-', '', $isbn );
2969 $num = str_replace( ' ', '', $num );
2970 $num = str_replace( 'x', 'X', $num );
2973 $text .= "ISBN $blank$x";
2975 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2976 $text .= '<a href="' .
2977 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2978 "\" class=\"internal\">ISBN $isbn</a>";
2982 wfProfileOut( $fname );
2987 * Return an HTML link for the "RFC 1234" text
2990 * @param string $text Text to be processed
2991 * @param string $keyword Magic keyword to use (default RFC)
2992 * @param string $urlmsg Interface message to use (default rfcurl)
2995 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2997 $valid = '0123456789';
3000 $a = split( $keyword, ' '.$text );
3001 if ( count ( $a ) < 2 ) {
3004 $text = substr( array_shift( $a ), 1);
3006 /* Check if keyword is preceed by [[.
3007 * This test is made here cause of the array_shift above
3008 * that prevent the test to be done in the foreach.
3010 if ( substr( $text, -2 ) == '[[' ) {
3014 foreach ( $a as $x ) {
3015 /* token might be empty if we have RFC RFC 1234 */
3023 /** remove and save whitespaces in $blank */
3024 while ( $x{0} == ' ' ) {
3026 $x = substr( $x, 1 );
3029 /** remove and save the rfc number in $id */
3030 while ( strstr( $valid, $x{0} ) != false ) {
3032 $x = substr( $x, 1 );
3036 /* call back stripped spaces*/
3037 $text .= $keyword.$blank.$x;
3038 } elseif( $internal ) {
3040 $text .= $keyword.$id.$x;
3042 /* build the external link*/
3043 $url = wfMsg( $urlmsg, $id);
3044 $sk =& $this->mOptions
->getSkin();
3045 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3046 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3049 /* Check if the next RFC keyword is preceed by [[ */
3050 $internal = ( substr($x,-2) == '[[' );
3056 * Transform wiki markup when saving a page by doing \r\n -> \n
3057 * conversion, substitting signatures, {{subst:}} templates, etc.
3059 * @param string $text the text to transform
3060 * @param Title &$title the Title object for the current article
3061 * @param User &$user the User object describing the current user
3062 * @param ParserOptions $options parsing options
3063 * @param bool $clearState whether to clear the parser state first
3064 * @return string the altered wiki markup
3067 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3068 $this->mOptions
= $options;
3069 $this->mTitle
=& $title;
3070 $this->mOutputType
= OT_WIKI
;
3072 if ( $clearState ) {
3073 $this->clearState();
3076 $stripState = false;
3080 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3081 $text = $this->strip( $text, $stripState, true );
3082 $text = $this->pstPass2( $text, $user );
3083 $text = $this->unstrip( $text, $stripState );
3084 $text = $this->unstripNoWiki( $text, $stripState );
3089 * Pre-save transform helper function
3092 function pstPass2( $text, &$user ) {
3093 global $wgContLang, $wgLocaltimezone;
3095 # Variable replacement
3096 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3097 $text = $this->replaceVariables( $text );
3101 $sigText = $this->getUserSig( $user );
3103 /* Note: This is the timestamp saved as hardcoded wikitext to
3104 * the database, we use $wgContLang here in order to give
3105 * everyone the same signiture and use the default one rather
3106 * than the one selected in each users preferences.
3108 if ( isset( $wgLocaltimezone ) ) {
3109 $oldtz = getenv( 'TZ' );
3110 putenv( 'TZ='.$wgLocaltimezone );
3112 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3113 ' (' . date( 'T' ) . ')';
3114 if ( isset( $wgLocaltimezone ) ) {
3115 putenv( 'TZ='.$oldtz );
3118 $text = preg_replace( '/~~~~~/', $d, $text );
3119 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3120 $text = preg_replace( '/~~~/', $sigText, $text );
3122 # Context links: [[|name]] and [[name (context)|]]
3124 global $wgLegalTitleChars;
3125 $tc = "[$wgLegalTitleChars]";
3126 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3128 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3129 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3131 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3132 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3133 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3134 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3136 $t = $this->mTitle
->getText();
3137 if ( preg_match( $conpat, $t, $m ) ) {
3140 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3141 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3142 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3144 if ( '' == $context ) {
3145 $text = preg_replace( $p2, '[[\\1]]', $text );
3147 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3150 # Trim trailing whitespace
3151 # MAG_END (__END__) tag allows for trailing
3152 # whitespace to be deliberately included
3153 $text = rtrim( $text );
3154 $mw =& MagicWord
::get( MAG_END
);
3155 $mw->matchAndRemove( $text );
3161 * Fetch the user's signature text, if any, and normalize to
3162 * validated, ready-to-insert wikitext.
3168 function getUserSig( &$user ) {
3169 $name = $user->getName();
3170 $nick = trim( $user->getOption( 'nickname' ) );
3171 if ( '' == $nick ) {
3175 if( $user->getOption( 'fancysig' ) ) {
3176 // A wikitext signature.
3177 $valid = $this->validateSig( $nick );
3178 if( $valid === false ) {
3179 // Fall back to default sig
3181 wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
3187 // Plain text linking to the user's homepage
3189 $page = $user->getUserPage();
3191 $page->getPrefixedText() .
3193 wfEscapeWikIText( $nick ) .
3198 * We want to enforce two rules on wikitext sigs here:
3199 * 1) Expand any templates at save time (forced subst:)
3200 * 2) Check for unbalanced XML tags, and reject if so.
3202 * @param string $text
3203 * @return mixed An expanded string, or false if invalid.
3205 * @todo Run brace substitutions
3206 * @todo ?? Check for unbalanced '' and ''' quotes, etc
3208 function validateSig( $text ) {
3209 if( wfIsWellFormedXmlFragment( $text ) ) {
3217 * Set up some variables which are usually set up in parse()
3218 * so that an external function can call some class members with confidence
3221 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3222 $this->mTitle
=& $title;
3223 $this->mOptions
= $options;
3224 $this->mOutputType
= $outputType;
3225 if ( $clearState ) {
3226 $this->clearState();
3231 * Transform a MediaWiki message by replacing magic variables.
3233 * @param string $text the text to transform
3234 * @param ParserOptions $options options
3235 * @return string the text with variables substituted
3238 function transformMsg( $text, $options ) {
3240 static $executing = false;
3242 # Guard against infinite recursion
3248 $this->mTitle
= $wgTitle;
3249 $this->mOptions
= $options;
3250 $this->mOutputType
= OT_MSG
;
3251 $this->clearState();
3252 $text = $this->replaceVariables( $text );
3259 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3260 * Callback will be called with the text within
3261 * Transform and return the text within
3265 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3266 * @param mixed $callback The callback function (and object) to use for the tag
3268 * @return The old value of the mTagHooks array associated with the hook
3270 function setHook( $tag, $callback ) {
3271 $oldVal = @$this->mTagHooks
[$tag];
3272 $this->mTagHooks
[$tag] = $callback;
3278 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3279 * Placeholders created in Skin::makeLinkObj()
3280 * Returns an array of links found, indexed by PDBK:
3284 * $options is a bit field, RLH_FOR_UPDATE to select for update
3286 function replaceLinkHolders( &$text, $options = 0 ) {
3287 global $wgUser, $wgLinkCache;
3288 global $wgOutputReplace;
3290 $fname = 'Parser::replaceLinkHolders';
3291 wfProfileIn( $fname );
3295 $sk = $this->mOptions
->getSkin();
3297 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3298 wfProfileIn( $fname.'-check' );
3299 $dbr =& wfGetDB( DB_SLAVE
);
3300 $page = $dbr->tableName( 'page' );
3301 $threshold = $wgUser->getOption('stubthreshold');
3304 asort( $this->mLinkHolders
['namespaces'] );
3308 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3310 $title = $this->mLinkHolders
['titles'][$key];
3312 # Skip invalid entries.
3313 # Result will be ugly, but prevents crash.
3314 if ( is_null( $title ) ) {
3317 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3319 # Check if it's in the link cache already
3320 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3321 $colours[$pdbk] = 1;
3322 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3323 $colours[$pdbk] = 0;
3325 # Not in the link cache, add it to the query
3326 if ( !isset( $current ) ) {
3328 $query = "SELECT page_id, page_namespace, page_title";
3329 if ( $threshold > 0 ) {
3330 $query .= ', page_len, page_is_redirect';
3332 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3333 } elseif ( $current != $val ) {
3335 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3340 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3345 if ( $options & RLH_FOR_UPDATE
) {
3346 $query .= ' FOR UPDATE';
3349 $res = $dbr->query( $query, $fname );
3351 # Fetch data and form into an associative array
3352 # non-existent = broken
3355 while ( $s = $dbr->fetchObject($res) ) {
3356 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3357 $pdbk = $title->getPrefixedDBkey();
3358 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3360 if ( $threshold > 0 ) {
3361 $size = $s->page_len
;
3362 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3363 $colours[$pdbk] = 1;
3365 $colours[$pdbk] = 2;
3368 $colours[$pdbk] = 1;
3372 wfProfileOut( $fname.'-check' );
3374 # Construct search and replace arrays
3375 wfProfileIn( $fname.'-construct' );
3376 $wgOutputReplace = array();
3377 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3378 $pdbk = $pdbks[$key];
3379 $searchkey = "<!--LINK $key-->";
3380 $title = $this->mLinkHolders
['titles'][$key];
3381 if ( empty( $colours[$pdbk] ) ) {
3382 $wgLinkCache->addBadLinkObj( $title );
3383 $colours[$pdbk] = 0;
3384 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3385 $this->mLinkHolders
['texts'][$key],
3386 $this->mLinkHolders
['queries'][$key] );
3387 } elseif ( $colours[$pdbk] == 1 ) {
3388 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3389 $this->mLinkHolders
['texts'][$key],
3390 $this->mLinkHolders
['queries'][$key] );
3391 } elseif ( $colours[$pdbk] == 2 ) {
3392 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3393 $this->mLinkHolders
['texts'][$key],
3394 $this->mLinkHolders
['queries'][$key] );
3397 wfProfileOut( $fname.'-construct' );
3400 wfProfileIn( $fname.'-replace' );
3402 $text = preg_replace_callback(
3403 '/(<!--LINK .*?-->)/',
3404 "wfOutputReplaceMatches",
3407 wfProfileOut( $fname.'-replace' );
3410 # Now process interwiki link holders
3411 # This is quite a bit simpler than internal links
3412 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3413 wfProfileIn( $fname.'-interwiki' );
3414 # Make interwiki link HTML
3415 $wgOutputReplace = array();
3416 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3417 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3418 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3421 $text = preg_replace_callback(
3422 '/<!--IWLINK (.*?)-->/',
3423 "wfOutputReplaceMatches",
3425 wfProfileOut( $fname.'-interwiki' );
3428 wfProfileOut( $fname );
3433 * Replace <!--LINK--> link placeholders with plain text of links
3434 * (not HTML-formatted).
3435 * @param string $text
3438 function replaceLinkHoldersText( $text ) {
3439 global $wgUser, $wgLinkCache;
3440 global $wgOutputReplace;
3442 $fname = 'Parser::replaceLinkHoldersText';
3443 wfProfileIn( $fname );
3445 $text = preg_replace_callback(
3446 '/<!--(LINK|IWLINK) (.*?)-->/',
3447 array( &$this, 'replaceLinkHoldersTextCallback' ),
3450 wfProfileOut( $fname );
3455 * @param array $matches
3459 function replaceLinkHoldersTextCallback( $matches ) {
3460 $type = $matches[1];
3462 if( $type == 'LINK' ) {
3463 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3464 return $this->mLinkHolders
['texts'][$key];
3466 } elseif( $type == 'IWLINK' ) {
3467 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3468 return $this->mInterwikiLinkHolders
['texts'][$key];
3475 * Renders an image gallery from a text with one line per image.
3476 * text labels may be given by using |-style alternative text. E.g.
3477 * Image:one.jpg|The number "1"
3478 * Image:tree.jpg|A tree
3479 * given as text will return the HTML of a gallery with two images,
3480 * labeled 'The number "1"' and
3485 function renderImageGallery( $text ) {
3487 global $wgUser, $wgTitle;
3488 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3489 $localParser = new Parser();
3491 global $wgLinkCache;
3492 $ig = new ImageGallery();
3493 $ig->setShowBytes( false );
3494 $ig->setShowFilename( false );
3495 $lines = explode( "\n", $text );
3497 foreach ( $lines as $line ) {
3498 # match lines like these:
3499 # Image:someimage.jpg|This is some image
3500 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3502 if ( count( $matches ) == 0 ) {
3505 $nt = Title
::newFromURL( $matches[1] );
3506 if( is_null( $nt ) ) {
3507 # Bogus title. Ignore these so we don't bomb out later.
3510 if ( isset( $matches[3] ) ) {
3511 $label = $matches[3];
3516 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3517 $html = $html->mText
;
3519 $ig->add( new Image( $nt ), $html );
3520 $wgLinkCache->addImageLinkObj( $nt );
3522 return $ig->toHTML();
3526 * Parse image options text and use it to make an image
3528 function makeImage( &$nt, $options ) {
3529 global $wgContLang, $wgUseImageResize, $wgUser;
3533 # Check if the options text is of the form "options|alt text"
3535 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3536 # * left no resizing, just left align. label is used for alt= only
3537 # * right same, but right aligned
3538 # * none same, but not aligned
3539 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3540 # * center center the image
3541 # * framed Keep original image size, no magnify-button.
3543 $part = explode( '|', $options);
3545 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3546 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3547 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3548 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3549 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3550 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3551 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3552 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3555 $width = $height = $framed = $thumb = false;
3556 $manual_thumb = '' ;
3558 foreach( $part as $key => $val ) {
3559 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3561 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3562 # use manually specified thumbnail
3564 $manual_thumb = $match;
3565 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3566 # remember to set an alignment, don't render immediately
3568 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3569 # remember to set an alignment, don't render immediately
3571 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3572 # remember to set an alignment, don't render immediately
3574 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3575 # remember to set an alignment, don't render immediately
3577 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3578 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3579 # $match is the image width in pixels
3580 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3581 $width = intval( $m[1] );
3582 $height = intval( $m[2] );
3584 $width = intval($match);
3586 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3592 # Strip bad stuff out of the alt text
3593 $alt = $this->replaceLinkHoldersText( $caption );
3594 $alt = Sanitizer
::stripAllTags( $alt );
3596 # Linker does the rest
3597 $sk =& $this->mOptions
->getSkin();
3598 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3602 * Set a flag in the output object indicating that the content is dynamic and
3603 * shouldn't be cached.
3605 function disableCache() {
3606 $this->mOutput
->mCacheTime
= -1;
3610 * Callback from the Sanitizer for expanding items found in HTML attribute
3611 * values, so they can be safely tested and escaped.
3612 * @param string $text
3613 * @param array $args
3617 function attributeStripCallback( &$text, $args ) {
3618 $text = $this->replaceVariables( $text, $args );
3619 $text = $this->unstripForHTML( $text );
3623 function unstripForHTML( $text ) {
3624 $text = $this->unstrip( $text, $this->mStripState
);
3625 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3629 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3630 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3631 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3636 * @package MediaWiki
3640 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3641 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3642 var $mVersion; # Compatibility check
3643 var $mTitleText; # title text of the chosen language variant
3645 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3646 $containsOldMagic = false, $titletext = '' )
3648 $this->mText
= $text;
3649 $this->mLanguageLinks
= $languageLinks;
3650 $this->mCategoryLinks
= $categoryLinks;
3651 $this->mContainsOldMagic
= $containsOldMagic;
3652 $this->mCacheTime
= '';
3653 $this->mVersion
= MW_PARSER_VERSION
;
3654 $this->mTitleText
= $titletext;
3657 function getText() { return $this->mText
; }
3658 function getLanguageLinks() { return $this->mLanguageLinks
; }
3659 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3660 function getCacheTime() { return $this->mCacheTime
; }
3661 function getTitleText() { return $this->mTitleText
; }
3662 function containsOldMagic() { return $this->mContainsOldMagic
; }
3663 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3664 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3665 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3666 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3667 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3668 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3670 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3672 function merge( $other ) {
3673 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3674 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3675 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3679 * Return true if this cached output object predates the global or
3680 * per-article cache invalidation timestamps, or if it comes from
3681 * an incompatible older version.
3683 * @param string $touched the affected article's last touched timestamp
3687 function expired( $touched ) {
3688 global $wgCacheEpoch;
3689 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3690 $this->getCacheTime() < $touched ||
3691 $this->getCacheTime() <= $wgCacheEpoch ||
3692 !isset( $this->mVersion
) ||
3693 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3698 * Set options of the Parser
3700 * @package MediaWiki
3704 # All variables are private
3705 var $mUseTeX; # Use texvc to expand <math> tags
3706 var $mUseDynamicDates; # Use DateFormatter to format dates
3707 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3708 var $mAllowExternalImages; # Allow external images inline
3709 var $mAllowExternalImagesFrom; # If not, any exception?
3710 var $mSkin; # Reference to the preferred skin
3711 var $mDateFormat; # Date format index
3712 var $mEditSection; # Create "edit section" links
3713 var $mNumberHeadings; # Automatically number headings
3714 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3716 function getUseTeX() { return $this->mUseTeX
; }
3717 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3718 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3719 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3720 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3721 function &getSkin() { return $this->mSkin
; }
3722 function getDateFormat() { return $this->mDateFormat
; }
3723 function getEditSection() { return $this->mEditSection
; }
3724 function getNumberHeadings() { return $this->mNumberHeadings
; }
3725 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3728 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3729 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3730 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3731 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3732 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3733 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3734 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3735 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3736 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3738 function setSkin( &$x ) { $this->mSkin
=& $x; }
3740 function ParserOptions() {
3742 $this->initialiseFromUser( $wgUser );
3746 * Get parser options
3749 function newFromUser( &$user ) {
3750 $popts = new ParserOptions
;
3751 $popts->initialiseFromUser( $user );
3755 /** Get user options */
3756 function initialiseFromUser( &$userInput ) {
3757 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3758 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3759 $fname = 'ParserOptions::initialiseFromUser';
3760 wfProfileIn( $fname );
3761 if ( !$userInput ) {
3763 $user->setLoaded( true );
3765 $user =& $userInput;
3768 $this->mUseTeX
= $wgUseTeX;
3769 $this->mUseDynamicDates
= $wgUseDynamicDates;
3770 $this->mInterwikiMagic
= $wgInterwikiMagic;
3771 $this->mAllowExternalImages
= $wgAllowExternalImages;
3772 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3773 wfProfileIn( $fname.'-skin' );
3774 $this->mSkin
=& $user->getSkin();
3775 wfProfileOut( $fname.'-skin' );
3776 $this->mDateFormat
= $user->getOption( 'date' );
3777 $this->mEditSection
= true;
3778 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3779 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3780 wfProfileOut( $fname );
3785 * Callback function used by Parser::replaceLinkHolders()
3786 * to substitute link placeholders.
3788 function &wfOutputReplaceMatches( $matches ) {
3789 global $wgOutputReplace;
3790 return $wgOutputReplace[$matches[1]];
3794 * Return the total number of articles
3796 function wfNumberOfArticles() {
3797 global $wgNumberOfArticles;
3800 return $wgNumberOfArticles;
3804 * Return the number of files
3806 function wfNumberOfFiles() {
3807 $fname = 'Parser::wfNumberOfFiles';
3809 wfProfileIn( $fname );
3810 $dbr =& wfGetDB( DB_SLAVE
);
3811 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3812 wfProfileOut( $fname );
3818 * Get various statistics from the database
3821 function wfLoadSiteStats() {
3822 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3823 $fname = 'wfLoadSiteStats';
3825 if ( -1 != $wgNumberOfArticles ) return;
3826 $dbr =& wfGetDB( DB_SLAVE
);
3827 $s = $dbr->selectRow( 'site_stats',
3828 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3829 array( 'ss_row_id' => 1 ), $fname
3832 if ( $s === false ) {
3835 $wgTotalViews = $s->ss_total_views
;
3836 $wgTotalEdits = $s->ss_total_edits
;
3837 $wgNumberOfArticles = $s->ss_good_articles
;
3843 * Basicly replacing " > and < with HTML entities ( ", >, <)
3845 * @param string $in Text that might contain HTML tags
3846 * @return string Escaped string
3848 function wfEscapeHTMLTagsOnly( $in ) {
3850 array( '"', '>', '<' ),
3851 array( '"', '>', '<' ),