3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12 require_once( 'ImageGallery.php' );
15 * Update this version number when the ParserOutput format
16 * changes in an incompatible way, so the parser cache
17 * can automatically discard old data.
19 define( 'MW_PARSER_VERSION', '1.6.1' );
22 * Variable substitution O(N^2) attack
24 * Without countermeasures, it would be possible to attack the parser by saving
25 * a page filled with a large number of inclusions of large pages. The size of
26 * the generated page would be proportional to the square of the input size.
27 * Hence, we limit the number of inclusions of any given page, thus bringing any
28 * attack back to O(N).
31 define( 'MAX_INCLUDE_REPEAT', 100 );
32 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
34 define( 'RLH_FOR_UPDATE', 1 );
36 # Allowed values for $mOutputType
37 define( 'OT_HTML', 1 );
38 define( 'OT_WIKI', 2 );
39 define( 'OT_MSG' , 3 );
41 # string parameter for extractTags which will cause it
42 # to strip HTML comments in addition to regular
43 # <XML>-style tags. This should not be anything we
44 # may want to use in wikisyntax
45 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
47 # Constants needed for external link processing
48 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
49 # Everything except bracket, space, or control characters
50 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
52 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
53 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
54 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
55 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
56 define( 'EXT_IMAGE_REGEX',
57 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
58 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
59 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
62 // State constants for the definition list colon extraction
63 define( 'MW_COLON_STATE_TEXT', 0 );
64 define( 'MW_COLON_STATE_TAG', 1 );
65 define( 'MW_COLON_STATE_TAGSTART', 2 );
66 define( 'MW_COLON_STATE_CLOSETAG', 3 );
67 define( 'MW_COLON_STATE_TAGSLASH', 4 );
68 define( 'MW_COLON_STATE_COMMENT', 5 );
69 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
70 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
75 * Processes wiki markup
78 * There are three main entry points into the Parser class:
80 * produces HTML output
82 * produces altered wiki markup.
84 * performs brace substitution on MediaWiki messages
87 * objects: $wgLang, $wgContLang
89 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
92 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
93 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
94 * $wgLocaltimezone, $wgAllowSpecialInclusion*
96 * * only within ParserOptions
107 var $mTagHooks, $mFunctionHooks;
109 # Cleared with clearState():
110 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
111 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
112 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
113 var $mTemplates, // cache of already loaded templates, avoids
114 // multiple SQL queries for the same string
115 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
116 // in this path. Used for loop detection.
119 # These are variables reset at least once per parse regardless of $clearState
120 var $mOptions, // ParserOptions object
121 $mTitle, // Title context, used for self-link rendering and similar things
122 $mOutputType, // Output type, one of the OT_xxx constants
123 $mRevisionId; // ID to display in {{REVISIONID}} tags
133 $this->mTagHooks
= array();
134 $this->mFunctionHooks
= array();
143 function clearState() {
144 $this->mOutput
= new ParserOutput
;
145 $this->mAutonumber
= 0;
146 $this->mLastSection
= '';
147 $this->mDTopen
= false;
148 $this->mVariables
= false;
149 $this->mIncludeCount
= array();
150 $this->mStripState
= array();
151 $this->mArgStack
= array();
152 $this->mInPre
= false;
153 $this->mInterwikiLinkHolders
= array(
157 $this->mLinkHolders
= array(
158 'namespaces' => array(),
160 'queries' => array(),
164 $this->mRevisionId
= null;
167 * Prefix for temporary replacement strings for the multipass parser.
168 * \x07 should never appear in input as it's disallowed in XML.
169 * Using it at the front also gives us a little extra robustness
170 * since it shouldn't match when butted up against identifier-like
173 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
175 # Clear these on every parse, bug 4549
176 $this->mTemplates
= array();
177 $this->mTemplatePath
= array();
179 $this->mShowToc
= true;
180 $this->mForceTocPosition
= false;
182 wfRunHooks( 'ParserClearState', array( &$this ) );
186 * Accessor for mUniqPrefix.
190 function UniqPrefix() {
191 return $this->mUniqPrefix
;
195 * Convert wikitext to HTML
196 * Do not call this function recursively.
199 * @param string $text Text we want to parse
200 * @param Title &$title A title object
201 * @param array $options
202 * @param boolean $linestart
203 * @param boolean $clearState
204 * @param int $revid number to pass in {{REVISIONID}}
205 * @return ParserOutput a ParserOutput
207 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
209 * First pass--just handle <nowiki> sections, pass the rest off
210 * to internalParse() which does all the real work.
213 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
214 $fname = 'Parser::parse';
215 wfProfileIn( $fname );
221 $this->mOptions
= $options;
222 $this->mTitle
=& $title;
223 $this->mRevisionId
= $revid;
224 $this->mOutputType
= OT_HTML
;
226 //$text = $this->strip( $text, $this->mStripState );
227 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
228 $x =& $this->mStripState
;
230 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
231 $text = $this->strip( $text, $x );
232 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
234 # Hook to suspend the parser in this state
235 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
236 wfProfileOut( $fname );
240 $text = $this->internalParse( $text );
242 $text = $this->unstrip( $text, $this->mStripState
);
244 # Clean up special characters, only run once, next-to-last before doBlockLevels
246 # french spaces, last one Guillemet-left
247 # only if there is something before the space
248 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
249 # french spaces, Guillemet-right
250 '/(\\302\\253) /' => '\\1 ',
251 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
253 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
256 $text = $this->doBlockLevels( $text, $linestart );
258 $this->replaceLinkHolders( $text );
260 # the position of the parserConvert() call should not be changed. it
261 # assumes that the links are all replaced and the only thing left
262 # is the <nowiki> mark.
263 # Side-effects: this calls $this->mOutput->setTitleText()
264 $text = $wgContLang->parserConvert( $text, $this );
266 $text = $this->unstripNoWiki( $text, $this->mStripState
);
268 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
270 $text = Sanitizer
::normalizeCharReferences( $text );
272 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
273 $text = Parser
::tidy($text);
275 # attempt to sanitize at least some nesting problems
276 # (bug #2702 and quite a few others)
278 # ''Something [http://www.cool.com cool''] -->
279 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
280 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
281 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
282 # fix up an anchor inside another anchor, only
283 # at least for a single single nested link (bug 3695)
284 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
285 '\\1\\2</a>\\3</a>\\1\\4</a>',
286 # fix div inside inline elements- doBlockLevels won't wrap a line which
287 # contains a div, so fix it up here; replace
288 # div with escaped text
289 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
290 '\\1\\3<div\\5>\\6</div>\\8\\9',
291 # remove empty italic or bold tag pairs, some
292 # introduced by rules above
293 '/<([bi])><\/\\1>/' => ''
296 $text = preg_replace(
297 array_keys( $tidyregs ),
298 array_values( $tidyregs ),
302 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
304 $this->mOutput
->setText( $text );
305 wfProfileOut( $fname );
307 return $this->mOutput
;
311 * Get a random string
316 function getRandomString() {
317 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
320 function &getTitle() { return $this->mTitle
; }
321 function getOptions() { return $this->mOptions
; }
324 * Replaces all occurrences of HTML-style comments and the given tags
325 * in the text with a random marker and returns teh next text. The output
326 * parameter $matches will be an associative array filled with data in
328 * 'UNIQ-xxxxx' => array(
331 * array( 'param' => 'x' ),
332 * '<element param="x">tag content</element>' ) )
334 * @param $elements list of element names. Comments are always extracted.
335 * @param $text Source text string.
336 * @param $uniq_prefix
341 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
342 $rand = Parser
::getRandomString();
347 $taglist = implode( '|', $elements );
348 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
350 while ( '' != $text ) {
351 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
353 if( count( $p ) < 5 ) {
356 if( count( $p ) > 5 ) {
370 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
);
371 $stripped .= $marker;
373 if ( $close === '/>' ) {
374 // Empty element tag, <tag />
379 if( $element == '!--' ) {
382 $end = "/(<\\/$element\\s*>)/i";
384 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
386 if( count( $q ) < 3 ) {
387 # No end tag -- let it run out to the end of the text.
396 $matches[$marker] = array( $element,
398 Sanitizer
::decodeTagAttributes( $attributes ),
399 "<$element$attributes$close$content$tail" );
405 * Strips and renders nowiki, pre, math, hiero
406 * If $render is set, performs necessary rendering operations on plugins
407 * Returns the text, and fills an array with data needed in unstrip()
408 * If the $state is already a valid strip state, it adds to the state
410 * @param bool $stripcomments when set, HTML comments <!-- like this -->
411 * will be stripped in addition to other tags. This is important
412 * for section editing, where these comments cause confusion when
413 * counting the sections in the wikisource
417 function strip( $text, &$state, $stripcomments = false ) {
418 $render = ($this->mOutputType
== OT_HTML
);
420 # Replace any instances of the placeholders
421 $uniq_prefix = $this->mUniqPrefix
;
422 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
423 $commentState = array();
425 $elements = array_merge(
426 array( 'nowiki', 'pre', 'gallery' ),
427 array_keys( $this->mTagHooks
) );
430 $elements[] = 'html';
432 if( $this->mOptions
->getUseTeX() ) {
433 $elements[] = 'math';
438 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
440 foreach( $matches as $marker => $data ) {
441 list( $element, $content, $params, $tag ) = $data;
443 $tagName = strtolower( $element );
447 if( substr( $tag, -3 ) == '-->' ) {
450 // Unclosed comment in input.
451 // Close it so later stripping can remove it
460 // Shouldn't happen otherwise. :)
462 $output = wfEscapeHTMLTagsOnly( $content );
465 $output = renderMath( $content );
468 // Backwards-compatibility hack
469 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $content );
470 $output = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
473 $output = $this->renderImageGallery( $content );
476 if( isset( $this->mTagHooks
[$tagName] ) ) {
477 $output = call_user_func_array( $this->mTagHooks
[$tagName],
478 array( $content, $params, $this ) );
480 wfDebugDieBacktrace( "Invalid call hook $element" );
484 // Just stripping tags; keep the source
487 if( !$stripcomments && $element == '!--' ) {
488 $commentState[$marker] = $output;
490 $state[$element][$marker] = $output;
494 # Unstrip comments unless explicitly told otherwise.
495 # (The comments are always stripped prior to this point, so as to
496 # not invoke any extension tags / parser hooks contained within
498 if ( !$stripcomments ) {
499 // Put them all back and forget them
500 $text = strtr( $text, $commentState );
507 * Restores pre, math, and other extensions removed by strip()
509 * always call unstripNoWiki() after this one
512 function unstrip( $text, &$state ) {
513 if ( !is_array( $state ) ) {
517 $replacements = array();
518 foreach( $state as $tag => $contentDict ) {
519 if( $tag != 'nowiki' && $tag != 'html' ) {
520 foreach( $contentDict as $uniq => $content ) {
521 $replacements[$uniq] = $content;
525 $text = strtr( $text, $replacements );
531 * Always call this after unstrip() to preserve the order
535 function unstripNoWiki( $text, &$state ) {
536 if ( !is_array( $state ) ) {
540 $replacements = array();
541 foreach( $state as $tag => $contentDict ) {
542 if( $tag == 'nowiki' ||
$tag == 'html' ) {
543 foreach( $contentDict as $uniq => $content ) {
544 $replacements[$uniq] = $content;
548 $text = strtr( $text, $replacements );
554 * Add an item to the strip state
555 * Returns the unique tag which must be inserted into the stripped text
556 * The tag will be replaced with the original text in unstrip()
560 function insertStripItem( $text, &$state ) {
561 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
565 $state['item'][$rnd] = $text;
570 * Interface with html tidy, used if $wgUseTidy = true.
571 * If tidy isn't able to correct the markup, the original will be
572 * returned in all its glory with a warning comment appended.
574 * Either the external tidy program or the in-process tidy extension
575 * will be used depending on availability. Override the default
576 * $wgTidyInternal setting to disable the internal if it's not working.
578 * @param string $text Hideous HTML input
579 * @return string Corrected HTML output
583 function tidy( $text ) {
584 global $wgTidyInternal;
585 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
586 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
587 '<head><title>test</title></head><body>'.$text.'</body></html>';
588 if( $wgTidyInternal ) {
589 $correctedtext = Parser
::internalTidy( $wrappedtext );
591 $correctedtext = Parser
::externalTidy( $wrappedtext );
593 if( is_null( $correctedtext ) ) {
594 wfDebug( "Tidy error detected!\n" );
595 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
597 return $correctedtext;
601 * Spawn an external HTML tidy process and get corrected markup back from it.
606 function externalTidy( $text ) {
607 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
608 $fname = 'Parser::externalTidy';
609 wfProfileIn( $fname );
614 $descriptorspec = array(
615 0 => array('pipe', 'r'),
616 1 => array('pipe', 'w'),
617 2 => array('file', '/dev/null', 'a')
620 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
621 if (is_resource($process)) {
622 // Theoretically, this style of communication could cause a deadlock
623 // here. If the stdout buffer fills up, then writes to stdin could
624 // block. This doesn't appear to happen with tidy, because tidy only
625 // writes to stdout after it's finished reading from stdin. Search
626 // for tidyParseStdin and tidySaveStdout in console/tidy.c
627 fwrite($pipes[0], $text);
629 while (!feof($pipes[1])) {
630 $cleansource .= fgets($pipes[1], 1024);
633 proc_close($process);
636 wfProfileOut( $fname );
638 if( $cleansource == '' && $text != '') {
639 // Some kind of error happened, so we couldn't get the corrected text.
640 // Just give up; we'll use the source text and append a warning.
648 * Use the HTML tidy PECL extension to use the tidy library in-process,
649 * saving the overhead of spawning a new process. Currently written to
650 * the PHP 4.3.x version of the extension, may not work on PHP 5.
652 * 'pear install tidy' should be able to compile the extension module.
657 function internalTidy( $text ) {
659 $fname = 'Parser::internalTidy';
660 wfProfileIn( $fname );
662 tidy_load_config( $wgTidyConf );
663 tidy_set_encoding( 'utf8' );
664 tidy_parse_string( $text );
666 if( tidy_get_status() == 2 ) {
667 // 2 is magic number for fatal error
668 // http://www.php.net/manual/en/function.tidy-get-status.php
671 $cleansource = tidy_get_output();
673 wfProfileOut( $fname );
678 * parse the wiki syntax used to render tables
682 function doTableStuff ( $t ) {
683 $fname = 'Parser::doTableStuff';
684 wfProfileIn( $fname );
686 $t = explode ( "\n" , $t ) ;
687 $td = array () ; # Is currently a td tag open?
688 $ltd = array () ; # Was it TD or TH?
689 $tr = array () ; # Is currently a tr tag open?
690 $ltr = array () ; # tr attributes
691 $has_opened_tr = array(); # Did this table open a <tr> element?
692 $indent_level = 0; # indent level of the table
693 foreach ( $t AS $k => $x )
696 $fc = substr ( $x , 0 , 1 ) ;
697 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
698 $indent_level = strlen( $matches[1] );
700 $attributes = $this->unstripForHTML( $matches[2] );
702 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
703 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
704 array_push ( $td , false ) ;
705 array_push ( $ltd , '' ) ;
706 array_push ( $tr , false ) ;
707 array_push ( $ltr , '' ) ;
708 array_push ( $has_opened_tr, false );
710 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
711 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
712 $z = "</table>" . substr ( $x , 2);
713 $l = array_pop ( $ltd ) ;
714 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
715 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
716 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
718 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
720 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
721 $x = substr ( $x , 1 ) ;
722 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
724 $l = array_pop ( $ltd ) ;
725 array_pop ( $has_opened_tr );
726 array_push ( $has_opened_tr , true ) ;
727 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
728 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
731 array_push ( $tr , false ) ;
732 array_push ( $td , false ) ;
733 array_push ( $ltd , '' ) ;
734 $attributes = $this->unstripForHTML( $x );
735 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
737 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
739 if ( '|+' == substr ( $x , 0 , 2 ) ) {
741 $x = substr ( $x , 1 ) ;
743 $after = substr ( $x , 1 ) ;
744 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
746 // Split up multiple cells on the same line.
747 // FIXME: This can result in improper nesting of tags processed
748 // by earlier parser steps, but should avoid splitting up eg
749 // attribute values containing literal "||".
750 $after = wfExplodeMarkup( '||', $after );
754 # Loop through each table cell
755 foreach ( $after AS $theline )
760 $tra = array_pop ( $ltr ) ;
761 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
762 array_push ( $tr , true ) ;
763 array_push ( $ltr , '' ) ;
764 array_pop ( $has_opened_tr );
765 array_push ( $has_opened_tr , true ) ;
768 $l = array_pop ( $ltd ) ;
769 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
770 if ( $fc == '|' ) $l = 'td' ;
771 else if ( $fc == '!' ) $l = 'th' ;
772 else if ( $fc == '+' ) $l = 'caption' ;
774 array_push ( $ltd , $l ) ;
777 $y = explode ( '|' , $theline , 2 ) ;
778 # Note that a '|' inside an invalid link should not
779 # be mistaken as delimiting cell parameters
780 if ( strpos( $y[0], '[[' ) !== false ) {
781 $y = array ($theline);
783 if ( count ( $y ) == 1 )
784 $y = "{$z}<{$l}>{$y[0]}" ;
786 $attributes = $this->unstripForHTML( $y[0] );
787 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
790 array_push ( $td , true ) ;
795 # Closing open td, tr && table
796 while ( count ( $td ) > 0 )
798 $l = array_pop ( $ltd ) ;
799 if ( array_pop ( $td ) ) $t[] = '</td>' ;
800 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
801 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
805 $t = implode ( "\n" , $t ) ;
806 # special case: don't return empty table
807 if($t == "<table>\n<tr><td></td></tr>\n</table>")
809 wfProfileOut( $fname );
814 * Helper function for parse() that transforms wiki markup into
815 * HTML. Only called for $mOutputType == OT_HTML.
819 function internalParse( $text ) {
822 $fname = 'Parser::internalParse';
823 wfProfileIn( $fname );
825 # Remove <noinclude> tags and <includeonly> sections
826 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
827 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
828 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
830 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
832 $text = $this->replaceVariables( $text, $args );
834 // Tables need to come after variable replacement for things to work
835 // properly; putting them before other transformations should keep
836 // exciting things like link expansions from showing up in surprising
838 $text = $this->doTableStuff( $text );
840 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
842 $text = $this->stripToc( $text );
843 $text = $this->doHeadings( $text );
844 if($this->mOptions
->getUseDynamicDates()) {
845 $df =& DateFormatter
::getInstance();
846 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
848 $text = $this->doAllQuotes( $text );
849 $text = $this->replaceInternalLinks( $text );
850 $text = $this->replaceExternalLinks( $text );
852 # replaceInternalLinks may sometimes leave behind
853 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
854 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
856 $text = $this->doMagicLinks( $text );
857 $text = $this->formatHeadings( $text, $isMain );
859 wfProfileOut( $fname );
864 * Replace special strings like "ISBN xxx" and "RFC xxx" with
865 * magic external links.
869 function &doMagicLinks( &$text ) {
870 $text = $this->magicISBN( $text );
871 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
872 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
877 * Parse headers and return html
881 function doHeadings( $text ) {
882 $fname = 'Parser::doHeadings';
883 wfProfileIn( $fname );
884 for ( $i = 6; $i >= 1; --$i ) {
885 $h = str_repeat( '=', $i );
886 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
887 "<h{$i}>\\1</h{$i}>\\2", $text );
889 wfProfileOut( $fname );
894 * Replace single quotes with HTML markup
896 * @return string the altered text
898 function doAllQuotes( $text ) {
899 $fname = 'Parser::doAllQuotes';
900 wfProfileIn( $fname );
902 $lines = explode( "\n", $text );
903 foreach ( $lines as $line ) {
904 $outtext .= $this->doQuotes ( $line ) . "\n";
906 $outtext = substr($outtext, 0,-1);
907 wfProfileOut( $fname );
912 * Helper function for doAllQuotes()
915 function doQuotes( $text ) {
916 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
917 if ( count( $arr ) == 1 )
921 # First, do some preliminary work. This may shift some apostrophes from
922 # being mark-up to being text. It also counts the number of occurrences
923 # of bold and italics mark-ups.
927 foreach ( $arr as $r )
929 if ( ( $i %
2 ) == 1 )
931 # If there are ever four apostrophes, assume the first is supposed to
932 # be text, and the remaining three constitute mark-up for bold text.
933 if ( strlen( $arr[$i] ) == 4 )
938 # If there are more than 5 apostrophes in a row, assume they're all
939 # text except for the last 5.
940 else if ( strlen( $arr[$i] ) > 5 )
942 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
945 # Count the number of occurrences of bold and italics mark-ups.
946 # We are not counting sequences of five apostrophes.
947 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
948 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
949 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
954 # If there is an odd number of both bold and italics, it is likely
955 # that one of the bold ones was meant to be an apostrophe followed
956 # by italics. Which one we cannot know for certain, but it is more
957 # likely to be one that has a single-letter word before it.
958 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
961 $firstsingleletterword = -1;
962 $firstmultiletterword = -1;
964 foreach ( $arr as $r )
966 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
968 $x1 = substr ($arr[$i-1], -1);
969 $x2 = substr ($arr[$i-1], -2, 1);
971 if ($firstspace == -1) $firstspace = $i;
972 } else if ($x2 == ' ') {
973 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
975 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
981 # If there is a single-letter word, use it!
982 if ($firstsingleletterword > -1)
984 $arr [ $firstsingleletterword ] = "''";
985 $arr [ $firstsingleletterword-1 ] .= "'";
987 # If not, but there's a multi-letter word, use that one.
988 else if ($firstmultiletterword > -1)
990 $arr [ $firstmultiletterword ] = "''";
991 $arr [ $firstmultiletterword-1 ] .= "'";
993 # ... otherwise use the first one that has neither.
994 # (notice that it is possible for all three to be -1 if, for example,
995 # there is only one pentuple-apostrophe in the line)
996 else if ($firstspace > -1)
998 $arr [ $firstspace ] = "''";
999 $arr [ $firstspace-1 ] .= "'";
1003 # Now let's actually convert our apostrophic mush to HTML!
1008 foreach ($arr as $r)
1012 if ($state == 'both')
1019 if (strlen ($r) == 2)
1022 { $output .= '</i>'; $state = ''; }
1023 else if ($state == 'bi')
1024 { $output .= '</i>'; $state = 'b'; }
1025 else if ($state == 'ib')
1026 { $output .= '</b></i><b>'; $state = 'b'; }
1027 else if ($state == 'both')
1028 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1029 else # $state can be 'b' or ''
1030 { $output .= '<i>'; $state .= 'i'; }
1032 else if (strlen ($r) == 3)
1035 { $output .= '</b>'; $state = ''; }
1036 else if ($state == 'bi')
1037 { $output .= '</i></b><i>'; $state = 'i'; }
1038 else if ($state == 'ib')
1039 { $output .= '</b>'; $state = 'i'; }
1040 else if ($state == 'both')
1041 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1042 else # $state can be 'i' or ''
1043 { $output .= '<b>'; $state .= 'b'; }
1045 else if (strlen ($r) == 5)
1048 { $output .= '</b><i>'; $state = 'i'; }
1049 else if ($state == 'i')
1050 { $output .= '</i><b>'; $state = 'b'; }
1051 else if ($state == 'bi')
1052 { $output .= '</i></b>'; $state = ''; }
1053 else if ($state == 'ib')
1054 { $output .= '</b></i>'; $state = ''; }
1055 else if ($state == 'both')
1056 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1057 else # ($state == '')
1058 { $buffer = ''; $state = 'both'; }
1063 # Now close all remaining tags. Notice that the order is important.
1064 if ($state == 'b' ||
$state == 'ib')
1066 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1070 if ($state == 'both')
1071 $output .= '<b><i>'.$buffer.'</i></b>';
1077 * Replace external links
1079 * Note: this is all very hackish and the order of execution matters a lot.
1080 * Make sure to run maintenance/parserTests.php if you change this code.
1084 function replaceExternalLinks( $text ) {
1086 $fname = 'Parser::replaceExternalLinks';
1087 wfProfileIn( $fname );
1089 $sk =& $this->mOptions
->getSkin();
1091 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1093 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1096 while ( $i<count( $bits ) ) {
1098 $protocol = $bits[$i++
];
1099 $text = $bits[$i++
];
1100 $trail = $bits[$i++
];
1102 # The characters '<' and '>' (which were escaped by
1103 # removeHTMLtags()) should not be included in
1104 # URLs, per RFC 2396.
1105 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1106 $text = substr($url, $m2[0][1]) . ' ' . $text;
1107 $url = substr($url, 0, $m2[0][1]);
1110 # If the link text is an image URL, replace it with an <img> tag
1111 # This happened by accident in the original parser, but some people used it extensively
1112 $img = $this->maybeMakeExternalImage( $text );
1113 if ( $img !== false ) {
1119 # Set linktype for CSS - if URL==text, link is essentially free
1120 $linktype = ($text == $url) ?
'free' : 'text';
1122 # No link text, e.g. [http://domain.tld/some.link]
1123 if ( $text == '' ) {
1124 # Autonumber if allowed. See bug #5918
1125 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1126 $text = '[' . ++
$this->mAutonumber
. ']';
1127 $linktype = 'autonumber';
1129 # Otherwise just use the URL
1130 $text = htmlspecialchars( $url );
1134 # Have link text, e.g. [http://domain.tld/some.link text]s
1136 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1139 $text = $wgContLang->markNoConversion($text);
1141 # Normalize any HTML entities in input. They will be
1142 # re-escaped by makeExternalLink().
1143 $url = Sanitizer
::decodeCharReferences( $url );
1145 # Process the trail (i.e. everything after this link up until start of the next link),
1146 # replacing any non-bracketed links
1147 $trail = $this->replaceFreeExternalLinks( $trail );
1149 # Use the encoded URL
1150 # This means that users can paste URLs directly into the text
1151 # Funny characters like ö aren't valid in URLs anyway
1152 # This was changed in August 2004
1153 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1155 # Register link in the output object.
1156 # Replace unnecessary URL escape codes with the referenced character
1157 # This prevents spammers from hiding links from the filters
1158 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1159 $this->mOutput
->addExternalLink( $pasteurized );
1162 wfProfileOut( $fname );
1167 * Replace anything that looks like a URL with a link
1170 function replaceFreeExternalLinks( $text ) {
1172 $fname = 'Parser::replaceFreeExternalLinks';
1173 wfProfileIn( $fname );
1175 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1176 $s = array_shift( $bits );
1179 $sk =& $this->mOptions
->getSkin();
1181 while ( $i < count( $bits ) ){
1182 $protocol = $bits[$i++
];
1183 $remainder = $bits[$i++
];
1185 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1186 # Found some characters after the protocol that look promising
1187 $url = $protocol . $m[1];
1190 # special case: handle urls as url args:
1191 # http://www.example.com/foo?=http://www.example.com/bar
1192 if(strlen($trail) == 0 &&
1194 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1195 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1198 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1203 # The characters '<' and '>' (which were escaped by
1204 # removeHTMLtags()) should not be included in
1205 # URLs, per RFC 2396.
1206 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1207 $trail = substr($url, $m2[0][1]) . $trail;
1208 $url = substr($url, 0, $m2[0][1]);
1211 # Move trailing punctuation to $trail
1213 # If there is no left bracket, then consider right brackets fair game too
1214 if ( strpos( $url, '(' ) === false ) {
1218 $numSepChars = strspn( strrev( $url ), $sep );
1219 if ( $numSepChars ) {
1220 $trail = substr( $url, -$numSepChars ) . $trail;
1221 $url = substr( $url, 0, -$numSepChars );
1224 # Normalize any HTML entities in input. They will be
1225 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1226 $url = Sanitizer
::decodeCharReferences( $url );
1228 # Is this an external image?
1229 $text = $this->maybeMakeExternalImage( $url );
1230 if ( $text === false ) {
1231 # Not an image, make a link
1232 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1233 # Register it in the output object...
1234 # Replace unnecessary URL escape codes with their equivalent characters
1235 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1236 $this->mOutput
->addExternalLink( $pasteurized );
1238 $s .= $text . $trail;
1240 $s .= $protocol . $remainder;
1243 wfProfileOut( $fname );
1248 * Replace unusual URL escape codes with their equivalent characters
1252 * @fixme This can merge genuinely required bits in the path or query string,
1253 * breaking legit URLs. A proper fix would treat the various parts of
1254 * the URL differently; as a workaround, just use the output for
1255 * statistical records, not for actual linking/output.
1257 function replaceUnusualEscapes( $url ) {
1258 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1259 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1263 * Callback function used in replaceUnusualEscapes().
1264 * Replaces unusual URL escape codes with their equivalent character
1268 function replaceUnusualEscapesCallback( $matches ) {
1269 $char = urldecode( $matches[0] );
1270 $ord = ord( $char );
1271 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1272 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1273 // No, shouldn't be escaped
1276 // Yes, leave it escaped
1282 * make an image if it's allowed, either through the global
1283 * option or through the exception
1286 function maybeMakeExternalImage( $url ) {
1287 $sk =& $this->mOptions
->getSkin();
1288 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1289 $imagesexception = !empty($imagesfrom);
1291 if ( $this->mOptions
->getAllowExternalImages()
1292 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1293 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1295 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1302 * Process [[ ]] wikilinks
1306 function replaceInternalLinks( $s ) {
1308 static $fname = 'Parser::replaceInternalLinks' ;
1310 wfProfileIn( $fname );
1312 wfProfileIn( $fname.'-setup' );
1314 # the % is needed to support urlencoded titles as well
1315 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1317 $sk =& $this->mOptions
->getSkin();
1319 #split the entire text string on occurences of [[
1320 $a = explode( '[[', ' ' . $s );
1321 #get the first element (all text up to first [[), and remove the space we added
1322 $s = array_shift( $a );
1323 $s = substr( $s, 1 );
1325 # Match a link having the form [[namespace:link|alternate]]trail
1327 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1328 # Match cases where there is no "]]", which might still be images
1329 static $e1_img = FALSE;
1330 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1331 # Match the end of a line for a word that's not followed by whitespace,
1332 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1333 $e2 = wfMsgForContent( 'linkprefix' );
1335 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1337 if( is_null( $this->mTitle
) ) {
1338 wfDebugDieBacktrace( 'nooo' );
1340 $nottalk = !$this->mTitle
->isTalkPage();
1342 if ( $useLinkPrefixExtension ) {
1343 if ( preg_match( $e2, $s, $m ) ) {
1344 $first_prefix = $m[2];
1346 $first_prefix = false;
1352 $selflink = $this->mTitle
->getPrefixedText();
1353 wfProfileOut( $fname.'-setup' );
1355 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1356 $useSubpages = $this->areSubpagesAllowed();
1358 # Loop for each link
1359 for ($k = 0; isset( $a[$k] ); $k++
) {
1361 if ( $useLinkPrefixExtension ) {
1362 wfProfileIn( $fname.'-prefixhandling' );
1363 if ( preg_match( $e2, $s, $m ) ) {
1371 $prefix = $first_prefix;
1372 $first_prefix = false;
1374 wfProfileOut( $fname.'-prefixhandling' );
1377 $might_be_img = false;
1379 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1381 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1382 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1383 # the real problem is with the $e1 regex
1386 # Still some problems for cases where the ] is meant to be outside punctuation,
1387 # and no image is in sight. See bug 2095.
1390 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1391 strpos($text, '[') !== false
1394 $text .= ']'; # so that replaceExternalLinks($text) works later
1397 # fix up urlencoded title texts
1398 if(preg_match('/%/', $m[1] ))
1399 # Should anchors '#' also be rejected?
1400 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1402 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1403 $might_be_img = true;
1405 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1407 } else { # Invalid form; output directly
1408 $s .= $prefix . '[[' . $line ;
1412 # Don't allow internal links to pages containing
1413 # PROTO: where PROTO is a valid URL protocol; these
1414 # should be external links.
1415 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1416 $s .= $prefix . '[[' . $line ;
1420 # Make subpage if necessary
1421 if( $useSubpages ) {
1422 $link = $this->maybeDoSubpageLink( $m[1], $text );
1427 $noforce = (substr($m[1], 0, 1) != ':');
1429 # Strip off leading ':'
1430 $link = substr($link, 1);
1433 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1435 $s .= $prefix . '[[' . $line;
1439 #check other language variants of the link
1440 #if the article does not exist
1441 if( $checkVariantLink
1442 && $nt->getArticleID() == 0 ) {
1443 $wgContLang->findVariantLink($link, $nt);
1446 $ns = $nt->getNamespace();
1447 $iw = $nt->getInterWiki();
1449 if ($might_be_img) { # if this is actually an invalid link
1450 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1452 while (isset ($a[$k+
1]) ) {
1453 #look at the next 'line' to see if we can close it there
1454 $spliced = array_splice( $a, $k +
1, 1 );
1455 $next_line = array_shift( $spliced );
1456 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1457 # the first ]] closes the inner link, the second the image
1459 $text .= '[[' . $m[1];
1462 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1463 #if there's exactly one ]] that's fine, we'll keep looking
1464 $text .= '[[' . $m[0];
1466 #if $next_line is invalid too, we need look no further
1467 $text .= '[[' . $next_line;
1472 # we couldn't find the end of this imageLink, so output it raw
1473 #but don't ignore what might be perfectly normal links in the text we've examined
1474 $text = $this->replaceInternalLinks($text);
1475 $s .= $prefix . '[[' . $link . '|' . $text;
1476 # note: no $trail, because without an end, there *is* no trail
1479 } else { #it's not an image, so output it raw
1480 $s .= $prefix . '[[' . $link . '|' . $text;
1481 # note: no $trail, because without an end, there *is* no trail
1486 $wasblank = ( '' == $text );
1487 if( $wasblank ) $text = $link;
1490 # Link not escaped by : , create the various objects
1494 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1495 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1496 $s = rtrim($s . "\n");
1497 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1501 if ( $ns == NS_IMAGE
) {
1502 wfProfileIn( "$fname-image" );
1503 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1504 # recursively parse links inside the image caption
1505 # actually, this will parse them in any other parameters, too,
1506 # but it might be hard to fix that, and it doesn't matter ATM
1507 $text = $this->replaceExternalLinks($text);
1508 $text = $this->replaceInternalLinks($text);
1510 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1511 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1512 $this->mOutput
->addImage( $nt->getDBkey() );
1514 wfProfileOut( "$fname-image" );
1517 wfProfileOut( "$fname-image" );
1521 if ( $ns == NS_CATEGORY
) {
1522 wfProfileIn( "$fname-category" );
1523 $s = rtrim($s . "\n"); # bug 87
1526 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1527 $sortkey = $this->mTitle
->getText();
1529 $sortkey = $this->mTitle
->getPrefixedText();
1534 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1535 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1536 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1539 * Strip the whitespace Category links produce, see bug 87
1540 * @todo We might want to use trim($tmp, "\n") here.
1542 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1544 wfProfileOut( "$fname-category" );
1549 if( ( $nt->getPrefixedText() === $selflink ) &&
1550 ( $nt->getFragment() === '' ) ) {
1551 # Self-links are handled specially; generally de-link and change to bold.
1552 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1556 # Special and Media are pseudo-namespaces; no pages actually exist in them
1557 if( $ns == NS_MEDIA
) {
1558 $link = $sk->makeMediaLinkObj( $nt, $text );
1559 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1560 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1561 $this->mOutput
->addImage( $nt->getDBkey() );
1563 } elseif( $ns == NS_SPECIAL
) {
1564 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1566 } elseif( $ns == NS_IMAGE
) {
1567 $img = Image
::newFromTitle( $nt );
1568 if( $img->exists() ) {
1569 // Force a blue link if the file exists; may be a remote
1570 // upload on the shared repository, and we want to see its
1571 // auto-generated page.
1572 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1576 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1578 wfProfileOut( $fname );
1583 * Make a link placeholder. The text returned can be later resolved to a real link with
1584 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1585 * parsing of interwiki links, and secondly to allow all extistence checks and
1586 * article length checks (for stub links) to be bundled into a single query.
1589 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1590 if ( ! is_object($nt) ) {
1592 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1594 # Separate the link trail from the rest of the link
1595 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1597 if ( $nt->isExternal() ) {
1598 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1599 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1600 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1602 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1603 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1604 $this->mLinkHolders
['queries'][] = $query;
1605 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1606 $this->mLinkHolders
['titles'][] = $nt;
1608 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1615 * Render a forced-blue link inline; protect against double expansion of
1616 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1617 * Since this little disaster has to split off the trail text to avoid
1618 * breaking URLs in the following text without breaking trails on the
1619 * wiki links, it's been made into a horrible function.
1622 * @param string $text
1623 * @param string $query
1624 * @param string $trail
1625 * @param string $prefix
1626 * @return string HTML-wikitext mix oh yuck
1628 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1629 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1630 $sk =& $this->mOptions
->getSkin();
1631 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1632 return $this->armorLinks( $link ) . $trail;
1636 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1637 * going to go through further parsing steps before inline URL expansion.
1639 * In particular this is important when using action=render, which causes
1640 * full URLs to be included.
1642 * Oh man I hate our multi-layer parser!
1644 * @param string more-or-less HTML
1645 * @return string less-or-more HTML with NOPARSE bits
1647 function armorLinks( $text ) {
1648 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1649 "{$this->mUniqPrefix}NOPARSE$1", $text );
1653 * Return true if subpage links should be expanded on this page.
1656 function areSubpagesAllowed() {
1657 # Some namespaces don't allow subpages
1658 global $wgNamespacesWithSubpages;
1659 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1663 * Handle link to subpage if necessary
1664 * @param string $target the source of the link
1665 * @param string &$text the link text, modified as necessary
1666 * @return string the full name of the link
1669 function maybeDoSubpageLink($target, &$text) {
1672 # :Foobar -- override special treatment of prefix (images, language links)
1673 # /Foobar -- convert to CurrentPage/Foobar
1674 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1675 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1676 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1678 $fname = 'Parser::maybeDoSubpageLink';
1679 wfProfileIn( $fname );
1680 $ret = $target; # default return value is no change
1682 # Some namespaces don't allow subpages,
1683 # so only perform processing if subpages are allowed
1684 if( $this->areSubpagesAllowed() ) {
1685 # Look at the first character
1686 if( $target != '' && $target{0} == '/' ) {
1687 # / at end means we don't want the slash to be shown
1688 if( substr( $target, -1, 1 ) == '/' ) {
1689 $target = substr( $target, 1, -1 );
1692 $noslash = substr( $target, 1 );
1695 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1696 if( '' === $text ) {
1698 } # this might be changed for ugliness reasons
1700 # check for .. subpage backlinks
1702 $nodotdot = $target;
1703 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1705 $nodotdot = substr( $nodotdot, 3 );
1707 if($dotdotcount > 0) {
1708 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1709 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1710 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1711 # / at the end means don't show full path
1712 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1713 $nodotdot = substr( $nodotdot, 0, -1 );
1714 if( '' === $text ) {
1718 $nodotdot = trim( $nodotdot );
1719 if( $nodotdot != '' ) {
1720 $ret .= '/' . $nodotdot;
1727 wfProfileOut( $fname );
1732 * Used by doBlockLevels()
1735 /* private */ function closeParagraph() {
1737 if ( '' != $this->mLastSection
) {
1738 $result = '</' . $this->mLastSection
. ">\n";
1740 $this->mInPre
= false;
1741 $this->mLastSection
= '';
1744 # getCommon() returns the length of the longest common substring
1745 # of both arguments, starting at the beginning of both.
1747 /* private */ function getCommon( $st1, $st2 ) {
1748 $fl = strlen( $st1 );
1749 $shorter = strlen( $st2 );
1750 if ( $fl < $shorter ) { $shorter = $fl; }
1752 for ( $i = 0; $i < $shorter; ++
$i ) {
1753 if ( $st1{$i} != $st2{$i} ) { break; }
1757 # These next three functions open, continue, and close the list
1758 # element appropriate to the prefix character passed into them.
1760 /* private */ function openList( $char ) {
1761 $result = $this->closeParagraph();
1763 if ( '*' == $char ) { $result .= '<ul><li>'; }
1764 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1765 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1766 else if ( ';' == $char ) {
1767 $result .= '<dl><dt>';
1768 $this->mDTopen
= true;
1770 else { $result = '<!-- ERR 1 -->'; }
1775 /* private */ function nextItem( $char ) {
1776 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1777 else if ( ':' == $char ||
';' == $char ) {
1779 if ( $this->mDTopen
) { $close = '</dt>'; }
1780 if ( ';' == $char ) {
1781 $this->mDTopen
= true;
1782 return $close . '<dt>';
1784 $this->mDTopen
= false;
1785 return $close . '<dd>';
1788 return '<!-- ERR 2 -->';
1791 /* private */ function closeList( $char ) {
1792 if ( '*' == $char ) { $text = '</li></ul>'; }
1793 else if ( '#' == $char ) { $text = '</li></ol>'; }
1794 else if ( ':' == $char ) {
1795 if ( $this->mDTopen
) {
1796 $this->mDTopen
= false;
1797 $text = '</dt></dl>';
1799 $text = '</dd></dl>';
1802 else { return '<!-- ERR 3 -->'; }
1808 * Make lists from lines starting with ':', '*', '#', etc.
1811 * @return string the lists rendered as HTML
1813 function doBlockLevels( $text, $linestart ) {
1814 $fname = 'Parser::doBlockLevels';
1815 wfProfileIn( $fname );
1817 # Parsing through the text line by line. The main thing
1818 # happening here is handling of block-level elements p, pre,
1819 # and making lists from lines starting with * # : etc.
1821 $textLines = explode( "\n", $text );
1823 $lastPrefix = $output = '';
1824 $this->mDTopen
= $inBlockElem = false;
1826 $paragraphStack = false;
1828 if ( !$linestart ) {
1829 $output .= array_shift( $textLines );
1831 foreach ( $textLines as $oLine ) {
1832 $lastPrefixLength = strlen( $lastPrefix );
1833 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1834 $preOpenMatch = preg_match('/<pre/i', $oLine );
1835 if ( !$this->mInPre
) {
1836 # Multiple prefixes may abut each other for nested lists.
1837 $prefixLength = strspn( $oLine, '*#:;' );
1838 $pref = substr( $oLine, 0, $prefixLength );
1841 $pref2 = str_replace( ';', ':', $pref );
1842 $t = substr( $oLine, $prefixLength );
1843 $this->mInPre
= !empty($preOpenMatch);
1845 # Don't interpret any other prefixes in preformatted text
1847 $pref = $pref2 = '';
1852 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1853 # Same as the last item, so no need to deal with nesting or opening stuff
1854 $output .= $this->nextItem( substr( $pref, -1 ) );
1855 $paragraphStack = false;
1857 if ( substr( $pref, -1 ) == ';') {
1858 # The one nasty exception: definition lists work like this:
1859 # ; title : definition text
1860 # So we check for : in the remainder text to split up the
1861 # title and definition, without b0rking links.
1863 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1865 $output .= $term . $this->nextItem( ':' );
1868 } elseif( $prefixLength ||
$lastPrefixLength ) {
1869 # Either open or close a level...
1870 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1871 $paragraphStack = false;
1873 while( $commonPrefixLength < $lastPrefixLength ) {
1874 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1875 --$lastPrefixLength;
1877 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1878 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1880 while ( $prefixLength > $commonPrefixLength ) {
1881 $char = substr( $pref, $commonPrefixLength, 1 );
1882 $output .= $this->openList( $char );
1884 if ( ';' == $char ) {
1885 # FIXME: This is dupe of code above
1886 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1888 $output .= $term . $this->nextItem( ':' );
1891 ++
$commonPrefixLength;
1893 $lastPrefix = $pref2;
1895 if( 0 == $prefixLength ) {
1896 wfProfileIn( "$fname-paragraph" );
1897 # No prefix (not in list)--go to paragraph mode
1898 // XXX: use a stack for nestable elements like span, table and div
1899 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1900 $closematch = preg_match(
1901 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1902 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol)/iS', $t );
1903 if ( $openmatch or $closematch ) {
1904 $paragraphStack = false;
1905 #Â TODO bug 5718: paragraph closed
1906 $output .= $this->closeParagraph();
1907 if ( $preOpenMatch and !$preCloseMatch ) {
1908 $this->mInPre
= true;
1910 if ( $closematch ) {
1911 $inBlockElem = false;
1913 $inBlockElem = true;
1915 } else if ( !$inBlockElem && !$this->mInPre
) {
1916 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1918 if ($this->mLastSection
!= 'pre') {
1919 $paragraphStack = false;
1920 $output .= $this->closeParagraph().'<pre>';
1921 $this->mLastSection
= 'pre';
1923 $t = substr( $t, 1 );
1926 if ( '' == trim($t) ) {
1927 if ( $paragraphStack ) {
1928 $output .= $paragraphStack.'<br />';
1929 $paragraphStack = false;
1930 $this->mLastSection
= 'p';
1932 if ($this->mLastSection
!= 'p' ) {
1933 $output .= $this->closeParagraph();
1934 $this->mLastSection
= '';
1935 $paragraphStack = '<p>';
1937 $paragraphStack = '</p><p>';
1941 if ( $paragraphStack ) {
1942 $output .= $paragraphStack;
1943 $paragraphStack = false;
1944 $this->mLastSection
= 'p';
1945 } else if ($this->mLastSection
!= 'p') {
1946 $output .= $this->closeParagraph().'<p>';
1947 $this->mLastSection
= 'p';
1952 wfProfileOut( "$fname-paragraph" );
1954 // somewhere above we forget to get out of pre block (bug 785)
1955 if($preCloseMatch && $this->mInPre
) {
1956 $this->mInPre
= false;
1958 if ($paragraphStack === false) {
1962 while ( $prefixLength ) {
1963 $output .= $this->closeList( $pref2{$prefixLength-1} );
1966 if ( '' != $this->mLastSection
) {
1967 $output .= '</' . $this->mLastSection
. '>';
1968 $this->mLastSection
= '';
1971 wfProfileOut( $fname );
1976 * Split up a string on ':', ignoring any occurences inside tags
1977 * to prevent illegal overlapping.
1978 * @param string $str the string to split
1979 * @param string &$before set to everything before the ':'
1980 * @param string &$after set to everything after the ':'
1981 * return string the position of the ':', or false if none found
1983 function findColonNoLinks($str, &$before, &$after) {
1984 $fname = 'Parser::findColonNoLinks';
1985 wfProfileIn( $fname );
1987 $pos = strpos( $str, ':' );
1988 if( $pos === false ) {
1990 wfProfileOut( $fname );
1994 $lt = strpos( $str, '<' );
1995 if( $lt === false ||
$lt > $pos ) {
1996 // Easy; no tag nesting to worry about
1997 $before = substr( $str, 0, $pos );
1998 $after = substr( $str, $pos+
1 );
1999 wfProfileOut( $fname );
2003 // Ugly state machine to walk through avoiding tags.
2004 $state = MW_COLON_STATE_TEXT
;
2006 $len = strlen( $str );
2007 for( $i = 0; $i < $len; $i++
) {
2011 // (Using the number is a performance hack for common cases)
2012 case 0: // MW_COLON_STATE_TEXT:
2015 // Could be either a <start> tag or an </end> tag
2016 $state = MW_COLON_STATE_TAGSTART
;
2021 $before = substr( $str, 0, $i );
2022 $after = substr( $str, $i +
1 );
2023 wfProfileOut( $fname );
2026 // Embedded in a tag; don't break it.
2029 // Skip ahead looking for something interesting
2030 $colon = strpos( $str, ':', $i );
2031 if( $colon === false ) {
2032 // Nothing else interesting
2033 wfProfileOut( $fname );
2036 $lt = strpos( $str, '<', $i );
2037 if( $stack === 0 ) {
2038 if( $lt === false ||
$colon < $lt ) {
2040 $before = substr( $str, 0, $colon );
2041 $after = substr( $str, $colon +
1 );
2042 wfProfileOut( $fname );
2046 if( $lt === false ) {
2047 // Nothing else interesting to find; abort!
2048 // We're nested, but there's no close tags left. Abort!
2051 // Skip ahead to next tag start
2053 $state = MW_COLON_STATE_TAGSTART
;
2056 case 1: // MW_COLON_STATE_TAG:
2061 $state = MW_COLON_STATE_TEXT
;
2064 // Slash may be followed by >?
2065 $state = MW_COLON_STATE_TAGSLASH
;
2071 case 2: // MW_COLON_STATE_TAGSTART:
2074 $state = MW_COLON_STATE_CLOSETAG
;
2077 $state = MW_COLON_STATE_COMMENT
;
2080 // Illegal early close? This shouldn't happen D:
2081 $state = MW_COLON_STATE_TEXT
;
2084 $state = MW_COLON_STATE_TAG
;
2087 case 3: // MW_COLON_STATE_CLOSETAG:
2092 wfDebug( "Invalid input in $fname; too many close tags\n" );
2093 wfProfileOut( $fname );
2096 $state = MW_COLON_STATE_TEXT
;
2099 case MW_COLON_STATE_TAGSLASH
:
2101 // Yes, a self-closed tag <blah/>
2102 $state = MW_COLON_STATE_TEXT
;
2104 // Probably we're jumping the gun, and this is an attribute
2105 $state = MW_COLON_STATE_TAG
;
2108 case 5: // MW_COLON_STATE_COMMENT:
2110 $state = MW_COLON_STATE_COMMENTDASH
;
2113 case MW_COLON_STATE_COMMENTDASH
:
2115 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2117 $state = MW_COLON_STATE_COMMENT
;
2120 case MW_COLON_STATE_COMMENTDASHDASH
:
2122 $state = MW_COLON_STATE_TEXT
;
2124 $state = MW_COLON_STATE_COMMENT
;
2128 wfDebugDieBacktrace( "State machine error in $fname" );
2132 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2135 wfProfileOut( $fname );
2140 * Return value of a magic variable (like PAGENAME)
2144 function getVariableValue( $index ) {
2145 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2148 * Some of these require message or data lookups and can be
2149 * expensive to check many times.
2151 static $varCache = array();
2152 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2153 if ( isset( $varCache[$index] ) )
2154 return $varCache[$index];
2157 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2160 case MAG_CURRENTMONTH
:
2161 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2162 case MAG_CURRENTMONTHNAME
:
2163 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2164 case MAG_CURRENTMONTHNAMEGEN
:
2165 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2166 case MAG_CURRENTMONTHABBREV
:
2167 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2168 case MAG_CURRENTDAY
:
2169 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2170 case MAG_CURRENTDAY2
:
2171 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2173 return $this->mTitle
->getText();
2175 return $this->mTitle
->getPartialURL();
2176 case MAG_FULLPAGENAME
:
2177 return $this->mTitle
->getPrefixedText();
2178 case MAG_FULLPAGENAMEE
:
2179 return $this->mTitle
->getPrefixedURL();
2180 case MAG_SUBPAGENAME
:
2181 return $this->mTitle
->getSubpageText();
2182 case MAG_SUBPAGENAMEE
:
2183 return $this->mTitle
->getSubpageUrlForm();
2184 case MAG_BASEPAGENAME
:
2185 return $this->mTitle
->getBaseText();
2186 case MAG_BASEPAGENAMEE
:
2187 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2188 case MAG_TALKPAGENAME
:
2189 if( $this->mTitle
->canTalk() ) {
2190 $talkPage = $this->mTitle
->getTalkPage();
2191 return $talkPage->getPrefixedText();
2195 case MAG_TALKPAGENAMEE
:
2196 if( $this->mTitle
->canTalk() ) {
2197 $talkPage = $this->mTitle
->getTalkPage();
2198 return $talkPage->getPrefixedUrl();
2202 case MAG_SUBJECTPAGENAME
:
2203 $subjPage = $this->mTitle
->getSubjectPage();
2204 return $subjPage->getPrefixedText();
2205 case MAG_SUBJECTPAGENAMEE
:
2206 $subjPage = $this->mTitle
->getSubjectPage();
2207 return $subjPage->getPrefixedUrl();
2208 case MAG_REVISIONID
:
2209 return $this->mRevisionId
;
2211 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2212 case MAG_NAMESPACEE
:
2213 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2215 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2216 case MAG_TALKSPACEE
:
2217 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2218 case MAG_SUBJECTSPACE
:
2219 return $this->mTitle
->getSubjectNsText();
2220 case MAG_SUBJECTSPACEE
:
2221 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2222 case MAG_CURRENTDAYNAME
:
2223 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2224 case MAG_CURRENTYEAR
:
2225 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2226 case MAG_CURRENTTIME
:
2227 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2228 case MAG_CURRENTWEEK
:
2229 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2230 // int to remove the padding
2231 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2232 case MAG_CURRENTDOW
:
2233 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2234 case MAG_NUMBEROFARTICLES
:
2235 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2236 case MAG_NUMBEROFFILES
:
2237 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2238 case MAG_NUMBEROFUSERS
:
2239 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2240 case MAG_NUMBEROFPAGES
:
2241 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2242 case MAG_CURRENTTIMESTAMP
:
2243 return $varCache[$index] = wfTimestampNow();
2244 case MAG_CURRENTVERSION
:
2251 case MAG_SERVERNAME
:
2252 return $wgServerName;
2253 case MAG_SCRIPTPATH
:
2254 return $wgScriptPath;
2255 case MAG_DIRECTIONMARK
:
2256 return $wgContLang->getDirMark();
2259 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2267 * initialise the magic variables (like CURRENTMONTHNAME)
2271 function initialiseVariables() {
2272 $fname = 'Parser::initialiseVariables';
2273 wfProfileIn( $fname );
2274 global $wgVariableIDs;
2275 $this->mVariables
= array();
2276 foreach ( $wgVariableIDs as $id ) {
2277 $mw =& MagicWord
::get( $id );
2278 $mw->addToArray( $this->mVariables
, $id );
2280 wfProfileOut( $fname );
2284 * parse any parentheses in format ((title|part|part))
2285 * and call callbacks to get a replacement text for any found piece
2287 * @param string $text The text to parse
2288 * @param array $callbacks rules in form:
2289 * '{' => array( # opening parentheses
2290 * 'end' => '}', # closing parentheses
2291 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2292 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2297 function replace_callback ($text, $callbacks) {
2298 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2299 $lastOpeningBrace = -1; # last not closed parentheses
2301 for ($i = 0; $i < strlen($text); $i++
) {
2302 # check for any opening brace
2305 foreach ($callbacks as $key => $value) {
2306 $pos = strpos ($text, $key, $i);
2307 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2313 if ($lastOpeningBrace >= 0) {
2314 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2316 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2321 $pos = strpos ($text, '|', $i);
2323 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2334 # found openning brace, lets add it to parentheses stack
2335 if (null != $rule) {
2336 $piece = array('brace' => $text[$i],
2337 'braceEnd' => $rule['end'],
2342 # count openning brace characters
2343 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2348 $piece['startAt'] = $i+
1;
2349 $piece['partStart'] = $i+
1;
2351 # we need to add to stack only if openning brace count is enough for any given rule
2352 foreach ($rule['cb'] as $cnt => $fn) {
2353 if ($piece['count'] >= $cnt) {
2354 $lastOpeningBrace ++
;
2355 $openingBraceStack[$lastOpeningBrace] = $piece;
2362 else if ($lastOpeningBrace >= 0) {
2363 # first check if it is a closing brace
2364 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2365 # lets check if it is enough characters for closing brace
2367 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2370 # if there are more closing parentheses than opening ones, we parse less
2371 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2372 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2374 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2376 $matchingCallback = null;
2377 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2378 if ($count >= $cnt && $matchingCount < $cnt) {
2379 $matchingCount = $cnt;
2380 $matchingCallback = $fn;
2384 if ($matchingCount == 0) {
2389 # lets set a title or last part (if '|' was found)
2390 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2391 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2393 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2395 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2396 $pieceEnd = $i +
$matchingCount;
2398 if( is_callable( $matchingCallback ) ) {
2400 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2401 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2402 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2403 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2405 # finally we can call a user callback and replace piece of text
2406 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2407 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2408 $i = $pieceStart +
strlen($replaceWith) - 1;
2411 # null value for callback means that parentheses should be parsed, but not replaced
2412 $i +
= $matchingCount - 1;
2415 # reset last openning parentheses, but keep it in case there are unused characters
2416 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2417 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2418 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2421 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2422 $openingBraceStack[$lastOpeningBrace--] = null;
2424 if ($matchingCount < $piece['count']) {
2425 $piece['count'] -= $matchingCount;
2426 $piece['startAt'] -= $matchingCount;
2427 $piece['partStart'] = $piece['startAt'];
2428 # do we still qualify for any callback with remaining count?
2429 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2430 if ($piece['count'] >= $cnt) {
2431 $lastOpeningBrace ++
;
2432 $openingBraceStack[$lastOpeningBrace] = $piece;
2440 # lets set a title if it is a first separator, or next part otherwise
2441 if ($text[$i] == '|') {
2442 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2443 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2444 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2447 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2449 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2458 * Replace magic variables, templates, and template arguments
2459 * with the appropriate text. Templates are substituted recursively,
2460 * taking care to avoid infinite loops.
2462 * Note that the substitution depends on value of $mOutputType:
2463 * OT_WIKI: only {{subst:}} templates
2464 * OT_MSG: only magic variables
2465 * OT_HTML: all templates and magic variables
2467 * @param string $tex The text to transform
2468 * @param array $args Key-value pairs representing template parameters to substitute
2469 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2472 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2473 # Prevent too big inclusions
2474 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2478 $fname = 'Parser::replaceVariables';
2479 wfProfileIn( $fname );
2481 # This function is called recursively. To keep track of arguments we need a stack:
2482 array_push( $this->mArgStack
, $args );
2484 $braceCallbacks = array();
2486 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2488 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2489 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2491 $callbacks = array();
2492 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2493 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2494 $text = $this->replace_callback ($text, $callbacks);
2496 array_pop( $this->mArgStack
);
2498 wfProfileOut( $fname );
2503 * Replace magic variables
2506 function variableSubstitution( $matches ) {
2507 $fname = 'Parser::variableSubstitution';
2508 $varname = $matches[1];
2509 wfProfileIn( $fname );
2510 if ( !$this->mVariables
) {
2511 $this->initialiseVariables();
2514 if ( $this->mOutputType
== OT_WIKI
) {
2515 # Do only magic variables prefixed by SUBST
2516 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2517 if (!$mwSubst->matchStartAndRemove( $varname ))
2519 # Note that if we don't substitute the variable below,
2520 # we don't remove the {{subst:}} magic word, in case
2521 # it is a template rather than a magic variable.
2523 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2524 $id = $this->mVariables
[$varname];
2525 $text = $this->getVariableValue( $id );
2526 $this->mOutput
->mContainsOldMagic
= true;
2528 $text = $matches[0];
2530 wfProfileOut( $fname );
2534 # Split template arguments
2535 function getTemplateArgs( $argsString ) {
2536 if ( $argsString === '' ) {
2540 $args = explode( '|', substr( $argsString, 1 ) );
2542 # If any of the arguments contains a '[[' but no ']]', it needs to be
2543 # merged with the next arg because the '|' character between belongs
2544 # to the link syntax and not the template parameter syntax.
2545 $argc = count($args);
2547 for ( $i = 0; $i < $argc-1; $i++
) {
2548 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2549 $args[$i] .= '|'.$args[$i+
1];
2550 array_splice($args, $i+
1, 1);
2560 * Return the text of a template, after recursively
2561 * replacing any variables or templates within the template.
2563 * @param array $piece The parts of the template
2564 * $piece['text']: matched text
2565 * $piece['title']: the title, i.e. the part before the |
2566 * $piece['parts']: the parameter array
2567 * @return string the text of the template
2570 function braceSubstitution( $piece ) {
2571 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2572 $fname = 'Parser::braceSubstitution';
2573 wfProfileIn( $fname );
2576 $found = false; # $text has been filled
2577 $nowiki = false; # wiki markup in $text should be escaped
2578 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2579 $noargs = false; # Don't replace triple-brace arguments in $text
2580 $replaceHeadings = false; # Make the edit section links go to the template not the article
2581 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2582 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2584 # Title object, where $text came from
2589 # $part1 is the bit before the first |, and must contain only title characters
2590 # $args is a list of arguments, starting from index 0, not including $part1
2592 $part1 = $piece['title'];
2593 # If the third subpattern matched anything, it will start with |
2595 if (null == $piece['parts']) {
2596 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2597 if ($replaceWith != $piece['text']) {
2598 $text = $replaceWith;
2605 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2606 $argc = count( $args );
2610 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2611 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2612 # One of two possibilities is true:
2613 # 1) Found SUBST but not in the PST phase
2614 # 2) Didn't find SUBST and in the PST phase
2615 # In either case, return without further processing
2616 $text = $piece['text'];
2623 # MSG, MSGNW, INT and RAW
2626 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2627 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2630 # Remove obsolete MSG:
2631 $mwMsg =& MagicWord
::get( MAG_MSG
);
2632 $mwMsg->matchStartAndRemove( $part1 );
2636 $mwRaw =& MagicWord
::get( MAG_RAW
);
2637 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2638 $forceRawInterwiki = true;
2641 # Check if it is an internal message
2642 $mwInt =& MagicWord
::get( MAG_INT
);
2643 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2644 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2645 $text = $linestart . wfMsgReal( $part1, $args, true );
2653 # Check for NS: (namespace expansion)
2654 $mwNs = MagicWord
::get( MAG_NS
);
2655 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2656 if ( intval( $part1 ) ||
$part1 == "0" ) {
2657 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2660 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2661 if ( !is_null( $index ) ) {
2662 $text = $linestart . $wgContLang->getNsText( $index );
2671 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2672 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2673 $text = $linestart . urlencode( $part1 );
2678 # LCFIRST, UCFIRST, LC and UC
2680 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2681 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2682 $lc =& MagicWord
::get( MAG_LC
);
2683 $uc =& MagicWord
::get( MAG_UC
);
2684 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2685 $text = $linestart . $wgContLang->lcfirst( $part1 );
2687 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2688 $text = $linestart . $wgContLang->ucfirst( $part1 );
2690 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2691 $text = $linestart . $wgContLang->lc( $part1 );
2693 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2694 $text = $linestart . $wgContLang->uc( $part1 );
2699 # LOCALURL and FULLURL
2701 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2702 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2703 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2704 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2707 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2708 $func = 'getLocalURL';
2709 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2710 $func = 'escapeLocalURL';
2711 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2712 $func = 'getFullURL';
2713 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2714 $func = 'escapeFullURL';
2719 if ( $func !== false ) {
2720 $title = Title
::newFromText( $part1 );
2721 # Due to order of execution of a lot of bits, the values might be encoded
2722 # before arriving here; if that's true, then the title can't be created
2723 # and the variable will fail. If we can't get a decent title from the first
2724 # attempt, url-decode and try for a second.
2725 if( is_null( $title ) )
2726 $title = Title
::newFromUrl( urldecode( $part1 ) );
2727 if ( !is_null( $title ) ) {
2729 $text = $linestart . $title->$func( $args[0] );
2731 $text = $linestart . $title->$func();
2738 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2740 if ( !$found && $argc == 1 ) {
2741 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2742 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2743 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2749 if ( !$found && $argc >= 2 ) {
2750 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2751 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2752 if ($argc==2) {$args[2]=$args[1];}
2753 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2759 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2760 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2761 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2763 # Set title in parser output object
2765 $parserOptions = new ParserOptions
;
2766 $local_parser = new Parser ();
2767 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2768 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2771 $t = $this->mTitle
->getPrefixedText();
2772 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2778 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2780 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2781 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2782 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2783 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2784 foreach( $mwWordsToCheck as $word => $func ) {
2785 $mwCurrentWord =& MagicWord
::get( $word );
2786 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2787 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2788 if( $mwRawSuffix->match( $args[0] ) ) {
2789 # Raw and unformatted
2790 $text = $linestart . call_user_func( $func );
2792 # Formatted according to the content default
2793 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2802 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2803 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2804 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2805 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2811 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2812 $colonPos = strpos( $part1, ':' );
2813 if ( $colonPos !== false ) {
2814 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2815 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2816 $funcArgs = array_map( 'trim', $args );
2817 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2818 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2821 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2825 if ( is_array( $result ) ) {
2826 $text = $linestart . $result[0];
2827 unset( $result[0] );
2829 // Extract flags into the local scope
2830 // This allows callers to set flags such as nowiki, noparse, found, etc.
2833 $text = $linestart . $result;
2839 # Template table test
2841 # Did we encounter this template already? If yes, it is in the cache
2842 # and we need to check for loops.
2843 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2846 # Infinite loop test
2847 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2851 $text = $linestart .
2852 '{{' . $part1 . '}}' .
2853 '<!-- WARNING: template loop detected -->';
2854 wfDebug( "$fname: template loop broken at '$part1'\n" );
2856 # set $text to cached message.
2857 $text = $linestart . $this->mTemplates
[$piece['title']];
2861 # Load from database
2862 $lastPathLevel = $this->mTemplatePath
;
2865 # declaring $subpage directly in the function call
2866 # does not work correctly with references and breaks
2867 # {{/subpage}}-style inclusions
2869 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2870 if ($subpage !== '') {
2871 $ns = $this->mTitle
->getNamespace();
2873 $title = Title
::newFromText( $part1, $ns );
2875 if ( !is_null( $title ) ) {
2876 if ( !$title->isExternal() ) {
2877 # Check for excessive inclusion
2878 $dbk = $title->getPrefixedDBkey();
2879 if ( $this->incrementIncludeCount( $dbk ) ) {
2880 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2881 $text = SpecialPage
::capturePath( $title );
2882 if ( is_string( $text ) ) {
2887 $this->disableCache();
2890 $articleContent = $this->fetchTemplate( $title );
2891 if ( $articleContent !== false ) {
2893 $text = $articleContent;
2894 $replaceHeadings = true;
2899 # If the title is valid but undisplayable, make a link to it
2900 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2901 $text = '[['.$title->getPrefixedText().']]';
2904 } elseif ( $title->isTrans() ) {
2905 // Interwiki transclusion
2906 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2907 $text = $this->interwikiTransclude( $title, 'render' );
2911 $text = $this->interwikiTransclude( $title, 'raw' );
2912 $replaceHeadings = true;
2917 # Template cache array insertion
2918 # Use the original $piece['title'] not the mangled $part1, so that
2919 # modifiers such as RAW: produce separate cache entries
2921 $this->mTemplates
[$piece['title']] = $text;
2922 $text = $linestart . $text;
2927 # Recursive parsing, escaping and link table handling
2928 # Only for HTML output
2929 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2930 $text = wfEscapeWikiText( $text );
2931 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2933 $assocArgs = array();
2935 # Clean up argument array
2936 $assocArgs = array();
2938 foreach( $args as $arg ) {
2939 $eqpos = strpos( $arg, '=' );
2940 if ( $eqpos === false ) {
2941 $assocArgs[$index++
] = $arg;
2943 $name = trim( substr( $arg, 0, $eqpos ) );
2944 $value = trim( substr( $arg, $eqpos+
1 ) );
2945 if ( $value === false ) {
2948 if ( $name !== false ) {
2949 $assocArgs[$name] = $value;
2954 # Add a new element to the templace recursion path
2955 $this->mTemplatePath
[$part1] = 1;
2959 # If there are any <onlyinclude> tags, only include them
2960 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2961 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2963 foreach ($m[1] as $piece)
2966 # Remove <noinclude> sections and <includeonly> tags
2967 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2968 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2970 if( $this->mOutputType
== OT_HTML
) {
2971 # Strip <nowiki>, <pre>, etc.
2972 $text = $this->strip( $text, $this->mStripState
);
2973 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2975 $text = $this->replaceVariables( $text, $assocArgs );
2977 # If the template begins with a table or block-level
2978 # element, it should be treated as beginning a new line.
2979 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2980 $text = "\n" . $text;
2982 } elseif ( !$noargs ) {
2983 # $noparse and !$noargs
2984 # Just replace the arguments, not any double-brace items
2985 # This is used for rendered interwiki transclusion
2986 $text = $this->replaceVariables( $text, $assocArgs, true );
2989 # Prune lower levels off the recursion check path
2990 $this->mTemplatePath
= $lastPathLevel;
2993 wfProfileOut( $fname );
2994 return $piece['text'];
2997 # Replace raw HTML by a placeholder
2998 # Add a blank line preceding, to prevent it from mucking up
2999 # immediately preceding headings
3000 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3002 # replace ==section headers==
3003 # XXX this needs to go away once we have a better parser.
3004 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3005 if( !is_null( $title ) )
3006 $encodedname = base64_encode($title->getPrefixedDBkey());
3008 $encodedname = base64_encode("");
3009 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3010 PREG_SPLIT_DELIM_CAPTURE
);
3013 for( $i = 0; $i < count($m); $i +
= 2 ) {
3015 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3017 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3021 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3022 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3023 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3031 # Prune lower levels off the recursion check path
3032 $this->mTemplatePath
= $lastPathLevel;
3035 wfProfileOut( $fname );
3036 return $piece['text'];
3038 wfProfileOut( $fname );
3044 * Fetch the unparsed text of a template and register a reference to it.
3046 function fetchTemplate( $title ) {
3048 // Loop to fetch the article, with up to 1 redirect
3049 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3050 $rev = Revision
::newFromTitle( $title );
3051 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3055 $text = $rev->getText();
3056 if ( $text === false ) {
3060 $title = Title
::newFromRedirect( $text );
3066 * Transclude an interwiki link.
3068 function interwikiTransclude( $title, $action ) {
3069 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3071 if (!$wgEnableScaryTranscluding)
3072 return wfMsg('scarytranscludedisabled');
3074 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3075 // But we'll handle it generally anyway
3076 if ( $title->getNamespace() ) {
3077 // Use the canonical namespace, which should work anywhere
3078 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3080 $articleName = $title->getDBkey();
3083 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3084 $url .= "?action=$action";
3085 if (strlen($url) > 255)
3086 return wfMsg('scarytranscludetoolong');
3087 return $this->fetchScaryTemplateMaybeFromCache($url);
3090 function fetchScaryTemplateMaybeFromCache($url) {
3091 global $wgTranscludeCacheExpiry;
3092 $dbr =& wfGetDB(DB_SLAVE
);
3093 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3094 array('tc_url' => $url));
3096 $time = $obj->tc_time
;
3097 $text = $obj->tc_contents
;
3098 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3103 $text = wfGetHTTP($url);
3105 return wfMsg('scarytranscludefailed', $url);
3107 $dbw =& wfGetDB(DB_MASTER
);
3108 $dbw->replace('transcache', array('tc_url'), array(
3110 'tc_time' => time(),
3111 'tc_contents' => $text));
3117 * Triple brace replacement -- used for template arguments
3120 function argSubstitution( $matches ) {
3121 $arg = trim( $matches['title'] );
3122 $text = $matches['text'];
3123 $inputArgs = end( $this->mArgStack
);
3125 if ( array_key_exists( $arg, $inputArgs ) ) {
3126 $text = $inputArgs[$arg];
3127 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3128 $text = $matches['parts'][0];
3135 * Returns true if the function is allowed to include this entity
3138 function incrementIncludeCount( $dbk ) {
3139 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3140 $this->mIncludeCount
[$dbk] = 0;
3142 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3150 * Detect __TOC__ magic word and set a placeholder
3152 function stripToc( $text ) {
3153 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3155 $mw = MagicWord
::get( MAG_NOTOC
);
3156 if( $mw->matchAndRemove( $text ) ) {
3157 $this->mShowToc
= false;
3160 $mw = MagicWord
::get( MAG_TOC
);
3161 if( $mw->match( $text ) ) {
3162 $this->mShowToc
= true;
3163 $this->mForceTocPosition
= true;
3165 // Set a placeholder. At the end we'll fill it in with the TOC.
3166 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3168 // Only keep the first one.
3169 $text = $mw->replace( '', $text );
3175 * This function accomplishes several tasks:
3176 * 1) Auto-number headings if that option is enabled
3177 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3178 * 3) Add a Table of contents on the top for users who have enabled the option
3179 * 4) Auto-anchor headings
3181 * It loops through all headlines, collects the necessary data, then splits up the
3182 * string and re-inserts the newly formatted headlines.
3184 * @param string $text
3185 * @param boolean $isMain
3188 function formatHeadings( $text, $isMain=true ) {
3189 global $wgMaxTocLevel, $wgContLang;
3191 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3192 if( !$this->mTitle
->userCanEdit() ) {
3195 $showEditLink = $this->mOptions
->getEditSection();
3198 # Inhibit editsection links if requested in the page
3199 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3200 if( $esw->matchAndRemove( $text ) ) {
3204 # Get all headlines for numbering them and adding funky stuff like [edit]
3205 # links - this is for later, but we need the number of headlines right now
3206 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3208 # if there are fewer than 4 headlines in the article, do not show TOC
3209 # unless it's been explicitly enabled.
3210 $enoughToc = $this->mShowToc
&&
3211 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3213 # Allow user to stipulate that a page should have a "new section"
3214 # link added via __NEWSECTIONLINK__
3215 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3216 if( $mw->matchAndRemove( $text ) )
3217 $this->mOutput
->setNewSection( true );
3219 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3220 # override above conditions and always show TOC above first header
3221 $mw =& MagicWord
::get( MAG_FORCETOC
);
3222 if ($mw->matchAndRemove( $text ) ) {
3223 $this->mShowToc
= true;
3227 # Never ever show TOC if no headers
3228 if( $numMatches < 1 ) {
3232 # We need this to perform operations on the HTML
3233 $sk =& $this->mOptions
->getSkin();
3237 $sectionCount = 0; # headlineCount excluding template sections
3239 # Ugh .. the TOC should have neat indentation levels which can be
3240 # passed to the skin functions. These are determined here
3244 $sublevelCount = array();
3245 $levelCount = array();
3252 foreach( $matches[3] as $headline ) {
3254 $templatetitle = '';
3255 $templatesection = 0;
3258 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3260 $templatetitle = base64_decode($mat[1]);
3261 $templatesection = 1 +
(int)base64_decode($mat[2]);
3262 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3266 $prevlevel = $level;
3267 $prevtoclevel = $toclevel;
3269 $level = $matches[1][$headlineCount];
3271 if( $doNumberHeadings ||
$enoughToc ) {
3273 if ( $level > $prevlevel ) {
3274 # Increase TOC level
3276 $sublevelCount[$toclevel] = 0;
3277 if( $toclevel<$wgMaxTocLevel ) {
3278 $toc .= $sk->tocIndent();
3281 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3282 # Decrease TOC level, find level to jump to
3284 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3285 # Can only go down to level 1
3288 for ($i = $toclevel; $i > 0; $i--) {
3289 if ( $levelCount[$i] == $level ) {
3290 # Found last matching level
3294 elseif ( $levelCount[$i] < $level ) {
3295 # Found first matching level below current level
3301 if( $toclevel<$wgMaxTocLevel ) {
3302 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3306 # No change in level, end TOC line
3307 if( $toclevel<$wgMaxTocLevel ) {
3308 $toc .= $sk->tocLineEnd();
3312 $levelCount[$toclevel] = $level;
3314 # count number of headlines for each level
3315 @$sublevelCount[$toclevel]++
;
3317 for( $i = 1; $i <= $toclevel; $i++
) {
3318 if( !empty( $sublevelCount[$i] ) ) {
3322 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3328 # The canonized header is a version of the header text safe to use for links
3329 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3330 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3331 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3333 # Remove link placeholders by the link text.
3334 # <!--LINK number-->
3336 # link text with suffix
3337 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3338 "\$this->mLinkHolders['texts'][\$1]",
3339 $canonized_headline );
3340 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3341 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3342 $canonized_headline );
3345 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3346 $tocline = trim( $canonized_headline );
3347 # Save headline for section edit hint before it's escaped
3348 $headline_hint = trim( $canonized_headline );
3349 $canonized_headline = Sanitizer
::escapeId( $tocline );
3350 $refers[$headlineCount] = $canonized_headline;
3352 # count how many in assoc. array so we can track dupes in anchors
3353 @$refers[$canonized_headline]++
;
3354 $refcount[$headlineCount]=$refers[$canonized_headline];
3356 # Don't number the heading if it is the only one (looks silly)
3357 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3358 # the two are different if the line contains a link
3359 $headline=$numbering . ' ' . $headline;
3362 # Create the anchor for linking from the TOC to the section
3363 $anchor = $canonized_headline;
3364 if($refcount[$headlineCount] > 1 ) {
3365 $anchor .= '_' . $refcount[$headlineCount];
3367 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3368 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3370 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3371 if ( empty( $head[$headlineCount] ) ) {
3372 $head[$headlineCount] = '';
3375 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3377 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3380 # give headline the correct <h#> tag
3381 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3389 if( $toclevel<$wgMaxTocLevel ) {
3390 $toc .= $sk->tocUnindent( $toclevel - 1 );
3392 $toc = $sk->tocList( $toc );
3395 # split up and insert constructed headlines
3397 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3400 foreach( $blocks as $block ) {
3401 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3402 # This is the [edit] link that appears for the top block of text when
3403 # section editing is enabled
3405 # Disabled because it broke block formatting
3406 # For example, a bullet point in the top line
3407 # $full .= $sk->editSectionLink(0);
3410 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3411 # Top anchor now in skin
3415 if( !empty( $head[$i] ) ) {
3420 if( $this->mForceTocPosition
) {
3421 return str_replace( '<!--MWTOC-->', $toc, $full );
3428 * Return an HTML link for the "ISBN 123456" text
3431 function magicISBN( $text ) {
3432 $fname = 'Parser::magicISBN';
3433 wfProfileIn( $fname );
3435 $a = split( 'ISBN ', ' '.$text );
3436 if ( count ( $a ) < 2 ) {
3437 wfProfileOut( $fname );
3440 $text = substr( array_shift( $a ), 1);
3441 $valid = '0123456789-Xx';
3443 foreach ( $a as $x ) {
3444 # hack: don't replace inside thumbnail title/alt
3446 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3451 $isbn = $blank = '' ;
3452 while ( ' ' == $x{0} ) {
3454 $x = substr( $x, 1 );
3456 if ( $x == '' ) { # blank isbn
3457 $text .= "ISBN $blank";
3460 while ( strstr( $valid, $x{0} ) != false ) {
3462 $x = substr( $x, 1 );
3464 $num = str_replace( '-', '', $isbn );
3465 $num = str_replace( ' ', '', $num );
3466 $num = str_replace( 'x', 'X', $num );
3469 $text .= "ISBN $blank$x";
3471 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3472 $text .= '<a href="' .
3473 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3474 "\" class=\"internal\">ISBN $isbn</a>";
3478 wfProfileOut( $fname );
3483 * Return an HTML link for the "RFC 1234" text
3486 * @param string $text Text to be processed
3487 * @param string $keyword Magic keyword to use (default RFC)
3488 * @param string $urlmsg Interface message to use (default rfcurl)
3491 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3493 $valid = '0123456789';
3496 $a = split( $keyword, ' '.$text );
3497 if ( count ( $a ) < 2 ) {
3500 $text = substr( array_shift( $a ), 1);
3502 /* Check if keyword is preceed by [[.
3503 * This test is made here cause of the array_shift above
3504 * that prevent the test to be done in the foreach.
3506 if ( substr( $text, -2 ) == '[[' ) {
3510 foreach ( $a as $x ) {
3511 /* token might be empty if we have RFC RFC 1234 */
3517 # hack: don't replace inside thumbnail title/alt
3519 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3520 $text .= $keyword . $x;
3526 /** remove and save whitespaces in $blank */
3527 while ( $x{0} == ' ' ) {
3529 $x = substr( $x, 1 );
3532 /** remove and save the rfc number in $id */
3533 while ( strstr( $valid, $x{0} ) != false ) {
3535 $x = substr( $x, 1 );
3539 /* call back stripped spaces*/
3540 $text .= $keyword.$blank.$x;
3541 } elseif( $internal ) {
3543 $text .= $keyword.$id.$x;
3545 /* build the external link*/
3546 $url = wfMsg( $urlmsg, $id);
3547 $sk =& $this->mOptions
->getSkin();
3548 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3549 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3552 /* Check if the next RFC keyword is preceed by [[ */
3553 $internal = ( substr($x,-2) == '[[' );
3559 * Transform wiki markup when saving a page by doing \r\n -> \n
3560 * conversion, substitting signatures, {{subst:}} templates, etc.
3562 * @param string $text the text to transform
3563 * @param Title &$title the Title object for the current article
3564 * @param User &$user the User object describing the current user
3565 * @param ParserOptions $options parsing options
3566 * @param bool $clearState whether to clear the parser state first
3567 * @return string the altered wiki markup
3570 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3571 $this->mOptions
= $options;
3572 $this->mTitle
=& $title;
3573 $this->mOutputType
= OT_WIKI
;
3575 if ( $clearState ) {
3576 $this->clearState();
3579 $stripState = false;
3583 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3584 $text = $this->strip( $text, $stripState, true );
3585 $text = $this->pstPass2( $text, $stripState, $user );
3586 $text = $this->unstrip( $text, $stripState );
3587 $text = $this->unstripNoWiki( $text, $stripState );
3592 * Pre-save transform helper function
3595 function pstPass2( $text, &$stripState, &$user ) {
3596 global $wgContLang, $wgLocaltimezone;
3598 /* Note: This is the timestamp saved as hardcoded wikitext to
3599 * the database, we use $wgContLang here in order to give
3600 * everyone the same signature and use the default one rather
3601 * than the one selected in each user's preferences.
3603 if ( isset( $wgLocaltimezone ) ) {
3604 $oldtz = getenv( 'TZ' );
3605 putenv( 'TZ='.$wgLocaltimezone );
3607 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3608 ' (' . date( 'T' ) . ')';
3609 if ( isset( $wgLocaltimezone ) ) {
3610 putenv( 'TZ='.$oldtz );
3613 # Variable replacement
3614 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3615 $text = $this->replaceVariables( $text );
3617 # Strip out <nowiki> etc. added via replaceVariables
3618 $text = $this->strip( $text, $stripState );
3621 $sigText = $this->getUserSig( $user );
3622 $text = strtr( $text, array(
3624 '~~~~' => "$sigText $d",
3628 # Context links: [[|name]] and [[name (context)|]]
3630 global $wgLegalTitleChars;
3631 $tc = "[$wgLegalTitleChars]";
3632 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3634 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3635 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3637 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3638 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3639 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3640 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3642 $t = $this->mTitle
->getText();
3643 if ( preg_match( $conpat, $t, $m ) ) {
3646 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3647 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3648 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3650 if ( '' == $context ) {
3651 $text = preg_replace( $p2, '[[\\1]]', $text );
3653 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3656 # Trim trailing whitespace
3657 # MAG_END (__END__) tag allows for trailing
3658 # whitespace to be deliberately included
3659 $text = rtrim( $text );
3660 $mw =& MagicWord
::get( MAG_END
);
3661 $mw->matchAndRemove( $text );
3667 * Fetch the user's signature text, if any, and normalize to
3668 * validated, ready-to-insert wikitext.
3674 function getUserSig( &$user ) {
3675 $username = $user->getName();
3676 $nickname = $user->getOption( 'nickname' );
3677 $nickname = $nickname === '' ?
$username : $nickname;
3679 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3680 # Sig. might contain markup; validate this
3681 if( $this->validateSig( $nickname ) !== false ) {
3682 # Validated; clean up (if needed) and return it
3683 return $this->cleanSig( $nickname, true );
3685 # Failed to validate; fall back to the default
3686 $nickname = $username;
3687 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3691 # If we're still here, make it a link to the user page
3692 $userpage = $user->getUserPage();
3693 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3697 * Check that the user's signature contains no bad XML
3699 * @param string $text
3700 * @return mixed An expanded string, or false if invalid.
3702 function validateSig( $text ) {
3703 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3707 * Clean up signature text
3709 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3710 * 2) Substitute all transclusions
3712 * @param string $text
3713 * @param $parsing Whether we're cleaning (preferences save) or parsing
3714 * @return string Signature text
3716 function cleanSig( $text, $parsing = false ) {
3718 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3720 $substWord = MagicWord
::get( MAG_SUBST
);
3721 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3722 $substText = '{{' . $substWord->getSynonym( 0 );
3724 $text = preg_replace( $substRegex, $substText, $text );
3725 $text = preg_replace( '/~{3,5}/', '', $text );
3726 $text = $this->replaceVariables( $text );
3728 $this->clearState();
3733 * Set up some variables which are usually set up in parse()
3734 * so that an external function can call some class members with confidence
3737 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3738 $this->mTitle
=& $title;
3739 $this->mOptions
= $options;
3740 $this->mOutputType
= $outputType;
3741 if ( $clearState ) {
3742 $this->clearState();
3747 * Transform a MediaWiki message by replacing magic variables.
3749 * @param string $text the text to transform
3750 * @param ParserOptions $options options
3751 * @return string the text with variables substituted
3754 function transformMsg( $text, $options ) {
3756 static $executing = false;
3758 $fname = "Parser::transformMsg";
3760 # Guard against infinite recursion
3766 wfProfileIn($fname);
3768 $this->mTitle
= $wgTitle;
3769 $this->mOptions
= $options;
3770 $this->mOutputType
= OT_MSG
;
3771 $this->clearState();
3772 $text = $this->replaceVariables( $text );
3775 wfProfileOut($fname);
3780 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3781 * The callback should have the following form:
3782 * function myParserHook( $text, $params, &$parser ) { ... }
3784 * Transform and return $text. Use $parser for any required context, e.g. use
3785 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3789 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3790 * @param mixed $callback The callback function (and object) to use for the tag
3792 * @return The old value of the mTagHooks array associated with the hook
3794 function setHook( $tag, $callback ) {
3795 $tag = strtolower( $tag );
3796 $oldVal = @$this->mTagHooks
[$tag];
3797 $this->mTagHooks
[$tag] = $callback;
3803 * Create a function, e.g. {{sum:1|2|3}}
3804 * The callback function should have the form:
3805 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3807 * The callback may either return the text result of the function, or an array with the text
3808 * in element 0, and a number of flags in the other elements. The names of the flags are
3809 * specified in the keys. Valid flags are:
3810 * found The text returned is valid, stop processing the template. This
3812 * nowiki Wiki markup in the return value should be escaped
3813 * noparse Unsafe HTML tags should not be stripped, etc.
3814 * noargs Don't replace triple-brace arguments in the return value
3815 * isHTML The returned text is HTML, armour it against wikitext transformation
3819 * @param string $name The function name. Function names are case-insensitive.
3820 * @param mixed $callback The callback function (and object) to use
3822 * @return The old callback function for this name, if any
3824 function setFunctionHook( $name, $callback ) {
3825 $name = strtolower( $name );
3826 $oldVal = @$this->mFunctionHooks
[$name];
3827 $this->mFunctionHooks
[$name] = $callback;
3832 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3833 * Placeholders created in Skin::makeLinkObj()
3834 * Returns an array of links found, indexed by PDBK:
3838 * $options is a bit field, RLH_FOR_UPDATE to select for update
3840 function replaceLinkHolders( &$text, $options = 0 ) {
3842 global $wgOutputReplace;
3844 $fname = 'Parser::replaceLinkHolders';
3845 wfProfileIn( $fname );
3849 $sk =& $this->mOptions
->getSkin();
3850 $linkCache =& LinkCache
::singleton();
3852 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3853 wfProfileIn( $fname.'-check' );
3854 $dbr =& wfGetDB( DB_SLAVE
);
3855 $page = $dbr->tableName( 'page' );
3856 $threshold = $wgUser->getOption('stubthreshold');
3859 asort( $this->mLinkHolders
['namespaces'] );
3863 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3865 $title = $this->mLinkHolders
['titles'][$key];
3867 # Skip invalid entries.
3868 # Result will be ugly, but prevents crash.
3869 if ( is_null( $title ) ) {
3872 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3874 # Check if it's a static known link, e.g. interwiki
3875 if ( $title->isAlwaysKnown() ) {
3876 $colours[$pdbk] = 1;
3877 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3878 $colours[$pdbk] = 1;
3879 $this->mOutput
->addLink( $title, $id );
3880 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3881 $colours[$pdbk] = 0;
3883 # Not in the link cache, add it to the query
3884 if ( !isset( $current ) ) {
3886 $query = "SELECT page_id, page_namespace, page_title";
3887 if ( $threshold > 0 ) {
3888 $query .= ', page_len, page_is_redirect';
3890 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3891 } elseif ( $current != $ns ) {
3893 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3898 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3903 if ( $options & RLH_FOR_UPDATE
) {
3904 $query .= ' FOR UPDATE';
3907 $res = $dbr->query( $query, $fname );
3909 # Fetch data and form into an associative array
3910 # non-existent = broken
3913 while ( $s = $dbr->fetchObject($res) ) {
3914 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3915 $pdbk = $title->getPrefixedDBkey();
3916 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3917 $this->mOutput
->addLink( $title, $s->page_id
);
3919 if ( $threshold > 0 ) {
3920 $size = $s->page_len
;
3921 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3922 $colours[$pdbk] = 1;
3924 $colours[$pdbk] = 2;
3927 $colours[$pdbk] = 1;
3931 wfProfileOut( $fname.'-check' );
3933 # Construct search and replace arrays
3934 wfProfileIn( $fname.'-construct' );
3935 $wgOutputReplace = array();
3936 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3937 $pdbk = $pdbks[$key];
3938 $searchkey = "<!--LINK $key-->";
3939 $title = $this->mLinkHolders
['titles'][$key];
3940 if ( empty( $colours[$pdbk] ) ) {
3941 $linkCache->addBadLinkObj( $title );
3942 $colours[$pdbk] = 0;
3943 $this->mOutput
->addLink( $title, 0 );
3944 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3945 $this->mLinkHolders
['texts'][$key],
3946 $this->mLinkHolders
['queries'][$key] );
3947 } elseif ( $colours[$pdbk] == 1 ) {
3948 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3949 $this->mLinkHolders
['texts'][$key],
3950 $this->mLinkHolders
['queries'][$key] );
3951 } elseif ( $colours[$pdbk] == 2 ) {
3952 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3953 $this->mLinkHolders
['texts'][$key],
3954 $this->mLinkHolders
['queries'][$key] );
3957 wfProfileOut( $fname.'-construct' );
3960 wfProfileIn( $fname.'-replace' );
3962 $text = preg_replace_callback(
3963 '/(<!--LINK .*?-->)/',
3964 "wfOutputReplaceMatches",
3967 wfProfileOut( $fname.'-replace' );
3970 # Now process interwiki link holders
3971 # This is quite a bit simpler than internal links
3972 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3973 wfProfileIn( $fname.'-interwiki' );
3974 # Make interwiki link HTML
3975 $wgOutputReplace = array();
3976 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3977 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3978 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3981 $text = preg_replace_callback(
3982 '/<!--IWLINK (.*?)-->/',
3983 "wfOutputReplaceMatches",
3985 wfProfileOut( $fname.'-interwiki' );
3988 wfProfileOut( $fname );
3993 * Replace <!--LINK--> link placeholders with plain text of links
3994 * (not HTML-formatted).
3995 * @param string $text
3998 function replaceLinkHoldersText( $text ) {
3999 $fname = 'Parser::replaceLinkHoldersText';
4000 wfProfileIn( $fname );
4002 $text = preg_replace_callback(
4003 '/<!--(LINK|IWLINK) (.*?)-->/',
4004 array( &$this, 'replaceLinkHoldersTextCallback' ),
4007 wfProfileOut( $fname );
4012 * @param array $matches
4016 function replaceLinkHoldersTextCallback( $matches ) {
4017 $type = $matches[1];
4019 if( $type == 'LINK' ) {
4020 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4021 return $this->mLinkHolders
['texts'][$key];
4023 } elseif( $type == 'IWLINK' ) {
4024 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4025 return $this->mInterwikiLinkHolders
['texts'][$key];
4032 * Renders an image gallery from a text with one line per image.
4033 * text labels may be given by using |-style alternative text. E.g.
4034 * Image:one.jpg|The number "1"
4035 * Image:tree.jpg|A tree
4036 * given as text will return the HTML of a gallery with two images,
4037 * labeled 'The number "1"' and
4040 function renderImageGallery( $text ) {
4041 $ig = new ImageGallery();
4042 $ig->setShowBytes( false );
4043 $ig->setShowFilename( false );
4045 $lines = explode( "\n", $text );
4047 foreach ( $lines as $line ) {
4048 # match lines like these:
4049 # Image:someimage.jpg|This is some image
4050 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4052 if ( count( $matches ) == 0 ) {
4055 $nt =& Title
::newFromText( $matches[1] );
4056 if( is_null( $nt ) ) {
4057 # Bogus title. Ignore these so we don't bomb out later.
4060 if ( isset( $matches[3] ) ) {
4061 $label = $matches[3];
4066 $pout = $this->parse( $label,
4069 false, // Strip whitespace...?
4070 false // Don't clear state!
4072 $html = $pout->getText();
4074 $ig->add( new Image( $nt ), $html );
4076 # Only add real images (bug #5586)
4077 if ( $nt->getNamespace() == NS_IMAGE
) {
4078 $this->mOutput
->addImage( $nt->getDBkey() );
4081 return $ig->toHTML();
4085 * Parse image options text and use it to make an image
4087 function makeImage( &$nt, $options ) {
4088 global $wgUseImageResize;
4092 # Check if the options text is of the form "options|alt text"
4094 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4095 # * left no resizing, just left align. label is used for alt= only
4096 # * right same, but right aligned
4097 # * none same, but not aligned
4098 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4099 # * center center the image
4100 # * framed Keep original image size, no magnify-button.
4102 $part = explode( '|', $options);
4104 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4105 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4106 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4107 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4108 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4109 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4110 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4111 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4114 $width = $height = $framed = $thumb = false;
4115 $manual_thumb = '' ;
4117 foreach( $part as $key => $val ) {
4118 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4120 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4121 # use manually specified thumbnail
4123 $manual_thumb = $match;
4124 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4125 # remember to set an alignment, don't render immediately
4127 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4128 # remember to set an alignment, don't render immediately
4130 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4131 # remember to set an alignment, don't render immediately
4133 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4134 # remember to set an alignment, don't render immediately
4136 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4137 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4138 # $match is the image width in pixels
4139 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4140 $width = intval( $m[1] );
4141 $height = intval( $m[2] );
4143 $width = intval($match);
4145 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4151 # Strip bad stuff out of the alt text
4152 $alt = $this->replaceLinkHoldersText( $caption );
4154 # make sure there are no placeholders in thumbnail attributes
4155 # that are later expanded to html- so expand them now and
4157 $alt = $this->unstrip($alt, $this->mStripState
);
4158 $alt = Sanitizer
::stripAllTags( $alt );
4160 # Linker does the rest
4161 $sk =& $this->mOptions
->getSkin();
4162 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4166 * Set a flag in the output object indicating that the content is dynamic and
4167 * shouldn't be cached.
4169 function disableCache() {
4170 wfDebug( "Parser output marked as uncacheable.\n" );
4171 $this->mOutput
->mCacheTime
= -1;
4175 * Callback from the Sanitizer for expanding items found in HTML attribute
4176 * values, so they can be safely tested and escaped.
4177 * @param string $text
4178 * @param array $args
4182 function attributeStripCallback( &$text, $args ) {
4183 $text = $this->replaceVariables( $text, $args );
4184 $text = $this->unstripForHTML( $text );
4188 function unstripForHTML( $text ) {
4189 $text = $this->unstrip( $text, $this->mStripState
);
4190 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4198 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4199 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4200 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4206 function getTags() { return array_keys( $this->mTagHooks
); }
4212 * @package MediaWiki
4216 var $mText, # The output text
4217 $mLanguageLinks, # List of the full text of language links, in the order they appear
4218 $mCategories, # Map of category names to sort keys
4219 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4220 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4221 $mVersion, # Compatibility check
4222 $mTitleText, # title text of the chosen language variant
4223 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4224 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4225 $mImages, # DB keys of the images used, in the array key only
4226 $mExternalLinks, # External link URLs, in the key only
4227 $mHTMLtitle, # Display HTML title
4228 $mSubtitle, # Additional subtitle
4229 $mNewSection; # Show a new section link?
4231 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4232 $containsOldMagic = false, $titletext = '' )
4234 $this->mText
= $text;
4235 $this->mLanguageLinks
= $languageLinks;
4236 $this->mCategories
= $categoryLinks;
4237 $this->mContainsOldMagic
= $containsOldMagic;
4238 $this->mCacheTime
= '';
4239 $this->mVersion
= MW_PARSER_VERSION
;
4240 $this->mTitleText
= $titletext;
4241 $this->mLinks
= array();
4242 $this->mTemplates
= array();
4243 $this->mImages
= array();
4244 $this->mExternalLinks
= array();
4245 $this->mHTMLtitle
= "" ;
4246 $this->mSubtitle
= "" ;
4247 $this->mNewSection
= false;
4250 function getText() { return $this->mText
; }
4251 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4252 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4253 function &getCategories() { return $this->mCategories
; }
4254 function getCacheTime() { return $this->mCacheTime
; }
4255 function getTitleText() { return $this->mTitleText
; }
4256 function &getLinks() { return $this->mLinks
; }
4257 function &getTemplates() { return $this->mTemplates
; }
4258 function &getImages() { return $this->mImages
; }
4259 function &getExternalLinks() { return $this->mExternalLinks
; }
4261 function containsOldMagic() { return $this->mContainsOldMagic
; }
4262 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4263 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4264 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4265 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4266 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4267 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4269 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4270 function addImage( $name ) { $this->mImages
[$name] = 1; }
4271 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4272 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4274 function setNewSection( $value ) {
4275 $this->mNewSection
= (bool)$value;
4277 function getNewSection() {
4278 return (bool)$this->mNewSection
;
4281 function addLink( $title, $id ) {
4282 $ns = $title->getNamespace();
4283 $dbk = $title->getDBkey();
4284 if ( !isset( $this->mLinks
[$ns] ) ) {
4285 $this->mLinks
[$ns] = array();
4287 $this->mLinks
[$ns][$dbk] = $id;
4290 function addTemplate( $title, $id ) {
4291 $ns = $title->getNamespace();
4292 $dbk = $title->getDBkey();
4293 if ( !isset( $this->mTemplates
[$ns] ) ) {
4294 $this->mTemplates
[$ns] = array();
4296 $this->mTemplates
[$ns][$dbk] = $id;
4300 * Return true if this cached output object predates the global or
4301 * per-article cache invalidation timestamps, or if it comes from
4302 * an incompatible older version.
4304 * @param string $touched the affected article's last touched timestamp
4308 function expired( $touched ) {
4309 global $wgCacheEpoch;
4310 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4311 $this->getCacheTime() < $touched ||
4312 $this->getCacheTime() <= $wgCacheEpoch ||
4313 !isset( $this->mVersion
) ||
4314 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4319 * Set options of the Parser
4321 * @package MediaWiki
4325 # All variables are private
4326 var $mUseTeX; # Use texvc to expand <math> tags
4327 var $mUseDynamicDates; # Use DateFormatter to format dates
4328 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4329 var $mAllowExternalImages; # Allow external images inline
4330 var $mAllowExternalImagesFrom; # If not, any exception?
4331 var $mSkin; # Reference to the preferred skin
4332 var $mDateFormat; # Date format index
4333 var $mEditSection; # Create "edit section" links
4334 var $mNumberHeadings; # Automatically number headings
4335 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4336 var $mTidy; # Ask for tidy cleanup
4337 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4339 function getUseTeX() { return $this->mUseTeX
; }
4340 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4341 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4342 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4343 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4344 function &getSkin() { return $this->mSkin
; }
4345 function getDateFormat() { return $this->mDateFormat
; }
4346 function getEditSection() { return $this->mEditSection
; }
4347 function getNumberHeadings() { return $this->mNumberHeadings
; }
4348 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4349 function getTidy() { return $this->mTidy
; }
4350 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4352 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4353 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4354 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4355 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4356 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4357 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4358 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4359 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4360 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4361 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4362 function setSkin( &$x ) { $this->mSkin
=& $x; }
4363 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4365 function ParserOptions() {
4367 $this->initialiseFromUser( $wgUser );
4371 * Get parser options
4374 function newFromUser( &$user ) {
4375 $popts = new ParserOptions
;
4376 $popts->initialiseFromUser( $user );
4380 /** Get user options */
4381 function initialiseFromUser( &$userInput ) {
4382 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4383 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4384 $fname = 'ParserOptions::initialiseFromUser';
4385 wfProfileIn( $fname );
4386 if ( !$userInput ) {
4388 $user->setLoaded( true );
4390 $user =& $userInput;
4393 $this->mUseTeX
= $wgUseTeX;
4394 $this->mUseDynamicDates
= $wgUseDynamicDates;
4395 $this->mInterwikiMagic
= $wgInterwikiMagic;
4396 $this->mAllowExternalImages
= $wgAllowExternalImages;
4397 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4398 wfProfileIn( $fname.'-skin' );
4399 $this->mSkin
=& $user->getSkin();
4400 wfProfileOut( $fname.'-skin' );
4401 $this->mDateFormat
= $user->getOption( 'date' );
4402 $this->mEditSection
= true;
4403 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4404 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4405 $this->mTidy
= false;
4406 $this->mInterfaceMessage
= false;
4407 wfProfileOut( $fname );
4412 * Callback function used by Parser::replaceLinkHolders()
4413 * to substitute link placeholders.
4415 function &wfOutputReplaceMatches( $matches ) {
4416 global $wgOutputReplace;
4417 return $wgOutputReplace[$matches[1]];
4421 * Return the total number of articles
4423 function wfNumberOfArticles() {
4424 global $wgNumberOfArticles;
4427 return $wgNumberOfArticles;
4431 * Return the number of files
4433 function wfNumberOfFiles() {
4434 $fname = 'wfNumberOfFiles';
4436 wfProfileIn( $fname );
4437 $dbr =& wfGetDB( DB_SLAVE
);
4438 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4439 wfProfileOut( $fname );
4445 * Return the number of user accounts
4448 function wfNumberOfUsers() {
4449 wfProfileIn( 'wfNumberOfUsers' );
4450 $dbr =& wfGetDB( DB_SLAVE
);
4451 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4452 wfProfileOut( 'wfNumberOfUsers' );
4457 * Return the total number of pages
4460 function wfNumberOfPages() {
4461 wfProfileIn( 'wfNumberOfPages' );
4462 $dbr =& wfGetDB( DB_SLAVE
);
4463 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4464 wfProfileOut( 'wfNumberOfPages' );
4469 * Get various statistics from the database
4472 function wfLoadSiteStats() {
4473 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4474 $fname = 'wfLoadSiteStats';
4476 if ( -1 != $wgNumberOfArticles ) return;
4477 $dbr =& wfGetDB( DB_SLAVE
);
4478 $s = $dbr->selectRow( 'site_stats',
4479 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4480 array( 'ss_row_id' => 1 ), $fname
4483 if ( $s === false ) {
4486 $wgTotalViews = $s->ss_total_views
;
4487 $wgTotalEdits = $s->ss_total_edits
;
4488 $wgNumberOfArticles = $s->ss_good_articles
;
4494 * Basically replacing " > and < with HTML entities ( ", >, <)
4496 * @param $in String: text that might contain HTML tags.
4497 * @return string Escaped string
4499 function wfEscapeHTMLTagsOnly( $in ) {
4501 array( '"', '>', '<' ),
4502 array( '"', '>', '<' ),