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->mFunctionSynonyms
= array();
133 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
141 function clearState() {
142 $this->mOutput
= new ParserOutput
;
143 $this->mAutonumber
= 0;
144 $this->mLastSection
= '';
145 $this->mDTopen
= false;
146 $this->mVariables
= false;
147 $this->mIncludeCount
= array();
148 $this->mStripState
= array();
149 $this->mArgStack
= array();
150 $this->mInPre
= false;
151 $this->mInterwikiLinkHolders
= array(
155 $this->mLinkHolders
= array(
156 'namespaces' => array(),
158 'queries' => array(),
162 $this->mRevisionId
= null;
165 * Prefix for temporary replacement strings for the multipass parser.
166 * \x07 should never appear in input as it's disallowed in XML.
167 * Using it at the front also gives us a little extra robustness
168 * since it shouldn't match when butted up against identifier-like
171 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
173 # Clear these on every parse, bug 4549
174 $this->mTemplates
= array();
175 $this->mTemplatePath
= array();
177 $this->mShowToc
= true;
178 $this->mForceTocPosition
= false;
180 wfRunHooks( 'ParserClearState', array( &$this ) );
184 * Accessor for mUniqPrefix.
188 function UniqPrefix() {
189 return $this->mUniqPrefix
;
193 * Convert wikitext to HTML
194 * Do not call this function recursively.
197 * @param string $text Text we want to parse
198 * @param Title &$title A title object
199 * @param array $options
200 * @param boolean $linestart
201 * @param boolean $clearState
202 * @param int $revid number to pass in {{REVISIONID}}
203 * @return ParserOutput a ParserOutput
205 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
207 * First pass--just handle <nowiki> sections, pass the rest off
208 * to internalParse() which does all the real work.
211 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
212 $fname = 'Parser::parse';
213 wfProfileIn( $fname );
219 $this->mOptions
= $options;
220 $this->mTitle
=& $title;
221 $this->mRevisionId
= $revid;
222 $this->mOutputType
= OT_HTML
;
224 //$text = $this->strip( $text, $this->mStripState );
225 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
226 $x =& $this->mStripState
;
228 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
229 $text = $this->strip( $text, $x );
230 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
232 # Hook to suspend the parser in this state
233 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
234 wfProfileOut( $fname );
238 $text = $this->internalParse( $text );
240 $text = $this->unstrip( $text, $this->mStripState
);
242 # Clean up special characters, only run once, next-to-last before doBlockLevels
244 # french spaces, last one Guillemet-left
245 # only if there is something before the space
246 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
247 # french spaces, Guillemet-right
248 '/(\\302\\253) /' => '\\1 ',
250 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
253 $text = $this->doBlockLevels( $text, $linestart );
255 $this->replaceLinkHolders( $text );
257 # the position of the parserConvert() call should not be changed. it
258 # assumes that the links are all replaced and the only thing left
259 # is the <nowiki> mark.
260 # Side-effects: this calls $this->mOutput->setTitleText()
261 $text = $wgContLang->parserConvert( $text, $this );
263 $text = $this->unstripNoWiki( $text, $this->mStripState
);
265 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
267 $text = Sanitizer
::normalizeCharReferences( $text );
269 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
270 $text = Parser
::tidy($text);
272 # attempt to sanitize at least some nesting problems
273 # (bug #2702 and quite a few others)
275 # ''Something [http://www.cool.com cool''] -->
276 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
277 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
278 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
279 # fix up an anchor inside another anchor, only
280 # at least for a single single nested link (bug 3695)
281 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
282 '\\1\\2</a>\\3</a>\\1\\4</a>',
283 # fix div inside inline elements- doBlockLevels won't wrap a line which
284 # contains a div, so fix it up here; replace
285 # div with escaped text
286 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
287 '\\1\\3<div\\5>\\6</div>\\8\\9',
288 # remove empty italic or bold tag pairs, some
289 # introduced by rules above
290 '/<([bi])><\/\\1>/' => ''
293 $text = preg_replace(
294 array_keys( $tidyregs ),
295 array_values( $tidyregs ),
299 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
301 $this->mOutput
->setText( $text );
302 wfProfileOut( $fname );
304 return $this->mOutput
;
308 * Get a random string
313 function getRandomString() {
314 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
317 function &getTitle() { return $this->mTitle
; }
318 function getOptions() { return $this->mOptions
; }
321 * Replaces all occurrences of HTML-style comments and the given tags
322 * in the text with a random marker and returns teh next text. The output
323 * parameter $matches will be an associative array filled with data in
325 * 'UNIQ-xxxxx' => array(
328 * array( 'param' => 'x' ),
329 * '<element param="x">tag content</element>' ) )
331 * @param $elements list of element names. Comments are always extracted.
332 * @param $text Source text string.
333 * @param $uniq_prefix
338 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
339 $rand = Parser
::getRandomString();
344 $taglist = implode( '|', $elements );
345 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
347 while ( '' != $text ) {
348 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
350 if( count( $p ) < 5 ) {
353 if( count( $p ) > 5 ) {
367 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
) . '-QINU';
368 $stripped .= $marker;
370 if ( $close === '/>' ) {
371 // Empty element tag, <tag />
376 if( $element == '!--' ) {
379 $end = "/(<\\/$element\\s*>)/i";
381 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
383 if( count( $q ) < 3 ) {
384 # No end tag -- let it run out to the end of the text.
393 $matches[$marker] = array( $element,
395 Sanitizer
::decodeTagAttributes( $attributes ),
396 "<$element$attributes$close$content$tail" );
402 * Strips and renders nowiki, pre, math, hiero
403 * If $render is set, performs necessary rendering operations on plugins
404 * Returns the text, and fills an array with data needed in unstrip()
405 * If the $state is already a valid strip state, it adds to the state
407 * @param bool $stripcomments when set, HTML comments <!-- like this -->
408 * will be stripped in addition to other tags. This is important
409 * for section editing, where these comments cause confusion when
410 * counting the sections in the wikisource
412 * @param array dontstrip contains tags which should not be stripped;
413 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
417 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
418 $render = ($this->mOutputType
== OT_HTML
);
420 # Replace any instances of the placeholders
421 $uniq_prefix = $this->mUniqPrefix
;
422 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
423 $commentState = array();
425 $elements = array_merge(
426 array( 'nowiki', 'gallery' ),
427 array_keys( $this->mTagHooks
) );
430 $elements[] = 'html';
432 if( $this->mOptions
->getUseTeX() ) {
433 $elements[] = 'math';
436 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
437 foreach ( $elements AS $k => $v ) {
438 if ( !in_array ( $v , $dontstrip ) ) continue;
439 unset ( $elements[$k] );
443 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
445 foreach( $matches as $marker => $data ) {
446 list( $element, $content, $params, $tag ) = $data;
448 $tagName = strtolower( $element );
452 if( substr( $tag, -3 ) == '-->' ) {
455 // Unclosed comment in input.
456 // Close it so later stripping can remove it
465 // Shouldn't happen otherwise. :)
467 $output = wfEscapeHTMLTagsOnly( $content );
470 $output = MathRenderer
::renderMath( $content );
473 $output = $this->renderImageGallery( $content, $params );
476 if( isset( $this->mTagHooks
[$tagName] ) ) {
477 $output = call_user_func_array( $this->mTagHooks
[$tagName],
478 array( $content, $params, $this ) );
480 throw new MWException( "Invalid call hook $element" );
484 // Just stripping tags; keep the source
487 if( !$stripcomments && $element == '!--' ) {
488 $commentState[$marker] = $output;
490 $state[$element][$marker] = $output;
494 # Unstrip comments unless explicitly told otherwise.
495 # (The comments are always stripped prior to this point, so as to
496 # not invoke any extension tags / parser hooks contained within
498 if ( !$stripcomments ) {
499 // Put them all back and forget them
500 $text = strtr( $text, $commentState );
507 * Restores pre, math, and other extensions removed by strip()
509 * always call unstripNoWiki() after this one
512 function unstrip( $text, &$state ) {
513 if ( !is_array( $state ) ) {
517 $replacements = array();
518 foreach( $state as $tag => $contentDict ) {
519 if( $tag != 'nowiki' && $tag != 'html' ) {
520 foreach( $contentDict as $uniq => $content ) {
521 $replacements[$uniq] = $content;
525 $text = strtr( $text, $replacements );
531 * Always call this after unstrip() to preserve the order
535 function unstripNoWiki( $text, &$state ) {
536 if ( !is_array( $state ) ) {
540 $replacements = array();
541 foreach( $state as $tag => $contentDict ) {
542 if( $tag == 'nowiki' ||
$tag == 'html' ) {
543 foreach( $contentDict as $uniq => $content ) {
544 $replacements[$uniq] = $content;
548 $text = strtr( $text, $replacements );
554 * Add an item to the strip state
555 * Returns the unique tag which must be inserted into the stripped text
556 * The tag will be replaced with the original text in unstrip()
560 function insertStripItem( $text, &$state ) {
561 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
565 $state['item'][$rnd] = $text;
570 * Interface with html tidy, used if $wgUseTidy = true.
571 * If tidy isn't able to correct the markup, the original will be
572 * returned in all its glory with a warning comment appended.
574 * Either the external tidy program or the in-process tidy extension
575 * will be used depending on availability. Override the default
576 * $wgTidyInternal setting to disable the internal if it's not working.
578 * @param string $text Hideous HTML input
579 * @return string Corrected HTML output
583 function tidy( $text ) {
584 global $wgTidyInternal;
585 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
586 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
587 '<head><title>test</title></head><body>'.$text.'</body></html>';
588 if( $wgTidyInternal ) {
589 $correctedtext = Parser
::internalTidy( $wrappedtext );
591 $correctedtext = Parser
::externalTidy( $wrappedtext );
593 if( is_null( $correctedtext ) ) {
594 wfDebug( "Tidy error detected!\n" );
595 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
597 return $correctedtext;
601 * Spawn an external HTML tidy process and get corrected markup back from it.
606 function externalTidy( $text ) {
607 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
608 $fname = 'Parser::externalTidy';
609 wfProfileIn( $fname );
614 $descriptorspec = array(
615 0 => array('pipe', 'r'),
616 1 => array('pipe', 'w'),
617 2 => array('file', '/dev/null', 'a')
620 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
621 if (is_resource($process)) {
622 // Theoretically, this style of communication could cause a deadlock
623 // here. If the stdout buffer fills up, then writes to stdin could
624 // block. This doesn't appear to happen with tidy, because tidy only
625 // writes to stdout after it's finished reading from stdin. Search
626 // for tidyParseStdin and tidySaveStdout in console/tidy.c
627 fwrite($pipes[0], $text);
629 while (!feof($pipes[1])) {
630 $cleansource .= fgets($pipes[1], 1024);
633 proc_close($process);
636 wfProfileOut( $fname );
638 if( $cleansource == '' && $text != '') {
639 // Some kind of error happened, so we couldn't get the corrected text.
640 // Just give up; we'll use the source text and append a warning.
648 * Use the HTML tidy PECL extension to use the tidy library in-process,
649 * saving the overhead of spawning a new process. Currently written to
650 * the PHP 4.3.x version of the extension, may not work on PHP 5.
652 * 'pear install tidy' should be able to compile the extension module.
657 function internalTidy( $text ) {
659 $fname = 'Parser::internalTidy';
660 wfProfileIn( $fname );
662 tidy_load_config( $wgTidyConf );
663 tidy_set_encoding( 'utf8' );
664 tidy_parse_string( $text );
666 if( tidy_get_status() == 2 ) {
667 // 2 is magic number for fatal error
668 // http://www.php.net/manual/en/function.tidy-get-status.php
671 $cleansource = tidy_get_output();
673 wfProfileOut( $fname );
678 * parse the wiki syntax used to render tables
682 function doTableStuff ( $t ) {
683 $fname = 'Parser::doTableStuff';
684 wfProfileIn( $fname );
686 $t = explode ( "\n" , $t ) ;
687 $td = array () ; # Is currently a td tag open?
688 $ltd = array () ; # Was it TD or TH?
689 $tr = array () ; # Is currently a tr tag open?
690 $ltr = array () ; # tr attributes
691 $has_opened_tr = array(); # Did this table open a <tr> element?
692 $indent_level = 0; # indent level of the table
693 foreach ( $t AS $k => $x )
696 $fc = substr ( $x , 0 , 1 ) ;
697 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
698 $indent_level = strlen( $matches[1] );
700 $attributes = $this->unstripForHTML( $matches[2] );
702 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
703 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
704 array_push ( $td , false ) ;
705 array_push ( $ltd , '' ) ;
706 array_push ( $tr , false ) ;
707 array_push ( $ltr , '' ) ;
708 array_push ( $has_opened_tr, false );
710 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
711 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
712 $z = "</table>" . substr ( $x , 2);
713 $l = array_pop ( $ltd ) ;
714 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
715 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
716 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
718 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
720 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
721 $x = substr ( $x , 1 ) ;
722 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
724 $l = array_pop ( $ltd ) ;
725 array_pop ( $has_opened_tr );
726 array_push ( $has_opened_tr , true ) ;
727 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
728 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
731 array_push ( $tr , false ) ;
732 array_push ( $td , false ) ;
733 array_push ( $ltd , '' ) ;
734 $attributes = $this->unstripForHTML( $x );
735 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
737 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
739 if ( '|+' == substr ( $x , 0 , 2 ) ) {
741 $x = substr ( $x , 1 ) ;
743 $after = substr ( $x , 1 ) ;
744 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
746 // Split up multiple cells on the same line.
747 // FIXME: This can result in improper nesting of tags processed
748 // by earlier parser steps, but should avoid splitting up eg
749 // attribute values containing literal "||".
750 $after = wfExplodeMarkup( '||', $after );
754 # Loop through each table cell
755 foreach ( $after AS $theline )
760 $tra = array_pop ( $ltr ) ;
761 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
762 array_push ( $tr , true ) ;
763 array_push ( $ltr , '' ) ;
764 array_pop ( $has_opened_tr );
765 array_push ( $has_opened_tr , true ) ;
768 $l = array_pop ( $ltd ) ;
769 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
770 if ( $fc == '|' ) $l = 'td' ;
771 else if ( $fc == '!' ) $l = 'th' ;
772 else if ( $fc == '+' ) $l = 'caption' ;
774 array_push ( $ltd , $l ) ;
777 $y = explode ( '|' , $theline , 2 ) ;
778 # Note that a '|' inside an invalid link should not
779 # be mistaken as delimiting cell parameters
780 if ( strpos( $y[0], '[[' ) !== false ) {
781 $y = array ($theline);
783 if ( count ( $y ) == 1 )
784 $y = "{$z}<{$l}>{$y[0]}" ;
786 $attributes = $this->unstripForHTML( $y[0] );
787 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
790 array_push ( $td , true ) ;
795 # Closing open td, tr && table
796 while ( count ( $td ) > 0 )
798 $l = array_pop ( $ltd ) ;
799 if ( array_pop ( $td ) ) $t[] = '</td>' ;
800 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
801 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
805 $t = implode ( "\n" , $t ) ;
806 # special case: don't return empty table
807 if($t == "<table>\n<tr><td></td></tr>\n</table>")
809 wfProfileOut( $fname );
814 * Helper function for parse() that transforms wiki markup into
815 * HTML. Only called for $mOutputType == OT_HTML.
819 function internalParse( $text ) {
822 $fname = 'Parser::internalParse';
823 wfProfileIn( $fname );
825 # Remove <noinclude> tags and <includeonly> sections
826 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
827 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
828 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
830 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
832 $text = $this->replaceVariables( $text, $args );
834 // Tables need to come after variable replacement for things to work
835 // properly; putting them before other transformations should keep
836 // exciting things like link expansions from showing up in surprising
838 $text = $this->doTableStuff( $text );
840 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
842 $text = $this->stripToc( $text );
843 $this->stripNoGallery( $text );
844 $text = $this->doHeadings( $text );
845 if($this->mOptions
->getUseDynamicDates()) {
846 $df =& DateFormatter
::getInstance();
847 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
849 $text = $this->doAllQuotes( $text );
850 $text = $this->replaceInternalLinks( $text );
851 $text = $this->replaceExternalLinks( $text );
853 # replaceInternalLinks may sometimes leave behind
854 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
855 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
857 $text = $this->doMagicLinks( $text );
858 $text = $this->formatHeadings( $text, $isMain );
860 wfProfileOut( $fname );
865 * Replace special strings like "ISBN xxx" and "RFC xxx" with
866 * magic external links.
870 function &doMagicLinks( &$text ) {
871 $text = $this->magicISBN( $text );
872 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
873 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
878 * Parse headers and return html
882 function doHeadings( $text ) {
883 $fname = 'Parser::doHeadings';
884 wfProfileIn( $fname );
885 for ( $i = 6; $i >= 1; --$i ) {
886 $h = str_repeat( '=', $i );
887 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
888 "<h{$i}>\\1</h{$i}>\\2", $text );
890 wfProfileOut( $fname );
895 * Replace single quotes with HTML markup
897 * @return string the altered text
899 function doAllQuotes( $text ) {
900 $fname = 'Parser::doAllQuotes';
901 wfProfileIn( $fname );
903 $lines = explode( "\n", $text );
904 foreach ( $lines as $line ) {
905 $outtext .= $this->doQuotes ( $line ) . "\n";
907 $outtext = substr($outtext, 0,-1);
908 wfProfileOut( $fname );
913 * Helper function for doAllQuotes()
916 function doQuotes( $text ) {
917 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
918 if ( count( $arr ) == 1 )
922 # First, do some preliminary work. This may shift some apostrophes from
923 # being mark-up to being text. It also counts the number of occurrences
924 # of bold and italics mark-ups.
928 foreach ( $arr as $r )
930 if ( ( $i %
2 ) == 1 )
932 # If there are ever four apostrophes, assume the first is supposed to
933 # be text, and the remaining three constitute mark-up for bold text.
934 if ( strlen( $arr[$i] ) == 4 )
939 # If there are more than 5 apostrophes in a row, assume they're all
940 # text except for the last 5.
941 else if ( strlen( $arr[$i] ) > 5 )
943 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
946 # Count the number of occurrences of bold and italics mark-ups.
947 # We are not counting sequences of five apostrophes.
948 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
949 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
950 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
955 # If there is an odd number of both bold and italics, it is likely
956 # that one of the bold ones was meant to be an apostrophe followed
957 # by italics. Which one we cannot know for certain, but it is more
958 # likely to be one that has a single-letter word before it.
959 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
962 $firstsingleletterword = -1;
963 $firstmultiletterword = -1;
965 foreach ( $arr as $r )
967 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
969 $x1 = substr ($arr[$i-1], -1);
970 $x2 = substr ($arr[$i-1], -2, 1);
972 if ($firstspace == -1) $firstspace = $i;
973 } else if ($x2 == ' ') {
974 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
976 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
982 # If there is a single-letter word, use it!
983 if ($firstsingleletterword > -1)
985 $arr [ $firstsingleletterword ] = "''";
986 $arr [ $firstsingleletterword-1 ] .= "'";
988 # If not, but there's a multi-letter word, use that one.
989 else if ($firstmultiletterword > -1)
991 $arr [ $firstmultiletterword ] = "''";
992 $arr [ $firstmultiletterword-1 ] .= "'";
994 # ... otherwise use the first one that has neither.
995 # (notice that it is possible for all three to be -1 if, for example,
996 # there is only one pentuple-apostrophe in the line)
997 else if ($firstspace > -1)
999 $arr [ $firstspace ] = "''";
1000 $arr [ $firstspace-1 ] .= "'";
1004 # Now let's actually convert our apostrophic mush to HTML!
1009 foreach ($arr as $r)
1013 if ($state == 'both')
1020 if (strlen ($r) == 2)
1023 { $output .= '</i>'; $state = ''; }
1024 else if ($state == 'bi')
1025 { $output .= '</i>'; $state = 'b'; }
1026 else if ($state == 'ib')
1027 { $output .= '</b></i><b>'; $state = 'b'; }
1028 else if ($state == 'both')
1029 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1030 else # $state can be 'b' or ''
1031 { $output .= '<i>'; $state .= 'i'; }
1033 else if (strlen ($r) == 3)
1036 { $output .= '</b>'; $state = ''; }
1037 else if ($state == 'bi')
1038 { $output .= '</i></b><i>'; $state = 'i'; }
1039 else if ($state == 'ib')
1040 { $output .= '</b>'; $state = 'i'; }
1041 else if ($state == 'both')
1042 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1043 else # $state can be 'i' or ''
1044 { $output .= '<b>'; $state .= 'b'; }
1046 else if (strlen ($r) == 5)
1049 { $output .= '</b><i>'; $state = 'i'; }
1050 else if ($state == 'i')
1051 { $output .= '</i><b>'; $state = 'b'; }
1052 else if ($state == 'bi')
1053 { $output .= '</i></b>'; $state = ''; }
1054 else if ($state == 'ib')
1055 { $output .= '</b></i>'; $state = ''; }
1056 else if ($state == 'both')
1057 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1058 else # ($state == '')
1059 { $buffer = ''; $state = 'both'; }
1064 # Now close all remaining tags. Notice that the order is important.
1065 if ($state == 'b' ||
$state == 'ib')
1067 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1071 if ($state == 'both')
1072 $output .= '<b><i>'.$buffer.'</i></b>';
1078 * Replace external links
1080 * Note: this is all very hackish and the order of execution matters a lot.
1081 * Make sure to run maintenance/parserTests.php if you change this code.
1085 function replaceExternalLinks( $text ) {
1087 $fname = 'Parser::replaceExternalLinks';
1088 wfProfileIn( $fname );
1090 $sk =& $this->mOptions
->getSkin();
1092 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1094 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1097 while ( $i<count( $bits ) ) {
1099 $protocol = $bits[$i++
];
1100 $text = $bits[$i++
];
1101 $trail = $bits[$i++
];
1103 # The characters '<' and '>' (which were escaped by
1104 # removeHTMLtags()) should not be included in
1105 # URLs, per RFC 2396.
1106 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1107 $text = substr($url, $m2[0][1]) . ' ' . $text;
1108 $url = substr($url, 0, $m2[0][1]);
1111 # If the link text is an image URL, replace it with an <img> tag
1112 # This happened by accident in the original parser, but some people used it extensively
1113 $img = $this->maybeMakeExternalImage( $text );
1114 if ( $img !== false ) {
1120 # Set linktype for CSS - if URL==text, link is essentially free
1121 $linktype = ($text == $url) ?
'free' : 'text';
1123 # No link text, e.g. [http://domain.tld/some.link]
1124 if ( $text == '' ) {
1125 # Autonumber if allowed. See bug #5918
1126 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1127 $text = '[' . ++
$this->mAutonumber
. ']';
1128 $linktype = 'autonumber';
1130 # Otherwise just use the URL
1131 $text = htmlspecialchars( $url );
1135 # Have link text, e.g. [http://domain.tld/some.link text]s
1137 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1140 $text = $wgContLang->markNoConversion($text);
1142 # Normalize any HTML entities in input. They will be
1143 # re-escaped by makeExternalLink().
1144 $url = Sanitizer
::decodeCharReferences( $url );
1146 # Escape any control characters introduced by the above step
1147 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1149 # Process the trail (i.e. everything after this link up until start of the next link),
1150 # replacing any non-bracketed links
1151 $trail = $this->replaceFreeExternalLinks( $trail );
1153 # Use the encoded URL
1154 # This means that users can paste URLs directly into the text
1155 # Funny characters like ö aren't valid in URLs anyway
1156 # This was changed in August 2004
1157 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1159 # Register link in the output object.
1160 # Replace unnecessary URL escape codes with the referenced character
1161 # This prevents spammers from hiding links from the filters
1162 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1163 $this->mOutput
->addExternalLink( $pasteurized );
1166 wfProfileOut( $fname );
1171 * Replace anything that looks like a URL with a link
1174 function replaceFreeExternalLinks( $text ) {
1176 $fname = 'Parser::replaceFreeExternalLinks';
1177 wfProfileIn( $fname );
1179 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1180 $s = array_shift( $bits );
1183 $sk =& $this->mOptions
->getSkin();
1185 while ( $i < count( $bits ) ){
1186 $protocol = $bits[$i++
];
1187 $remainder = $bits[$i++
];
1189 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1190 # Found some characters after the protocol that look promising
1191 $url = $protocol . $m[1];
1194 # special case: handle urls as url args:
1195 # http://www.example.com/foo?=http://www.example.com/bar
1196 if(strlen($trail) == 0 &&
1198 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1199 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1202 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1207 # The characters '<' and '>' (which were escaped by
1208 # removeHTMLtags()) should not be included in
1209 # URLs, per RFC 2396.
1210 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1211 $trail = substr($url, $m2[0][1]) . $trail;
1212 $url = substr($url, 0, $m2[0][1]);
1215 # Move trailing punctuation to $trail
1217 # If there is no left bracket, then consider right brackets fair game too
1218 if ( strpos( $url, '(' ) === false ) {
1222 $numSepChars = strspn( strrev( $url ), $sep );
1223 if ( $numSepChars ) {
1224 $trail = substr( $url, -$numSepChars ) . $trail;
1225 $url = substr( $url, 0, -$numSepChars );
1228 # Normalize any HTML entities in input. They will be
1229 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1230 $url = Sanitizer
::decodeCharReferences( $url );
1232 # Escape any control characters introduced by the above step
1233 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1235 # Is this an external image?
1236 $text = $this->maybeMakeExternalImage( $url );
1237 if ( $text === false ) {
1238 # Not an image, make a link
1239 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1240 # Register it in the output object...
1241 # Replace unnecessary URL escape codes with their equivalent characters
1242 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1243 $this->mOutput
->addExternalLink( $pasteurized );
1245 $s .= $text . $trail;
1247 $s .= $protocol . $remainder;
1250 wfProfileOut( $fname );
1255 * Replace unusual URL escape codes with their equivalent characters
1259 * @fixme This can merge genuinely required bits in the path or query string,
1260 * breaking legit URLs. A proper fix would treat the various parts of
1261 * the URL differently; as a workaround, just use the output for
1262 * statistical records, not for actual linking/output.
1264 function replaceUnusualEscapes( $url ) {
1265 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1266 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1270 * Callback function used in replaceUnusualEscapes().
1271 * Replaces unusual URL escape codes with their equivalent character
1275 function replaceUnusualEscapesCallback( $matches ) {
1276 $char = urldecode( $matches[0] );
1277 $ord = ord( $char );
1278 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1279 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1280 // No, shouldn't be escaped
1283 // Yes, leave it escaped
1289 * make an image if it's allowed, either through the global
1290 * option or through the exception
1293 function maybeMakeExternalImage( $url ) {
1294 $sk =& $this->mOptions
->getSkin();
1295 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1296 $imagesexception = !empty($imagesfrom);
1298 if ( $this->mOptions
->getAllowExternalImages()
1299 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1300 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1302 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1309 * Process [[ ]] wikilinks
1313 function replaceInternalLinks( $s ) {
1315 static $fname = 'Parser::replaceInternalLinks' ;
1317 wfProfileIn( $fname );
1319 wfProfileIn( $fname.'-setup' );
1321 # the % is needed to support urlencoded titles as well
1322 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1324 $sk =& $this->mOptions
->getSkin();
1326 #split the entire text string on occurences of [[
1327 $a = explode( '[[', ' ' . $s );
1328 #get the first element (all text up to first [[), and remove the space we added
1329 $s = array_shift( $a );
1330 $s = substr( $s, 1 );
1332 # Match a link having the form [[namespace:link|alternate]]trail
1334 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1335 # Match cases where there is no "]]", which might still be images
1336 static $e1_img = FALSE;
1337 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1338 # Match the end of a line for a word that's not followed by whitespace,
1339 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1340 $e2 = wfMsgForContent( 'linkprefix' );
1342 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1344 if( is_null( $this->mTitle
) ) {
1345 throw new MWException( 'nooo' );
1347 $nottalk = !$this->mTitle
->isTalkPage();
1349 if ( $useLinkPrefixExtension ) {
1350 if ( preg_match( $e2, $s, $m ) ) {
1351 $first_prefix = $m[2];
1353 $first_prefix = false;
1359 $selflink = $this->mTitle
->getPrefixedText();
1360 wfProfileOut( $fname.'-setup' );
1362 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1363 $useSubpages = $this->areSubpagesAllowed();
1365 # Loop for each link
1366 for ($k = 0; isset( $a[$k] ); $k++
) {
1368 if ( $useLinkPrefixExtension ) {
1369 wfProfileIn( $fname.'-prefixhandling' );
1370 if ( preg_match( $e2, $s, $m ) ) {
1378 $prefix = $first_prefix;
1379 $first_prefix = false;
1381 wfProfileOut( $fname.'-prefixhandling' );
1384 $might_be_img = false;
1386 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1388 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1389 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1390 # the real problem is with the $e1 regex
1393 # Still some problems for cases where the ] is meant to be outside punctuation,
1394 # and no image is in sight. See bug 2095.
1397 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1398 strpos($text, '[') !== false
1401 $text .= ']'; # so that replaceExternalLinks($text) works later
1404 # fix up urlencoded title texts
1405 if(preg_match('/%/', $m[1] ))
1406 # Should anchors '#' also be rejected?
1407 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1409 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1410 $might_be_img = true;
1412 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1414 } else { # Invalid form; output directly
1415 $s .= $prefix . '[[' . $line ;
1419 # Don't allow internal links to pages containing
1420 # PROTO: where PROTO is a valid URL protocol; these
1421 # should be external links.
1422 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1423 $s .= $prefix . '[[' . $line ;
1427 # Make subpage if necessary
1428 if( $useSubpages ) {
1429 $link = $this->maybeDoSubpageLink( $m[1], $text );
1434 $noforce = (substr($m[1], 0, 1) != ':');
1436 # Strip off leading ':'
1437 $link = substr($link, 1);
1440 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1442 $s .= $prefix . '[[' . $line;
1446 #check other language variants of the link
1447 #if the article does not exist
1448 if( $checkVariantLink
1449 && $nt->getArticleID() == 0 ) {
1450 $wgContLang->findVariantLink($link, $nt);
1453 $ns = $nt->getNamespace();
1454 $iw = $nt->getInterWiki();
1456 if ($might_be_img) { # if this is actually an invalid link
1457 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1459 while (isset ($a[$k+
1]) ) {
1460 #look at the next 'line' to see if we can close it there
1461 $spliced = array_splice( $a, $k +
1, 1 );
1462 $next_line = array_shift( $spliced );
1463 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1464 # the first ]] closes the inner link, the second the image
1466 $text .= '[[' . $m[1];
1469 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1470 #if there's exactly one ]] that's fine, we'll keep looking
1471 $text .= '[[' . $m[0];
1473 #if $next_line is invalid too, we need look no further
1474 $text .= '[[' . $next_line;
1479 # we couldn't find the end of this imageLink, so output it raw
1480 #but don't ignore what might be perfectly normal links in the text we've examined
1481 $text = $this->replaceInternalLinks($text);
1482 $s .= $prefix . '[[' . $link . '|' . $text;
1483 # note: no $trail, because without an end, there *is* no trail
1486 } else { #it's not an image, so output it raw
1487 $s .= $prefix . '[[' . $link . '|' . $text;
1488 # note: no $trail, because without an end, there *is* no trail
1493 $wasblank = ( '' == $text );
1494 if( $wasblank ) $text = $link;
1497 # Link not escaped by : , create the various objects
1501 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1502 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1503 $s = rtrim($s . "\n");
1504 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1508 if ( $ns == NS_IMAGE
) {
1509 wfProfileIn( "$fname-image" );
1510 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1511 # recursively parse links inside the image caption
1512 # actually, this will parse them in any other parameters, too,
1513 # but it might be hard to fix that, and it doesn't matter ATM
1514 $text = $this->replaceExternalLinks($text);
1515 $text = $this->replaceInternalLinks($text);
1517 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1518 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1519 $this->mOutput
->addImage( $nt->getDBkey() );
1521 wfProfileOut( "$fname-image" );
1524 wfProfileOut( "$fname-image" );
1528 if ( $ns == NS_CATEGORY
) {
1529 wfProfileIn( "$fname-category" );
1530 $s = rtrim($s . "\n"); # bug 87
1533 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1534 $sortkey = $this->mTitle
->getText();
1536 $sortkey = $this->mTitle
->getPrefixedText();
1541 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1542 $sortkey = str_replace( "\n", '', $sortkey );
1543 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1544 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1547 * Strip the whitespace Category links produce, see bug 87
1548 * @todo We might want to use trim($tmp, "\n") here.
1550 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1552 wfProfileOut( "$fname-category" );
1557 if( ( $nt->getPrefixedText() === $selflink ) &&
1558 ( $nt->getFragment() === '' ) ) {
1559 # Self-links are handled specially; generally de-link and change to bold.
1560 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1564 # Special and Media are pseudo-namespaces; no pages actually exist in them
1565 if( $ns == NS_MEDIA
) {
1566 $link = $sk->makeMediaLinkObj( $nt, $text );
1567 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1568 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1569 $this->mOutput
->addImage( $nt->getDBkey() );
1571 } elseif( $ns == NS_SPECIAL
) {
1572 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1574 } elseif( $ns == NS_IMAGE
) {
1575 $img = Image
::newFromTitle( $nt );
1576 if( $img->exists() ) {
1577 // Force a blue link if the file exists; may be a remote
1578 // upload on the shared repository, and we want to see its
1579 // auto-generated page.
1580 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1584 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1586 wfProfileOut( $fname );
1591 * Make a link placeholder. The text returned can be later resolved to a real link with
1592 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1593 * parsing of interwiki links, and secondly to allow all extistence checks and
1594 * article length checks (for stub links) to be bundled into a single query.
1597 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1598 if ( ! is_object($nt) ) {
1600 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1602 # Separate the link trail from the rest of the link
1603 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1605 if ( $nt->isExternal() ) {
1606 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1607 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1608 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1610 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1611 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1612 $this->mLinkHolders
['queries'][] = $query;
1613 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1614 $this->mLinkHolders
['titles'][] = $nt;
1616 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1623 * Render a forced-blue link inline; protect against double expansion of
1624 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1625 * Since this little disaster has to split off the trail text to avoid
1626 * breaking URLs in the following text without breaking trails on the
1627 * wiki links, it's been made into a horrible function.
1630 * @param string $text
1631 * @param string $query
1632 * @param string $trail
1633 * @param string $prefix
1634 * @return string HTML-wikitext mix oh yuck
1636 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1637 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1638 $sk =& $this->mOptions
->getSkin();
1639 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1640 return $this->armorLinks( $link ) . $trail;
1644 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1645 * going to go through further parsing steps before inline URL expansion.
1647 * In particular this is important when using action=render, which causes
1648 * full URLs to be included.
1650 * Oh man I hate our multi-layer parser!
1652 * @param string more-or-less HTML
1653 * @return string less-or-more HTML with NOPARSE bits
1655 function armorLinks( $text ) {
1656 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1657 "{$this->mUniqPrefix}NOPARSE$1", $text );
1661 * Return true if subpage links should be expanded on this page.
1664 function areSubpagesAllowed() {
1665 # Some namespaces don't allow subpages
1666 global $wgNamespacesWithSubpages;
1667 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1671 * Handle link to subpage if necessary
1672 * @param string $target the source of the link
1673 * @param string &$text the link text, modified as necessary
1674 * @return string the full name of the link
1677 function maybeDoSubpageLink($target, &$text) {
1680 # :Foobar -- override special treatment of prefix (images, language links)
1681 # /Foobar -- convert to CurrentPage/Foobar
1682 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1683 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1684 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1686 $fname = 'Parser::maybeDoSubpageLink';
1687 wfProfileIn( $fname );
1688 $ret = $target; # default return value is no change
1690 # Some namespaces don't allow subpages,
1691 # so only perform processing if subpages are allowed
1692 if( $this->areSubpagesAllowed() ) {
1693 # Look at the first character
1694 if( $target != '' && $target{0} == '/' ) {
1695 # / at end means we don't want the slash to be shown
1696 if( substr( $target, -1, 1 ) == '/' ) {
1697 $target = substr( $target, 1, -1 );
1700 $noslash = substr( $target, 1 );
1703 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1704 if( '' === $text ) {
1706 } # this might be changed for ugliness reasons
1708 # check for .. subpage backlinks
1710 $nodotdot = $target;
1711 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1713 $nodotdot = substr( $nodotdot, 3 );
1715 if($dotdotcount > 0) {
1716 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1717 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1718 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1719 # / at the end means don't show full path
1720 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1721 $nodotdot = substr( $nodotdot, 0, -1 );
1722 if( '' === $text ) {
1726 $nodotdot = trim( $nodotdot );
1727 if( $nodotdot != '' ) {
1728 $ret .= '/' . $nodotdot;
1735 wfProfileOut( $fname );
1740 * Used by doBlockLevels()
1743 /* private */ function closeParagraph() {
1745 if ( '' != $this->mLastSection
) {
1746 $result = '</' . $this->mLastSection
. ">\n";
1748 $this->mInPre
= false;
1749 $this->mLastSection
= '';
1752 # getCommon() returns the length of the longest common substring
1753 # of both arguments, starting at the beginning of both.
1755 /* private */ function getCommon( $st1, $st2 ) {
1756 $fl = strlen( $st1 );
1757 $shorter = strlen( $st2 );
1758 if ( $fl < $shorter ) { $shorter = $fl; }
1760 for ( $i = 0; $i < $shorter; ++
$i ) {
1761 if ( $st1{$i} != $st2{$i} ) { break; }
1765 # These next three functions open, continue, and close the list
1766 # element appropriate to the prefix character passed into them.
1768 /* private */ function openList( $char ) {
1769 $result = $this->closeParagraph();
1771 if ( '*' == $char ) { $result .= '<ul><li>'; }
1772 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1773 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1774 else if ( ';' == $char ) {
1775 $result .= '<dl><dt>';
1776 $this->mDTopen
= true;
1778 else { $result = '<!-- ERR 1 -->'; }
1783 /* private */ function nextItem( $char ) {
1784 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1785 else if ( ':' == $char ||
';' == $char ) {
1787 if ( $this->mDTopen
) { $close = '</dt>'; }
1788 if ( ';' == $char ) {
1789 $this->mDTopen
= true;
1790 return $close . '<dt>';
1792 $this->mDTopen
= false;
1793 return $close . '<dd>';
1796 return '<!-- ERR 2 -->';
1799 /* private */ function closeList( $char ) {
1800 if ( '*' == $char ) { $text = '</li></ul>'; }
1801 else if ( '#' == $char ) { $text = '</li></ol>'; }
1802 else if ( ':' == $char ) {
1803 if ( $this->mDTopen
) {
1804 $this->mDTopen
= false;
1805 $text = '</dt></dl>';
1807 $text = '</dd></dl>';
1810 else { return '<!-- ERR 3 -->'; }
1816 * Make lists from lines starting with ':', '*', '#', etc.
1819 * @return string the lists rendered as HTML
1821 function doBlockLevels( $text, $linestart ) {
1822 $fname = 'Parser::doBlockLevels';
1823 wfProfileIn( $fname );
1825 # Parsing through the text line by line. The main thing
1826 # happening here is handling of block-level elements p, pre,
1827 # and making lists from lines starting with * # : etc.
1829 $textLines = explode( "\n", $text );
1831 $lastPrefix = $output = '';
1832 $this->mDTopen
= $inBlockElem = false;
1834 $paragraphStack = false;
1836 if ( !$linestart ) {
1837 $output .= array_shift( $textLines );
1839 foreach ( $textLines as $oLine ) {
1840 $lastPrefixLength = strlen( $lastPrefix );
1841 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1842 $preOpenMatch = preg_match('/<pre/i', $oLine );
1843 if ( !$this->mInPre
) {
1844 # Multiple prefixes may abut each other for nested lists.
1845 $prefixLength = strspn( $oLine, '*#:;' );
1846 $pref = substr( $oLine, 0, $prefixLength );
1849 $pref2 = str_replace( ';', ':', $pref );
1850 $t = substr( $oLine, $prefixLength );
1851 $this->mInPre
= !empty($preOpenMatch);
1853 # Don't interpret any other prefixes in preformatted text
1855 $pref = $pref2 = '';
1860 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1861 # Same as the last item, so no need to deal with nesting or opening stuff
1862 $output .= $this->nextItem( substr( $pref, -1 ) );
1863 $paragraphStack = false;
1865 if ( substr( $pref, -1 ) == ';') {
1866 # The one nasty exception: definition lists work like this:
1867 # ; title : definition text
1868 # So we check for : in the remainder text to split up the
1869 # title and definition, without b0rking links.
1871 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1873 $output .= $term . $this->nextItem( ':' );
1876 } elseif( $prefixLength ||
$lastPrefixLength ) {
1877 # Either open or close a level...
1878 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1879 $paragraphStack = false;
1881 while( $commonPrefixLength < $lastPrefixLength ) {
1882 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1883 --$lastPrefixLength;
1885 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1886 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1888 while ( $prefixLength > $commonPrefixLength ) {
1889 $char = substr( $pref, $commonPrefixLength, 1 );
1890 $output .= $this->openList( $char );
1892 if ( ';' == $char ) {
1893 # FIXME: This is dupe of code above
1894 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1896 $output .= $term . $this->nextItem( ':' );
1899 ++
$commonPrefixLength;
1901 $lastPrefix = $pref2;
1903 if( 0 == $prefixLength ) {
1904 wfProfileIn( "$fname-paragraph" );
1905 # No prefix (not in list)--go to paragraph mode
1906 // XXX: use a stack for nestable elements like span, table and div
1907 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1908 $closematch = preg_match(
1909 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1910 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1911 if ( $openmatch or $closematch ) {
1912 $paragraphStack = false;
1913 #Â TODO bug 5718: paragraph closed
1914 $output .= $this->closeParagraph();
1915 if ( $preOpenMatch and !$preCloseMatch ) {
1916 $this->mInPre
= true;
1918 if ( $closematch ) {
1919 $inBlockElem = false;
1921 $inBlockElem = true;
1923 } else if ( !$inBlockElem && !$this->mInPre
) {
1924 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1926 if ($this->mLastSection
!= 'pre') {
1927 $paragraphStack = false;
1928 $output .= $this->closeParagraph().'<pre>';
1929 $this->mLastSection
= 'pre';
1931 $t = substr( $t, 1 );
1934 if ( '' == trim($t) ) {
1935 if ( $paragraphStack ) {
1936 $output .= $paragraphStack.'<br />';
1937 $paragraphStack = false;
1938 $this->mLastSection
= 'p';
1940 if ($this->mLastSection
!= 'p' ) {
1941 $output .= $this->closeParagraph();
1942 $this->mLastSection
= '';
1943 $paragraphStack = '<p>';
1945 $paragraphStack = '</p><p>';
1949 if ( $paragraphStack ) {
1950 $output .= $paragraphStack;
1951 $paragraphStack = false;
1952 $this->mLastSection
= 'p';
1953 } else if ($this->mLastSection
!= 'p') {
1954 $output .= $this->closeParagraph().'<p>';
1955 $this->mLastSection
= 'p';
1960 wfProfileOut( "$fname-paragraph" );
1962 // somewhere above we forget to get out of pre block (bug 785)
1963 if($preCloseMatch && $this->mInPre
) {
1964 $this->mInPre
= false;
1966 if ($paragraphStack === false) {
1970 while ( $prefixLength ) {
1971 $output .= $this->closeList( $pref2{$prefixLength-1} );
1974 if ( '' != $this->mLastSection
) {
1975 $output .= '</' . $this->mLastSection
. '>';
1976 $this->mLastSection
= '';
1979 wfProfileOut( $fname );
1984 * Split up a string on ':', ignoring any occurences inside tags
1985 * to prevent illegal overlapping.
1986 * @param string $str the string to split
1987 * @param string &$before set to everything before the ':'
1988 * @param string &$after set to everything after the ':'
1989 * return string the position of the ':', or false if none found
1991 function findColonNoLinks($str, &$before, &$after) {
1992 $fname = 'Parser::findColonNoLinks';
1993 wfProfileIn( $fname );
1995 $pos = strpos( $str, ':' );
1996 if( $pos === false ) {
1998 wfProfileOut( $fname );
2002 $lt = strpos( $str, '<' );
2003 if( $lt === false ||
$lt > $pos ) {
2004 // Easy; no tag nesting to worry about
2005 $before = substr( $str, 0, $pos );
2006 $after = substr( $str, $pos+
1 );
2007 wfProfileOut( $fname );
2011 // Ugly state machine to walk through avoiding tags.
2012 $state = MW_COLON_STATE_TEXT
;
2014 $len = strlen( $str );
2015 for( $i = 0; $i < $len; $i++
) {
2019 // (Using the number is a performance hack for common cases)
2020 case 0: // MW_COLON_STATE_TEXT:
2023 // Could be either a <start> tag or an </end> tag
2024 $state = MW_COLON_STATE_TAGSTART
;
2029 $before = substr( $str, 0, $i );
2030 $after = substr( $str, $i +
1 );
2031 wfProfileOut( $fname );
2034 // Embedded in a tag; don't break it.
2037 // Skip ahead looking for something interesting
2038 $colon = strpos( $str, ':', $i );
2039 if( $colon === false ) {
2040 // Nothing else interesting
2041 wfProfileOut( $fname );
2044 $lt = strpos( $str, '<', $i );
2045 if( $stack === 0 ) {
2046 if( $lt === false ||
$colon < $lt ) {
2048 $before = substr( $str, 0, $colon );
2049 $after = substr( $str, $colon +
1 );
2050 wfProfileOut( $fname );
2054 if( $lt === false ) {
2055 // Nothing else interesting to find; abort!
2056 // We're nested, but there's no close tags left. Abort!
2059 // Skip ahead to next tag start
2061 $state = MW_COLON_STATE_TAGSTART
;
2064 case 1: // MW_COLON_STATE_TAG:
2069 $state = MW_COLON_STATE_TEXT
;
2072 // Slash may be followed by >?
2073 $state = MW_COLON_STATE_TAGSLASH
;
2079 case 2: // MW_COLON_STATE_TAGSTART:
2082 $state = MW_COLON_STATE_CLOSETAG
;
2085 $state = MW_COLON_STATE_COMMENT
;
2088 // Illegal early close? This shouldn't happen D:
2089 $state = MW_COLON_STATE_TEXT
;
2092 $state = MW_COLON_STATE_TAG
;
2095 case 3: // MW_COLON_STATE_CLOSETAG:
2100 wfDebug( "Invalid input in $fname; too many close tags\n" );
2101 wfProfileOut( $fname );
2104 $state = MW_COLON_STATE_TEXT
;
2107 case MW_COLON_STATE_TAGSLASH
:
2109 // Yes, a self-closed tag <blah/>
2110 $state = MW_COLON_STATE_TEXT
;
2112 // Probably we're jumping the gun, and this is an attribute
2113 $state = MW_COLON_STATE_TAG
;
2116 case 5: // MW_COLON_STATE_COMMENT:
2118 $state = MW_COLON_STATE_COMMENTDASH
;
2121 case MW_COLON_STATE_COMMENTDASH
:
2123 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2125 $state = MW_COLON_STATE_COMMENT
;
2128 case MW_COLON_STATE_COMMENTDASHDASH
:
2130 $state = MW_COLON_STATE_TEXT
;
2132 $state = MW_COLON_STATE_COMMENT
;
2136 throw new MWException( "State machine error in $fname" );
2140 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2143 wfProfileOut( $fname );
2148 * Return value of a magic variable (like PAGENAME)
2152 function getVariableValue( $index ) {
2153 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2156 * Some of these require message or data lookups and can be
2157 * expensive to check many times.
2159 static $varCache = array();
2160 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2161 if ( isset( $varCache[$index] ) )
2162 return $varCache[$index];
2165 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2168 case MAG_CURRENTMONTH
:
2169 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2170 case MAG_CURRENTMONTHNAME
:
2171 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2172 case MAG_CURRENTMONTHNAMEGEN
:
2173 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2174 case MAG_CURRENTMONTHABBREV
:
2175 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2176 case MAG_CURRENTDAY
:
2177 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2178 case MAG_CURRENTDAY2
:
2179 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2181 return $this->mTitle
->getText();
2183 return $this->mTitle
->getPartialURL();
2184 case MAG_FULLPAGENAME
:
2185 return $this->mTitle
->getPrefixedText();
2186 case MAG_FULLPAGENAMEE
:
2187 return $this->mTitle
->getPrefixedURL();
2188 case MAG_SUBPAGENAME
:
2189 return $this->mTitle
->getSubpageText();
2190 case MAG_SUBPAGENAMEE
:
2191 return $this->mTitle
->getSubpageUrlForm();
2192 case MAG_BASEPAGENAME
:
2193 return $this->mTitle
->getBaseText();
2194 case MAG_BASEPAGENAMEE
:
2195 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2196 case MAG_TALKPAGENAME
:
2197 if( $this->mTitle
->canTalk() ) {
2198 $talkPage = $this->mTitle
->getTalkPage();
2199 return $talkPage->getPrefixedText();
2203 case MAG_TALKPAGENAMEE
:
2204 if( $this->mTitle
->canTalk() ) {
2205 $talkPage = $this->mTitle
->getTalkPage();
2206 return $talkPage->getPrefixedUrl();
2210 case MAG_SUBJECTPAGENAME
:
2211 $subjPage = $this->mTitle
->getSubjectPage();
2212 return $subjPage->getPrefixedText();
2213 case MAG_SUBJECTPAGENAMEE
:
2214 $subjPage = $this->mTitle
->getSubjectPage();
2215 return $subjPage->getPrefixedUrl();
2216 case MAG_REVISIONID
:
2217 return $this->mRevisionId
;
2219 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2220 case MAG_NAMESPACEE
:
2221 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2223 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2224 case MAG_TALKSPACEE
:
2225 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2226 case MAG_SUBJECTSPACE
:
2227 return $this->mTitle
->getSubjectNsText();
2228 case MAG_SUBJECTSPACEE
:
2229 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2230 case MAG_CURRENTDAYNAME
:
2231 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2232 case MAG_CURRENTYEAR
:
2233 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2234 case MAG_CURRENTTIME
:
2235 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2236 case MAG_CURRENTWEEK
:
2237 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2238 // int to remove the padding
2239 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2240 case MAG_CURRENTDOW
:
2241 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2242 case MAG_NUMBEROFARTICLES
:
2243 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2244 case MAG_NUMBEROFFILES
:
2245 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2246 case MAG_NUMBEROFUSERS
:
2247 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2248 case MAG_NUMBEROFPAGES
:
2249 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2250 case MAG_NUMBEROFADMINS
:
2251 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2252 case MAG_CURRENTTIMESTAMP
:
2253 return $varCache[$index] = wfTimestampNow();
2254 case MAG_CURRENTVERSION
:
2261 case MAG_SERVERNAME
:
2262 return $wgServerName;
2263 case MAG_SCRIPTPATH
:
2264 return $wgScriptPath;
2265 case MAG_DIRECTIONMARK
:
2266 return $wgContLang->getDirMark();
2267 case MAG_CONTENTLANGUAGE
:
2268 global $wgContLanguageCode;
2269 return $wgContLanguageCode;
2272 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2280 * initialise the magic variables (like CURRENTMONTHNAME)
2284 function initialiseVariables() {
2285 $fname = 'Parser::initialiseVariables';
2286 wfProfileIn( $fname );
2287 global $wgVariableIDs;
2288 $this->mVariables
= array();
2289 foreach ( $wgVariableIDs as $id ) {
2290 $mw =& MagicWord
::get( $id );
2291 $mw->addToArray( $this->mVariables
, $id );
2293 wfProfileOut( $fname );
2297 * parse any parentheses in format ((title|part|part))
2298 * and call callbacks to get a replacement text for any found piece
2300 * @param string $text The text to parse
2301 * @param array $callbacks rules in form:
2302 * '{' => array( # opening parentheses
2303 * 'end' => '}', # closing parentheses
2304 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2305 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2310 function replace_callback ($text, $callbacks) {
2311 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2312 $lastOpeningBrace = -1; # last not closed parentheses
2314 for ($i = 0; $i < strlen($text); $i++
) {
2315 # check for any opening brace
2318 foreach ($callbacks as $key => $value) {
2319 $pos = strpos ($text, $key, $i);
2320 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2326 if ($lastOpeningBrace >= 0) {
2327 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2329 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2334 $pos = strpos ($text, '|', $i);
2336 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2347 # found openning brace, lets add it to parentheses stack
2348 if (null != $rule) {
2349 $piece = array('brace' => $text[$i],
2350 'braceEnd' => $rule['end'],
2355 # count openning brace characters
2356 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2361 $piece['startAt'] = $i+
1;
2362 $piece['partStart'] = $i+
1;
2364 # we need to add to stack only if openning brace count is enough for any given rule
2365 foreach ($rule['cb'] as $cnt => $fn) {
2366 if ($piece['count'] >= $cnt) {
2367 $lastOpeningBrace ++
;
2368 $openingBraceStack[$lastOpeningBrace] = $piece;
2375 else if ($lastOpeningBrace >= 0) {
2376 # first check if it is a closing brace
2377 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2378 # lets check if it is enough characters for closing brace
2380 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2383 # if there are more closing parentheses than opening ones, we parse less
2384 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2385 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2387 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2389 $matchingCallback = null;
2390 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2391 if ($count >= $cnt && $matchingCount < $cnt) {
2392 $matchingCount = $cnt;
2393 $matchingCallback = $fn;
2397 if ($matchingCount == 0) {
2402 # lets set a title or last part (if '|' was found)
2403 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2404 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2406 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2408 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2409 $pieceEnd = $i +
$matchingCount;
2411 if( is_callable( $matchingCallback ) ) {
2413 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2414 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2415 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2416 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2418 # finally we can call a user callback and replace piece of text
2419 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2420 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2421 $i = $pieceStart +
strlen($replaceWith) - 1;
2424 # null value for callback means that parentheses should be parsed, but not replaced
2425 $i +
= $matchingCount - 1;
2428 # reset last openning parentheses, but keep it in case there are unused characters
2429 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2430 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2431 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2434 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2435 $openingBraceStack[$lastOpeningBrace--] = null;
2437 if ($matchingCount < $piece['count']) {
2438 $piece['count'] -= $matchingCount;
2439 $piece['startAt'] -= $matchingCount;
2440 $piece['partStart'] = $piece['startAt'];
2441 # do we still qualify for any callback with remaining count?
2442 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2443 if ($piece['count'] >= $cnt) {
2444 $lastOpeningBrace ++
;
2445 $openingBraceStack[$lastOpeningBrace] = $piece;
2453 # lets set a title if it is a first separator, or next part otherwise
2454 if ($text[$i] == '|') {
2455 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2456 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2457 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2460 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2462 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2471 * Replace magic variables, templates, and template arguments
2472 * with the appropriate text. Templates are substituted recursively,
2473 * taking care to avoid infinite loops.
2475 * Note that the substitution depends on value of $mOutputType:
2476 * OT_WIKI: only {{subst:}} templates
2477 * OT_MSG: only magic variables
2478 * OT_HTML: all templates and magic variables
2480 * @param string $tex The text to transform
2481 * @param array $args Key-value pairs representing template parameters to substitute
2482 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2485 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2486 # Prevent too big inclusions
2487 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2491 $fname = 'Parser::replaceVariables';
2492 wfProfileIn( $fname );
2494 # This function is called recursively. To keep track of arguments we need a stack:
2495 array_push( $this->mArgStack
, $args );
2497 $braceCallbacks = array();
2499 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2501 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2502 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2504 $callbacks = array();
2505 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2506 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2507 $text = $this->replace_callback ($text, $callbacks);
2509 array_pop( $this->mArgStack
);
2511 wfProfileOut( $fname );
2516 * Replace magic variables
2519 function variableSubstitution( $matches ) {
2520 $fname = 'Parser::variableSubstitution';
2521 $varname = $matches[1];
2522 wfProfileIn( $fname );
2523 if ( !$this->mVariables
) {
2524 $this->initialiseVariables();
2527 if ( $this->mOutputType
== OT_WIKI
) {
2528 # Do only magic variables prefixed by SUBST
2529 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2530 if (!$mwSubst->matchStartAndRemove( $varname ))
2532 # Note that if we don't substitute the variable below,
2533 # we don't remove the {{subst:}} magic word, in case
2534 # it is a template rather than a magic variable.
2536 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2537 $id = $this->mVariables
[$varname];
2538 $text = $this->getVariableValue( $id );
2539 $this->mOutput
->mContainsOldMagic
= true;
2541 $text = $matches[0];
2543 wfProfileOut( $fname );
2547 # Split template arguments
2548 function getTemplateArgs( $argsString ) {
2549 if ( $argsString === '' ) {
2553 $args = explode( '|', substr( $argsString, 1 ) );
2555 # If any of the arguments contains a '[[' but no ']]', it needs to be
2556 # merged with the next arg because the '|' character between belongs
2557 # to the link syntax and not the template parameter syntax.
2558 $argc = count($args);
2560 for ( $i = 0; $i < $argc-1; $i++
) {
2561 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2562 $args[$i] .= '|'.$args[$i+
1];
2563 array_splice($args, $i+
1, 1);
2573 * Return the text of a template, after recursively
2574 * replacing any variables or templates within the template.
2576 * @param array $piece The parts of the template
2577 * $piece['text']: matched text
2578 * $piece['title']: the title, i.e. the part before the |
2579 * $piece['parts']: the parameter array
2580 * @return string the text of the template
2583 function braceSubstitution( $piece ) {
2584 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2585 $fname = 'Parser::braceSubstitution';
2586 wfProfileIn( $fname );
2589 $found = false; # $text has been filled
2590 $nowiki = false; # wiki markup in $text should be escaped
2591 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2592 $noargs = false; # Don't replace triple-brace arguments in $text
2593 $replaceHeadings = false; # Make the edit section links go to the template not the article
2594 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2595 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2597 # Title object, where $text came from
2602 # $part1 is the bit before the first |, and must contain only title characters
2603 # $args is a list of arguments, starting from index 0, not including $part1
2605 $part1 = $piece['title'];
2606 # If the third subpattern matched anything, it will start with |
2608 if (null == $piece['parts']) {
2609 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2610 if ($replaceWith != $piece['text']) {
2611 $text = $replaceWith;
2618 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2619 $argc = count( $args );
2623 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2624 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2625 # One of two possibilities is true:
2626 # 1) Found SUBST but not in the PST phase
2627 # 2) Didn't find SUBST and in the PST phase
2628 # In either case, return without further processing
2629 $text = $piece['text'];
2636 # MSG, MSGNW, INT and RAW
2639 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2640 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2643 # Remove obsolete MSG:
2644 $mwMsg =& MagicWord
::get( MAG_MSG
);
2645 $mwMsg->matchStartAndRemove( $part1 );
2649 $mwRaw =& MagicWord
::get( MAG_RAW
);
2650 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2651 $forceRawInterwiki = true;
2654 # Check if it is an internal message
2655 $mwInt =& MagicWord
::get( MAG_INT
);
2656 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2657 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2658 $text = $linestart . wfMsgReal( $part1, $args, true );
2666 # Check for NS: (namespace expansion)
2667 $mwNs = MagicWord
::get( MAG_NS
);
2668 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2669 if ( intval( $part1 ) ||
$part1 == "0" ) {
2670 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2673 $param = str_replace( ' ', '_', strtolower( $part1 ) );
2674 $index = Namespace::getCanonicalIndex( strtolower( $param ) );
2675 if ( !is_null( $index ) ) {
2676 $text = $linestart . $wgContLang->getNsText( $index );
2685 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2686 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2687 $text = $linestart . urlencode( $part1 );
2692 # LCFIRST, UCFIRST, LC and UC
2694 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2695 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2696 $lc =& MagicWord
::get( MAG_LC
);
2697 $uc =& MagicWord
::get( MAG_UC
);
2698 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2699 $text = $linestart . $wgContLang->lcfirst( $part1 );
2701 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2702 $text = $linestart . $wgContLang->ucfirst( $part1 );
2704 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2705 $text = $linestart . $wgContLang->lc( $part1 );
2707 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2708 $text = $linestart . $wgContLang->uc( $part1 );
2713 # LOCALURL and FULLURL
2715 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2716 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2717 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2718 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2721 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2722 $func = 'getLocalURL';
2723 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2724 $func = 'escapeLocalURL';
2725 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2726 $func = 'getFullURL';
2727 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2728 $func = 'escapeFullURL';
2733 if ( $func !== false ) {
2734 $title = Title
::newFromText( $part1 );
2735 # Due to order of execution of a lot of bits, the values might be encoded
2736 # before arriving here; if that's true, then the title can't be created
2737 # and the variable will fail. If we can't get a decent title from the first
2738 # attempt, url-decode and try for a second.
2739 if( is_null( $title ) )
2740 $title = Title
::newFromUrl( urldecode( $part1 ) );
2741 if ( !is_null( $title ) ) {
2743 $text = $linestart . $title->$func( $args[0] );
2745 $text = $linestart . $title->$func();
2752 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2753 if ( !$found && $argc == 1 ) {
2754 $mwGrammar =& MagicWord
::get( MAG_FORMATNUM
);
2755 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2756 $text = $linestart . $lang->formatNum( $args[0] );
2763 if ( !$found && $argc == 1 ) {
2764 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2765 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2766 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2772 if ( !$found && $argc >= 2 ) {
2773 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2774 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2775 while ( count($args) < 5 ) { $args[] = $args[count($args)-1]; }
2776 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1],
2777 $args[2], $args[3], $args[4]);
2783 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2784 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2785 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2787 # Set title in parser output object
2789 $parserOptions = new ParserOptions
;
2790 $local_parser = new Parser ();
2791 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2792 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2795 $t = $this->mTitle
->getPrefixedText();
2796 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2802 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2804 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2805 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2806 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2807 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles',
2808 MAG_NUMBEROFADMINS
=> 'wfNumberOfAdmins' );
2809 foreach( $mwWordsToCheck as $word => $func ) {
2810 $mwCurrentWord =& MagicWord
::get( $word );
2811 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2812 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2813 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2814 # Raw and unformatted
2815 $text = $linestart . call_user_func( $func );
2817 # Formatted according to the content default
2818 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2827 $mwPagesInNs =& MagicWord
::get( MAG_PAGESINNAMESPACE
);
2828 if( $mwPagesInNs->matchStartAndRemove( $part1 ) ) {
2830 $count = wfPagesInNs( intval( $part1 ) );
2831 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2832 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2833 $text = $linestart . $count;
2835 $text = $linestart . $wgContLang->formatNum( $count );
2842 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2843 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2844 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2845 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2851 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2852 $colonPos = strpos( $part1, ':' );
2853 if ( $colonPos !== false ) {
2854 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2855 if ( isset( $this->mFunctionSynonyms
[$function] ) ) {
2856 $function = $this->mFunctionSynonyms
[$function];
2857 $funcArgs = array_map( 'trim', $args );
2858 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2859 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2862 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2866 if ( is_array( $result ) ) {
2867 $text = $linestart . $result[0];
2868 unset( $result[0] );
2870 // Extract flags into the local scope
2871 // This allows callers to set flags such as nowiki, noparse, found, etc.
2874 $text = $linestart . $result;
2880 # Template table test
2882 # Did we encounter this template already? If yes, it is in the cache
2883 # and we need to check for loops.
2884 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2887 # Infinite loop test
2888 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2892 $text = $linestart .
2893 '{{' . $part1 . '}}' .
2894 '<!-- WARNING: template loop detected -->';
2895 wfDebug( "$fname: template loop broken at '$part1'\n" );
2897 # set $text to cached message.
2898 $text = $linestart . $this->mTemplates
[$piece['title']];
2902 # Load from database
2903 $lastPathLevel = $this->mTemplatePath
;
2906 # declaring $subpage directly in the function call
2907 # does not work correctly with references and breaks
2908 # {{/subpage}}-style inclusions
2910 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2911 if ($subpage !== '') {
2912 $ns = $this->mTitle
->getNamespace();
2914 $title = Title
::newFromText( $part1, $ns );
2917 if ( !is_null( $title ) ) {
2918 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2919 # Check for language variants if the template is not found
2920 if($checkVariantLink && $title->getArticleID() == 0){
2921 $wgContLang->findVariantLink($part1, $title);
2924 if ( !$title->isExternal() ) {
2925 # Check for excessive inclusion
2926 $dbk = $title->getPrefixedDBkey();
2927 if ( $this->incrementIncludeCount( $dbk ) ) {
2928 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2929 $text = SpecialPage
::capturePath( $title );
2930 if ( is_string( $text ) ) {
2935 $this->disableCache();
2938 $articleContent = $this->fetchTemplate( $title );
2939 if ( $articleContent !== false ) {
2941 $text = $articleContent;
2942 $replaceHeadings = true;
2947 # If the title is valid but undisplayable, make a link to it
2948 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2949 $text = '[['.$title->getPrefixedText().']]';
2952 } elseif ( $title->isTrans() ) {
2953 // Interwiki transclusion
2954 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2955 $text = $this->interwikiTransclude( $title, 'render' );
2959 $text = $this->interwikiTransclude( $title, 'raw' );
2960 $replaceHeadings = true;
2965 # Template cache array insertion
2966 # Use the original $piece['title'] not the mangled $part1, so that
2967 # modifiers such as RAW: produce separate cache entries
2970 // A special page; don't store it in the template cache.
2972 $this->mTemplates
[$piece['title']] = $text;
2974 $text = $linestart . $text;
2979 # Recursive parsing, escaping and link table handling
2980 # Only for HTML output
2981 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2982 $text = wfEscapeWikiText( $text );
2983 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2985 $assocArgs = array();
2987 # Clean up argument array
2988 $assocArgs = array();
2990 foreach( $args as $arg ) {
2991 $eqpos = strpos( $arg, '=' );
2992 if ( $eqpos === false ) {
2993 $assocArgs[$index++
] = $arg;
2995 $name = trim( substr( $arg, 0, $eqpos ) );
2996 $value = trim( substr( $arg, $eqpos+
1 ) );
2997 if ( $value === false ) {
3000 if ( $name !== false ) {
3001 $assocArgs[$name] = $value;
3006 # Add a new element to the templace recursion path
3007 $this->mTemplatePath
[$part1] = 1;
3011 # If there are any <onlyinclude> tags, only include them
3012 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3013 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3015 foreach ($m[1] as $piece)
3018 # Remove <noinclude> sections and <includeonly> tags
3019 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3020 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3022 if( $this->mOutputType
== OT_HTML
) {
3023 # Strip <nowiki>, <pre>, etc.
3024 $text = $this->strip( $text, $this->mStripState
);
3025 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3027 $text = $this->replaceVariables( $text, $assocArgs );
3029 # If the template begins with a table or block-level
3030 # element, it should be treated as beginning a new line.
3031 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
3032 $text = "\n" . $text;
3034 } elseif ( !$noargs ) {
3035 # $noparse and !$noargs
3036 # Just replace the arguments, not any double-brace items
3037 # This is used for rendered interwiki transclusion
3038 $text = $this->replaceVariables( $text, $assocArgs, true );
3041 # Prune lower levels off the recursion check path
3042 $this->mTemplatePath
= $lastPathLevel;
3045 wfProfileOut( $fname );
3046 return $piece['text'];
3049 # Replace raw HTML by a placeholder
3050 # Add a blank line preceding, to prevent it from mucking up
3051 # immediately preceding headings
3052 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3054 # replace ==section headers==
3055 # XXX this needs to go away once we have a better parser.
3056 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3057 if( !is_null( $title ) )
3058 $encodedname = base64_encode($title->getPrefixedDBkey());
3060 $encodedname = base64_encode("");
3061 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3062 PREG_SPLIT_DELIM_CAPTURE
);
3065 for( $i = 0; $i < count($m); $i +
= 2 ) {
3067 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3069 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3073 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3074 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3075 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3083 # Prune lower levels off the recursion check path
3084 $this->mTemplatePath
= $lastPathLevel;
3087 wfProfileOut( $fname );
3088 return $piece['text'];
3090 wfProfileOut( $fname );
3096 * Fetch the unparsed text of a template and register a reference to it.
3098 function fetchTemplate( $title ) {
3100 // Loop to fetch the article, with up to 1 redirect
3101 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3102 $rev = Revision
::newFromTitle( $title );
3103 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3107 $text = $rev->getText();
3108 if ( $text === false ) {
3112 $title = Title
::newFromRedirect( $text );
3118 * Transclude an interwiki link.
3120 function interwikiTransclude( $title, $action ) {
3121 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3123 if (!$wgEnableScaryTranscluding)
3124 return wfMsg('scarytranscludedisabled');
3126 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3127 // But we'll handle it generally anyway
3128 if ( $title->getNamespace() ) {
3129 // Use the canonical namespace, which should work anywhere
3130 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3132 $articleName = $title->getDBkey();
3135 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3136 $url .= "?action=$action";
3137 if (strlen($url) > 255)
3138 return wfMsg('scarytranscludetoolong');
3139 return $this->fetchScaryTemplateMaybeFromCache($url);
3142 function fetchScaryTemplateMaybeFromCache($url) {
3143 global $wgTranscludeCacheExpiry;
3144 $dbr =& wfGetDB(DB_SLAVE
);
3145 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3146 array('tc_url' => $url));
3148 $time = $obj->tc_time
;
3149 $text = $obj->tc_contents
;
3150 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3155 $text = Http
::get($url);
3157 return wfMsg('scarytranscludefailed', $url);
3159 $dbw =& wfGetDB(DB_MASTER
);
3160 $dbw->replace('transcache', array('tc_url'), array(
3162 'tc_time' => time(),
3163 'tc_contents' => $text));
3169 * Triple brace replacement -- used for template arguments
3172 function argSubstitution( $matches ) {
3173 $arg = trim( $matches['title'] );
3174 $text = $matches['text'];
3175 $inputArgs = end( $this->mArgStack
);
3177 if ( array_key_exists( $arg, $inputArgs ) ) {
3178 $text = $inputArgs[$arg];
3179 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3180 $text = $matches['parts'][0];
3187 * Returns true if the function is allowed to include this entity
3190 function incrementIncludeCount( $dbk ) {
3191 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3192 $this->mIncludeCount
[$dbk] = 0;
3194 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3202 * Detect __NOGALLERY__ magic word and set a placeholder
3204 function stripNoGallery( &$text ) {
3205 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3207 $mw = MagicWord
::get( MAG_NOGALLERY
);
3208 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3212 * Detect __TOC__ magic word and set a placeholder
3214 function stripToc( $text ) {
3215 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3217 $mw = MagicWord
::get( MAG_NOTOC
);
3218 if( $mw->matchAndRemove( $text ) ) {
3219 $this->mShowToc
= false;
3222 $mw = MagicWord
::get( MAG_TOC
);
3223 if( $mw->match( $text ) ) {
3224 $this->mShowToc
= true;
3225 $this->mForceTocPosition
= true;
3227 // Set a placeholder. At the end we'll fill it in with the TOC.
3228 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3230 // Only keep the first one.
3231 $text = $mw->replace( '', $text );
3237 * This function accomplishes several tasks:
3238 * 1) Auto-number headings if that option is enabled
3239 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3240 * 3) Add a Table of contents on the top for users who have enabled the option
3241 * 4) Auto-anchor headings
3243 * It loops through all headlines, collects the necessary data, then splits up the
3244 * string and re-inserts the newly formatted headlines.
3246 * @param string $text
3247 * @param boolean $isMain
3250 function formatHeadings( $text, $isMain=true ) {
3251 global $wgMaxTocLevel, $wgContLang;
3253 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3254 if( !$this->mTitle
->userCanEdit() ) {
3257 $showEditLink = $this->mOptions
->getEditSection();
3260 # Inhibit editsection links if requested in the page
3261 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3262 if( $esw->matchAndRemove( $text ) ) {
3266 # Get all headlines for numbering them and adding funky stuff like [edit]
3267 # links - this is for later, but we need the number of headlines right now
3268 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3270 # if there are fewer than 4 headlines in the article, do not show TOC
3271 # unless it's been explicitly enabled.
3272 $enoughToc = $this->mShowToc
&&
3273 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3275 # Allow user to stipulate that a page should have a "new section"
3276 # link added via __NEWSECTIONLINK__
3277 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3278 if( $mw->matchAndRemove( $text ) )
3279 $this->mOutput
->setNewSection( true );
3281 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3282 # override above conditions and always show TOC above first header
3283 $mw =& MagicWord
::get( MAG_FORCETOC
);
3284 if ($mw->matchAndRemove( $text ) ) {
3285 $this->mShowToc
= true;
3289 # Never ever show TOC if no headers
3290 if( $numMatches < 1 ) {
3294 # We need this to perform operations on the HTML
3295 $sk =& $this->mOptions
->getSkin();
3299 $sectionCount = 0; # headlineCount excluding template sections
3301 # Ugh .. the TOC should have neat indentation levels which can be
3302 # passed to the skin functions. These are determined here
3306 $sublevelCount = array();
3307 $levelCount = array();
3314 foreach( $matches[3] as $headline ) {
3316 $templatetitle = '';
3317 $templatesection = 0;
3320 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3322 $templatetitle = base64_decode($mat[1]);
3323 $templatesection = 1 +
(int)base64_decode($mat[2]);
3324 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3328 $prevlevel = $level;
3329 $prevtoclevel = $toclevel;
3331 $level = $matches[1][$headlineCount];
3333 if( $doNumberHeadings ||
$enoughToc ) {
3335 if ( $level > $prevlevel ) {
3336 # Increase TOC level
3338 $sublevelCount[$toclevel] = 0;
3339 if( $toclevel<$wgMaxTocLevel ) {
3340 $toc .= $sk->tocIndent();
3343 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3344 # Decrease TOC level, find level to jump to
3346 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3347 # Can only go down to level 1
3350 for ($i = $toclevel; $i > 0; $i--) {
3351 if ( $levelCount[$i] == $level ) {
3352 # Found last matching level
3356 elseif ( $levelCount[$i] < $level ) {
3357 # Found first matching level below current level
3363 if( $toclevel<$wgMaxTocLevel ) {
3364 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3368 # No change in level, end TOC line
3369 if( $toclevel<$wgMaxTocLevel ) {
3370 $toc .= $sk->tocLineEnd();
3374 $levelCount[$toclevel] = $level;
3376 # count number of headlines for each level
3377 @$sublevelCount[$toclevel]++
;
3379 for( $i = 1; $i <= $toclevel; $i++
) {
3380 if( !empty( $sublevelCount[$i] ) ) {
3384 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3390 # The canonized header is a version of the header text safe to use for links
3391 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3392 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3393 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3395 # Remove link placeholders by the link text.
3396 # <!--LINK number-->
3398 # link text with suffix
3399 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3400 "\$this->mLinkHolders['texts'][\$1]",
3401 $canonized_headline );
3402 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3403 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3404 $canonized_headline );
3407 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3408 $tocline = trim( $canonized_headline );
3409 # Save headline for section edit hint before it's escaped
3410 $headline_hint = trim( $canonized_headline );
3411 $canonized_headline = Sanitizer
::escapeId( $tocline );
3412 $refers[$headlineCount] = $canonized_headline;
3414 # count how many in assoc. array so we can track dupes in anchors
3415 @$refers[$canonized_headline]++
;
3416 $refcount[$headlineCount]=$refers[$canonized_headline];
3418 # Don't number the heading if it is the only one (looks silly)
3419 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3420 # the two are different if the line contains a link
3421 $headline=$numbering . ' ' . $headline;
3424 # Create the anchor for linking from the TOC to the section
3425 $anchor = $canonized_headline;
3426 if($refcount[$headlineCount] > 1 ) {
3427 $anchor .= '_' . $refcount[$headlineCount];
3429 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3430 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3432 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3433 if ( empty( $head[$headlineCount] ) ) {
3434 $head[$headlineCount] = '';
3437 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3439 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3442 # give headline the correct <h#> tag
3443 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3451 if( $toclevel<$wgMaxTocLevel ) {
3452 $toc .= $sk->tocUnindent( $toclevel - 1 );
3454 $toc = $sk->tocList( $toc );
3457 # split up and insert constructed headlines
3459 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3462 foreach( $blocks as $block ) {
3463 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3464 # This is the [edit] link that appears for the top block of text when
3465 # section editing is enabled
3467 # Disabled because it broke block formatting
3468 # For example, a bullet point in the top line
3469 # $full .= $sk->editSectionLink(0);
3472 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3473 # Top anchor now in skin
3477 if( !empty( $head[$i] ) ) {
3482 if( $this->mForceTocPosition
) {
3483 return str_replace( '<!--MWTOC-->', $toc, $full );
3490 * Return an HTML link for the "ISBN 123456" text
3493 function magicISBN( $text ) {
3494 $fname = 'Parser::magicISBN';
3495 wfProfileIn( $fname );
3497 $a = split( 'ISBN ', ' '.$text );
3498 if ( count ( $a ) < 2 ) {
3499 wfProfileOut( $fname );
3502 $text = substr( array_shift( $a ), 1);
3503 $valid = '0123456789-Xx';
3505 foreach ( $a as $x ) {
3506 # hack: don't replace inside thumbnail title/alt
3508 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3513 $isbn = $blank = '' ;
3514 while ( ' ' == $x{0} ) {
3516 $x = substr( $x, 1 );
3518 if ( $x == '' ) { # blank isbn
3519 $text .= "ISBN $blank";
3522 while ( strstr( $valid, $x{0} ) != false ) {
3524 $x = substr( $x, 1 );
3526 $num = str_replace( '-', '', $isbn );
3527 $num = str_replace( ' ', '', $num );
3528 $num = str_replace( 'x', 'X', $num );
3531 $text .= "ISBN $blank$x";
3533 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3534 $text .= '<a href="' .
3535 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3536 "\" class=\"internal\">ISBN $isbn</a>";
3540 wfProfileOut( $fname );
3545 * Return an HTML link for the "RFC 1234" text
3548 * @param string $text Text to be processed
3549 * @param string $keyword Magic keyword to use (default RFC)
3550 * @param string $urlmsg Interface message to use (default rfcurl)
3553 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3555 $valid = '0123456789';
3558 $a = split( $keyword, ' '.$text );
3559 if ( count ( $a ) < 2 ) {
3562 $text = substr( array_shift( $a ), 1);
3564 /* Check if keyword is preceed by [[.
3565 * This test is made here cause of the array_shift above
3566 * that prevent the test to be done in the foreach.
3568 if ( substr( $text, -2 ) == '[[' ) {
3572 foreach ( $a as $x ) {
3573 /* token might be empty if we have RFC RFC 1234 */
3579 # hack: don't replace inside thumbnail title/alt
3581 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3582 $text .= $keyword . $x;
3588 /** remove and save whitespaces in $blank */
3589 while ( $x{0} == ' ' ) {
3591 $x = substr( $x, 1 );
3594 /** remove and save the rfc number in $id */
3595 while ( strstr( $valid, $x{0} ) != false ) {
3597 $x = substr( $x, 1 );
3601 /* call back stripped spaces*/
3602 $text .= $keyword.$blank.$x;
3603 } elseif( $internal ) {
3605 $text .= $keyword.$id.$x;
3607 /* build the external link*/
3608 $url = wfMsg( $urlmsg, $id);
3609 $sk =& $this->mOptions
->getSkin();
3610 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3611 $text .= "<a href=\"{$url}\"{$la}>{$keyword}{$id}</a>{$x}";
3614 /* Check if the next RFC keyword is preceed by [[ */
3615 $internal = ( substr($x,-2) == '[[' );
3621 * Transform wiki markup when saving a page by doing \r\n -> \n
3622 * conversion, substitting signatures, {{subst:}} templates, etc.
3624 * @param string $text the text to transform
3625 * @param Title &$title the Title object for the current article
3626 * @param User &$user the User object describing the current user
3627 * @param ParserOptions $options parsing options
3628 * @param bool $clearState whether to clear the parser state first
3629 * @return string the altered wiki markup
3632 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3633 $this->mOptions
= $options;
3634 $this->mTitle
=& $title;
3635 $this->mOutputType
= OT_WIKI
;
3637 if ( $clearState ) {
3638 $this->clearState();
3641 $stripState = false;
3645 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3646 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3647 $text = $this->pstPass2( $text, $stripState, $user );
3648 $text = $this->unstrip( $text, $stripState );
3649 $text = $this->unstripNoWiki( $text, $stripState );
3654 * Pre-save transform helper function
3657 function pstPass2( $text, &$stripState, &$user ) {
3658 global $wgContLang, $wgLocaltimezone;
3660 /* Note: This is the timestamp saved as hardcoded wikitext to
3661 * the database, we use $wgContLang here in order to give
3662 * everyone the same signature and use the default one rather
3663 * than the one selected in each user's preferences.
3665 if ( isset( $wgLocaltimezone ) ) {
3666 $oldtz = getenv( 'TZ' );
3667 putenv( 'TZ='.$wgLocaltimezone );
3669 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3670 ' (' . date( 'T' ) . ')';
3671 if ( isset( $wgLocaltimezone ) ) {
3672 putenv( 'TZ='.$oldtz );
3675 # Variable replacement
3676 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3677 $text = $this->replaceVariables( $text );
3679 # Strip out <nowiki> etc. added via replaceVariables
3680 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3683 $sigText = $this->getUserSig( $user );
3684 $text = strtr( $text, array(
3686 '~~~~' => "$sigText $d",
3690 # Context links: [[|name]] and [[name (context)|]]
3692 global $wgLegalTitleChars;
3693 $tc = "[$wgLegalTitleChars]";
3694 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3696 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3697 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3699 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3700 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3701 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3702 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3704 $t = $this->mTitle
->getText();
3705 if ( preg_match( $conpat, $t, $m ) ) {
3708 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3709 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3710 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3712 if ( '' == $context ) {
3713 $text = preg_replace( $p2, '[[\\1]]', $text );
3715 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3718 # Trim trailing whitespace
3719 # MAG_END (__END__) tag allows for trailing
3720 # whitespace to be deliberately included
3721 $text = rtrim( $text );
3722 $mw =& MagicWord
::get( MAG_END
);
3723 $mw->matchAndRemove( $text );
3729 * Fetch the user's signature text, if any, and normalize to
3730 * validated, ready-to-insert wikitext.
3736 function getUserSig( &$user ) {
3737 $username = $user->getName();
3738 $nickname = $user->getOption( 'nickname' );
3739 $nickname = $nickname === '' ?
$username : $nickname;
3741 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3742 # Sig. might contain markup; validate this
3743 if( $this->validateSig( $nickname ) !== false ) {
3744 # Validated; clean up (if needed) and return it
3745 return $this->cleanSig( $nickname, true );
3747 # Failed to validate; fall back to the default
3748 $nickname = $username;
3749 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3753 // Make sure nickname doesnt get a sig in a sig
3754 $nickname = $this->cleanSigInSig( $nickname );
3756 # If we're still here, make it a link to the user page
3757 $userpage = $user->getUserPage();
3758 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3762 * Check that the user's signature contains no bad XML
3764 * @param string $text
3765 * @return mixed An expanded string, or false if invalid.
3767 function validateSig( $text ) {
3768 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3772 * Clean up signature text
3774 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3775 * 2) Substitute all transclusions
3777 * @param string $text
3778 * @param $parsing Whether we're cleaning (preferences save) or parsing
3779 * @return string Signature text
3781 function cleanSig( $text, $parsing = false ) {
3783 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3785 $substWord = MagicWord
::get( MAG_SUBST
);
3786 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3787 $substText = '{{' . $substWord->getSynonym( 0 );
3789 $text = preg_replace( $substRegex, $substText, $text );
3790 $text = $this->cleanSigInSig( $text );
3791 $text = $this->replaceVariables( $text );
3793 $this->clearState();
3798 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3799 * @param string $text
3800 * @return string Signature text with /~{3,5}/ removed
3802 function cleanSigInSig( $text ) {
3803 $text = preg_replace( '/~{3,5}/', '', $text );
3808 * Set up some variables which are usually set up in parse()
3809 * so that an external function can call some class members with confidence
3812 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3813 $this->mTitle
=& $title;
3814 $this->mOptions
= $options;
3815 $this->mOutputType
= $outputType;
3816 if ( $clearState ) {
3817 $this->clearState();
3822 * Transform a MediaWiki message by replacing magic variables.
3824 * @param string $text the text to transform
3825 * @param ParserOptions $options options
3826 * @return string the text with variables substituted
3829 function transformMsg( $text, $options ) {
3831 static $executing = false;
3833 $fname = "Parser::transformMsg";
3835 # Guard against infinite recursion
3841 wfProfileIn($fname);
3843 $this->mTitle
= $wgTitle;
3844 $this->mOptions
= $options;
3845 $this->mOutputType
= OT_MSG
;
3846 $this->clearState();
3847 $text = $this->replaceVariables( $text );
3850 wfProfileOut($fname);
3855 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3856 * The callback should have the following form:
3857 * function myParserHook( $text, $params, &$parser ) { ... }
3859 * Transform and return $text. Use $parser for any required context, e.g. use
3860 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3864 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3865 * @param mixed $callback The callback function (and object) to use for the tag
3867 * @return The old value of the mTagHooks array associated with the hook
3869 function setHook( $tag, $callback ) {
3870 $tag = strtolower( $tag );
3871 $oldVal = @$this->mTagHooks
[$tag];
3872 $this->mTagHooks
[$tag] = $callback;
3878 * Create a function, e.g. {{sum:1|2|3}}
3879 * The callback function should have the form:
3880 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3882 * The callback may either return the text result of the function, or an array with the text
3883 * in element 0, and a number of flags in the other elements. The names of the flags are
3884 * specified in the keys. Valid flags are:
3885 * found The text returned is valid, stop processing the template. This
3887 * nowiki Wiki markup in the return value should be escaped
3888 * noparse Unsafe HTML tags should not be stripped, etc.
3889 * noargs Don't replace triple-brace arguments in the return value
3890 * isHTML The returned text is HTML, armour it against wikitext transformation
3894 * @param mixed $id The magic word ID, or (deprecated) the function name. Function names are case-insensitive.
3895 * @param mixed $callback The callback function (and object) to use
3897 * @return The old callback function for this name, if any
3899 function setFunctionHook( $id, $callback ) {
3900 if( is_string( $id ) ) {
3901 $id = strtolower( $id );
3903 $oldVal = @$this->mFunctionHooks
[$id];
3904 $this->mFunctionHooks
[$id] = $callback;
3905 # Add to function cache
3906 if ( is_int( $id ) ) {
3907 $mw = MagicWord
::get( $id );
3908 $mw->addToArray( $this->mFunctionSynonyms
, $id );
3910 $this->mFunctionSynonyms
[$id] = $id;
3916 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3917 * Placeholders created in Skin::makeLinkObj()
3918 * Returns an array of links found, indexed by PDBK:
3922 * $options is a bit field, RLH_FOR_UPDATE to select for update
3924 function replaceLinkHolders( &$text, $options = 0 ) {
3926 global $wgOutputReplace;
3928 $fname = 'Parser::replaceLinkHolders';
3929 wfProfileIn( $fname );
3933 $sk =& $this->mOptions
->getSkin();
3934 $linkCache =& LinkCache
::singleton();
3936 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3937 wfProfileIn( $fname.'-check' );
3938 $dbr =& wfGetDB( DB_SLAVE
);
3939 $page = $dbr->tableName( 'page' );
3940 $threshold = $wgUser->getOption('stubthreshold');
3943 asort( $this->mLinkHolders
['namespaces'] );
3947 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3949 $title = $this->mLinkHolders
['titles'][$key];
3951 # Skip invalid entries.
3952 # Result will be ugly, but prevents crash.
3953 if ( is_null( $title ) ) {
3956 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3958 # Check if it's a static known link, e.g. interwiki
3959 if ( $title->isAlwaysKnown() ) {
3960 $colours[$pdbk] = 1;
3961 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3962 $colours[$pdbk] = 1;
3963 $this->mOutput
->addLink( $title, $id );
3964 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3965 $colours[$pdbk] = 0;
3967 # Not in the link cache, add it to the query
3968 if ( !isset( $current ) ) {
3970 $query = "SELECT page_id, page_namespace, page_title";
3971 if ( $threshold > 0 ) {
3972 $query .= ', page_len, page_is_redirect';
3974 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3975 } elseif ( $current != $ns ) {
3977 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3982 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3987 if ( $options & RLH_FOR_UPDATE
) {
3988 $query .= ' FOR UPDATE';
3991 $res = $dbr->query( $query, $fname );
3993 # Fetch data and form into an associative array
3994 # non-existent = broken
3997 while ( $s = $dbr->fetchObject($res) ) {
3998 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3999 $pdbk = $title->getPrefixedDBkey();
4000 $linkCache->addGoodLinkObj( $s->page_id
, $title );
4001 $this->mOutput
->addLink( $title, $s->page_id
);
4003 if ( $threshold > 0 ) {
4004 $size = $s->page_len
;
4005 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
4006 $colours[$pdbk] = 1;
4008 $colours[$pdbk] = 2;
4011 $colours[$pdbk] = 1;
4015 wfProfileOut( $fname.'-check' );
4017 # Construct search and replace arrays
4018 wfProfileIn( $fname.'-construct' );
4019 $wgOutputReplace = array();
4020 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
4021 $pdbk = $pdbks[$key];
4022 $searchkey = "<!--LINK $key-->";
4023 $title = $this->mLinkHolders
['titles'][$key];
4024 if ( empty( $colours[$pdbk] ) ) {
4025 $linkCache->addBadLinkObj( $title );
4026 $colours[$pdbk] = 0;
4027 $this->mOutput
->addLink( $title, 0 );
4028 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
4029 $this->mLinkHolders
['texts'][$key],
4030 $this->mLinkHolders
['queries'][$key] );
4031 } elseif ( $colours[$pdbk] == 1 ) {
4032 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4033 $this->mLinkHolders
['texts'][$key],
4034 $this->mLinkHolders
['queries'][$key] );
4035 } elseif ( $colours[$pdbk] == 2 ) {
4036 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4037 $this->mLinkHolders
['texts'][$key],
4038 $this->mLinkHolders
['queries'][$key] );
4041 wfProfileOut( $fname.'-construct' );
4044 wfProfileIn( $fname.'-replace' );
4046 $text = preg_replace_callback(
4047 '/(<!--LINK .*?-->)/',
4048 "wfOutputReplaceMatches",
4051 wfProfileOut( $fname.'-replace' );
4054 # Now process interwiki link holders
4055 # This is quite a bit simpler than internal links
4056 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
4057 wfProfileIn( $fname.'-interwiki' );
4058 # Make interwiki link HTML
4059 $wgOutputReplace = array();
4060 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
4061 $title = $this->mInterwikiLinkHolders
['titles'][$key];
4062 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4065 $text = preg_replace_callback(
4066 '/<!--IWLINK (.*?)-->/',
4067 "wfOutputReplaceMatches",
4069 wfProfileOut( $fname.'-interwiki' );
4072 wfProfileOut( $fname );
4077 * Replace <!--LINK--> link placeholders with plain text of links
4078 * (not HTML-formatted).
4079 * @param string $text
4082 function replaceLinkHoldersText( $text ) {
4083 $fname = 'Parser::replaceLinkHoldersText';
4084 wfProfileIn( $fname );
4086 $text = preg_replace_callback(
4087 '/<!--(LINK|IWLINK) (.*?)-->/',
4088 array( &$this, 'replaceLinkHoldersTextCallback' ),
4091 wfProfileOut( $fname );
4096 * @param array $matches
4100 function replaceLinkHoldersTextCallback( $matches ) {
4101 $type = $matches[1];
4103 if( $type == 'LINK' ) {
4104 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4105 return $this->mLinkHolders
['texts'][$key];
4107 } elseif( $type == 'IWLINK' ) {
4108 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4109 return $this->mInterwikiLinkHolders
['texts'][$key];
4116 * Tag hook handler for 'pre'.
4118 function renderPreTag( $text, $attribs, $parser ) {
4119 // Backwards-compatibility hack
4120 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4122 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4123 return wfOpenElement( 'pre', $attribs ) .
4124 wfEscapeHTMLTagsOnly( $content ) .
4129 * Renders an image gallery from a text with one line per image.
4130 * text labels may be given by using |-style alternative text. E.g.
4131 * Image:one.jpg|The number "1"
4132 * Image:tree.jpg|A tree
4133 * given as text will return the HTML of a gallery with two images,
4134 * labeled 'The number "1"' and
4137 function renderImageGallery( $text, $params ) {
4138 $ig = new ImageGallery();
4139 $ig->setShowBytes( false );
4140 $ig->setShowFilename( false );
4142 $ig->useSkin( $this->mOptions
->getSkin() );
4144 if( isset( $params['caption'] ) )
4145 $ig->setCaption( $params['caption'] );
4147 $lines = explode( "\n", $text );
4148 foreach ( $lines as $line ) {
4149 # match lines like these:
4150 # Image:someimage.jpg|This is some image
4151 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4153 if ( count( $matches ) == 0 ) {
4156 $nt =& Title
::newFromText( $matches[1] );
4157 if( is_null( $nt ) ) {
4158 # Bogus title. Ignore these so we don't bomb out later.
4161 if ( isset( $matches[3] ) ) {
4162 $label = $matches[3];
4167 $pout = $this->parse( $label,
4170 false, // Strip whitespace...?
4171 false // Don't clear state!
4173 $html = $pout->getText();
4175 $ig->add( new Image( $nt ), $html );
4177 # Only add real images (bug #5586)
4178 if ( $nt->getNamespace() == NS_IMAGE
) {
4179 $this->mOutput
->addImage( $nt->getDBkey() );
4182 return $ig->toHTML();
4186 * Parse image options text and use it to make an image
4188 function makeImage( &$nt, $options ) {
4189 global $wgUseImageResize;
4193 # Check if the options text is of the form "options|alt text"
4195 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4196 # * left no resizing, just left align. label is used for alt= only
4197 # * right same, but right aligned
4198 # * none same, but not aligned
4199 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4200 # * center center the image
4201 # * framed Keep original image size, no magnify-button.
4203 $part = explode( '|', $options);
4205 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4206 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4207 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4208 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4209 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4210 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4211 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4212 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4215 $width = $height = $framed = $thumb = false;
4216 $manual_thumb = '' ;
4218 foreach( $part as $key => $val ) {
4219 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4221 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4222 # use manually specified thumbnail
4224 $manual_thumb = $match;
4225 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4226 # remember to set an alignment, don't render immediately
4228 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4229 # remember to set an alignment, don't render immediately
4231 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4232 # remember to set an alignment, don't render immediately
4234 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4235 # remember to set an alignment, don't render immediately
4237 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4238 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4239 # $match is the image width in pixels
4240 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4241 $width = intval( $m[1] );
4242 $height = intval( $m[2] );
4244 $width = intval($match);
4246 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4252 # Strip bad stuff out of the alt text
4253 $alt = $this->replaceLinkHoldersText( $caption );
4255 # make sure there are no placeholders in thumbnail attributes
4256 # that are later expanded to html- so expand them now and
4258 $alt = $this->unstrip($alt, $this->mStripState
);
4259 $alt = Sanitizer
::stripAllTags( $alt );
4261 # Linker does the rest
4262 $sk =& $this->mOptions
->getSkin();
4263 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4267 * Set a flag in the output object indicating that the content is dynamic and
4268 * shouldn't be cached.
4270 function disableCache() {
4271 wfDebug( "Parser output marked as uncacheable.\n" );
4272 $this->mOutput
->mCacheTime
= -1;
4276 * Callback from the Sanitizer for expanding items found in HTML attribute
4277 * values, so they can be safely tested and escaped.
4278 * @param string $text
4279 * @param array $args
4283 function attributeStripCallback( &$text, $args ) {
4284 $text = $this->replaceVariables( $text, $args );
4285 $text = $this->unstripForHTML( $text );
4289 function unstripForHTML( $text ) {
4290 $text = $this->unstrip( $text, $this->mStripState
);
4291 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4299 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4300 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4301 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4307 function getTags() { return array_keys( $this->mTagHooks
); }
4312 * Break wikitext input into sections, and either pull or replace
4313 * some particular section's text.
4315 * External callers should use the getSection and replaceSection methods.
4317 * @param $text Page wikitext
4318 * @param $section Numbered section. 0 pulls the text before the first
4319 * heading; other numbers will pull the given section
4320 * along with its lower-level subsections.
4321 * @param $mode One of "get" or "replace"
4322 * @param $newtext Replacement text for section data.
4323 * @return string for "get", the extracted section text.
4324 * for "replace", the whole page with the section replaced.
4326 private function extractSections( $text, $section, $mode, $newtext='' ) {
4327 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4328 # comments to be stripped as well)
4329 $striparray = array();
4331 $oldOutputType = $this->mOutputType
;
4332 $oldOptions = $this->mOptions
;
4333 $this->mOptions
= new ParserOptions();
4334 $this->mOutputType
= OT_WIKI
;
4336 $striptext = $this->strip( $text, $striparray, true );
4338 $this->mOutputType
= $oldOutputType;
4339 $this->mOptions
= $oldOptions;
4341 # now that we can be sure that no pseudo-sections are in the source,
4342 # split it up by section
4343 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4344 $comment = "(?:$uniq-!--.*?QINU)";
4349 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4351 (=+) # Should this be limited to 6?
4352 .+? # Section title...
4353 \\2 # Ending = count must match start
4360 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4367 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4368 (=+) # Should this be limited to 6?
4369 .+? # Section title...
4370 \\2 # Ending = count must match start
4371 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4380 PREG_SPLIT_DELIM_CAPTURE
);
4382 if( $mode == "get" ) {
4383 if( $section == 0 ) {
4384 // "Section 0" returns the content before any other section.
4389 } elseif( $mode == "replace" ) {
4390 if( $section == 0 ) {
4391 $rv = $newtext . "\n\n";
4400 for( $index = 1; $index < count( $secs ); ) {
4401 $headerLine = $secs[$index++
];
4402 if( $secs[$index] ) {
4404 $headerLevel = strlen( $secs[$index++
] );
4408 $headerLevel = intval( $secs[$index++
] );
4410 $content = $secs[$index++
];
4413 if( $mode == "get" ) {
4414 if( $count == $section ) {
4415 $rv = $headerLine . $content;
4416 $sectionLevel = $headerLevel;
4417 } elseif( $count > $section ) {
4418 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4419 $rv .= $headerLine . $content;
4421 // Broke out to a higher-level section
4425 } elseif( $mode == "replace" ) {
4426 if( $count < $section ) {
4427 $rv .= $headerLine . $content;
4428 } elseif( $count == $section ) {
4429 $rv .= $newtext . "\n\n";
4430 $sectionLevel = $headerLevel;
4431 } elseif( $count > $section ) {
4432 if( $headerLevel <= $sectionLevel ) {
4433 // Passed the section's sub-parts.
4437 $rv .= $headerLine . $content;
4442 # reinsert stripped tags
4443 $rv = $this->unstrip( $rv, $striparray );
4444 $rv = $this->unstripNoWiki( $rv, $striparray );
4450 * This function returns the text of a section, specified by a number ($section).
4451 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4452 * the first section before any such heading (section 0).
4454 * If a section contains subsections, these are also returned.
4456 * @param $text String: text to look in
4457 * @param $section Integer: section number
4458 * @return string text of the requested section
4460 function getSection( $text, $section ) {
4461 return $this->extractSections( $text, $section, "get" );
4464 function replaceSection( $oldtext, $section, $text ) {
4465 return $this->extractSections( $oldtext, $section, "replace", $text );
4472 * @package MediaWiki
4476 var $mText, # The output text
4477 $mLanguageLinks, # List of the full text of language links, in the order they appear
4478 $mCategories, # Map of category names to sort keys
4479 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4480 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4481 $mVersion, # Compatibility check
4482 $mTitleText, # title text of the chosen language variant
4483 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4484 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4485 $mImages, # DB keys of the images used, in the array key only
4486 $mExternalLinks, # External link URLs, in the key only
4487 $mHTMLtitle, # Display HTML title
4488 $mSubtitle, # Additional subtitle
4489 $mNewSection, # Show a new section link?
4490 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4492 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4493 $containsOldMagic = false, $titletext = '' )
4495 $this->mText
= $text;
4496 $this->mLanguageLinks
= $languageLinks;
4497 $this->mCategories
= $categoryLinks;
4498 $this->mContainsOldMagic
= $containsOldMagic;
4499 $this->mCacheTime
= '';
4500 $this->mVersion
= MW_PARSER_VERSION
;
4501 $this->mTitleText
= $titletext;
4502 $this->mLinks
= array();
4503 $this->mTemplates
= array();
4504 $this->mImages
= array();
4505 $this->mExternalLinks
= array();
4506 $this->mHTMLtitle
= "" ;
4507 $this->mSubtitle
= "" ;
4508 $this->mNewSection
= false;
4509 $this->mNoGallery
= false;
4512 function getText() { return $this->mText
; }
4513 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4514 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4515 function &getCategories() { return $this->mCategories
; }
4516 function getCacheTime() { return $this->mCacheTime
; }
4517 function getTitleText() { return $this->mTitleText
; }
4518 function &getLinks() { return $this->mLinks
; }
4519 function &getTemplates() { return $this->mTemplates
; }
4520 function &getImages() { return $this->mImages
; }
4521 function &getExternalLinks() { return $this->mExternalLinks
; }
4522 function getNoGallery() { return $this->mNoGallery
; }
4524 function containsOldMagic() { return $this->mContainsOldMagic
; }
4525 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4526 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4527 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4528 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4529 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4530 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4532 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4533 function addImage( $name ) { $this->mImages
[$name] = 1; }
4534 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4535 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4537 function setNewSection( $value ) {
4538 $this->mNewSection
= (bool)$value;
4540 function getNewSection() {
4541 return (bool)$this->mNewSection
;
4544 function addLink( $title, $id ) {
4545 $ns = $title->getNamespace();
4546 $dbk = $title->getDBkey();
4547 if ( !isset( $this->mLinks
[$ns] ) ) {
4548 $this->mLinks
[$ns] = array();
4550 $this->mLinks
[$ns][$dbk] = $id;
4553 function addTemplate( $title, $id ) {
4554 $ns = $title->getNamespace();
4555 $dbk = $title->getDBkey();
4556 if ( !isset( $this->mTemplates
[$ns] ) ) {
4557 $this->mTemplates
[$ns] = array();
4559 $this->mTemplates
[$ns][$dbk] = $id;
4563 * Return true if this cached output object predates the global or
4564 * per-article cache invalidation timestamps, or if it comes from
4565 * an incompatible older version.
4567 * @param string $touched the affected article's last touched timestamp
4571 function expired( $touched ) {
4572 global $wgCacheEpoch;
4573 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4574 $this->getCacheTime() < $touched ||
4575 $this->getCacheTime() <= $wgCacheEpoch ||
4576 !isset( $this->mVersion
) ||
4577 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4582 * Set options of the Parser
4584 * @package MediaWiki
4588 # All variables are private
4589 var $mUseTeX; # Use texvc to expand <math> tags
4590 var $mUseDynamicDates; # Use DateFormatter to format dates
4591 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4592 var $mAllowExternalImages; # Allow external images inline
4593 var $mAllowExternalImagesFrom; # If not, any exception?
4594 var $mSkin; # Reference to the preferred skin
4595 var $mDateFormat; # Date format index
4596 var $mEditSection; # Create "edit section" links
4597 var $mNumberHeadings; # Automatically number headings
4598 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4599 var $mTidy; # Ask for tidy cleanup
4600 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4602 var $mUser; # Stored user object, just used to initialise the skin
4604 function getUseTeX() { return $this->mUseTeX
; }
4605 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4606 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4607 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4608 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4609 function getDateFormat() { return $this->mDateFormat
; }
4610 function getEditSection() { return $this->mEditSection
; }
4611 function getNumberHeadings() { return $this->mNumberHeadings
; }
4612 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4613 function getTidy() { return $this->mTidy
; }
4614 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4616 function &getSkin() {
4617 if ( !isset( $this->mSkin
) ) {
4618 $this->mSkin
= $this->mUser
->getSkin();
4620 return $this->mSkin
;
4623 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4624 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4625 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4626 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4627 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4628 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4629 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4630 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4631 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4632 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4633 function setSkin( &$x ) { $this->mSkin
=& $x; }
4634 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4636 function ParserOptions( $user = null ) {
4637 $this->initialiseFromUser( $user );
4641 * Get parser options
4644 function newFromUser( &$user ) {
4645 return new ParserOptions( $user );
4648 /** Get user options */
4649 function initialiseFromUser( &$userInput ) {
4650 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4651 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4652 $fname = 'ParserOptions::initialiseFromUser';
4653 wfProfileIn( $fname );
4654 if ( !$userInput ) {
4656 if ( isset( $wgUser ) ) {
4660 $user->setLoaded( true );
4663 $user =& $userInput;
4666 $this->mUser
= $user;
4668 $this->mUseTeX
= $wgUseTeX;
4669 $this->mUseDynamicDates
= $wgUseDynamicDates;
4670 $this->mInterwikiMagic
= $wgInterwikiMagic;
4671 $this->mAllowExternalImages
= $wgAllowExternalImages;
4672 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4673 $this->mSkin
= null; # Deferred
4674 $this->mDateFormat
= $user->getOption( 'date' );
4675 $this->mEditSection
= true;
4676 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4677 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4678 $this->mTidy
= false;
4679 $this->mInterfaceMessage
= false;
4680 wfProfileOut( $fname );
4685 * Callback function used by Parser::replaceLinkHolders()
4686 * to substitute link placeholders.
4688 function &wfOutputReplaceMatches( $matches ) {
4689 global $wgOutputReplace;
4690 return $wgOutputReplace[$matches[1]];
4694 * Return the total number of articles
4696 function wfNumberOfArticles() {
4697 global $wgNumberOfArticles;
4700 return $wgNumberOfArticles;
4704 * Return the number of files
4706 function wfNumberOfFiles() {
4707 $fname = 'wfNumberOfFiles';
4709 wfProfileIn( $fname );
4710 $dbr =& wfGetDB( DB_SLAVE
);
4711 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4712 wfProfileOut( $fname );
4718 * Return the number of user accounts
4721 function wfNumberOfUsers() {
4722 wfProfileIn( 'wfNumberOfUsers' );
4723 $dbr =& wfGetDB( DB_SLAVE
);
4724 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4725 wfProfileOut( 'wfNumberOfUsers' );
4730 * Return the total number of pages
4733 function wfNumberOfPages() {
4734 wfProfileIn( 'wfNumberOfPages' );
4735 $dbr =& wfGetDB( DB_SLAVE
);
4736 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4737 wfProfileOut( 'wfNumberOfPages' );
4742 * Return the total number of admins
4746 function wfNumberOfAdmins() {
4747 static $admins = -1;
4748 wfProfileIn( 'wfNumberOfAdmins' );
4749 if( $admins == -1 ) {
4750 $dbr =& wfGetDB( DB_SLAVE
);
4751 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4753 wfProfileOut( 'wfNumberOfAdmins' );
4754 return (int)$admins;
4758 * Count the number of pages in a particular namespace
4760 * @param $ns Namespace
4763 function wfPagesInNs( $ns ) {
4764 static $pageCount = array();
4765 wfProfileIn( 'wfPagesInNs' );
4766 if( !isset( $pageCount[$ns] ) ) {
4767 $dbr =& wfGetDB( DB_SLAVE
);
4768 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4770 wfProfileOut( 'wfPagesInNs' );
4771 return (int)$pageCount[$ns];
4775 * Get various statistics from the database
4778 function wfLoadSiteStats() {
4779 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4780 $fname = 'wfLoadSiteStats';
4782 if ( -1 != $wgNumberOfArticles ) return;
4783 $dbr =& wfGetDB( DB_SLAVE
);
4784 $s = $dbr->selectRow( 'site_stats',
4785 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4786 array( 'ss_row_id' => 1 ), $fname
4789 if ( $s === false ) {
4792 $wgTotalViews = $s->ss_total_views
;
4793 $wgTotalEdits = $s->ss_total_edits
;
4794 $wgNumberOfArticles = $s->ss_good_articles
;
4800 * Basically replacing " > and < with HTML entities ( ", >, <)
4802 * @param $in String: text that might contain HTML tags.
4803 * @return string Escaped string
4805 function wfEscapeHTMLTagsOnly( $in ) {
4807 array( '"', '>', '<' ),
4808 array( '"', '>', '<' ),