3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
17 * Variable substitution O(N^2) attack
19 * Without countermeasures, it would be possible to attack the parser by saving
20 * a page filled with a large number of inclusions of large pages. The size of
21 * the generated page would be proportional to the square of the input size.
22 * Hence, we limit the number of inclusions of any given page, thus bringing any
23 * attack back to O(N).
26 define( 'MAX_INCLUDE_REPEAT', 100 );
27 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
29 define( 'RLH_FOR_UPDATE', 1 );
31 # Allowed values for $mOutputType
32 define( 'OT_HTML', 1 );
33 define( 'OT_WIKI', 2 );
34 define( 'OT_MSG' , 3 );
36 # string parameter for extractTags which will cause it
37 # to strip HTML comments in addition to regular
38 # <XML>-style tags. This should not be anything we
39 # may want to use in wikisyntax
40 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
42 # Constants needed for external link processing
43 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
44 # Everything except bracket, space, or control characters
45 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
46 # Including space, but excluding newlines
47 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
48 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
49 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
50 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
51 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
52 define( 'EXT_IMAGE_REGEX',
53 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
54 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
55 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
58 // State constants for the definition list colon extraction
59 define( 'MW_COLON_STATE_TEXT', 0 );
60 define( 'MW_COLON_STATE_TAG', 1 );
61 define( 'MW_COLON_STATE_TAGSTART', 2 );
62 define( 'MW_COLON_STATE_CLOSETAG', 3 );
63 define( 'MW_COLON_STATE_TAGSLASH', 4 );
64 define( 'MW_COLON_STATE_COMMENT', 5 );
65 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
66 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
71 * Processes wiki markup
74 * There are three main entry points into the Parser class:
76 * produces HTML output
78 * produces altered wiki markup.
80 * performs brace substitution on MediaWiki messages
83 * objects: $wgLang, $wgContLang
85 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
88 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
89 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
90 * $wgLocaltimezone, $wgAllowSpecialInclusion*
92 * * only within ParserOptions
103 var $mTagHooks, $mFunctionHooks;
105 # Cleared with clearState():
106 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
107 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
108 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
109 var $mTemplates, // cache of already loaded templates, avoids
110 // multiple SQL queries for the same string
111 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
112 // in this path. Used for loop detection.
115 # These are variables reset at least once per parse regardless of $clearState
116 var $mOptions, // ParserOptions object
117 $mTitle, // Title context, used for self-link rendering and similar things
118 $mOutputType, // Output type, one of the OT_xxx constants
119 $mRevisionId; // ID to display in {{REVISIONID}} tags
129 $this->mTagHooks
= array();
130 $this->mFunctionHooks
= array();
131 $this->mFunctionSynonymsValid
= true;
132 $this->mFunctionSynonyms
= array();
134 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
142 function clearState() {
143 $this->mOutput
= new ParserOutput
;
144 $this->mAutonumber
= 0;
145 $this->mLastSection
= '';
146 $this->mDTopen
= false;
147 $this->mVariables
= false;
148 $this->mIncludeCount
= array();
149 $this->mStripState
= array();
150 $this->mArgStack
= array();
151 $this->mInPre
= false;
152 $this->mInterwikiLinkHolders
= array(
156 $this->mLinkHolders
= array(
157 'namespaces' => array(),
159 'queries' => array(),
163 $this->mRevisionId
= null;
166 * Prefix for temporary replacement strings for the multipass parser.
167 * \x07 should never appear in input as it's disallowed in XML.
168 * Using it at the front also gives us a little extra robustness
169 * since it shouldn't match when butted up against identifier-like
172 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
174 # Clear these on every parse, bug 4549
175 $this->mTemplates
= array();
176 $this->mTemplatePath
= array();
178 $this->mShowToc
= true;
179 $this->mForceTocPosition
= false;
181 # This doesn't actually clear anything, but it seemed like a nice place to put it
182 # Fill the function cache, if it needs filling
183 $this->refreshFunctionCache();
185 wfRunHooks( 'ParserClearState', array( &$this ) );
189 * Accessor for mUniqPrefix.
193 function UniqPrefix() {
194 return $this->mUniqPrefix
;
198 * Convert wikitext to HTML
199 * Do not call this function recursively.
202 * @param string $text Text we want to parse
203 * @param Title &$title A title object
204 * @param array $options
205 * @param boolean $linestart
206 * @param boolean $clearState
207 * @param int $revid number to pass in {{REVISIONID}}
208 * @return ParserOutput a ParserOutput
210 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
212 * First pass--just handle <nowiki> sections, pass the rest off
213 * to internalParse() which does all the real work.
216 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
217 $fname = 'Parser::parse';
218 wfProfileIn( $fname );
224 $this->mOptions
= $options;
225 $this->mTitle
=& $title;
226 $this->mRevisionId
= $revid;
227 $this->mOutputType
= OT_HTML
;
229 //$text = $this->strip( $text, $this->mStripState );
230 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
231 $x =& $this->mStripState
;
233 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
234 $text = $this->strip( $text, $x );
235 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
237 # Hook to suspend the parser in this state
238 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
239 wfProfileOut( $fname );
243 $text = $this->internalParse( $text );
245 $text = $this->unstrip( $text, $this->mStripState
);
247 # Clean up special characters, only run once, next-to-last before doBlockLevels
249 # french spaces, last one Guillemet-left
250 # only if there is something before the space
251 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
252 # french spaces, Guillemet-right
253 '/(\\302\\253) /' => '\\1 ',
255 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
258 $text = $this->doBlockLevels( $text, $linestart );
260 $this->replaceLinkHolders( $text );
262 # the position of the parserConvert() call should not be changed. it
263 # assumes that the links are all replaced and the only thing left
264 # is the <nowiki> mark.
265 # Side-effects: this calls $this->mOutput->setTitleText()
266 $text = $wgContLang->parserConvert( $text, $this );
268 $text = $this->unstripNoWiki( $text, $this->mStripState
);
270 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
272 $text = Sanitizer
::normalizeCharReferences( $text );
274 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
275 $text = Parser
::tidy($text);
277 # attempt to sanitize at least some nesting problems
278 # (bug #2702 and quite a few others)
280 # ''Something [http://www.cool.com cool''] -->
281 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
282 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
283 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
284 # fix up an anchor inside another anchor, only
285 # at least for a single single nested link (bug 3695)
286 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
287 '\\1\\2</a>\\3</a>\\1\\4</a>',
288 # fix div inside inline elements- doBlockLevels won't wrap a line which
289 # contains a div, so fix it up here; replace
290 # div with escaped text
291 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
292 '\\1\\3<div\\5>\\6</div>\\8\\9',
293 # remove empty italic or bold tag pairs, some
294 # introduced by rules above
295 '/<([bi])><\/\\1>/' => ''
298 $text = preg_replace(
299 array_keys( $tidyregs ),
300 array_values( $tidyregs ),
304 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
306 $this->mOutput
->setText( $text );
307 wfProfileOut( $fname );
309 return $this->mOutput
;
313 * Get a random string
318 function getRandomString() {
319 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
322 function &getTitle() { return $this->mTitle
; }
323 function getOptions() { return $this->mOptions
; }
326 * Replaces all occurrences of HTML-style comments and the given tags
327 * in the text with a random marker and returns teh next text. The output
328 * parameter $matches will be an associative array filled with data in
330 * 'UNIQ-xxxxx' => array(
333 * array( 'param' => 'x' ),
334 * '<element param="x">tag content</element>' ) )
336 * @param $elements list of element names. Comments are always extracted.
337 * @param $text Source text string.
338 * @param $uniq_prefix
343 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
344 $rand = Parser
::getRandomString();
349 $taglist = implode( '|', $elements );
350 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
352 while ( '' != $text ) {
353 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
355 if( count( $p ) < 5 ) {
358 if( count( $p ) > 5 ) {
372 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
) . '-QINU';
373 $stripped .= $marker;
375 if ( $close === '/>' ) {
376 // Empty element tag, <tag />
381 if( $element == '!--' ) {
384 $end = "/(<\\/$element\\s*>)/i";
386 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
388 if( count( $q ) < 3 ) {
389 # No end tag -- let it run out to the end of the text.
398 $matches[$marker] = array( $element,
400 Sanitizer
::decodeTagAttributes( $attributes ),
401 "<$element$attributes$close$content$tail" );
407 * Strips and renders nowiki, pre, math, hiero
408 * If $render is set, performs necessary rendering operations on plugins
409 * Returns the text, and fills an array with data needed in unstrip()
410 * If the $state is already a valid strip state, it adds to the state
412 * @param bool $stripcomments when set, HTML comments <!-- like this -->
413 * will be stripped in addition to other tags. This is important
414 * for section editing, where these comments cause confusion when
415 * counting the sections in the wikisource
417 * @param array dontstrip contains tags which should not be stripped;
418 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
422 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
423 $render = ($this->mOutputType
== OT_HTML
);
425 # Replace any instances of the placeholders
426 $uniq_prefix = $this->mUniqPrefix
;
427 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
428 $commentState = array();
430 $elements = array_merge(
431 array( 'nowiki', 'gallery' ),
432 array_keys( $this->mTagHooks
) );
435 $elements[] = 'html';
437 if( $this->mOptions
->getUseTeX() ) {
438 $elements[] = 'math';
441 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
442 foreach ( $elements AS $k => $v ) {
443 if ( !in_array ( $v , $dontstrip ) ) continue;
444 unset ( $elements[$k] );
448 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
450 foreach( $matches as $marker => $data ) {
451 list( $element, $content, $params, $tag ) = $data;
453 $tagName = strtolower( $element );
457 if( substr( $tag, -3 ) == '-->' ) {
460 // Unclosed comment in input.
461 // Close it so later stripping can remove it
470 // Shouldn't happen otherwise. :)
472 $output = wfEscapeHTMLTagsOnly( $content );
475 $output = MathRenderer
::renderMath( $content );
478 $output = $this->renderImageGallery( $content, $params );
481 if( isset( $this->mTagHooks
[$tagName] ) ) {
482 $output = call_user_func_array( $this->mTagHooks
[$tagName],
483 array( $content, $params, $this ) );
485 throw new MWException( "Invalid call hook $element" );
489 // Just stripping tags; keep the source
492 if( !$stripcomments && $element == '!--' ) {
493 $commentState[$marker] = $output;
495 $state[$element][$marker] = $output;
499 # Unstrip comments unless explicitly told otherwise.
500 # (The comments are always stripped prior to this point, so as to
501 # not invoke any extension tags / parser hooks contained within
503 if ( !$stripcomments ) {
504 // Put them all back and forget them
505 $text = strtr( $text, $commentState );
512 * Restores pre, math, and other extensions removed by strip()
514 * always call unstripNoWiki() after this one
517 function unstrip( $text, &$state ) {
518 if ( !is_array( $state ) ) {
522 $replacements = array();
523 foreach( $state as $tag => $contentDict ) {
524 if( $tag != 'nowiki' && $tag != 'html' ) {
525 foreach( $contentDict as $uniq => $content ) {
526 $replacements[$uniq] = $content;
530 $text = strtr( $text, $replacements );
536 * Always call this after unstrip() to preserve the order
540 function unstripNoWiki( $text, &$state ) {
541 if ( !is_array( $state ) ) {
545 $replacements = array();
546 foreach( $state as $tag => $contentDict ) {
547 if( $tag == 'nowiki' ||
$tag == 'html' ) {
548 foreach( $contentDict as $uniq => $content ) {
549 $replacements[$uniq] = $content;
553 $text = strtr( $text, $replacements );
559 * Add an item to the strip state
560 * Returns the unique tag which must be inserted into the stripped text
561 * The tag will be replaced with the original text in unstrip()
565 function insertStripItem( $text, &$state ) {
566 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
570 $state['item'][$rnd] = $text;
575 * Interface with html tidy, used if $wgUseTidy = true.
576 * If tidy isn't able to correct the markup, the original will be
577 * returned in all its glory with a warning comment appended.
579 * Either the external tidy program or the in-process tidy extension
580 * will be used depending on availability. Override the default
581 * $wgTidyInternal setting to disable the internal if it's not working.
583 * @param string $text Hideous HTML input
584 * @return string Corrected HTML output
588 function tidy( $text ) {
589 global $wgTidyInternal;
590 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
591 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
592 '<head><title>test</title></head><body>'.$text.'</body></html>';
593 if( $wgTidyInternal ) {
594 $correctedtext = Parser
::internalTidy( $wrappedtext );
596 $correctedtext = Parser
::externalTidy( $wrappedtext );
598 if( is_null( $correctedtext ) ) {
599 wfDebug( "Tidy error detected!\n" );
600 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
602 return $correctedtext;
606 * Spawn an external HTML tidy process and get corrected markup back from it.
611 function externalTidy( $text ) {
612 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
613 $fname = 'Parser::externalTidy';
614 wfProfileIn( $fname );
619 $descriptorspec = array(
620 0 => array('pipe', 'r'),
621 1 => array('pipe', 'w'),
622 2 => array('file', '/dev/null', 'a')
625 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
626 if (is_resource($process)) {
627 // Theoretically, this style of communication could cause a deadlock
628 // here. If the stdout buffer fills up, then writes to stdin could
629 // block. This doesn't appear to happen with tidy, because tidy only
630 // writes to stdout after it's finished reading from stdin. Search
631 // for tidyParseStdin and tidySaveStdout in console/tidy.c
632 fwrite($pipes[0], $text);
634 while (!feof($pipes[1])) {
635 $cleansource .= fgets($pipes[1], 1024);
638 proc_close($process);
641 wfProfileOut( $fname );
643 if( $cleansource == '' && $text != '') {
644 // Some kind of error happened, so we couldn't get the corrected text.
645 // Just give up; we'll use the source text and append a warning.
653 * Use the HTML tidy PECL extension to use the tidy library in-process,
654 * saving the overhead of spawning a new process. Currently written to
655 * the PHP 4.3.x version of the extension, may not work on PHP 5.
657 * 'pear install tidy' should be able to compile the extension module.
662 function internalTidy( $text ) {
664 $fname = 'Parser::internalTidy';
665 wfProfileIn( $fname );
667 tidy_load_config( $wgTidyConf );
668 tidy_set_encoding( 'utf8' );
669 tidy_parse_string( $text );
671 if( tidy_get_status() == 2 ) {
672 // 2 is magic number for fatal error
673 // http://www.php.net/manual/en/function.tidy-get-status.php
676 $cleansource = tidy_get_output();
678 wfProfileOut( $fname );
683 * parse the wiki syntax used to render tables
687 function doTableStuff ( $t ) {
688 $fname = 'Parser::doTableStuff';
689 wfProfileIn( $fname );
691 $t = explode ( "\n" , $t ) ;
692 $td = array () ; # Is currently a td tag open?
693 $ltd = array () ; # Was it TD or TH?
694 $tr = array () ; # Is currently a tr tag open?
695 $ltr = array () ; # tr attributes
696 $has_opened_tr = array(); # Did this table open a <tr> element?
697 $indent_level = 0; # indent level of the table
698 foreach ( $t AS $k => $x )
701 $fc = substr ( $x , 0 , 1 ) ;
702 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
703 $indent_level = strlen( $matches[1] );
705 $attributes = $this->unstripForHTML( $matches[2] );
707 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
708 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
709 array_push ( $td , false ) ;
710 array_push ( $ltd , '' ) ;
711 array_push ( $tr , false ) ;
712 array_push ( $ltr , '' ) ;
713 array_push ( $has_opened_tr, false );
715 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
716 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
717 $z = "</table>" . substr ( $x , 2);
718 $l = array_pop ( $ltd ) ;
719 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
720 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
721 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
723 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
725 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
726 $x = substr ( $x , 1 ) ;
727 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
729 $l = array_pop ( $ltd ) ;
730 array_pop ( $has_opened_tr );
731 array_push ( $has_opened_tr , true ) ;
732 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
733 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
736 array_push ( $tr , false ) ;
737 array_push ( $td , false ) ;
738 array_push ( $ltd , '' ) ;
739 $attributes = $this->unstripForHTML( $x );
740 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
742 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
744 if ( '|+' == substr ( $x , 0 , 2 ) ) {
746 $x = substr ( $x , 1 ) ;
748 $after = substr ( $x , 1 ) ;
749 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
751 // Split up multiple cells on the same line.
752 // FIXME: This can result in improper nesting of tags processed
753 // by earlier parser steps, but should avoid splitting up eg
754 // attribute values containing literal "||".
755 $after = wfExplodeMarkup( '||', $after );
759 # Loop through each table cell
760 foreach ( $after AS $theline )
765 $tra = array_pop ( $ltr ) ;
766 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
767 array_push ( $tr , true ) ;
768 array_push ( $ltr , '' ) ;
769 array_pop ( $has_opened_tr );
770 array_push ( $has_opened_tr , true ) ;
773 $l = array_pop ( $ltd ) ;
774 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
775 if ( $fc == '|' ) $l = 'td' ;
776 else if ( $fc == '!' ) $l = 'th' ;
777 else if ( $fc == '+' ) $l = 'caption' ;
779 array_push ( $ltd , $l ) ;
782 $y = explode ( '|' , $theline , 2 ) ;
783 # Note that a '|' inside an invalid link should not
784 # be mistaken as delimiting cell parameters
785 if ( strpos( $y[0], '[[' ) !== false ) {
786 $y = array ($theline);
788 if ( count ( $y ) == 1 )
789 $y = "{$z}<{$l}>{$y[0]}" ;
791 $attributes = $this->unstripForHTML( $y[0] );
792 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
795 array_push ( $td , true ) ;
800 # Closing open td, tr && table
801 while ( count ( $td ) > 0 )
803 $l = array_pop ( $ltd ) ;
804 if ( array_pop ( $td ) ) $t[] = '</td>' ;
805 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
806 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
810 $t = implode ( "\n" , $t ) ;
811 # special case: don't return empty table
812 if($t == "<table>\n<tr><td></td></tr>\n</table>")
814 wfProfileOut( $fname );
819 * Helper function for parse() that transforms wiki markup into
820 * HTML. Only called for $mOutputType == OT_HTML.
824 function internalParse( $text ) {
827 $fname = 'Parser::internalParse';
828 wfProfileIn( $fname );
830 # Remove <noinclude> tags and <includeonly> sections
831 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
832 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
833 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
835 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
837 $text = $this->replaceVariables( $text, $args );
839 // Tables need to come after variable replacement for things to work
840 // properly; putting them before other transformations should keep
841 // exciting things like link expansions from showing up in surprising
843 $text = $this->doTableStuff( $text );
845 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
847 $text = $this->stripToc( $text );
848 $this->stripNoGallery( $text );
849 $text = $this->doHeadings( $text );
850 if($this->mOptions
->getUseDynamicDates()) {
851 $df =& DateFormatter
::getInstance();
852 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
854 $text = $this->doAllQuotes( $text );
855 $text = $this->replaceInternalLinks( $text );
856 $text = $this->replaceExternalLinks( $text );
858 # replaceInternalLinks may sometimes leave behind
859 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
860 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
862 $text = $this->doMagicLinks( $text );
863 $text = $this->formatHeadings( $text, $isMain );
865 wfProfileOut( $fname );
870 * Replace special strings like "ISBN xxx" and "RFC xxx" with
871 * magic external links.
875 function &doMagicLinks( &$text ) {
876 $text = $this->magicISBN( $text );
877 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
878 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
883 * Parse headers and return html
887 function doHeadings( $text ) {
888 $fname = 'Parser::doHeadings';
889 wfProfileIn( $fname );
890 for ( $i = 6; $i >= 1; --$i ) {
891 $h = str_repeat( '=', $i );
892 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
893 "<h{$i}>\\1</h{$i}>\\2", $text );
895 wfProfileOut( $fname );
900 * Replace single quotes with HTML markup
902 * @return string the altered text
904 function doAllQuotes( $text ) {
905 $fname = 'Parser::doAllQuotes';
906 wfProfileIn( $fname );
908 $lines = explode( "\n", $text );
909 foreach ( $lines as $line ) {
910 $outtext .= $this->doQuotes ( $line ) . "\n";
912 $outtext = substr($outtext, 0,-1);
913 wfProfileOut( $fname );
918 * Helper function for doAllQuotes()
921 function doQuotes( $text ) {
922 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
923 if ( count( $arr ) == 1 )
927 # First, do some preliminary work. This may shift some apostrophes from
928 # being mark-up to being text. It also counts the number of occurrences
929 # of bold and italics mark-ups.
933 foreach ( $arr as $r )
935 if ( ( $i %
2 ) == 1 )
937 # If there are ever four apostrophes, assume the first is supposed to
938 # be text, and the remaining three constitute mark-up for bold text.
939 if ( strlen( $arr[$i] ) == 4 )
944 # If there are more than 5 apostrophes in a row, assume they're all
945 # text except for the last 5.
946 else if ( strlen( $arr[$i] ) > 5 )
948 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
951 # Count the number of occurrences of bold and italics mark-ups.
952 # We are not counting sequences of five apostrophes.
953 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
954 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
955 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
960 # If there is an odd number of both bold and italics, it is likely
961 # that one of the bold ones was meant to be an apostrophe followed
962 # by italics. Which one we cannot know for certain, but it is more
963 # likely to be one that has a single-letter word before it.
964 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
967 $firstsingleletterword = -1;
968 $firstmultiletterword = -1;
970 foreach ( $arr as $r )
972 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
974 $x1 = substr ($arr[$i-1], -1);
975 $x2 = substr ($arr[$i-1], -2, 1);
977 if ($firstspace == -1) $firstspace = $i;
978 } else if ($x2 == ' ') {
979 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
981 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
987 # If there is a single-letter word, use it!
988 if ($firstsingleletterword > -1)
990 $arr [ $firstsingleletterword ] = "''";
991 $arr [ $firstsingleletterword-1 ] .= "'";
993 # If not, but there's a multi-letter word, use that one.
994 else if ($firstmultiletterword > -1)
996 $arr [ $firstmultiletterword ] = "''";
997 $arr [ $firstmultiletterword-1 ] .= "'";
999 # ... otherwise use the first one that has neither.
1000 # (notice that it is possible for all three to be -1 if, for example,
1001 # there is only one pentuple-apostrophe in the line)
1002 else if ($firstspace > -1)
1004 $arr [ $firstspace ] = "''";
1005 $arr [ $firstspace-1 ] .= "'";
1009 # Now let's actually convert our apostrophic mush to HTML!
1014 foreach ($arr as $r)
1018 if ($state == 'both')
1025 if (strlen ($r) == 2)
1028 { $output .= '</i>'; $state = ''; }
1029 else if ($state == 'bi')
1030 { $output .= '</i>'; $state = 'b'; }
1031 else if ($state == 'ib')
1032 { $output .= '</b></i><b>'; $state = 'b'; }
1033 else if ($state == 'both')
1034 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1035 else # $state can be 'b' or ''
1036 { $output .= '<i>'; $state .= 'i'; }
1038 else if (strlen ($r) == 3)
1041 { $output .= '</b>'; $state = ''; }
1042 else if ($state == 'bi')
1043 { $output .= '</i></b><i>'; $state = 'i'; }
1044 else if ($state == 'ib')
1045 { $output .= '</b>'; $state = 'i'; }
1046 else if ($state == 'both')
1047 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1048 else # $state can be 'i' or ''
1049 { $output .= '<b>'; $state .= 'b'; }
1051 else if (strlen ($r) == 5)
1054 { $output .= '</b><i>'; $state = 'i'; }
1055 else if ($state == 'i')
1056 { $output .= '</i><b>'; $state = 'b'; }
1057 else if ($state == 'bi')
1058 { $output .= '</i></b>'; $state = ''; }
1059 else if ($state == 'ib')
1060 { $output .= '</b></i>'; $state = ''; }
1061 else if ($state == 'both')
1062 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1063 else # ($state == '')
1064 { $buffer = ''; $state = 'both'; }
1069 # Now close all remaining tags. Notice that the order is important.
1070 if ($state == 'b' ||
$state == 'ib')
1072 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1076 if ($state == 'both')
1077 $output .= '<b><i>'.$buffer.'</i></b>';
1083 * Replace external links
1085 * Note: this is all very hackish and the order of execution matters a lot.
1086 * Make sure to run maintenance/parserTests.php if you change this code.
1090 function replaceExternalLinks( $text ) {
1092 $fname = 'Parser::replaceExternalLinks';
1093 wfProfileIn( $fname );
1095 $sk =& $this->mOptions
->getSkin();
1097 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1099 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1102 while ( $i<count( $bits ) ) {
1104 $protocol = $bits[$i++
];
1105 $text = $bits[$i++
];
1106 $trail = $bits[$i++
];
1108 # The characters '<' and '>' (which were escaped by
1109 # removeHTMLtags()) should not be included in
1110 # URLs, per RFC 2396.
1111 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1112 $text = substr($url, $m2[0][1]) . ' ' . $text;
1113 $url = substr($url, 0, $m2[0][1]);
1116 # If the link text is an image URL, replace it with an <img> tag
1117 # This happened by accident in the original parser, but some people used it extensively
1118 $img = $this->maybeMakeExternalImage( $text );
1119 if ( $img !== false ) {
1125 # Set linktype for CSS - if URL==text, link is essentially free
1126 $linktype = ($text == $url) ?
'free' : 'text';
1128 # No link text, e.g. [http://domain.tld/some.link]
1129 if ( $text == '' ) {
1130 # Autonumber if allowed. See bug #5918
1131 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1132 $text = '[' . ++
$this->mAutonumber
. ']';
1133 $linktype = 'autonumber';
1135 # Otherwise just use the URL
1136 $text = htmlspecialchars( $url );
1140 # Have link text, e.g. [http://domain.tld/some.link text]s
1142 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1145 $text = $wgContLang->markNoConversion($text);
1147 # Normalize any HTML entities in input. They will be
1148 # re-escaped by makeExternalLink().
1149 $url = Sanitizer
::decodeCharReferences( $url );
1151 # Escape any control characters introduced by the above step
1152 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1154 # Process the trail (i.e. everything after this link up until start of the next link),
1155 # replacing any non-bracketed links
1156 $trail = $this->replaceFreeExternalLinks( $trail );
1158 # Use the encoded URL
1159 # This means that users can paste URLs directly into the text
1160 # Funny characters like ö aren't valid in URLs anyway
1161 # This was changed in August 2004
1162 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1164 # Register link in the output object.
1165 # Replace unnecessary URL escape codes with the referenced character
1166 # This prevents spammers from hiding links from the filters
1167 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1168 $this->mOutput
->addExternalLink( $pasteurized );
1171 wfProfileOut( $fname );
1176 * Replace anything that looks like a URL with a link
1179 function replaceFreeExternalLinks( $text ) {
1181 $fname = 'Parser::replaceFreeExternalLinks';
1182 wfProfileIn( $fname );
1184 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1185 $s = array_shift( $bits );
1188 $sk =& $this->mOptions
->getSkin();
1190 while ( $i < count( $bits ) ){
1191 $protocol = $bits[$i++
];
1192 $remainder = $bits[$i++
];
1194 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1195 # Found some characters after the protocol that look promising
1196 $url = $protocol . $m[1];
1199 # special case: handle urls as url args:
1200 # http://www.example.com/foo?=http://www.example.com/bar
1201 if(strlen($trail) == 0 &&
1203 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1204 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1207 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1212 # The characters '<' and '>' (which were escaped by
1213 # removeHTMLtags()) should not be included in
1214 # URLs, per RFC 2396.
1215 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1216 $trail = substr($url, $m2[0][1]) . $trail;
1217 $url = substr($url, 0, $m2[0][1]);
1220 # Move trailing punctuation to $trail
1222 # If there is no left bracket, then consider right brackets fair game too
1223 if ( strpos( $url, '(' ) === false ) {
1227 $numSepChars = strspn( strrev( $url ), $sep );
1228 if ( $numSepChars ) {
1229 $trail = substr( $url, -$numSepChars ) . $trail;
1230 $url = substr( $url, 0, -$numSepChars );
1233 # Normalize any HTML entities in input. They will be
1234 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1235 $url = Sanitizer
::decodeCharReferences( $url );
1237 # Escape any control characters introduced by the above step
1238 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1240 # Is this an external image?
1241 $text = $this->maybeMakeExternalImage( $url );
1242 if ( $text === false ) {
1243 # Not an image, make a link
1244 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1245 # Register it in the output object...
1246 # Replace unnecessary URL escape codes with their equivalent characters
1247 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1248 $this->mOutput
->addExternalLink( $pasteurized );
1250 $s .= $text . $trail;
1252 $s .= $protocol . $remainder;
1255 wfProfileOut( $fname );
1260 * Replace unusual URL escape codes with their equivalent characters
1264 * @fixme This can merge genuinely required bits in the path or query string,
1265 * breaking legit URLs. A proper fix would treat the various parts of
1266 * the URL differently; as a workaround, just use the output for
1267 * statistical records, not for actual linking/output.
1269 function replaceUnusualEscapes( $url ) {
1270 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1271 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1275 * Callback function used in replaceUnusualEscapes().
1276 * Replaces unusual URL escape codes with their equivalent character
1280 function replaceUnusualEscapesCallback( $matches ) {
1281 $char = urldecode( $matches[0] );
1282 $ord = ord( $char );
1283 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1284 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1285 // No, shouldn't be escaped
1288 // Yes, leave it escaped
1294 * make an image if it's allowed, either through the global
1295 * option or through the exception
1298 function maybeMakeExternalImage( $url ) {
1299 $sk =& $this->mOptions
->getSkin();
1300 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1301 $imagesexception = !empty($imagesfrom);
1303 if ( $this->mOptions
->getAllowExternalImages()
1304 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1305 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1307 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1314 * Process [[ ]] wikilinks
1318 function replaceInternalLinks( $s ) {
1320 static $fname = 'Parser::replaceInternalLinks' ;
1322 wfProfileIn( $fname );
1324 wfProfileIn( $fname.'-setup' );
1326 # the % is needed to support urlencoded titles as well
1327 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1329 $sk =& $this->mOptions
->getSkin();
1331 #split the entire text string on occurences of [[
1332 $a = explode( '[[', ' ' . $s );
1333 #get the first element (all text up to first [[), and remove the space we added
1334 $s = array_shift( $a );
1335 $s = substr( $s, 1 );
1337 # Match a link having the form [[namespace:link|alternate]]trail
1339 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1340 # Match cases where there is no "]]", which might still be images
1341 static $e1_img = FALSE;
1342 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1343 # Match the end of a line for a word that's not followed by whitespace,
1344 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1345 $e2 = wfMsgForContent( 'linkprefix' );
1347 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1349 if( is_null( $this->mTitle
) ) {
1350 throw new MWException( 'nooo' );
1352 $nottalk = !$this->mTitle
->isTalkPage();
1354 if ( $useLinkPrefixExtension ) {
1355 if ( preg_match( $e2, $s, $m ) ) {
1356 $first_prefix = $m[2];
1358 $first_prefix = false;
1364 $selflink = $this->mTitle
->getPrefixedText();
1365 wfProfileOut( $fname.'-setup' );
1367 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1368 $useSubpages = $this->areSubpagesAllowed();
1370 # Loop for each link
1371 for ($k = 0; isset( $a[$k] ); $k++
) {
1373 if ( $useLinkPrefixExtension ) {
1374 wfProfileIn( $fname.'-prefixhandling' );
1375 if ( preg_match( $e2, $s, $m ) ) {
1383 $prefix = $first_prefix;
1384 $first_prefix = false;
1386 wfProfileOut( $fname.'-prefixhandling' );
1389 $might_be_img = false;
1391 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1393 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1394 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1395 # the real problem is with the $e1 regex
1398 # Still some problems for cases where the ] is meant to be outside punctuation,
1399 # and no image is in sight. See bug 2095.
1402 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1403 strpos($text, '[') !== false
1406 $text .= ']'; # so that replaceExternalLinks($text) works later
1409 # fix up urlencoded title texts
1410 if(preg_match('/%/', $m[1] ))
1411 # Should anchors '#' also be rejected?
1412 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1414 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1415 $might_be_img = true;
1417 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1419 } else { # Invalid form; output directly
1420 $s .= $prefix . '[[' . $line ;
1424 # Don't allow internal links to pages containing
1425 # PROTO: where PROTO is a valid URL protocol; these
1426 # should be external links.
1427 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1428 $s .= $prefix . '[[' . $line ;
1432 # Make subpage if necessary
1433 if( $useSubpages ) {
1434 $link = $this->maybeDoSubpageLink( $m[1], $text );
1439 $noforce = (substr($m[1], 0, 1) != ':');
1441 # Strip off leading ':'
1442 $link = substr($link, 1);
1445 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1447 $s .= $prefix . '[[' . $line;
1451 #check other language variants of the link
1452 #if the article does not exist
1453 if( $checkVariantLink
1454 && $nt->getArticleID() == 0 ) {
1455 $wgContLang->findVariantLink($link, $nt);
1458 $ns = $nt->getNamespace();
1459 $iw = $nt->getInterWiki();
1461 if ($might_be_img) { # if this is actually an invalid link
1462 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1464 while (isset ($a[$k+
1]) ) {
1465 #look at the next 'line' to see if we can close it there
1466 $spliced = array_splice( $a, $k +
1, 1 );
1467 $next_line = array_shift( $spliced );
1468 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1469 # the first ]] closes the inner link, the second the image
1471 $text .= '[[' . $m[1];
1474 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1475 #if there's exactly one ]] that's fine, we'll keep looking
1476 $text .= '[[' . $m[0];
1478 #if $next_line is invalid too, we need look no further
1479 $text .= '[[' . $next_line;
1484 # we couldn't find the end of this imageLink, so output it raw
1485 #but don't ignore what might be perfectly normal links in the text we've examined
1486 $text = $this->replaceInternalLinks($text);
1487 $s .= $prefix . '[[' . $link . '|' . $text;
1488 # note: no $trail, because without an end, there *is* no trail
1491 } else { #it's not an image, so output it raw
1492 $s .= $prefix . '[[' . $link . '|' . $text;
1493 # note: no $trail, because without an end, there *is* no trail
1498 $wasblank = ( '' == $text );
1499 if( $wasblank ) $text = $link;
1502 # Link not escaped by : , create the various objects
1506 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1507 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1508 $s = rtrim($s . "\n");
1509 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1513 if ( $ns == NS_IMAGE
) {
1514 wfProfileIn( "$fname-image" );
1515 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1516 # recursively parse links inside the image caption
1517 # actually, this will parse them in any other parameters, too,
1518 # but it might be hard to fix that, and it doesn't matter ATM
1519 $text = $this->replaceExternalLinks($text);
1520 $text = $this->replaceInternalLinks($text);
1522 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1523 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1524 $this->mOutput
->addImage( $nt->getDBkey() );
1526 wfProfileOut( "$fname-image" );
1529 wfProfileOut( "$fname-image" );
1533 if ( $ns == NS_CATEGORY
) {
1534 wfProfileIn( "$fname-category" );
1535 $s = rtrim($s . "\n"); # bug 87
1538 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1539 $sortkey = $this->mTitle
->getText();
1541 $sortkey = $this->mTitle
->getPrefixedText();
1546 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1547 $sortkey = str_replace( "\n", '', $sortkey );
1548 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1549 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1552 * Strip the whitespace Category links produce, see bug 87
1553 * @todo We might want to use trim($tmp, "\n") here.
1555 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1557 wfProfileOut( "$fname-category" );
1562 if( ( $nt->getPrefixedText() === $selflink ) &&
1563 ( $nt->getFragment() === '' ) ) {
1564 # Self-links are handled specially; generally de-link and change to bold.
1565 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1569 # Special and Media are pseudo-namespaces; no pages actually exist in them
1570 if( $ns == NS_MEDIA
) {
1571 $link = $sk->makeMediaLinkObj( $nt, $text );
1572 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1573 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1574 $this->mOutput
->addImage( $nt->getDBkey() );
1576 } elseif( $ns == NS_SPECIAL
) {
1577 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1579 } elseif( $ns == NS_IMAGE
) {
1580 $img = Image
::newFromTitle( $nt );
1581 if( $img->exists() ) {
1582 // Force a blue link if the file exists; may be a remote
1583 // upload on the shared repository, and we want to see its
1584 // auto-generated page.
1585 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1589 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1591 wfProfileOut( $fname );
1596 * Make a link placeholder. The text returned can be later resolved to a real link with
1597 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1598 * parsing of interwiki links, and secondly to allow all extistence checks and
1599 * article length checks (for stub links) to be bundled into a single query.
1602 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1603 if ( ! is_object($nt) ) {
1605 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1607 # Separate the link trail from the rest of the link
1608 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1610 if ( $nt->isExternal() ) {
1611 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1612 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1613 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1615 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1616 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1617 $this->mLinkHolders
['queries'][] = $query;
1618 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1619 $this->mLinkHolders
['titles'][] = $nt;
1621 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1628 * Render a forced-blue link inline; protect against double expansion of
1629 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1630 * Since this little disaster has to split off the trail text to avoid
1631 * breaking URLs in the following text without breaking trails on the
1632 * wiki links, it's been made into a horrible function.
1635 * @param string $text
1636 * @param string $query
1637 * @param string $trail
1638 * @param string $prefix
1639 * @return string HTML-wikitext mix oh yuck
1641 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1642 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1643 $sk =& $this->mOptions
->getSkin();
1644 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1645 return $this->armorLinks( $link ) . $trail;
1649 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1650 * going to go through further parsing steps before inline URL expansion.
1652 * In particular this is important when using action=render, which causes
1653 * full URLs to be included.
1655 * Oh man I hate our multi-layer parser!
1657 * @param string more-or-less HTML
1658 * @return string less-or-more HTML with NOPARSE bits
1660 function armorLinks( $text ) {
1661 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1662 "{$this->mUniqPrefix}NOPARSE$1", $text );
1666 * Return true if subpage links should be expanded on this page.
1669 function areSubpagesAllowed() {
1670 # Some namespaces don't allow subpages
1671 global $wgNamespacesWithSubpages;
1672 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1676 * Handle link to subpage if necessary
1677 * @param string $target the source of the link
1678 * @param string &$text the link text, modified as necessary
1679 * @return string the full name of the link
1682 function maybeDoSubpageLink($target, &$text) {
1685 # :Foobar -- override special treatment of prefix (images, language links)
1686 # /Foobar -- convert to CurrentPage/Foobar
1687 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1688 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1689 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1691 $fname = 'Parser::maybeDoSubpageLink';
1692 wfProfileIn( $fname );
1693 $ret = $target; # default return value is no change
1695 # Some namespaces don't allow subpages,
1696 # so only perform processing if subpages are allowed
1697 if( $this->areSubpagesAllowed() ) {
1698 # Look at the first character
1699 if( $target != '' && $target{0} == '/' ) {
1700 # / at end means we don't want the slash to be shown
1701 if( substr( $target, -1, 1 ) == '/' ) {
1702 $target = substr( $target, 1, -1 );
1705 $noslash = substr( $target, 1 );
1708 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1709 if( '' === $text ) {
1711 } # this might be changed for ugliness reasons
1713 # check for .. subpage backlinks
1715 $nodotdot = $target;
1716 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1718 $nodotdot = substr( $nodotdot, 3 );
1720 if($dotdotcount > 0) {
1721 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1722 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1723 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1724 # / at the end means don't show full path
1725 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1726 $nodotdot = substr( $nodotdot, 0, -1 );
1727 if( '' === $text ) {
1731 $nodotdot = trim( $nodotdot );
1732 if( $nodotdot != '' ) {
1733 $ret .= '/' . $nodotdot;
1740 wfProfileOut( $fname );
1745 * Used by doBlockLevels()
1748 /* private */ function closeParagraph() {
1750 if ( '' != $this->mLastSection
) {
1751 $result = '</' . $this->mLastSection
. ">\n";
1753 $this->mInPre
= false;
1754 $this->mLastSection
= '';
1757 # getCommon() returns the length of the longest common substring
1758 # of both arguments, starting at the beginning of both.
1760 /* private */ function getCommon( $st1, $st2 ) {
1761 $fl = strlen( $st1 );
1762 $shorter = strlen( $st2 );
1763 if ( $fl < $shorter ) { $shorter = $fl; }
1765 for ( $i = 0; $i < $shorter; ++
$i ) {
1766 if ( $st1{$i} != $st2{$i} ) { break; }
1770 # These next three functions open, continue, and close the list
1771 # element appropriate to the prefix character passed into them.
1773 /* private */ function openList( $char ) {
1774 $result = $this->closeParagraph();
1776 if ( '*' == $char ) { $result .= '<ul><li>'; }
1777 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1778 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1779 else if ( ';' == $char ) {
1780 $result .= '<dl><dt>';
1781 $this->mDTopen
= true;
1783 else { $result = '<!-- ERR 1 -->'; }
1788 /* private */ function nextItem( $char ) {
1789 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1790 else if ( ':' == $char ||
';' == $char ) {
1792 if ( $this->mDTopen
) { $close = '</dt>'; }
1793 if ( ';' == $char ) {
1794 $this->mDTopen
= true;
1795 return $close . '<dt>';
1797 $this->mDTopen
= false;
1798 return $close . '<dd>';
1801 return '<!-- ERR 2 -->';
1804 /* private */ function closeList( $char ) {
1805 if ( '*' == $char ) { $text = '</li></ul>'; }
1806 else if ( '#' == $char ) { $text = '</li></ol>'; }
1807 else if ( ':' == $char ) {
1808 if ( $this->mDTopen
) {
1809 $this->mDTopen
= false;
1810 $text = '</dt></dl>';
1812 $text = '</dd></dl>';
1815 else { return '<!-- ERR 3 -->'; }
1821 * Make lists from lines starting with ':', '*', '#', etc.
1824 * @return string the lists rendered as HTML
1826 function doBlockLevels( $text, $linestart ) {
1827 $fname = 'Parser::doBlockLevels';
1828 wfProfileIn( $fname );
1830 # Parsing through the text line by line. The main thing
1831 # happening here is handling of block-level elements p, pre,
1832 # and making lists from lines starting with * # : etc.
1834 $textLines = explode( "\n", $text );
1836 $lastPrefix = $output = '';
1837 $this->mDTopen
= $inBlockElem = false;
1839 $paragraphStack = false;
1841 if ( !$linestart ) {
1842 $output .= array_shift( $textLines );
1844 foreach ( $textLines as $oLine ) {
1845 $lastPrefixLength = strlen( $lastPrefix );
1846 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1847 $preOpenMatch = preg_match('/<pre/i', $oLine );
1848 if ( !$this->mInPre
) {
1849 # Multiple prefixes may abut each other for nested lists.
1850 $prefixLength = strspn( $oLine, '*#:;' );
1851 $pref = substr( $oLine, 0, $prefixLength );
1854 $pref2 = str_replace( ';', ':', $pref );
1855 $t = substr( $oLine, $prefixLength );
1856 $this->mInPre
= !empty($preOpenMatch);
1858 # Don't interpret any other prefixes in preformatted text
1860 $pref = $pref2 = '';
1865 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1866 # Same as the last item, so no need to deal with nesting or opening stuff
1867 $output .= $this->nextItem( substr( $pref, -1 ) );
1868 $paragraphStack = false;
1870 if ( substr( $pref, -1 ) == ';') {
1871 # The one nasty exception: definition lists work like this:
1872 # ; title : definition text
1873 # So we check for : in the remainder text to split up the
1874 # title and definition, without b0rking links.
1876 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1878 $output .= $term . $this->nextItem( ':' );
1881 } elseif( $prefixLength ||
$lastPrefixLength ) {
1882 # Either open or close a level...
1883 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1884 $paragraphStack = false;
1886 while( $commonPrefixLength < $lastPrefixLength ) {
1887 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1888 --$lastPrefixLength;
1890 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1891 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1893 while ( $prefixLength > $commonPrefixLength ) {
1894 $char = substr( $pref, $commonPrefixLength, 1 );
1895 $output .= $this->openList( $char );
1897 if ( ';' == $char ) {
1898 # FIXME: This is dupe of code above
1899 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1901 $output .= $term . $this->nextItem( ':' );
1904 ++
$commonPrefixLength;
1906 $lastPrefix = $pref2;
1908 if( 0 == $prefixLength ) {
1909 wfProfileIn( "$fname-paragraph" );
1910 # No prefix (not in list)--go to paragraph mode
1911 // XXX: use a stack for nestable elements like span, table and div
1912 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1913 $closematch = preg_match(
1914 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1915 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1916 if ( $openmatch or $closematch ) {
1917 $paragraphStack = false;
1918 #Â TODO bug 5718: paragraph closed
1919 $output .= $this->closeParagraph();
1920 if ( $preOpenMatch and !$preCloseMatch ) {
1921 $this->mInPre
= true;
1923 if ( $closematch ) {
1924 $inBlockElem = false;
1926 $inBlockElem = true;
1928 } else if ( !$inBlockElem && !$this->mInPre
) {
1929 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1931 if ($this->mLastSection
!= 'pre') {
1932 $paragraphStack = false;
1933 $output .= $this->closeParagraph().'<pre>';
1934 $this->mLastSection
= 'pre';
1936 $t = substr( $t, 1 );
1939 if ( '' == trim($t) ) {
1940 if ( $paragraphStack ) {
1941 $output .= $paragraphStack.'<br />';
1942 $paragraphStack = false;
1943 $this->mLastSection
= 'p';
1945 if ($this->mLastSection
!= 'p' ) {
1946 $output .= $this->closeParagraph();
1947 $this->mLastSection
= '';
1948 $paragraphStack = '<p>';
1950 $paragraphStack = '</p><p>';
1954 if ( $paragraphStack ) {
1955 $output .= $paragraphStack;
1956 $paragraphStack = false;
1957 $this->mLastSection
= 'p';
1958 } else if ($this->mLastSection
!= 'p') {
1959 $output .= $this->closeParagraph().'<p>';
1960 $this->mLastSection
= 'p';
1965 wfProfileOut( "$fname-paragraph" );
1967 // somewhere above we forget to get out of pre block (bug 785)
1968 if($preCloseMatch && $this->mInPre
) {
1969 $this->mInPre
= false;
1971 if ($paragraphStack === false) {
1975 while ( $prefixLength ) {
1976 $output .= $this->closeList( $pref2{$prefixLength-1} );
1979 if ( '' != $this->mLastSection
) {
1980 $output .= '</' . $this->mLastSection
. '>';
1981 $this->mLastSection
= '';
1984 wfProfileOut( $fname );
1989 * Split up a string on ':', ignoring any occurences inside tags
1990 * to prevent illegal overlapping.
1991 * @param string $str the string to split
1992 * @param string &$before set to everything before the ':'
1993 * @param string &$after set to everything after the ':'
1994 * return string the position of the ':', or false if none found
1996 function findColonNoLinks($str, &$before, &$after) {
1997 $fname = 'Parser::findColonNoLinks';
1998 wfProfileIn( $fname );
2000 $pos = strpos( $str, ':' );
2001 if( $pos === false ) {
2003 wfProfileOut( $fname );
2007 $lt = strpos( $str, '<' );
2008 if( $lt === false ||
$lt > $pos ) {
2009 // Easy; no tag nesting to worry about
2010 $before = substr( $str, 0, $pos );
2011 $after = substr( $str, $pos+
1 );
2012 wfProfileOut( $fname );
2016 // Ugly state machine to walk through avoiding tags.
2017 $state = MW_COLON_STATE_TEXT
;
2019 $len = strlen( $str );
2020 for( $i = 0; $i < $len; $i++
) {
2024 // (Using the number is a performance hack for common cases)
2025 case 0: // MW_COLON_STATE_TEXT:
2028 // Could be either a <start> tag or an </end> tag
2029 $state = MW_COLON_STATE_TAGSTART
;
2034 $before = substr( $str, 0, $i );
2035 $after = substr( $str, $i +
1 );
2036 wfProfileOut( $fname );
2039 // Embedded in a tag; don't break it.
2042 // Skip ahead looking for something interesting
2043 $colon = strpos( $str, ':', $i );
2044 if( $colon === false ) {
2045 // Nothing else interesting
2046 wfProfileOut( $fname );
2049 $lt = strpos( $str, '<', $i );
2050 if( $stack === 0 ) {
2051 if( $lt === false ||
$colon < $lt ) {
2053 $before = substr( $str, 0, $colon );
2054 $after = substr( $str, $colon +
1 );
2055 wfProfileOut( $fname );
2059 if( $lt === false ) {
2060 // Nothing else interesting to find; abort!
2061 // We're nested, but there's no close tags left. Abort!
2064 // Skip ahead to next tag start
2066 $state = MW_COLON_STATE_TAGSTART
;
2069 case 1: // MW_COLON_STATE_TAG:
2074 $state = MW_COLON_STATE_TEXT
;
2077 // Slash may be followed by >?
2078 $state = MW_COLON_STATE_TAGSLASH
;
2084 case 2: // MW_COLON_STATE_TAGSTART:
2087 $state = MW_COLON_STATE_CLOSETAG
;
2090 $state = MW_COLON_STATE_COMMENT
;
2093 // Illegal early close? This shouldn't happen D:
2094 $state = MW_COLON_STATE_TEXT
;
2097 $state = MW_COLON_STATE_TAG
;
2100 case 3: // MW_COLON_STATE_CLOSETAG:
2105 wfDebug( "Invalid input in $fname; too many close tags\n" );
2106 wfProfileOut( $fname );
2109 $state = MW_COLON_STATE_TEXT
;
2112 case MW_COLON_STATE_TAGSLASH
:
2114 // Yes, a self-closed tag <blah/>
2115 $state = MW_COLON_STATE_TEXT
;
2117 // Probably we're jumping the gun, and this is an attribute
2118 $state = MW_COLON_STATE_TAG
;
2121 case 5: // MW_COLON_STATE_COMMENT:
2123 $state = MW_COLON_STATE_COMMENTDASH
;
2126 case MW_COLON_STATE_COMMENTDASH
:
2128 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2130 $state = MW_COLON_STATE_COMMENT
;
2133 case MW_COLON_STATE_COMMENTDASHDASH
:
2135 $state = MW_COLON_STATE_TEXT
;
2137 $state = MW_COLON_STATE_COMMENT
;
2141 throw new MWException( "State machine error in $fname" );
2145 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2148 wfProfileOut( $fname );
2153 * Return value of a magic variable (like PAGENAME)
2157 function getVariableValue( $index ) {
2158 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2161 * Some of these require message or data lookups and can be
2162 * expensive to check many times.
2164 static $varCache = array();
2165 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2166 if ( isset( $varCache[$index] ) )
2167 return $varCache[$index];
2170 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2173 case MAG_CURRENTMONTH
:
2174 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2175 case MAG_CURRENTMONTHNAME
:
2176 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2177 case MAG_CURRENTMONTHNAMEGEN
:
2178 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2179 case MAG_CURRENTMONTHABBREV
:
2180 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2181 case MAG_CURRENTDAY
:
2182 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2183 case MAG_CURRENTDAY2
:
2184 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2186 return $this->mTitle
->getText();
2188 return $this->mTitle
->getPartialURL();
2189 case MAG_FULLPAGENAME
:
2190 return $this->mTitle
->getPrefixedText();
2191 case MAG_FULLPAGENAMEE
:
2192 return $this->mTitle
->getPrefixedURL();
2193 case MAG_SUBPAGENAME
:
2194 return $this->mTitle
->getSubpageText();
2195 case MAG_SUBPAGENAMEE
:
2196 return $this->mTitle
->getSubpageUrlForm();
2197 case MAG_BASEPAGENAME
:
2198 return $this->mTitle
->getBaseText();
2199 case MAG_BASEPAGENAMEE
:
2200 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2201 case MAG_TALKPAGENAME
:
2202 if( $this->mTitle
->canTalk() ) {
2203 $talkPage = $this->mTitle
->getTalkPage();
2204 return $talkPage->getPrefixedText();
2208 case MAG_TALKPAGENAMEE
:
2209 if( $this->mTitle
->canTalk() ) {
2210 $talkPage = $this->mTitle
->getTalkPage();
2211 return $talkPage->getPrefixedUrl();
2215 case MAG_SUBJECTPAGENAME
:
2216 $subjPage = $this->mTitle
->getSubjectPage();
2217 return $subjPage->getPrefixedText();
2218 case MAG_SUBJECTPAGENAMEE
:
2219 $subjPage = $this->mTitle
->getSubjectPage();
2220 return $subjPage->getPrefixedUrl();
2221 case MAG_REVISIONID
:
2222 return $this->mRevisionId
;
2224 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2225 case MAG_NAMESPACEE
:
2226 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2228 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2229 case MAG_TALKSPACEE
:
2230 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2231 case MAG_SUBJECTSPACE
:
2232 return $this->mTitle
->getSubjectNsText();
2233 case MAG_SUBJECTSPACEE
:
2234 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2235 case MAG_CURRENTDAYNAME
:
2236 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2237 case MAG_CURRENTYEAR
:
2238 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2239 case MAG_CURRENTTIME
:
2240 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2241 case MAG_CURRENTWEEK
:
2242 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2243 // int to remove the padding
2244 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2245 case MAG_CURRENTDOW
:
2246 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2247 case MAG_NUMBEROFARTICLES
:
2248 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2249 case MAG_NUMBEROFFILES
:
2250 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2251 case MAG_NUMBEROFUSERS
:
2252 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2253 case MAG_NUMBEROFPAGES
:
2254 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2255 case MAG_NUMBEROFADMINS
:
2256 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2257 case MAG_CURRENTTIMESTAMP
:
2258 return $varCache[$index] = wfTimestampNow();
2259 case MAG_CURRENTVERSION
:
2266 case MAG_SERVERNAME
:
2267 return $wgServerName;
2268 case MAG_SCRIPTPATH
:
2269 return $wgScriptPath;
2270 case MAG_DIRECTIONMARK
:
2271 return $wgContLang->getDirMark();
2272 case MAG_CONTENTLANGUAGE
:
2273 global $wgContLanguageCode;
2274 return $wgContLanguageCode;
2277 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2285 * initialise the magic variables (like CURRENTMONTHNAME)
2289 function initialiseVariables() {
2290 $fname = 'Parser::initialiseVariables';
2291 wfProfileIn( $fname );
2292 global $wgVariableIDs;
2293 $this->mVariables
= array();
2294 foreach ( $wgVariableIDs as $id ) {
2295 $mw =& MagicWord
::get( $id );
2296 $mw->addToArray( $this->mVariables
, $id );
2298 wfProfileOut( $fname );
2302 * parse any parentheses in format ((title|part|part))
2303 * and call callbacks to get a replacement text for any found piece
2305 * @param string $text The text to parse
2306 * @param array $callbacks rules in form:
2307 * '{' => array( # opening parentheses
2308 * 'end' => '}', # closing parentheses
2309 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2310 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2315 function replace_callback ($text, $callbacks) {
2316 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2317 $lastOpeningBrace = -1; # last not closed parentheses
2319 for ($i = 0; $i < strlen($text); $i++
) {
2320 # check for any opening brace
2323 foreach ($callbacks as $key => $value) {
2324 $pos = strpos ($text, $key, $i);
2325 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2331 if ($lastOpeningBrace >= 0) {
2332 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2334 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2339 $pos = strpos ($text, '|', $i);
2341 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2352 # found openning brace, lets add it to parentheses stack
2353 if (null != $rule) {
2354 $piece = array('brace' => $text[$i],
2355 'braceEnd' => $rule['end'],
2360 # count openning brace characters
2361 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2366 $piece['startAt'] = $i+
1;
2367 $piece['partStart'] = $i+
1;
2369 # we need to add to stack only if openning brace count is enough for any given rule
2370 foreach ($rule['cb'] as $cnt => $fn) {
2371 if ($piece['count'] >= $cnt) {
2372 $lastOpeningBrace ++
;
2373 $openingBraceStack[$lastOpeningBrace] = $piece;
2380 else if ($lastOpeningBrace >= 0) {
2381 # first check if it is a closing brace
2382 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2383 # lets check if it is enough characters for closing brace
2385 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2388 # if there are more closing parentheses than opening ones, we parse less
2389 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2390 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2392 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2394 $matchingCallback = null;
2395 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2396 if ($count >= $cnt && $matchingCount < $cnt) {
2397 $matchingCount = $cnt;
2398 $matchingCallback = $fn;
2402 if ($matchingCount == 0) {
2407 # lets set a title or last part (if '|' was found)
2408 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2409 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2411 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2413 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2414 $pieceEnd = $i +
$matchingCount;
2416 if( is_callable( $matchingCallback ) ) {
2418 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2419 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2420 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2421 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2423 # finally we can call a user callback and replace piece of text
2424 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2425 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2426 $i = $pieceStart +
strlen($replaceWith) - 1;
2429 # null value for callback means that parentheses should be parsed, but not replaced
2430 $i +
= $matchingCount - 1;
2433 # reset last openning parentheses, but keep it in case there are unused characters
2434 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2435 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2436 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2439 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2440 $openingBraceStack[$lastOpeningBrace--] = null;
2442 if ($matchingCount < $piece['count']) {
2443 $piece['count'] -= $matchingCount;
2444 $piece['startAt'] -= $matchingCount;
2445 $piece['partStart'] = $piece['startAt'];
2446 # do we still qualify for any callback with remaining count?
2447 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2448 if ($piece['count'] >= $cnt) {
2449 $lastOpeningBrace ++
;
2450 $openingBraceStack[$lastOpeningBrace] = $piece;
2458 # lets set a title if it is a first separator, or next part otherwise
2459 if ($text[$i] == '|') {
2460 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2461 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2462 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2465 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2467 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2476 * Replace magic variables, templates, and template arguments
2477 * with the appropriate text. Templates are substituted recursively,
2478 * taking care to avoid infinite loops.
2480 * Note that the substitution depends on value of $mOutputType:
2481 * OT_WIKI: only {{subst:}} templates
2482 * OT_MSG: only magic variables
2483 * OT_HTML: all templates and magic variables
2485 * @param string $tex The text to transform
2486 * @param array $args Key-value pairs representing template parameters to substitute
2487 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2490 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2491 # Prevent too big inclusions
2492 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2496 $fname = 'Parser::replaceVariables';
2497 wfProfileIn( $fname );
2499 # This function is called recursively. To keep track of arguments we need a stack:
2500 array_push( $this->mArgStack
, $args );
2502 $braceCallbacks = array();
2504 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2506 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2507 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2509 $callbacks = array();
2510 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2511 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2512 $text = $this->replace_callback ($text, $callbacks);
2514 array_pop( $this->mArgStack
);
2516 wfProfileOut( $fname );
2521 * Replace magic variables
2524 function variableSubstitution( $matches ) {
2525 $fname = 'Parser::variableSubstitution';
2526 $varname = $matches[1];
2527 wfProfileIn( $fname );
2528 if ( !$this->mVariables
) {
2529 $this->initialiseVariables();
2532 if ( $this->mOutputType
== OT_WIKI
) {
2533 # Do only magic variables prefixed by SUBST
2534 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2535 if (!$mwSubst->matchStartAndRemove( $varname ))
2537 # Note that if we don't substitute the variable below,
2538 # we don't remove the {{subst:}} magic word, in case
2539 # it is a template rather than a magic variable.
2541 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2542 $id = $this->mVariables
[$varname];
2543 $text = $this->getVariableValue( $id );
2544 $this->mOutput
->mContainsOldMagic
= true;
2546 $text = $matches[0];
2548 wfProfileOut( $fname );
2552 # Split template arguments
2553 function getTemplateArgs( $argsString ) {
2554 if ( $argsString === '' ) {
2558 $args = explode( '|', substr( $argsString, 1 ) );
2560 # If any of the arguments contains a '[[' but no ']]', it needs to be
2561 # merged with the next arg because the '|' character between belongs
2562 # to the link syntax and not the template parameter syntax.
2563 $argc = count($args);
2565 for ( $i = 0; $i < $argc-1; $i++
) {
2566 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2567 $args[$i] .= '|'.$args[$i+
1];
2568 array_splice($args, $i+
1, 1);
2578 * Return the text of a template, after recursively
2579 * replacing any variables or templates within the template.
2581 * @param array $piece The parts of the template
2582 * $piece['text']: matched text
2583 * $piece['title']: the title, i.e. the part before the |
2584 * $piece['parts']: the parameter array
2585 * @return string the text of the template
2588 function braceSubstitution( $piece ) {
2589 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2590 $fname = 'Parser::braceSubstitution';
2591 wfProfileIn( $fname );
2594 $found = false; # $text has been filled
2595 $nowiki = false; # wiki markup in $text should be escaped
2596 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2597 $noargs = false; # Don't replace triple-brace arguments in $text
2598 $replaceHeadings = false; # Make the edit section links go to the template not the article
2599 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2600 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2602 # Title object, where $text came from
2607 # $part1 is the bit before the first |, and must contain only title characters
2608 # $args is a list of arguments, starting from index 0, not including $part1
2610 $part1 = $piece['title'];
2611 # If the third subpattern matched anything, it will start with |
2613 if (null == $piece['parts']) {
2614 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2615 if ($replaceWith != $piece['text']) {
2616 $text = $replaceWith;
2623 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2624 $argc = count( $args );
2628 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2629 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2630 # One of two possibilities is true:
2631 # 1) Found SUBST but not in the PST phase
2632 # 2) Didn't find SUBST and in the PST phase
2633 # In either case, return without further processing
2634 $text = $piece['text'];
2641 # MSG, MSGNW, INT and RAW
2644 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2645 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2648 # Remove obsolete MSG:
2649 $mwMsg =& MagicWord
::get( MAG_MSG
);
2650 $mwMsg->matchStartAndRemove( $part1 );
2654 $mwRaw =& MagicWord
::get( MAG_RAW
);
2655 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2656 $forceRawInterwiki = true;
2659 # Check if it is an internal message
2660 $mwInt =& MagicWord
::get( MAG_INT
);
2661 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2662 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2663 $text = $linestart . wfMsgReal( $part1, $args, true );
2671 # Check for NS: (namespace expansion)
2672 $mwNs = MagicWord
::get( MAG_NS
);
2673 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2674 if ( intval( $part1 ) ||
$part1 == "0" ) {
2675 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2678 $param = str_replace( ' ', '_', strtolower( $part1 ) );
2679 $index = Namespace::getCanonicalIndex( strtolower( $param ) );
2680 if ( !is_null( $index ) ) {
2681 $text = $linestart . $wgContLang->getNsText( $index );
2690 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2691 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2692 $text = $linestart . urlencode( $part1 );
2697 # LCFIRST, UCFIRST, LC and UC
2699 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2700 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2701 $lc =& MagicWord
::get( MAG_LC
);
2702 $uc =& MagicWord
::get( MAG_UC
);
2703 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2704 $text = $linestart . $wgContLang->lcfirst( $part1 );
2706 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2707 $text = $linestart . $wgContLang->ucfirst( $part1 );
2709 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2710 $text = $linestart . $wgContLang->lc( $part1 );
2712 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2713 $text = $linestart . $wgContLang->uc( $part1 );
2718 # LOCALURL and FULLURL
2720 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2721 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2722 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2723 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2726 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2727 $func = 'getLocalURL';
2728 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2729 $func = 'escapeLocalURL';
2730 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2731 $func = 'getFullURL';
2732 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2733 $func = 'escapeFullURL';
2738 if ( $func !== false ) {
2739 $title = Title
::newFromText( $part1 );
2740 # Due to order of execution of a lot of bits, the values might be encoded
2741 # before arriving here; if that's true, then the title can't be created
2742 # and the variable will fail. If we can't get a decent title from the first
2743 # attempt, url-decode and try for a second.
2744 if( is_null( $title ) )
2745 $title = Title
::newFromUrl( urldecode( $part1 ) );
2746 if ( !is_null( $title ) ) {
2748 $text = $linestart . $title->$func( $args[0] );
2750 $text = $linestart . $title->$func();
2757 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2758 if ( !$found && $argc == 1 ) {
2759 $mwGrammar =& MagicWord
::get( MAG_FORMATNUM
);
2760 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2761 $text = $linestart . $lang->formatNum( $args[0] );
2768 if ( !$found && $argc == 1 ) {
2769 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2770 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2771 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2777 if ( !$found && $argc >= 2 ) {
2778 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2779 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2780 while ( count($args) < 5 ) { $args[] = $args[count($args)-1]; }
2781 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1],
2782 $args[2], $args[3], $args[4]);
2788 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2789 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2790 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2792 # Set title in parser output object
2794 $parserOptions = new ParserOptions
;
2795 $local_parser = new Parser ();
2796 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2797 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2800 $t = $this->mTitle
->getPrefixedText();
2801 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2807 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2809 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2810 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2811 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2812 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles',
2813 MAG_NUMBEROFADMINS
=> 'wfNumberOfAdmins' );
2814 foreach( $mwWordsToCheck as $word => $func ) {
2815 $mwCurrentWord =& MagicWord
::get( $word );
2816 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2817 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2818 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2819 # Raw and unformatted
2820 $text = $linestart . call_user_func( $func );
2822 # Formatted according to the content default
2823 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2832 $mwPagesInNs =& MagicWord
::get( MAG_PAGESINNAMESPACE
);
2833 if( $mwPagesInNs->matchStartAndRemove( $part1 ) ) {
2835 $count = wfPagesInNs( intval( $part1 ) );
2836 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2837 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2838 $text = $linestart . $count;
2840 $text = $linestart . $wgContLang->formatNum( $count );
2847 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2848 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2849 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2850 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2856 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2857 $colonPos = strpos( $part1, ':' );
2858 if ( $colonPos !== false ) {
2859 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2860 if ( isset( $this->mFunctionSynonyms
[$function] ) ) {
2861 $function = $this->mFunctionSynonyms
[$function];
2863 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2864 $funcArgs = array_map( 'trim', $args );
2865 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2866 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2869 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2873 if ( is_array( $result ) ) {
2874 $text = $linestart . $result[0];
2875 unset( $result[0] );
2877 // Extract flags into the local scope
2878 // This allows callers to set flags such as nowiki, noparse, found, etc.
2881 $text = $linestart . $result;
2887 # Template table test
2889 # Did we encounter this template already? If yes, it is in the cache
2890 # and we need to check for loops.
2891 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2894 # Infinite loop test
2895 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2899 $text = $linestart .
2900 '{{' . $part1 . '}}' .
2901 '<!-- WARNING: template loop detected -->';
2902 wfDebug( "$fname: template loop broken at '$part1'\n" );
2904 # set $text to cached message.
2905 $text = $linestart . $this->mTemplates
[$piece['title']];
2909 # Load from database
2910 $lastPathLevel = $this->mTemplatePath
;
2913 # declaring $subpage directly in the function call
2914 # does not work correctly with references and breaks
2915 # {{/subpage}}-style inclusions
2917 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2918 if ($subpage !== '') {
2919 $ns = $this->mTitle
->getNamespace();
2921 $title = Title
::newFromText( $part1, $ns );
2924 if ( !is_null( $title ) ) {
2925 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2926 # Check for language variants if the template is not found
2927 if($checkVariantLink && $title->getArticleID() == 0){
2928 $wgContLang->findVariantLink($part1, $title);
2931 if ( !$title->isExternal() ) {
2932 # Check for excessive inclusion
2933 $dbk = $title->getPrefixedDBkey();
2934 if ( $this->incrementIncludeCount( $dbk ) ) {
2935 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2936 $text = SpecialPage
::capturePath( $title );
2937 if ( is_string( $text ) ) {
2942 $this->disableCache();
2945 $articleContent = $this->fetchTemplate( $title );
2946 if ( $articleContent !== false ) {
2948 $text = $articleContent;
2949 $replaceHeadings = true;
2954 # If the title is valid but undisplayable, make a link to it
2955 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2956 $text = '[['.$title->getPrefixedText().']]';
2959 } elseif ( $title->isTrans() ) {
2960 // Interwiki transclusion
2961 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2962 $text = $this->interwikiTransclude( $title, 'render' );
2966 $text = $this->interwikiTransclude( $title, 'raw' );
2967 $replaceHeadings = true;
2972 # Template cache array insertion
2973 # Use the original $piece['title'] not the mangled $part1, so that
2974 # modifiers such as RAW: produce separate cache entries
2977 // A special page; don't store it in the template cache.
2979 $this->mTemplates
[$piece['title']] = $text;
2981 $text = $linestart . $text;
2986 # Recursive parsing, escaping and link table handling
2987 # Only for HTML output
2988 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2989 $text = wfEscapeWikiText( $text );
2990 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2992 $assocArgs = array();
2994 # Clean up argument array
2995 $assocArgs = array();
2997 foreach( $args as $arg ) {
2998 $eqpos = strpos( $arg, '=' );
2999 if ( $eqpos === false ) {
3000 $assocArgs[$index++
] = $arg;
3002 $name = trim( substr( $arg, 0, $eqpos ) );
3003 $value = trim( substr( $arg, $eqpos+
1 ) );
3004 if ( $value === false ) {
3007 if ( $name !== false ) {
3008 $assocArgs[$name] = $value;
3013 # Add a new element to the templace recursion path
3014 $this->mTemplatePath
[$part1] = 1;
3018 # If there are any <onlyinclude> tags, only include them
3019 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3020 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3022 foreach ($m[1] as $piece)
3025 # Remove <noinclude> sections and <includeonly> tags
3026 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3027 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3029 if( $this->mOutputType
== OT_HTML
) {
3030 # Strip <nowiki>, <pre>, etc.
3031 $text = $this->strip( $text, $this->mStripState
);
3032 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3034 $text = $this->replaceVariables( $text, $assocArgs );
3036 # If the template begins with a table or block-level
3037 # element, it should be treated as beginning a new line.
3038 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
3039 $text = "\n" . $text;
3041 } elseif ( !$noargs ) {
3042 # $noparse and !$noargs
3043 # Just replace the arguments, not any double-brace items
3044 # This is used for rendered interwiki transclusion
3045 $text = $this->replaceVariables( $text, $assocArgs, true );
3048 # Prune lower levels off the recursion check path
3049 $this->mTemplatePath
= $lastPathLevel;
3052 wfProfileOut( $fname );
3053 return $piece['text'];
3056 # Replace raw HTML by a placeholder
3057 # Add a blank line preceding, to prevent it from mucking up
3058 # immediately preceding headings
3059 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3061 # replace ==section headers==
3062 # XXX this needs to go away once we have a better parser.
3063 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3064 if( !is_null( $title ) )
3065 $encodedname = base64_encode($title->getPrefixedDBkey());
3067 $encodedname = base64_encode("");
3068 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3069 PREG_SPLIT_DELIM_CAPTURE
);
3072 for( $i = 0; $i < count($m); $i +
= 2 ) {
3074 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3076 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3080 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3081 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3082 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3090 # Prune lower levels off the recursion check path
3091 $this->mTemplatePath
= $lastPathLevel;
3094 wfProfileOut( $fname );
3095 return $piece['text'];
3097 wfProfileOut( $fname );
3103 * Fetch the unparsed text of a template and register a reference to it.
3105 function fetchTemplate( $title ) {
3107 // Loop to fetch the article, with up to 1 redirect
3108 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3109 $rev = Revision
::newFromTitle( $title );
3110 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3114 $text = $rev->getText();
3115 if ( $text === false ) {
3119 $title = Title
::newFromRedirect( $text );
3125 * Transclude an interwiki link.
3127 function interwikiTransclude( $title, $action ) {
3128 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3130 if (!$wgEnableScaryTranscluding)
3131 return wfMsg('scarytranscludedisabled');
3133 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3134 // But we'll handle it generally anyway
3135 if ( $title->getNamespace() ) {
3136 // Use the canonical namespace, which should work anywhere
3137 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3139 $articleName = $title->getDBkey();
3142 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3143 $url .= "?action=$action";
3144 if (strlen($url) > 255)
3145 return wfMsg('scarytranscludetoolong');
3146 return $this->fetchScaryTemplateMaybeFromCache($url);
3149 function fetchScaryTemplateMaybeFromCache($url) {
3150 global $wgTranscludeCacheExpiry;
3151 $dbr =& wfGetDB(DB_SLAVE
);
3152 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3153 array('tc_url' => $url));
3155 $time = $obj->tc_time
;
3156 $text = $obj->tc_contents
;
3157 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3162 $text = Http
::get($url);
3164 return wfMsg('scarytranscludefailed', $url);
3166 $dbw =& wfGetDB(DB_MASTER
);
3167 $dbw->replace('transcache', array('tc_url'), array(
3169 'tc_time' => time(),
3170 'tc_contents' => $text));
3176 * Triple brace replacement -- used for template arguments
3179 function argSubstitution( $matches ) {
3180 $arg = trim( $matches['title'] );
3181 $text = $matches['text'];
3182 $inputArgs = end( $this->mArgStack
);
3184 if ( array_key_exists( $arg, $inputArgs ) ) {
3185 $text = $inputArgs[$arg];
3186 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3187 $text = $matches['parts'][0];
3194 * Returns true if the function is allowed to include this entity
3197 function incrementIncludeCount( $dbk ) {
3198 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3199 $this->mIncludeCount
[$dbk] = 0;
3201 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3209 * Detect __NOGALLERY__ magic word and set a placeholder
3211 function stripNoGallery( &$text ) {
3212 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3214 $mw = MagicWord
::get( MAG_NOGALLERY
);
3215 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3219 * Detect __TOC__ magic word and set a placeholder
3221 function stripToc( $text ) {
3222 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3224 $mw = MagicWord
::get( MAG_NOTOC
);
3225 if( $mw->matchAndRemove( $text ) ) {
3226 $this->mShowToc
= false;
3229 $mw = MagicWord
::get( MAG_TOC
);
3230 if( $mw->match( $text ) ) {
3231 $this->mShowToc
= true;
3232 $this->mForceTocPosition
= true;
3234 // Set a placeholder. At the end we'll fill it in with the TOC.
3235 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3237 // Only keep the first one.
3238 $text = $mw->replace( '', $text );
3244 * This function accomplishes several tasks:
3245 * 1) Auto-number headings if that option is enabled
3246 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3247 * 3) Add a Table of contents on the top for users who have enabled the option
3248 * 4) Auto-anchor headings
3250 * It loops through all headlines, collects the necessary data, then splits up the
3251 * string and re-inserts the newly formatted headlines.
3253 * @param string $text
3254 * @param boolean $isMain
3257 function formatHeadings( $text, $isMain=true ) {
3258 global $wgMaxTocLevel, $wgContLang;
3260 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3261 if( !$this->mTitle
->userCanEdit() ) {
3264 $showEditLink = $this->mOptions
->getEditSection();
3267 # Inhibit editsection links if requested in the page
3268 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3269 if( $esw->matchAndRemove( $text ) ) {
3273 # Get all headlines for numbering them and adding funky stuff like [edit]
3274 # links - this is for later, but we need the number of headlines right now
3275 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3277 # if there are fewer than 4 headlines in the article, do not show TOC
3278 # unless it's been explicitly enabled.
3279 $enoughToc = $this->mShowToc
&&
3280 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3282 # Allow user to stipulate that a page should have a "new section"
3283 # link added via __NEWSECTIONLINK__
3284 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3285 if( $mw->matchAndRemove( $text ) )
3286 $this->mOutput
->setNewSection( true );
3288 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3289 # override above conditions and always show TOC above first header
3290 $mw =& MagicWord
::get( MAG_FORCETOC
);
3291 if ($mw->matchAndRemove( $text ) ) {
3292 $this->mShowToc
= true;
3296 # Never ever show TOC if no headers
3297 if( $numMatches < 1 ) {
3301 # We need this to perform operations on the HTML
3302 $sk =& $this->mOptions
->getSkin();
3306 $sectionCount = 0; # headlineCount excluding template sections
3308 # Ugh .. the TOC should have neat indentation levels which can be
3309 # passed to the skin functions. These are determined here
3313 $sublevelCount = array();
3314 $levelCount = array();
3321 foreach( $matches[3] as $headline ) {
3323 $templatetitle = '';
3324 $templatesection = 0;
3327 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3329 $templatetitle = base64_decode($mat[1]);
3330 $templatesection = 1 +
(int)base64_decode($mat[2]);
3331 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3335 $prevlevel = $level;
3336 $prevtoclevel = $toclevel;
3338 $level = $matches[1][$headlineCount];
3340 if( $doNumberHeadings ||
$enoughToc ) {
3342 if ( $level > $prevlevel ) {
3343 # Increase TOC level
3345 $sublevelCount[$toclevel] = 0;
3346 if( $toclevel<$wgMaxTocLevel ) {
3347 $toc .= $sk->tocIndent();
3350 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3351 # Decrease TOC level, find level to jump to
3353 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3354 # Can only go down to level 1
3357 for ($i = $toclevel; $i > 0; $i--) {
3358 if ( $levelCount[$i] == $level ) {
3359 # Found last matching level
3363 elseif ( $levelCount[$i] < $level ) {
3364 # Found first matching level below current level
3370 if( $toclevel<$wgMaxTocLevel ) {
3371 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3375 # No change in level, end TOC line
3376 if( $toclevel<$wgMaxTocLevel ) {
3377 $toc .= $sk->tocLineEnd();
3381 $levelCount[$toclevel] = $level;
3383 # count number of headlines for each level
3384 @$sublevelCount[$toclevel]++
;
3386 for( $i = 1; $i <= $toclevel; $i++
) {
3387 if( !empty( $sublevelCount[$i] ) ) {
3391 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3397 # The canonized header is a version of the header text safe to use for links
3398 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3399 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3400 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3402 # Remove link placeholders by the link text.
3403 # <!--LINK number-->
3405 # link text with suffix
3406 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3407 "\$this->mLinkHolders['texts'][\$1]",
3408 $canonized_headline );
3409 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3410 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3411 $canonized_headline );
3414 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3415 $tocline = trim( $canonized_headline );
3416 # Save headline for section edit hint before it's escaped
3417 $headline_hint = trim( $canonized_headline );
3418 $canonized_headline = Sanitizer
::escapeId( $tocline );
3419 $refers[$headlineCount] = $canonized_headline;
3421 # count how many in assoc. array so we can track dupes in anchors
3422 @$refers[$canonized_headline]++
;
3423 $refcount[$headlineCount]=$refers[$canonized_headline];
3425 # Don't number the heading if it is the only one (looks silly)
3426 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3427 # the two are different if the line contains a link
3428 $headline=$numbering . ' ' . $headline;
3431 # Create the anchor for linking from the TOC to the section
3432 $anchor = $canonized_headline;
3433 if($refcount[$headlineCount] > 1 ) {
3434 $anchor .= '_' . $refcount[$headlineCount];
3436 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3437 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3439 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3440 if ( empty( $head[$headlineCount] ) ) {
3441 $head[$headlineCount] = '';
3444 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3446 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3449 # give headline the correct <h#> tag
3450 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3458 if( $toclevel<$wgMaxTocLevel ) {
3459 $toc .= $sk->tocUnindent( $toclevel - 1 );
3461 $toc = $sk->tocList( $toc );
3464 # split up and insert constructed headlines
3466 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3469 foreach( $blocks as $block ) {
3470 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3471 # This is the [edit] link that appears for the top block of text when
3472 # section editing is enabled
3474 # Disabled because it broke block formatting
3475 # For example, a bullet point in the top line
3476 # $full .= $sk->editSectionLink(0);
3479 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3480 # Top anchor now in skin
3484 if( !empty( $head[$i] ) ) {
3489 if( $this->mForceTocPosition
) {
3490 return str_replace( '<!--MWTOC-->', $toc, $full );
3497 * Return an HTML link for the "ISBN 123456" text
3500 function magicISBN( $text ) {
3501 $fname = 'Parser::magicISBN';
3502 wfProfileIn( $fname );
3504 $a = split( 'ISBN ', ' '.$text );
3505 if ( count ( $a ) < 2 ) {
3506 wfProfileOut( $fname );
3509 $text = substr( array_shift( $a ), 1);
3510 $valid = '0123456789-Xx';
3512 foreach ( $a as $x ) {
3513 # hack: don't replace inside thumbnail title/alt
3515 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3520 $isbn = $blank = '' ;
3521 while ( ' ' == $x{0} ) {
3523 $x = substr( $x, 1 );
3525 if ( $x == '' ) { # blank isbn
3526 $text .= "ISBN $blank";
3529 while ( strstr( $valid, $x{0} ) != false ) {
3531 $x = substr( $x, 1 );
3533 $num = str_replace( '-', '', $isbn );
3534 $num = str_replace( ' ', '', $num );
3535 $num = str_replace( 'x', 'X', $num );
3538 $text .= "ISBN $blank$x";
3540 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3541 $text .= '<a href="' .
3542 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3543 "\" class=\"internal\">ISBN $isbn</a>";
3547 wfProfileOut( $fname );
3552 * Return an HTML link for the "RFC 1234" text
3555 * @param string $text Text to be processed
3556 * @param string $keyword Magic keyword to use (default RFC)
3557 * @param string $urlmsg Interface message to use (default rfcurl)
3560 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3562 $valid = '0123456789';
3565 $a = split( $keyword, ' '.$text );
3566 if ( count ( $a ) < 2 ) {
3569 $text = substr( array_shift( $a ), 1);
3571 /* Check if keyword is preceed by [[.
3572 * This test is made here cause of the array_shift above
3573 * that prevent the test to be done in the foreach.
3575 if ( substr( $text, -2 ) == '[[' ) {
3579 foreach ( $a as $x ) {
3580 /* token might be empty if we have RFC RFC 1234 */
3586 # hack: don't replace inside thumbnail title/alt
3588 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3589 $text .= $keyword . $x;
3595 /** remove and save whitespaces in $blank */
3596 while ( $x{0} == ' ' ) {
3598 $x = substr( $x, 1 );
3601 /** remove and save the rfc number in $id */
3602 while ( strstr( $valid, $x{0} ) != false ) {
3604 $x = substr( $x, 1 );
3608 /* call back stripped spaces*/
3609 $text .= $keyword.$blank.$x;
3610 } elseif( $internal ) {
3612 $text .= $keyword.$id.$x;
3614 /* build the external link*/
3615 $url = wfMsg( $urlmsg, $id);
3616 $sk =& $this->mOptions
->getSkin();
3617 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3618 $text .= "<a href=\"{$url}\"{$la}>{$keyword}{$id}</a>{$x}";
3621 /* Check if the next RFC keyword is preceed by [[ */
3622 $internal = ( substr($x,-2) == '[[' );
3628 * Transform wiki markup when saving a page by doing \r\n -> \n
3629 * conversion, substitting signatures, {{subst:}} templates, etc.
3631 * @param string $text the text to transform
3632 * @param Title &$title the Title object for the current article
3633 * @param User &$user the User object describing the current user
3634 * @param ParserOptions $options parsing options
3635 * @param bool $clearState whether to clear the parser state first
3636 * @return string the altered wiki markup
3639 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3640 $this->mOptions
= $options;
3641 $this->mTitle
=& $title;
3642 $this->mOutputType
= OT_WIKI
;
3644 if ( $clearState ) {
3645 $this->clearState();
3648 $stripState = false;
3652 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3653 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3654 $text = $this->pstPass2( $text, $stripState, $user );
3655 $text = $this->unstrip( $text, $stripState );
3656 $text = $this->unstripNoWiki( $text, $stripState );
3661 * Pre-save transform helper function
3664 function pstPass2( $text, &$stripState, &$user ) {
3665 global $wgContLang, $wgLocaltimezone;
3667 /* Note: This is the timestamp saved as hardcoded wikitext to
3668 * the database, we use $wgContLang here in order to give
3669 * everyone the same signature and use the default one rather
3670 * than the one selected in each user's preferences.
3672 if ( isset( $wgLocaltimezone ) ) {
3673 $oldtz = getenv( 'TZ' );
3674 putenv( 'TZ='.$wgLocaltimezone );
3676 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3677 ' (' . date( 'T' ) . ')';
3678 if ( isset( $wgLocaltimezone ) ) {
3679 putenv( 'TZ='.$oldtz );
3682 # Variable replacement
3683 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3684 $text = $this->replaceVariables( $text );
3686 # Strip out <nowiki> etc. added via replaceVariables
3687 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3690 $sigText = $this->getUserSig( $user );
3691 $text = strtr( $text, array(
3693 '~~~~' => "$sigText $d",
3697 # Context links: [[|name]] and [[name (context)|]]
3699 global $wgLegalTitleChars;
3700 $tc = "[$wgLegalTitleChars]";
3701 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3703 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3704 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3706 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3707 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3708 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3709 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3711 $t = $this->mTitle
->getText();
3712 if ( preg_match( $conpat, $t, $m ) ) {
3715 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3716 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3717 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3719 if ( '' == $context ) {
3720 $text = preg_replace( $p2, '[[\\1]]', $text );
3722 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3725 # Trim trailing whitespace
3726 # MAG_END (__END__) tag allows for trailing
3727 # whitespace to be deliberately included
3728 $text = rtrim( $text );
3729 $mw =& MagicWord
::get( MAG_END
);
3730 $mw->matchAndRemove( $text );
3736 * Fetch the user's signature text, if any, and normalize to
3737 * validated, ready-to-insert wikitext.
3743 function getUserSig( &$user ) {
3744 $username = $user->getName();
3745 $nickname = $user->getOption( 'nickname' );
3746 $nickname = $nickname === '' ?
$username : $nickname;
3748 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3749 # Sig. might contain markup; validate this
3750 if( $this->validateSig( $nickname ) !== false ) {
3751 # Validated; clean up (if needed) and return it
3752 return $this->cleanSig( $nickname, true );
3754 # Failed to validate; fall back to the default
3755 $nickname = $username;
3756 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3760 // Make sure nickname doesnt get a sig in a sig
3761 $nickname = $this->cleanSigInSig( $nickname );
3763 # If we're still here, make it a link to the user page
3764 $userpage = $user->getUserPage();
3765 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3769 * Check that the user's signature contains no bad XML
3771 * @param string $text
3772 * @return mixed An expanded string, or false if invalid.
3774 function validateSig( $text ) {
3775 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3779 * Clean up signature text
3781 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3782 * 2) Substitute all transclusions
3784 * @param string $text
3785 * @param $parsing Whether we're cleaning (preferences save) or parsing
3786 * @return string Signature text
3788 function cleanSig( $text, $parsing = false ) {
3790 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3792 $substWord = MagicWord
::get( MAG_SUBST
);
3793 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3794 $substText = '{{' . $substWord->getSynonym( 0 );
3796 $text = preg_replace( $substRegex, $substText, $text );
3797 $text = $this->cleanSigInSig( $text );
3798 $text = $this->replaceVariables( $text );
3800 $this->clearState();
3805 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3806 * @param string $text
3807 * @return string Signature text with /~{3,5}/ removed
3809 function cleanSigInSig( $text ) {
3810 $text = preg_replace( '/~{3,5}/', '', $text );
3815 * Set up some variables which are usually set up in parse()
3816 * so that an external function can call some class members with confidence
3819 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3820 $this->mTitle
=& $title;
3821 $this->mOptions
= $options;
3822 $this->mOutputType
= $outputType;
3823 if ( $clearState ) {
3824 $this->clearState();
3829 * Transform a MediaWiki message by replacing magic variables.
3831 * @param string $text the text to transform
3832 * @param ParserOptions $options options
3833 * @return string the text with variables substituted
3836 function transformMsg( $text, $options ) {
3838 static $executing = false;
3840 $fname = "Parser::transformMsg";
3842 # Guard against infinite recursion
3848 wfProfileIn($fname);
3850 $this->mTitle
= $wgTitle;
3851 $this->mOptions
= $options;
3852 $this->mOutputType
= OT_MSG
;
3853 $this->clearState();
3854 $text = $this->replaceVariables( $text );
3857 wfProfileOut($fname);
3862 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3863 * The callback should have the following form:
3864 * function myParserHook( $text, $params, &$parser ) { ... }
3866 * Transform and return $text. Use $parser for any required context, e.g. use
3867 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3871 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3872 * @param mixed $callback The callback function (and object) to use for the tag
3874 * @return The old value of the mTagHooks array associated with the hook
3876 function setHook( $tag, $callback ) {
3877 $tag = strtolower( $tag );
3878 $oldVal = @$this->mTagHooks
[$tag];
3879 $this->mTagHooks
[$tag] = $callback;
3885 * Create a function, e.g. {{sum:1|2|3}}
3886 * The callback function should have the form:
3887 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3889 * The callback may either return the text result of the function, or an array with the text
3890 * in element 0, and a number of flags in the other elements. The names of the flags are
3891 * specified in the keys. Valid flags are:
3892 * found The text returned is valid, stop processing the template. This
3894 * nowiki Wiki markup in the return value should be escaped
3895 * noparse Unsafe HTML tags should not be stripped, etc.
3896 * noargs Don't replace triple-brace arguments in the return value
3897 * isHTML The returned text is HTML, armour it against wikitext transformation
3901 * @param mixed $id The magic word ID, or (deprecated) the function name. Function names are case-insensitive.
3902 * @param mixed $callback The callback function (and object) to use
3904 * @return The old callback function for this name, if any
3906 function setFunctionHook( $id, $callback ) {
3907 if( is_string( $id ) ) {
3908 $id = strtolower( $id );
3910 $oldVal = @$this->mFunctionHooks
[$id];
3911 $this->mFunctionHooks
[$id] = $callback;
3912 # Invalidate function synonym cache
3913 $this->mFunctionSynonymsValid
= false;
3918 * Make sure the function synonym cache is up to date
3920 function refreshFunctionCache() {
3921 if ( !$this->mFunctionSynonymsValid
) {
3922 $this->mFunctionSynonyms
= array();
3923 foreach( $this->mFunctionHooks
as $key => $value ) {
3924 if ( is_int( $key ) ) {
3925 $mw = MagicWord
::get( $key );
3926 $synonyms = $mw->getSynonyms();
3927 foreach( $synonyms as $synonym ) {
3928 $this->mFunctionSynonyms
[strtolower($synonym)] = $key;
3932 $this->mFunctionSynonymsValid
= true;
3937 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3938 * Placeholders created in Skin::makeLinkObj()
3939 * Returns an array of links found, indexed by PDBK:
3943 * $options is a bit field, RLH_FOR_UPDATE to select for update
3945 function replaceLinkHolders( &$text, $options = 0 ) {
3947 global $wgOutputReplace;
3949 $fname = 'Parser::replaceLinkHolders';
3950 wfProfileIn( $fname );
3954 $sk =& $this->mOptions
->getSkin();
3955 $linkCache =& LinkCache
::singleton();
3957 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3958 wfProfileIn( $fname.'-check' );
3959 $dbr =& wfGetDB( DB_SLAVE
);
3960 $page = $dbr->tableName( 'page' );
3961 $threshold = $wgUser->getOption('stubthreshold');
3964 asort( $this->mLinkHolders
['namespaces'] );
3968 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3970 $title = $this->mLinkHolders
['titles'][$key];
3972 # Skip invalid entries.
3973 # Result will be ugly, but prevents crash.
3974 if ( is_null( $title ) ) {
3977 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3979 # Check if it's a static known link, e.g. interwiki
3980 if ( $title->isAlwaysKnown() ) {
3981 $colours[$pdbk] = 1;
3982 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3983 $colours[$pdbk] = 1;
3984 $this->mOutput
->addLink( $title, $id );
3985 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3986 $colours[$pdbk] = 0;
3988 # Not in the link cache, add it to the query
3989 if ( !isset( $current ) ) {
3991 $query = "SELECT page_id, page_namespace, page_title";
3992 if ( $threshold > 0 ) {
3993 $query .= ', page_len, page_is_redirect';
3995 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3996 } elseif ( $current != $ns ) {
3998 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4003 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
4008 if ( $options & RLH_FOR_UPDATE
) {
4009 $query .= ' FOR UPDATE';
4012 $res = $dbr->query( $query, $fname );
4014 # Fetch data and form into an associative array
4015 # non-existent = broken
4018 while ( $s = $dbr->fetchObject($res) ) {
4019 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
4020 $pdbk = $title->getPrefixedDBkey();
4021 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4022 $this->mOutput
->addLink( $title, $s->page_id
);
4024 if ( $threshold > 0 ) {
4025 $size = $s->page_len
;
4026 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4027 $colours[$pdbk] = 1;
4029 $colours[$pdbk] = 2;
4032 $colours[$pdbk] = 1;
4036 wfProfileOut( $fname.'-check' );
4038 # Construct search and replace arrays
4039 wfProfileIn( $fname.'-construct' );
4040 $wgOutputReplace = array();
4041 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4042 $pdbk = $pdbks[$key];
4043 $searchkey = "<!--LINK $key-->";
4044 $title = $this->mLinkHolders
['titles'][$key];
4045 if ( empty( $colours[$pdbk] ) ) {
4046 $linkCache->addBadLinkObj( $title );
4047 $colours[$pdbk] = 0;
4048 $this->mOutput
->addLink( $title, 0 );
4049 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4050 $this->mLinkHolders
['texts'][$key],
4051 $this->mLinkHolders
['queries'][$key] );
4052 } elseif ( $colours[$pdbk] == 1 ) {
4053 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4054 $this->mLinkHolders
['texts'][$key],
4055 $this->mLinkHolders
['queries'][$key] );
4056 } elseif ( $colours[$pdbk] == 2 ) {
4057 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4058 $this->mLinkHolders
['texts'][$key],
4059 $this->mLinkHolders
['queries'][$key] );
4062 wfProfileOut( $fname.'-construct' );
4065 wfProfileIn( $fname.'-replace' );
4067 $text = preg_replace_callback(
4068 '/(<!--LINK .*?-->)/',
4069 "wfOutputReplaceMatches",
4072 wfProfileOut( $fname.'-replace' );
4075 # Now process interwiki link holders
4076 # This is quite a bit simpler than internal links
4077 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4078 wfProfileIn( $fname.'-interwiki' );
4079 # Make interwiki link HTML
4080 $wgOutputReplace = array();
4081 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4082 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4083 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4086 $text = preg_replace_callback(
4087 '/<!--IWLINK (.*?)-->/',
4088 "wfOutputReplaceMatches",
4090 wfProfileOut( $fname.'-interwiki' );
4093 wfProfileOut( $fname );
4098 * Replace <!--LINK--> link placeholders with plain text of links
4099 * (not HTML-formatted).
4100 * @param string $text
4103 function replaceLinkHoldersText( $text ) {
4104 $fname = 'Parser::replaceLinkHoldersText';
4105 wfProfileIn( $fname );
4107 $text = preg_replace_callback(
4108 '/<!--(LINK|IWLINK) (.*?)-->/',
4109 array( &$this, 'replaceLinkHoldersTextCallback' ),
4112 wfProfileOut( $fname );
4117 * @param array $matches
4121 function replaceLinkHoldersTextCallback( $matches ) {
4122 $type = $matches[1];
4124 if( $type == 'LINK' ) {
4125 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4126 return $this->mLinkHolders
['texts'][$key];
4128 } elseif( $type == 'IWLINK' ) {
4129 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4130 return $this->mInterwikiLinkHolders
['texts'][$key];
4137 * Tag hook handler for 'pre'.
4139 function renderPreTag( $text, $attribs, $parser ) {
4140 // Backwards-compatibility hack
4141 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4143 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4144 return wfOpenElement( 'pre', $attribs ) .
4145 wfEscapeHTMLTagsOnly( $content ) .
4150 * Renders an image gallery from a text with one line per image.
4151 * text labels may be given by using |-style alternative text. E.g.
4152 * Image:one.jpg|The number "1"
4153 * Image:tree.jpg|A tree
4154 * given as text will return the HTML of a gallery with two images,
4155 * labeled 'The number "1"' and
4158 function renderImageGallery( $text, $params ) {
4159 $ig = new ImageGallery();
4160 $ig->setShowBytes( false );
4161 $ig->setShowFilename( false );
4163 $ig->useSkin( $this->mOptions
->getSkin() );
4165 if( isset( $params['caption'] ) )
4166 $ig->setCaption( $params['caption'] );
4168 $lines = explode( "\n", $text );
4169 foreach ( $lines as $line ) {
4170 # match lines like these:
4171 # Image:someimage.jpg|This is some image
4172 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4174 if ( count( $matches ) == 0 ) {
4177 $nt =& Title
::newFromText( $matches[1] );
4178 if( is_null( $nt ) ) {
4179 # Bogus title. Ignore these so we don't bomb out later.
4182 if ( isset( $matches[3] ) ) {
4183 $label = $matches[3];
4188 $pout = $this->parse( $label,
4191 false, // Strip whitespace...?
4192 false // Don't clear state!
4194 $html = $pout->getText();
4196 $ig->add( new Image( $nt ), $html );
4198 # Only add real images (bug #5586)
4199 if ( $nt->getNamespace() == NS_IMAGE
) {
4200 $this->mOutput
->addImage( $nt->getDBkey() );
4203 return $ig->toHTML();
4207 * Parse image options text and use it to make an image
4209 function makeImage( &$nt, $options ) {
4210 global $wgUseImageResize;
4214 # Check if the options text is of the form "options|alt text"
4216 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4217 # * left no resizing, just left align. label is used for alt= only
4218 # * right same, but right aligned
4219 # * none same, but not aligned
4220 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4221 # * center center the image
4222 # * framed Keep original image size, no magnify-button.
4224 $part = explode( '|', $options);
4226 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4227 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4228 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4229 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4230 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4231 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4232 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4233 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4236 $width = $height = $framed = $thumb = false;
4237 $manual_thumb = '' ;
4239 foreach( $part as $key => $val ) {
4240 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4242 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4243 # use manually specified thumbnail
4245 $manual_thumb = $match;
4246 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4247 # remember to set an alignment, don't render immediately
4249 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4250 # remember to set an alignment, don't render immediately
4252 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4253 # remember to set an alignment, don't render immediately
4255 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4256 # remember to set an alignment, don't render immediately
4258 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4259 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4260 # $match is the image width in pixels
4261 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4262 $width = intval( $m[1] );
4263 $height = intval( $m[2] );
4265 $width = intval($match);
4267 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4273 # Strip bad stuff out of the alt text
4274 $alt = $this->replaceLinkHoldersText( $caption );
4276 # make sure there are no placeholders in thumbnail attributes
4277 # that are later expanded to html- so expand them now and
4279 $alt = $this->unstrip($alt, $this->mStripState
);
4280 $alt = Sanitizer
::stripAllTags( $alt );
4282 # Linker does the rest
4283 $sk =& $this->mOptions
->getSkin();
4284 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4288 * Set a flag in the output object indicating that the content is dynamic and
4289 * shouldn't be cached.
4291 function disableCache() {
4292 wfDebug( "Parser output marked as uncacheable.\n" );
4293 $this->mOutput
->mCacheTime
= -1;
4297 * Callback from the Sanitizer for expanding items found in HTML attribute
4298 * values, so they can be safely tested and escaped.
4299 * @param string $text
4300 * @param array $args
4304 function attributeStripCallback( &$text, $args ) {
4305 $text = $this->replaceVariables( $text, $args );
4306 $text = $this->unstripForHTML( $text );
4310 function unstripForHTML( $text ) {
4311 $text = $this->unstrip( $text, $this->mStripState
);
4312 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4320 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4321 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4322 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4328 function getTags() { return array_keys( $this->mTagHooks
); }
4333 * Break wikitext input into sections, and either pull or replace
4334 * some particular section's text.
4336 * External callers should use the getSection and replaceSection methods.
4338 * @param $text Page wikitext
4339 * @param $section Numbered section. 0 pulls the text before the first
4340 * heading; other numbers will pull the given section
4341 * along with its lower-level subsections.
4342 * @param $mode One of "get" or "replace"
4343 * @param $newtext Replacement text for section data.
4344 * @return string for "get", the extracted section text.
4345 * for "replace", the whole page with the section replaced.
4347 private function extractSections( $text, $section, $mode, $newtext='' ) {
4348 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4349 # comments to be stripped as well)
4350 $striparray = array();
4352 $oldOutputType = $this->mOutputType
;
4353 $oldOptions = $this->mOptions
;
4354 $this->mOptions
= new ParserOptions();
4355 $this->mOutputType
= OT_WIKI
;
4357 $striptext = $this->strip( $text, $striparray, true );
4359 $this->mOutputType
= $oldOutputType;
4360 $this->mOptions
= $oldOptions;
4362 # now that we can be sure that no pseudo-sections are in the source,
4363 # split it up by section
4364 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4365 $comment = "(?:$uniq-!--.*?QINU)";
4370 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4372 (=+) # Should this be limited to 6?
4373 .+? # Section title...
4374 \\2 # Ending = count must match start
4381 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4388 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4389 (=+) # Should this be limited to 6?
4390 .+? # Section title...
4391 \\2 # Ending = count must match start
4392 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4401 PREG_SPLIT_DELIM_CAPTURE
);
4403 if( $mode == "get" ) {
4404 if( $section == 0 ) {
4405 // "Section 0" returns the content before any other section.
4410 } elseif( $mode == "replace" ) {
4411 if( $section == 0 ) {
4412 $rv = $newtext . "\n\n";
4421 for( $index = 1; $index < count( $secs ); ) {
4422 $headerLine = $secs[$index++
];
4423 if( $secs[$index] ) {
4425 $headerLevel = strlen( $secs[$index++
] );
4429 $headerLevel = intval( $secs[$index++
] );
4431 $content = $secs[$index++
];
4434 if( $mode == "get" ) {
4435 if( $count == $section ) {
4436 $rv = $headerLine . $content;
4437 $sectionLevel = $headerLevel;
4438 } elseif( $count > $section ) {
4439 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4440 $rv .= $headerLine . $content;
4442 // Broke out to a higher-level section
4446 } elseif( $mode == "replace" ) {
4447 if( $count < $section ) {
4448 $rv .= $headerLine . $content;
4449 } elseif( $count == $section ) {
4450 $rv .= $newtext . "\n\n";
4451 $sectionLevel = $headerLevel;
4452 } elseif( $count > $section ) {
4453 if( $headerLevel <= $sectionLevel ) {
4454 // Passed the section's sub-parts.
4458 $rv .= $headerLine . $content;
4463 # reinsert stripped tags
4464 $rv = $this->unstrip( $rv, $striparray );
4465 $rv = $this->unstripNoWiki( $rv, $striparray );
4471 * This function returns the text of a section, specified by a number ($section).
4472 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4473 * the first section before any such heading (section 0).
4475 * If a section contains subsections, these are also returned.
4477 * @param $text String: text to look in
4478 * @param $section Integer: section number
4479 * @return string text of the requested section
4481 function getSection( $text, $section ) {
4482 return $this->extractSections( $text, $section, "get" );
4485 function replaceSection( $oldtext, $section, $text ) {
4486 return $this->extractSections( $oldtext, $section, "replace", $text );
4493 * @package MediaWiki
4497 var $mText, # The output text
4498 $mLanguageLinks, # List of the full text of language links, in the order they appear
4499 $mCategories, # Map of category names to sort keys
4500 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4501 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4502 $mVersion, # Compatibility check
4503 $mTitleText, # title text of the chosen language variant
4504 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4505 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4506 $mImages, # DB keys of the images used, in the array key only
4507 $mExternalLinks, # External link URLs, in the key only
4508 $mHTMLtitle, # Display HTML title
4509 $mSubtitle, # Additional subtitle
4510 $mNewSection, # Show a new section link?
4511 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4513 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4514 $containsOldMagic = false, $titletext = '' )
4516 $this->mText
= $text;
4517 $this->mLanguageLinks
= $languageLinks;
4518 $this->mCategories
= $categoryLinks;
4519 $this->mContainsOldMagic
= $containsOldMagic;
4520 $this->mCacheTime
= '';
4521 $this->mVersion
= MW_PARSER_VERSION
;
4522 $this->mTitleText
= $titletext;
4523 $this->mLinks
= array();
4524 $this->mTemplates
= array();
4525 $this->mImages
= array();
4526 $this->mExternalLinks
= array();
4527 $this->mHTMLtitle
= "" ;
4528 $this->mSubtitle
= "" ;
4529 $this->mNewSection
= false;
4530 $this->mNoGallery
= false;
4533 function getText() { return $this->mText
; }
4534 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4535 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4536 function &getCategories() { return $this->mCategories
; }
4537 function getCacheTime() { return $this->mCacheTime
; }
4538 function getTitleText() { return $this->mTitleText
; }
4539 function &getLinks() { return $this->mLinks
; }
4540 function &getTemplates() { return $this->mTemplates
; }
4541 function &getImages() { return $this->mImages
; }
4542 function &getExternalLinks() { return $this->mExternalLinks
; }
4543 function getNoGallery() { return $this->mNoGallery
; }
4545 function containsOldMagic() { return $this->mContainsOldMagic
; }
4546 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4547 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4548 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4549 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4550 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4551 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4553 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4554 function addImage( $name ) { $this->mImages
[$name] = 1; }
4555 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4556 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4558 function setNewSection( $value ) {
4559 $this->mNewSection
= (bool)$value;
4561 function getNewSection() {
4562 return (bool)$this->mNewSection
;
4565 function addLink( $title, $id ) {
4566 $ns = $title->getNamespace();
4567 $dbk = $title->getDBkey();
4568 if ( !isset( $this->mLinks
[$ns] ) ) {
4569 $this->mLinks
[$ns] = array();
4571 $this->mLinks
[$ns][$dbk] = $id;
4574 function addTemplate( $title, $id ) {
4575 $ns = $title->getNamespace();
4576 $dbk = $title->getDBkey();
4577 if ( !isset( $this->mTemplates
[$ns] ) ) {
4578 $this->mTemplates
[$ns] = array();
4580 $this->mTemplates
[$ns][$dbk] = $id;
4584 * Return true if this cached output object predates the global or
4585 * per-article cache invalidation timestamps, or if it comes from
4586 * an incompatible older version.
4588 * @param string $touched the affected article's last touched timestamp
4592 function expired( $touched ) {
4593 global $wgCacheEpoch;
4594 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4595 $this->getCacheTime() < $touched ||
4596 $this->getCacheTime() <= $wgCacheEpoch ||
4597 !isset( $this->mVersion
) ||
4598 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4603 * Set options of the Parser
4605 * @package MediaWiki
4609 # All variables are private
4610 var $mUseTeX; # Use texvc to expand <math> tags
4611 var $mUseDynamicDates; # Use DateFormatter to format dates
4612 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4613 var $mAllowExternalImages; # Allow external images inline
4614 var $mAllowExternalImagesFrom; # If not, any exception?
4615 var $mSkin; # Reference to the preferred skin
4616 var $mDateFormat; # Date format index
4617 var $mEditSection; # Create "edit section" links
4618 var $mNumberHeadings; # Automatically number headings
4619 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4620 var $mTidy; # Ask for tidy cleanup
4621 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4623 var $mUser; # Stored user object, just used to initialise the skin
4625 function getUseTeX() { return $this->mUseTeX
; }
4626 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4627 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4628 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4629 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4630 function getDateFormat() { return $this->mDateFormat
; }
4631 function getEditSection() { return $this->mEditSection
; }
4632 function getNumberHeadings() { return $this->mNumberHeadings
; }
4633 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4634 function getTidy() { return $this->mTidy
; }
4635 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4637 function &getSkin() {
4638 if ( !isset( $this->mSkin
) ) {
4639 $this->mSkin
= $this->mUser
->getSkin();
4641 return $this->mSkin
;
4644 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4645 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4646 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4647 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4648 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4649 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4650 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4651 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4652 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4653 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4654 function setSkin( &$x ) { $this->mSkin
=& $x; }
4655 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4657 function ParserOptions( $user = null ) {
4658 $this->initialiseFromUser( $user );
4662 * Get parser options
4665 function newFromUser( &$user ) {
4666 return new ParserOptions( $user );
4669 /** Get user options */
4670 function initialiseFromUser( &$userInput ) {
4671 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4672 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4673 $fname = 'ParserOptions::initialiseFromUser';
4674 wfProfileIn( $fname );
4675 if ( !$userInput ) {
4677 if ( isset( $wgUser ) ) {
4681 $user->setLoaded( true );
4684 $user =& $userInput;
4687 $this->mUser
= $user;
4689 $this->mUseTeX
= $wgUseTeX;
4690 $this->mUseDynamicDates
= $wgUseDynamicDates;
4691 $this->mInterwikiMagic
= $wgInterwikiMagic;
4692 $this->mAllowExternalImages
= $wgAllowExternalImages;
4693 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4694 $this->mSkin
= null; # Deferred
4695 $this->mDateFormat
= $user->getOption( 'date' );
4696 $this->mEditSection
= true;
4697 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4698 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4699 $this->mTidy
= false;
4700 $this->mInterfaceMessage
= false;
4701 wfProfileOut( $fname );
4706 * Callback function used by Parser::replaceLinkHolders()
4707 * to substitute link placeholders.
4709 function &wfOutputReplaceMatches( $matches ) {
4710 global $wgOutputReplace;
4711 return $wgOutputReplace[$matches[1]];
4715 * Return the total number of articles
4717 function wfNumberOfArticles() {
4718 global $wgNumberOfArticles;
4721 return $wgNumberOfArticles;
4725 * Return the number of files
4727 function wfNumberOfFiles() {
4728 $fname = 'wfNumberOfFiles';
4730 wfProfileIn( $fname );
4731 $dbr =& wfGetDB( DB_SLAVE
);
4732 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4733 wfProfileOut( $fname );
4739 * Return the number of user accounts
4742 function wfNumberOfUsers() {
4743 wfProfileIn( 'wfNumberOfUsers' );
4744 $dbr =& wfGetDB( DB_SLAVE
);
4745 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4746 wfProfileOut( 'wfNumberOfUsers' );
4751 * Return the total number of pages
4754 function wfNumberOfPages() {
4755 wfProfileIn( 'wfNumberOfPages' );
4756 $dbr =& wfGetDB( DB_SLAVE
);
4757 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4758 wfProfileOut( 'wfNumberOfPages' );
4763 * Return the total number of admins
4767 function wfNumberOfAdmins() {
4768 static $admins = -1;
4769 wfProfileIn( 'wfNumberOfAdmins' );
4770 if( $admins == -1 ) {
4771 $dbr =& wfGetDB( DB_SLAVE
);
4772 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4774 wfProfileOut( 'wfNumberOfAdmins' );
4775 return (int)$admins;
4779 * Count the number of pages in a particular namespace
4781 * @param $ns Namespace
4784 function wfPagesInNs( $ns ) {
4785 static $pageCount = array();
4786 wfProfileIn( 'wfPagesInNs' );
4787 if( !isset( $pageCount[$ns] ) ) {
4788 $dbr =& wfGetDB( DB_SLAVE
);
4789 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4791 wfProfileOut( 'wfPagesInNs' );
4792 return (int)$pageCount[$ns];
4796 * Get various statistics from the database
4799 function wfLoadSiteStats() {
4800 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4801 $fname = 'wfLoadSiteStats';
4803 if ( -1 != $wgNumberOfArticles ) return;
4804 $dbr =& wfGetDB( DB_SLAVE
);
4805 $s = $dbr->selectRow( 'site_stats',
4806 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4807 array( 'ss_row_id' => 1 ), $fname
4810 if ( $s === false ) {
4813 $wgTotalViews = $s->ss_total_views
;
4814 $wgTotalEdits = $s->ss_total_edits
;
4815 $wgNumberOfArticles = $s->ss_good_articles
;
4821 * Basically replacing " > and < with HTML entities ( ", >, <)
4823 * @param $in String: text that might contain HTML tags.
4824 * @return string Escaped string
4826 function wfEscapeHTMLTagsOnly( $in ) {
4828 array( '"', '>', '<' ),
4829 array( '"', '>', '<' ),