3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.1' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
61 // State constants for the definition list colon extraction
62 define( 'MW_COLON_STATE_TEXT', 0 );
63 define( 'MW_COLON_STATE_TAG', 1 );
64 define( 'MW_COLON_STATE_TAGSTART', 2 );
65 define( 'MW_COLON_STATE_CLOSETAG', 3 );
66 define( 'MW_COLON_STATE_TAGSLASH', 4 );
67 define( 'MW_COLON_STATE_COMMENT', 5 );
68 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
69 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
74 * Processes wiki markup
77 * There are three main entry points into the Parser class:
79 * produces HTML output
81 * produces altered wiki markup.
83 * performs brace substitution on MediaWiki messages
86 * objects: $wgLang, $wgContLang
88 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
91 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
92 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
93 * $wgLocaltimezone, $wgAllowSpecialInclusion*
95 * * only within ParserOptions
106 var $mTagHooks, $mFunctionHooks;
108 # Cleared with clearState():
109 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
110 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
111 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
112 var $mTemplates, // cache of already loaded templates, avoids
113 // multiple SQL queries for the same string
114 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
115 // in this path. Used for loop detection.
118 # These are variables reset at least once per parse regardless of $clearState
119 var $mOptions, // ParserOptions object
120 $mTitle, // Title context, used for self-link rendering and similar things
121 $mOutputType, // Output type, one of the OT_xxx constants
122 $mRevisionId; // ID to display in {{REVISIONID}} tags
132 $this->mTagHooks
= array();
133 $this->mFunctionHooks
= array();
135 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
143 function clearState() {
144 $this->mOutput
= new ParserOutput
;
145 $this->mAutonumber
= 0;
146 $this->mLastSection
= '';
147 $this->mDTopen
= false;
148 $this->mVariables
= false;
149 $this->mIncludeCount
= array();
150 $this->mStripState
= array();
151 $this->mArgStack
= array();
152 $this->mInPre
= false;
153 $this->mInterwikiLinkHolders
= array(
157 $this->mLinkHolders
= array(
158 'namespaces' => array(),
160 'queries' => array(),
164 $this->mRevisionId
= null;
167 * Prefix for temporary replacement strings for the multipass parser.
168 * \x07 should never appear in input as it's disallowed in XML.
169 * Using it at the front also gives us a little extra robustness
170 * since it shouldn't match when butted up against identifier-like
173 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
175 # Clear these on every parse, bug 4549
176 $this->mTemplates
= array();
177 $this->mTemplatePath
= array();
179 $this->mShowToc
= true;
180 $this->mForceTocPosition
= false;
182 wfRunHooks( 'ParserClearState', array( &$this ) );
186 * Accessor for mUniqPrefix.
190 function UniqPrefix() {
191 return $this->mUniqPrefix
;
195 * Convert wikitext to HTML
196 * Do not call this function recursively.
199 * @param string $text Text we want to parse
200 * @param Title &$title A title object
201 * @param array $options
202 * @param boolean $linestart
203 * @param boolean $clearState
204 * @param int $revid number to pass in {{REVISIONID}}
205 * @return ParserOutput a ParserOutput
207 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
209 * First pass--just handle <nowiki> sections, pass the rest off
210 * to internalParse() which does all the real work.
213 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
214 $fname = 'Parser::parse';
215 wfProfileIn( $fname );
221 $this->mOptions
= $options;
222 $this->mTitle
=& $title;
223 $this->mRevisionId
= $revid;
224 $this->mOutputType
= OT_HTML
;
226 //$text = $this->strip( $text, $this->mStripState );
227 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
228 $x =& $this->mStripState
;
230 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
231 $text = $this->strip( $text, $x );
232 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
234 # Hook to suspend the parser in this state
235 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
236 wfProfileOut( $fname );
240 $text = $this->internalParse( $text );
242 $text = $this->unstrip( $text, $this->mStripState
);
244 # Clean up special characters, only run once, next-to-last before doBlockLevels
246 # french spaces, last one Guillemet-left
247 # only if there is something before the space
248 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
249 # french spaces, Guillemet-right
250 '/(\\302\\253) /' => '\\1 ',
252 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
255 $text = $this->doBlockLevels( $text, $linestart );
257 $this->replaceLinkHolders( $text );
259 # the position of the parserConvert() call should not be changed. it
260 # assumes that the links are all replaced and the only thing left
261 # is the <nowiki> mark.
262 # Side-effects: this calls $this->mOutput->setTitleText()
263 $text = $wgContLang->parserConvert( $text, $this );
265 $text = $this->unstripNoWiki( $text, $this->mStripState
);
267 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
269 $text = Sanitizer
::normalizeCharReferences( $text );
271 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
272 $text = Parser
::tidy($text);
274 # attempt to sanitize at least some nesting problems
275 # (bug #2702 and quite a few others)
277 # ''Something [http://www.cool.com cool''] -->
278 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
279 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
280 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
281 # fix up an anchor inside another anchor, only
282 # at least for a single single nested link (bug 3695)
283 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
284 '\\1\\2</a>\\3</a>\\1\\4</a>',
285 # fix div inside inline elements- doBlockLevels won't wrap a line which
286 # contains a div, so fix it up here; replace
287 # div with escaped text
288 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
289 '\\1\\3<div\\5>\\6</div>\\8\\9',
290 # remove empty italic or bold tag pairs, some
291 # introduced by rules above
292 '/<([bi])><\/\\1>/' => ''
295 $text = preg_replace(
296 array_keys( $tidyregs ),
297 array_values( $tidyregs ),
301 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
303 $this->mOutput
->setText( $text );
304 wfProfileOut( $fname );
306 return $this->mOutput
;
310 * Get a random string
315 function getRandomString() {
316 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
319 function &getTitle() { return $this->mTitle
; }
320 function getOptions() { return $this->mOptions
; }
323 * Replaces all occurrences of HTML-style comments and the given tags
324 * in the text with a random marker and returns teh next text. The output
325 * parameter $matches will be an associative array filled with data in
327 * 'UNIQ-xxxxx' => array(
330 * array( 'param' => 'x' ),
331 * '<element param="x">tag content</element>' ) )
333 * @param $elements list of element names. Comments are always extracted.
334 * @param $text Source text string.
335 * @param $uniq_prefix
340 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
341 $rand = Parser
::getRandomString();
346 $taglist = implode( '|', $elements );
347 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
349 while ( '' != $text ) {
350 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
352 if( count( $p ) < 5 ) {
355 if( count( $p ) > 5 ) {
369 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
) . '-QINU';
370 $stripped .= $marker;
372 if ( $close === '/>' ) {
373 // Empty element tag, <tag />
378 if( $element == '!--' ) {
381 $end = "/(<\\/$element\\s*>)/i";
383 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
385 if( count( $q ) < 3 ) {
386 # No end tag -- let it run out to the end of the text.
395 $matches[$marker] = array( $element,
397 Sanitizer
::decodeTagAttributes( $attributes ),
398 "<$element$attributes$close$content$tail" );
404 * Strips and renders nowiki, pre, math, hiero
405 * If $render is set, performs necessary rendering operations on plugins
406 * Returns the text, and fills an array with data needed in unstrip()
407 * If the $state is already a valid strip state, it adds to the state
409 * @param bool $stripcomments when set, HTML comments <!-- like this -->
410 * will be stripped in addition to other tags. This is important
411 * for section editing, where these comments cause confusion when
412 * counting the sections in the wikisource
416 function strip( $text, &$state, $stripcomments = false ) {
417 $render = ($this->mOutputType
== OT_HTML
);
419 # Replace any instances of the placeholders
420 $uniq_prefix = $this->mUniqPrefix
;
421 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
422 $commentState = array();
424 $elements = array_merge(
425 array( 'nowiki', 'gallery' ),
426 array_keys( $this->mTagHooks
) );
429 $elements[] = 'html';
431 if( $this->mOptions
->getUseTeX() ) {
432 $elements[] = 'math';
437 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
439 foreach( $matches as $marker => $data ) {
440 list( $element, $content, $params, $tag ) = $data;
442 $tagName = strtolower( $element );
446 if( substr( $tag, -3 ) == '-->' ) {
449 // Unclosed comment in input.
450 // Close it so later stripping can remove it
459 // Shouldn't happen otherwise. :)
461 $output = wfEscapeHTMLTagsOnly( $content );
464 $output = MathRenderer
::renderMath( $content );
467 $output = $this->renderImageGallery( $content );
470 if( isset( $this->mTagHooks
[$tagName] ) ) {
471 $output = call_user_func_array( $this->mTagHooks
[$tagName],
472 array( $content, $params, $this ) );
474 wfDebugDieBacktrace( "Invalid call hook $element" );
478 // Just stripping tags; keep the source
481 if( !$stripcomments && $element == '!--' ) {
482 $commentState[$marker] = $output;
484 $state[$element][$marker] = $output;
488 # Unstrip comments unless explicitly told otherwise.
489 # (The comments are always stripped prior to this point, so as to
490 # not invoke any extension tags / parser hooks contained within
492 if ( !$stripcomments ) {
493 // Put them all back and forget them
494 $text = strtr( $text, $commentState );
501 * Restores pre, math, and other extensions removed by strip()
503 * always call unstripNoWiki() after this one
506 function unstrip( $text, &$state ) {
507 if ( !is_array( $state ) ) {
511 $replacements = array();
512 foreach( $state as $tag => $contentDict ) {
513 if( $tag != 'nowiki' && $tag != 'html' ) {
514 foreach( $contentDict as $uniq => $content ) {
515 $replacements[$uniq] = $content;
519 $text = strtr( $text, $replacements );
525 * Always call this after unstrip() to preserve the order
529 function unstripNoWiki( $text, &$state ) {
530 if ( !is_array( $state ) ) {
534 $replacements = array();
535 foreach( $state as $tag => $contentDict ) {
536 if( $tag == 'nowiki' ||
$tag == 'html' ) {
537 foreach( $contentDict as $uniq => $content ) {
538 $replacements[$uniq] = $content;
542 $text = strtr( $text, $replacements );
548 * Add an item to the strip state
549 * Returns the unique tag which must be inserted into the stripped text
550 * The tag will be replaced with the original text in unstrip()
554 function insertStripItem( $text, &$state ) {
555 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
559 $state['item'][$rnd] = $text;
564 * Interface with html tidy, used if $wgUseTidy = true.
565 * If tidy isn't able to correct the markup, the original will be
566 * returned in all its glory with a warning comment appended.
568 * Either the external tidy program or the in-process tidy extension
569 * will be used depending on availability. Override the default
570 * $wgTidyInternal setting to disable the internal if it's not working.
572 * @param string $text Hideous HTML input
573 * @return string Corrected HTML output
577 function tidy( $text ) {
578 global $wgTidyInternal;
579 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
580 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
581 '<head><title>test</title></head><body>'.$text.'</body></html>';
582 if( $wgTidyInternal ) {
583 $correctedtext = Parser
::internalTidy( $wrappedtext );
585 $correctedtext = Parser
::externalTidy( $wrappedtext );
587 if( is_null( $correctedtext ) ) {
588 wfDebug( "Tidy error detected!\n" );
589 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
591 return $correctedtext;
595 * Spawn an external HTML tidy process and get corrected markup back from it.
600 function externalTidy( $text ) {
601 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
602 $fname = 'Parser::externalTidy';
603 wfProfileIn( $fname );
608 $descriptorspec = array(
609 0 => array('pipe', 'r'),
610 1 => array('pipe', 'w'),
611 2 => array('file', '/dev/null', 'a')
614 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
615 if (is_resource($process)) {
616 // Theoretically, this style of communication could cause a deadlock
617 // here. If the stdout buffer fills up, then writes to stdin could
618 // block. This doesn't appear to happen with tidy, because tidy only
619 // writes to stdout after it's finished reading from stdin. Search
620 // for tidyParseStdin and tidySaveStdout in console/tidy.c
621 fwrite($pipes[0], $text);
623 while (!feof($pipes[1])) {
624 $cleansource .= fgets($pipes[1], 1024);
627 proc_close($process);
630 wfProfileOut( $fname );
632 if( $cleansource == '' && $text != '') {
633 // Some kind of error happened, so we couldn't get the corrected text.
634 // Just give up; we'll use the source text and append a warning.
642 * Use the HTML tidy PECL extension to use the tidy library in-process,
643 * saving the overhead of spawning a new process. Currently written to
644 * the PHP 4.3.x version of the extension, may not work on PHP 5.
646 * 'pear install tidy' should be able to compile the extension module.
651 function internalTidy( $text ) {
653 $fname = 'Parser::internalTidy';
654 wfProfileIn( $fname );
656 tidy_load_config( $wgTidyConf );
657 tidy_set_encoding( 'utf8' );
658 tidy_parse_string( $text );
660 if( tidy_get_status() == 2 ) {
661 // 2 is magic number for fatal error
662 // http://www.php.net/manual/en/function.tidy-get-status.php
665 $cleansource = tidy_get_output();
667 wfProfileOut( $fname );
672 * parse the wiki syntax used to render tables
676 function doTableStuff ( $t ) {
677 $fname = 'Parser::doTableStuff';
678 wfProfileIn( $fname );
680 $t = explode ( "\n" , $t ) ;
681 $td = array () ; # Is currently a td tag open?
682 $ltd = array () ; # Was it TD or TH?
683 $tr = array () ; # Is currently a tr tag open?
684 $ltr = array () ; # tr attributes
685 $has_opened_tr = array(); # Did this table open a <tr> element?
686 $indent_level = 0; # indent level of the table
687 foreach ( $t AS $k => $x )
690 $fc = substr ( $x , 0 , 1 ) ;
691 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
692 $indent_level = strlen( $matches[1] );
694 $attributes = $this->unstripForHTML( $matches[2] );
696 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
697 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
698 array_push ( $td , false ) ;
699 array_push ( $ltd , '' ) ;
700 array_push ( $tr , false ) ;
701 array_push ( $ltr , '' ) ;
702 array_push ( $has_opened_tr, false );
704 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
705 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
706 $z = "</table>" . substr ( $x , 2);
707 $l = array_pop ( $ltd ) ;
708 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
709 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
710 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
712 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
714 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
715 $x = substr ( $x , 1 ) ;
716 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
718 $l = array_pop ( $ltd ) ;
719 array_pop ( $has_opened_tr );
720 array_push ( $has_opened_tr , true ) ;
721 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
722 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
725 array_push ( $tr , false ) ;
726 array_push ( $td , false ) ;
727 array_push ( $ltd , '' ) ;
728 $attributes = $this->unstripForHTML( $x );
729 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
731 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
733 if ( '|+' == substr ( $x , 0 , 2 ) ) {
735 $x = substr ( $x , 1 ) ;
737 $after = substr ( $x , 1 ) ;
738 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
740 // Split up multiple cells on the same line.
741 // FIXME: This can result in improper nesting of tags processed
742 // by earlier parser steps, but should avoid splitting up eg
743 // attribute values containing literal "||".
744 $after = wfExplodeMarkup( '||', $after );
748 # Loop through each table cell
749 foreach ( $after AS $theline )
754 $tra = array_pop ( $ltr ) ;
755 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
756 array_push ( $tr , true ) ;
757 array_push ( $ltr , '' ) ;
758 array_pop ( $has_opened_tr );
759 array_push ( $has_opened_tr , true ) ;
762 $l = array_pop ( $ltd ) ;
763 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
764 if ( $fc == '|' ) $l = 'td' ;
765 else if ( $fc == '!' ) $l = 'th' ;
766 else if ( $fc == '+' ) $l = 'caption' ;
768 array_push ( $ltd , $l ) ;
771 $y = explode ( '|' , $theline , 2 ) ;
772 # Note that a '|' inside an invalid link should not
773 # be mistaken as delimiting cell parameters
774 if ( strpos( $y[0], '[[' ) !== false ) {
775 $y = array ($theline);
777 if ( count ( $y ) == 1 )
778 $y = "{$z}<{$l}>{$y[0]}" ;
780 $attributes = $this->unstripForHTML( $y[0] );
781 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
784 array_push ( $td , true ) ;
789 # Closing open td, tr && table
790 while ( count ( $td ) > 0 )
792 $l = array_pop ( $ltd ) ;
793 if ( array_pop ( $td ) ) $t[] = '</td>' ;
794 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
795 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
799 $t = implode ( "\n" , $t ) ;
800 # special case: don't return empty table
801 if($t == "<table>\n<tr><td></td></tr>\n</table>")
803 wfProfileOut( $fname );
808 * Helper function for parse() that transforms wiki markup into
809 * HTML. Only called for $mOutputType == OT_HTML.
813 function internalParse( $text ) {
816 $fname = 'Parser::internalParse';
817 wfProfileIn( $fname );
819 # Remove <noinclude> tags and <includeonly> sections
820 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
821 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
822 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
824 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
826 $text = $this->replaceVariables( $text, $args );
828 // Tables need to come after variable replacement for things to work
829 // properly; putting them before other transformations should keep
830 // exciting things like link expansions from showing up in surprising
832 $text = $this->doTableStuff( $text );
834 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
836 $text = $this->stripToc( $text );
837 $text = $this->doHeadings( $text );
838 if($this->mOptions
->getUseDynamicDates()) {
839 $df =& DateFormatter
::getInstance();
840 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
842 $text = $this->doAllQuotes( $text );
843 $text = $this->replaceInternalLinks( $text );
844 $text = $this->replaceExternalLinks( $text );
846 # replaceInternalLinks may sometimes leave behind
847 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
848 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
850 $text = $this->doMagicLinks( $text );
851 $text = $this->formatHeadings( $text, $isMain );
853 wfProfileOut( $fname );
858 * Replace special strings like "ISBN xxx" and "RFC xxx" with
859 * magic external links.
863 function &doMagicLinks( &$text ) {
864 $text = $this->magicISBN( $text );
865 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
866 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
871 * Parse headers and return html
875 function doHeadings( $text ) {
876 $fname = 'Parser::doHeadings';
877 wfProfileIn( $fname );
878 for ( $i = 6; $i >= 1; --$i ) {
879 $h = str_repeat( '=', $i );
880 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
881 "<h{$i}>\\1</h{$i}>\\2", $text );
883 wfProfileOut( $fname );
888 * Replace single quotes with HTML markup
890 * @return string the altered text
892 function doAllQuotes( $text ) {
893 $fname = 'Parser::doAllQuotes';
894 wfProfileIn( $fname );
896 $lines = explode( "\n", $text );
897 foreach ( $lines as $line ) {
898 $outtext .= $this->doQuotes ( $line ) . "\n";
900 $outtext = substr($outtext, 0,-1);
901 wfProfileOut( $fname );
906 * Helper function for doAllQuotes()
909 function doQuotes( $text ) {
910 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
911 if ( count( $arr ) == 1 )
915 # First, do some preliminary work. This may shift some apostrophes from
916 # being mark-up to being text. It also counts the number of occurrences
917 # of bold and italics mark-ups.
921 foreach ( $arr as $r )
923 if ( ( $i %
2 ) == 1 )
925 # If there are ever four apostrophes, assume the first is supposed to
926 # be text, and the remaining three constitute mark-up for bold text.
927 if ( strlen( $arr[$i] ) == 4 )
932 # If there are more than 5 apostrophes in a row, assume they're all
933 # text except for the last 5.
934 else if ( strlen( $arr[$i] ) > 5 )
936 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
939 # Count the number of occurrences of bold and italics mark-ups.
940 # We are not counting sequences of five apostrophes.
941 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
942 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
943 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
948 # If there is an odd number of both bold and italics, it is likely
949 # that one of the bold ones was meant to be an apostrophe followed
950 # by italics. Which one we cannot know for certain, but it is more
951 # likely to be one that has a single-letter word before it.
952 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
955 $firstsingleletterword = -1;
956 $firstmultiletterword = -1;
958 foreach ( $arr as $r )
960 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
962 $x1 = substr ($arr[$i-1], -1);
963 $x2 = substr ($arr[$i-1], -2, 1);
965 if ($firstspace == -1) $firstspace = $i;
966 } else if ($x2 == ' ') {
967 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
969 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
975 # If there is a single-letter word, use it!
976 if ($firstsingleletterword > -1)
978 $arr [ $firstsingleletterword ] = "''";
979 $arr [ $firstsingleletterword-1 ] .= "'";
981 # If not, but there's a multi-letter word, use that one.
982 else if ($firstmultiletterword > -1)
984 $arr [ $firstmultiletterword ] = "''";
985 $arr [ $firstmultiletterword-1 ] .= "'";
987 # ... otherwise use the first one that has neither.
988 # (notice that it is possible for all three to be -1 if, for example,
989 # there is only one pentuple-apostrophe in the line)
990 else if ($firstspace > -1)
992 $arr [ $firstspace ] = "''";
993 $arr [ $firstspace-1 ] .= "'";
997 # Now let's actually convert our apostrophic mush to HTML!
1002 foreach ($arr as $r)
1006 if ($state == 'both')
1013 if (strlen ($r) == 2)
1016 { $output .= '</i>'; $state = ''; }
1017 else if ($state == 'bi')
1018 { $output .= '</i>'; $state = 'b'; }
1019 else if ($state == 'ib')
1020 { $output .= '</b></i><b>'; $state = 'b'; }
1021 else if ($state == 'both')
1022 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1023 else # $state can be 'b' or ''
1024 { $output .= '<i>'; $state .= 'i'; }
1026 else if (strlen ($r) == 3)
1029 { $output .= '</b>'; $state = ''; }
1030 else if ($state == 'bi')
1031 { $output .= '</i></b><i>'; $state = 'i'; }
1032 else if ($state == 'ib')
1033 { $output .= '</b>'; $state = 'i'; }
1034 else if ($state == 'both')
1035 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1036 else # $state can be 'i' or ''
1037 { $output .= '<b>'; $state .= 'b'; }
1039 else if (strlen ($r) == 5)
1042 { $output .= '</b><i>'; $state = 'i'; }
1043 else if ($state == 'i')
1044 { $output .= '</i><b>'; $state = 'b'; }
1045 else if ($state == 'bi')
1046 { $output .= '</i></b>'; $state = ''; }
1047 else if ($state == 'ib')
1048 { $output .= '</b></i>'; $state = ''; }
1049 else if ($state == 'both')
1050 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1051 else # ($state == '')
1052 { $buffer = ''; $state = 'both'; }
1057 # Now close all remaining tags. Notice that the order is important.
1058 if ($state == 'b' ||
$state == 'ib')
1060 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1064 if ($state == 'both')
1065 $output .= '<b><i>'.$buffer.'</i></b>';
1071 * Replace external links
1073 * Note: this is all very hackish and the order of execution matters a lot.
1074 * Make sure to run maintenance/parserTests.php if you change this code.
1078 function replaceExternalLinks( $text ) {
1080 $fname = 'Parser::replaceExternalLinks';
1081 wfProfileIn( $fname );
1083 $sk =& $this->mOptions
->getSkin();
1085 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1087 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1090 while ( $i<count( $bits ) ) {
1092 $protocol = $bits[$i++
];
1093 $text = $bits[$i++
];
1094 $trail = $bits[$i++
];
1096 # The characters '<' and '>' (which were escaped by
1097 # removeHTMLtags()) should not be included in
1098 # URLs, per RFC 2396.
1099 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1100 $text = substr($url, $m2[0][1]) . ' ' . $text;
1101 $url = substr($url, 0, $m2[0][1]);
1104 # If the link text is an image URL, replace it with an <img> tag
1105 # This happened by accident in the original parser, but some people used it extensively
1106 $img = $this->maybeMakeExternalImage( $text );
1107 if ( $img !== false ) {
1113 # Set linktype for CSS - if URL==text, link is essentially free
1114 $linktype = ($text == $url) ?
'free' : 'text';
1116 # No link text, e.g. [http://domain.tld/some.link]
1117 if ( $text == '' ) {
1118 # Autonumber if allowed. See bug #5918
1119 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1120 $text = '[' . ++
$this->mAutonumber
. ']';
1121 $linktype = 'autonumber';
1123 # Otherwise just use the URL
1124 $text = htmlspecialchars( $url );
1128 # Have link text, e.g. [http://domain.tld/some.link text]s
1130 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1133 $text = $wgContLang->markNoConversion($text);
1135 # Normalize any HTML entities in input. They will be
1136 # re-escaped by makeExternalLink().
1137 $url = Sanitizer
::decodeCharReferences( $url );
1139 # Process the trail (i.e. everything after this link up until start of the next link),
1140 # replacing any non-bracketed links
1141 $trail = $this->replaceFreeExternalLinks( $trail );
1143 # Use the encoded URL
1144 # This means that users can paste URLs directly into the text
1145 # Funny characters like ö aren't valid in URLs anyway
1146 # This was changed in August 2004
1147 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1149 # Register link in the output object.
1150 # Replace unnecessary URL escape codes with the referenced character
1151 # This prevents spammers from hiding links from the filters
1152 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1153 $this->mOutput
->addExternalLink( $pasteurized );
1156 wfProfileOut( $fname );
1161 * Replace anything that looks like a URL with a link
1164 function replaceFreeExternalLinks( $text ) {
1166 $fname = 'Parser::replaceFreeExternalLinks';
1167 wfProfileIn( $fname );
1169 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1170 $s = array_shift( $bits );
1173 $sk =& $this->mOptions
->getSkin();
1175 while ( $i < count( $bits ) ){
1176 $protocol = $bits[$i++
];
1177 $remainder = $bits[$i++
];
1179 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1180 # Found some characters after the protocol that look promising
1181 $url = $protocol . $m[1];
1184 # special case: handle urls as url args:
1185 # http://www.example.com/foo?=http://www.example.com/bar
1186 if(strlen($trail) == 0 &&
1188 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1189 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1192 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1197 # The characters '<' and '>' (which were escaped by
1198 # removeHTMLtags()) should not be included in
1199 # URLs, per RFC 2396.
1200 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1201 $trail = substr($url, $m2[0][1]) . $trail;
1202 $url = substr($url, 0, $m2[0][1]);
1205 # Move trailing punctuation to $trail
1207 # If there is no left bracket, then consider right brackets fair game too
1208 if ( strpos( $url, '(' ) === false ) {
1212 $numSepChars = strspn( strrev( $url ), $sep );
1213 if ( $numSepChars ) {
1214 $trail = substr( $url, -$numSepChars ) . $trail;
1215 $url = substr( $url, 0, -$numSepChars );
1218 # Normalize any HTML entities in input. They will be
1219 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1220 $url = Sanitizer
::decodeCharReferences( $url );
1222 # Is this an external image?
1223 $text = $this->maybeMakeExternalImage( $url );
1224 if ( $text === false ) {
1225 # Not an image, make a link
1226 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1227 # Register it in the output object...
1228 # Replace unnecessary URL escape codes with their equivalent characters
1229 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1230 $this->mOutput
->addExternalLink( $pasteurized );
1232 $s .= $text . $trail;
1234 $s .= $protocol . $remainder;
1237 wfProfileOut( $fname );
1242 * Replace unusual URL escape codes with their equivalent characters
1246 * @fixme This can merge genuinely required bits in the path or query string,
1247 * breaking legit URLs. A proper fix would treat the various parts of
1248 * the URL differently; as a workaround, just use the output for
1249 * statistical records, not for actual linking/output.
1251 function replaceUnusualEscapes( $url ) {
1252 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1253 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1257 * Callback function used in replaceUnusualEscapes().
1258 * Replaces unusual URL escape codes with their equivalent character
1262 function replaceUnusualEscapesCallback( $matches ) {
1263 $char = urldecode( $matches[0] );
1264 $ord = ord( $char );
1265 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1266 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1267 // No, shouldn't be escaped
1270 // Yes, leave it escaped
1276 * make an image if it's allowed, either through the global
1277 * option or through the exception
1280 function maybeMakeExternalImage( $url ) {
1281 $sk =& $this->mOptions
->getSkin();
1282 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1283 $imagesexception = !empty($imagesfrom);
1285 if ( $this->mOptions
->getAllowExternalImages()
1286 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1287 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1289 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1296 * Process [[ ]] wikilinks
1300 function replaceInternalLinks( $s ) {
1302 static $fname = 'Parser::replaceInternalLinks' ;
1304 wfProfileIn( $fname );
1306 wfProfileIn( $fname.'-setup' );
1308 # the % is needed to support urlencoded titles as well
1309 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1311 $sk =& $this->mOptions
->getSkin();
1313 #split the entire text string on occurences of [[
1314 $a = explode( '[[', ' ' . $s );
1315 #get the first element (all text up to first [[), and remove the space we added
1316 $s = array_shift( $a );
1317 $s = substr( $s, 1 );
1319 # Match a link having the form [[namespace:link|alternate]]trail
1321 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1322 # Match cases where there is no "]]", which might still be images
1323 static $e1_img = FALSE;
1324 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1325 # Match the end of a line for a word that's not followed by whitespace,
1326 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1327 $e2 = wfMsgForContent( 'linkprefix' );
1329 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1331 if( is_null( $this->mTitle
) ) {
1332 wfDebugDieBacktrace( 'nooo' );
1334 $nottalk = !$this->mTitle
->isTalkPage();
1336 if ( $useLinkPrefixExtension ) {
1337 if ( preg_match( $e2, $s, $m ) ) {
1338 $first_prefix = $m[2];
1340 $first_prefix = false;
1346 $selflink = $this->mTitle
->getPrefixedText();
1347 wfProfileOut( $fname.'-setup' );
1349 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1350 $useSubpages = $this->areSubpagesAllowed();
1352 # Loop for each link
1353 for ($k = 0; isset( $a[$k] ); $k++
) {
1355 if ( $useLinkPrefixExtension ) {
1356 wfProfileIn( $fname.'-prefixhandling' );
1357 if ( preg_match( $e2, $s, $m ) ) {
1365 $prefix = $first_prefix;
1366 $first_prefix = false;
1368 wfProfileOut( $fname.'-prefixhandling' );
1371 $might_be_img = false;
1373 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1375 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1376 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1377 # the real problem is with the $e1 regex
1380 # Still some problems for cases where the ] is meant to be outside punctuation,
1381 # and no image is in sight. See bug 2095.
1384 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1385 strpos($text, '[') !== false
1388 $text .= ']'; # so that replaceExternalLinks($text) works later
1391 # fix up urlencoded title texts
1392 if(preg_match('/%/', $m[1] ))
1393 # Should anchors '#' also be rejected?
1394 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1396 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1397 $might_be_img = true;
1399 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1401 } else { # Invalid form; output directly
1402 $s .= $prefix . '[[' . $line ;
1406 # Don't allow internal links to pages containing
1407 # PROTO: where PROTO is a valid URL protocol; these
1408 # should be external links.
1409 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1410 $s .= $prefix . '[[' . $line ;
1414 # Make subpage if necessary
1415 if( $useSubpages ) {
1416 $link = $this->maybeDoSubpageLink( $m[1], $text );
1421 $noforce = (substr($m[1], 0, 1) != ':');
1423 # Strip off leading ':'
1424 $link = substr($link, 1);
1427 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1429 $s .= $prefix . '[[' . $line;
1433 #check other language variants of the link
1434 #if the article does not exist
1435 if( $checkVariantLink
1436 && $nt->getArticleID() == 0 ) {
1437 $wgContLang->findVariantLink($link, $nt);
1440 $ns = $nt->getNamespace();
1441 $iw = $nt->getInterWiki();
1443 if ($might_be_img) { # if this is actually an invalid link
1444 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1446 while (isset ($a[$k+
1]) ) {
1447 #look at the next 'line' to see if we can close it there
1448 $spliced = array_splice( $a, $k +
1, 1 );
1449 $next_line = array_shift( $spliced );
1450 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1451 # the first ]] closes the inner link, the second the image
1453 $text .= '[[' . $m[1];
1456 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1457 #if there's exactly one ]] that's fine, we'll keep looking
1458 $text .= '[[' . $m[0];
1460 #if $next_line is invalid too, we need look no further
1461 $text .= '[[' . $next_line;
1466 # we couldn't find the end of this imageLink, so output it raw
1467 #but don't ignore what might be perfectly normal links in the text we've examined
1468 $text = $this->replaceInternalLinks($text);
1469 $s .= $prefix . '[[' . $link . '|' . $text;
1470 # note: no $trail, because without an end, there *is* no trail
1473 } else { #it's not an image, so output it raw
1474 $s .= $prefix . '[[' . $link . '|' . $text;
1475 # note: no $trail, because without an end, there *is* no trail
1480 $wasblank = ( '' == $text );
1481 if( $wasblank ) $text = $link;
1484 # Link not escaped by : , create the various objects
1488 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1489 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1490 $s = rtrim($s . "\n");
1491 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1495 if ( $ns == NS_IMAGE
) {
1496 wfProfileIn( "$fname-image" );
1497 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1498 # recursively parse links inside the image caption
1499 # actually, this will parse them in any other parameters, too,
1500 # but it might be hard to fix that, and it doesn't matter ATM
1501 $text = $this->replaceExternalLinks($text);
1502 $text = $this->replaceInternalLinks($text);
1504 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1505 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1506 $this->mOutput
->addImage( $nt->getDBkey() );
1508 wfProfileOut( "$fname-image" );
1511 wfProfileOut( "$fname-image" );
1515 if ( $ns == NS_CATEGORY
) {
1516 wfProfileIn( "$fname-category" );
1517 $s = rtrim($s . "\n"); # bug 87
1520 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1521 $sortkey = $this->mTitle
->getText();
1523 $sortkey = $this->mTitle
->getPrefixedText();
1528 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1529 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1530 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1533 * Strip the whitespace Category links produce, see bug 87
1534 * @todo We might want to use trim($tmp, "\n") here.
1536 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1538 wfProfileOut( "$fname-category" );
1543 if( ( $nt->getPrefixedText() === $selflink ) &&
1544 ( $nt->getFragment() === '' ) ) {
1545 # Self-links are handled specially; generally de-link and change to bold.
1546 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1550 # Special and Media are pseudo-namespaces; no pages actually exist in them
1551 if( $ns == NS_MEDIA
) {
1552 $link = $sk->makeMediaLinkObj( $nt, $text );
1553 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1554 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1555 $this->mOutput
->addImage( $nt->getDBkey() );
1557 } elseif( $ns == NS_SPECIAL
) {
1558 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1560 } elseif( $ns == NS_IMAGE
) {
1561 $img = Image
::newFromTitle( $nt );
1562 if( $img->exists() ) {
1563 // Force a blue link if the file exists; may be a remote
1564 // upload on the shared repository, and we want to see its
1565 // auto-generated page.
1566 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1570 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1572 wfProfileOut( $fname );
1577 * Make a link placeholder. The text returned can be later resolved to a real link with
1578 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1579 * parsing of interwiki links, and secondly to allow all extistence checks and
1580 * article length checks (for stub links) to be bundled into a single query.
1583 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1584 if ( ! is_object($nt) ) {
1586 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1588 # Separate the link trail from the rest of the link
1589 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1591 if ( $nt->isExternal() ) {
1592 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1593 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1594 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1596 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1597 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1598 $this->mLinkHolders
['queries'][] = $query;
1599 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1600 $this->mLinkHolders
['titles'][] = $nt;
1602 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1609 * Render a forced-blue link inline; protect against double expansion of
1610 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1611 * Since this little disaster has to split off the trail text to avoid
1612 * breaking URLs in the following text without breaking trails on the
1613 * wiki links, it's been made into a horrible function.
1616 * @param string $text
1617 * @param string $query
1618 * @param string $trail
1619 * @param string $prefix
1620 * @return string HTML-wikitext mix oh yuck
1622 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1623 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1624 $sk =& $this->mOptions
->getSkin();
1625 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1626 return $this->armorLinks( $link ) . $trail;
1630 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1631 * going to go through further parsing steps before inline URL expansion.
1633 * In particular this is important when using action=render, which causes
1634 * full URLs to be included.
1636 * Oh man I hate our multi-layer parser!
1638 * @param string more-or-less HTML
1639 * @return string less-or-more HTML with NOPARSE bits
1641 function armorLinks( $text ) {
1642 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1643 "{$this->mUniqPrefix}NOPARSE$1", $text );
1647 * Return true if subpage links should be expanded on this page.
1650 function areSubpagesAllowed() {
1651 # Some namespaces don't allow subpages
1652 global $wgNamespacesWithSubpages;
1653 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1657 * Handle link to subpage if necessary
1658 * @param string $target the source of the link
1659 * @param string &$text the link text, modified as necessary
1660 * @return string the full name of the link
1663 function maybeDoSubpageLink($target, &$text) {
1666 # :Foobar -- override special treatment of prefix (images, language links)
1667 # /Foobar -- convert to CurrentPage/Foobar
1668 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1669 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1670 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1672 $fname = 'Parser::maybeDoSubpageLink';
1673 wfProfileIn( $fname );
1674 $ret = $target; # default return value is no change
1676 # Some namespaces don't allow subpages,
1677 # so only perform processing if subpages are allowed
1678 if( $this->areSubpagesAllowed() ) {
1679 # Look at the first character
1680 if( $target != '' && $target{0} == '/' ) {
1681 # / at end means we don't want the slash to be shown
1682 if( substr( $target, -1, 1 ) == '/' ) {
1683 $target = substr( $target, 1, -1 );
1686 $noslash = substr( $target, 1 );
1689 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1690 if( '' === $text ) {
1692 } # this might be changed for ugliness reasons
1694 # check for .. subpage backlinks
1696 $nodotdot = $target;
1697 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1699 $nodotdot = substr( $nodotdot, 3 );
1701 if($dotdotcount > 0) {
1702 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1703 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1704 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1705 # / at the end means don't show full path
1706 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1707 $nodotdot = substr( $nodotdot, 0, -1 );
1708 if( '' === $text ) {
1712 $nodotdot = trim( $nodotdot );
1713 if( $nodotdot != '' ) {
1714 $ret .= '/' . $nodotdot;
1721 wfProfileOut( $fname );
1726 * Used by doBlockLevels()
1729 /* private */ function closeParagraph() {
1731 if ( '' != $this->mLastSection
) {
1732 $result = '</' . $this->mLastSection
. ">\n";
1734 $this->mInPre
= false;
1735 $this->mLastSection
= '';
1738 # getCommon() returns the length of the longest common substring
1739 # of both arguments, starting at the beginning of both.
1741 /* private */ function getCommon( $st1, $st2 ) {
1742 $fl = strlen( $st1 );
1743 $shorter = strlen( $st2 );
1744 if ( $fl < $shorter ) { $shorter = $fl; }
1746 for ( $i = 0; $i < $shorter; ++
$i ) {
1747 if ( $st1{$i} != $st2{$i} ) { break; }
1751 # These next three functions open, continue, and close the list
1752 # element appropriate to the prefix character passed into them.
1754 /* private */ function openList( $char ) {
1755 $result = $this->closeParagraph();
1757 if ( '*' == $char ) { $result .= '<ul><li>'; }
1758 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1759 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1760 else if ( ';' == $char ) {
1761 $result .= '<dl><dt>';
1762 $this->mDTopen
= true;
1764 else { $result = '<!-- ERR 1 -->'; }
1769 /* private */ function nextItem( $char ) {
1770 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1771 else if ( ':' == $char ||
';' == $char ) {
1773 if ( $this->mDTopen
) { $close = '</dt>'; }
1774 if ( ';' == $char ) {
1775 $this->mDTopen
= true;
1776 return $close . '<dt>';
1778 $this->mDTopen
= false;
1779 return $close . '<dd>';
1782 return '<!-- ERR 2 -->';
1785 /* private */ function closeList( $char ) {
1786 if ( '*' == $char ) { $text = '</li></ul>'; }
1787 else if ( '#' == $char ) { $text = '</li></ol>'; }
1788 else if ( ':' == $char ) {
1789 if ( $this->mDTopen
) {
1790 $this->mDTopen
= false;
1791 $text = '</dt></dl>';
1793 $text = '</dd></dl>';
1796 else { return '<!-- ERR 3 -->'; }
1802 * Make lists from lines starting with ':', '*', '#', etc.
1805 * @return string the lists rendered as HTML
1807 function doBlockLevels( $text, $linestart ) {
1808 $fname = 'Parser::doBlockLevels';
1809 wfProfileIn( $fname );
1811 # Parsing through the text line by line. The main thing
1812 # happening here is handling of block-level elements p, pre,
1813 # and making lists from lines starting with * # : etc.
1815 $textLines = explode( "\n", $text );
1817 $lastPrefix = $output = '';
1818 $this->mDTopen
= $inBlockElem = false;
1820 $paragraphStack = false;
1822 if ( !$linestart ) {
1823 $output .= array_shift( $textLines );
1825 foreach ( $textLines as $oLine ) {
1826 $lastPrefixLength = strlen( $lastPrefix );
1827 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1828 $preOpenMatch = preg_match('/<pre/i', $oLine );
1829 if ( !$this->mInPre
) {
1830 # Multiple prefixes may abut each other for nested lists.
1831 $prefixLength = strspn( $oLine, '*#:;' );
1832 $pref = substr( $oLine, 0, $prefixLength );
1835 $pref2 = str_replace( ';', ':', $pref );
1836 $t = substr( $oLine, $prefixLength );
1837 $this->mInPre
= !empty($preOpenMatch);
1839 # Don't interpret any other prefixes in preformatted text
1841 $pref = $pref2 = '';
1846 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1847 # Same as the last item, so no need to deal with nesting or opening stuff
1848 $output .= $this->nextItem( substr( $pref, -1 ) );
1849 $paragraphStack = false;
1851 if ( substr( $pref, -1 ) == ';') {
1852 # The one nasty exception: definition lists work like this:
1853 # ; title : definition text
1854 # So we check for : in the remainder text to split up the
1855 # title and definition, without b0rking links.
1857 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1859 $output .= $term . $this->nextItem( ':' );
1862 } elseif( $prefixLength ||
$lastPrefixLength ) {
1863 # Either open or close a level...
1864 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1865 $paragraphStack = false;
1867 while( $commonPrefixLength < $lastPrefixLength ) {
1868 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1869 --$lastPrefixLength;
1871 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1872 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1874 while ( $prefixLength > $commonPrefixLength ) {
1875 $char = substr( $pref, $commonPrefixLength, 1 );
1876 $output .= $this->openList( $char );
1878 if ( ';' == $char ) {
1879 # FIXME: This is dupe of code above
1880 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1882 $output .= $term . $this->nextItem( ':' );
1885 ++
$commonPrefixLength;
1887 $lastPrefix = $pref2;
1889 if( 0 == $prefixLength ) {
1890 wfProfileIn( "$fname-paragraph" );
1891 # No prefix (not in list)--go to paragraph mode
1892 // XXX: use a stack for nestable elements like span, table and div
1893 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1894 $closematch = preg_match(
1895 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1896 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/center)/iS', $t );
1897 if ( $openmatch or $closematch ) {
1898 $paragraphStack = false;
1899 #Â TODO bug 5718: paragraph closed
1900 $output .= $this->closeParagraph();
1901 if ( $preOpenMatch and !$preCloseMatch ) {
1902 $this->mInPre
= true;
1904 if ( $closematch ) {
1905 $inBlockElem = false;
1907 $inBlockElem = true;
1909 } else if ( !$inBlockElem && !$this->mInPre
) {
1910 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1912 if ($this->mLastSection
!= 'pre') {
1913 $paragraphStack = false;
1914 $output .= $this->closeParagraph().'<pre>';
1915 $this->mLastSection
= 'pre';
1917 $t = substr( $t, 1 );
1920 if ( '' == trim($t) ) {
1921 if ( $paragraphStack ) {
1922 $output .= $paragraphStack.'<br />';
1923 $paragraphStack = false;
1924 $this->mLastSection
= 'p';
1926 if ($this->mLastSection
!= 'p' ) {
1927 $output .= $this->closeParagraph();
1928 $this->mLastSection
= '';
1929 $paragraphStack = '<p>';
1931 $paragraphStack = '</p><p>';
1935 if ( $paragraphStack ) {
1936 $output .= $paragraphStack;
1937 $paragraphStack = false;
1938 $this->mLastSection
= 'p';
1939 } else if ($this->mLastSection
!= 'p') {
1940 $output .= $this->closeParagraph().'<p>';
1941 $this->mLastSection
= 'p';
1946 wfProfileOut( "$fname-paragraph" );
1948 // somewhere above we forget to get out of pre block (bug 785)
1949 if($preCloseMatch && $this->mInPre
) {
1950 $this->mInPre
= false;
1952 if ($paragraphStack === false) {
1956 while ( $prefixLength ) {
1957 $output .= $this->closeList( $pref2{$prefixLength-1} );
1960 if ( '' != $this->mLastSection
) {
1961 $output .= '</' . $this->mLastSection
. '>';
1962 $this->mLastSection
= '';
1965 wfProfileOut( $fname );
1970 * Split up a string on ':', ignoring any occurences inside tags
1971 * to prevent illegal overlapping.
1972 * @param string $str the string to split
1973 * @param string &$before set to everything before the ':'
1974 * @param string &$after set to everything after the ':'
1975 * return string the position of the ':', or false if none found
1977 function findColonNoLinks($str, &$before, &$after) {
1978 $fname = 'Parser::findColonNoLinks';
1979 wfProfileIn( $fname );
1981 $pos = strpos( $str, ':' );
1982 if( $pos === false ) {
1984 wfProfileOut( $fname );
1988 $lt = strpos( $str, '<' );
1989 if( $lt === false ||
$lt > $pos ) {
1990 // Easy; no tag nesting to worry about
1991 $before = substr( $str, 0, $pos );
1992 $after = substr( $str, $pos+
1 );
1993 wfProfileOut( $fname );
1997 // Ugly state machine to walk through avoiding tags.
1998 $state = MW_COLON_STATE_TEXT
;
2000 $len = strlen( $str );
2001 for( $i = 0; $i < $len; $i++
) {
2005 // (Using the number is a performance hack for common cases)
2006 case 0: // MW_COLON_STATE_TEXT:
2009 // Could be either a <start> tag or an </end> tag
2010 $state = MW_COLON_STATE_TAGSTART
;
2015 $before = substr( $str, 0, $i );
2016 $after = substr( $str, $i +
1 );
2017 wfProfileOut( $fname );
2020 // Embedded in a tag; don't break it.
2023 // Skip ahead looking for something interesting
2024 $colon = strpos( $str, ':', $i );
2025 if( $colon === false ) {
2026 // Nothing else interesting
2027 wfProfileOut( $fname );
2030 $lt = strpos( $str, '<', $i );
2031 if( $stack === 0 ) {
2032 if( $lt === false ||
$colon < $lt ) {
2034 $before = substr( $str, 0, $colon );
2035 $after = substr( $str, $colon +
1 );
2036 wfProfileOut( $fname );
2040 if( $lt === false ) {
2041 // Nothing else interesting to find; abort!
2042 // We're nested, but there's no close tags left. Abort!
2045 // Skip ahead to next tag start
2047 $state = MW_COLON_STATE_TAGSTART
;
2050 case 1: // MW_COLON_STATE_TAG:
2055 $state = MW_COLON_STATE_TEXT
;
2058 // Slash may be followed by >?
2059 $state = MW_COLON_STATE_TAGSLASH
;
2065 case 2: // MW_COLON_STATE_TAGSTART:
2068 $state = MW_COLON_STATE_CLOSETAG
;
2071 $state = MW_COLON_STATE_COMMENT
;
2074 // Illegal early close? This shouldn't happen D:
2075 $state = MW_COLON_STATE_TEXT
;
2078 $state = MW_COLON_STATE_TAG
;
2081 case 3: // MW_COLON_STATE_CLOSETAG:
2086 wfDebug( "Invalid input in $fname; too many close tags\n" );
2087 wfProfileOut( $fname );
2090 $state = MW_COLON_STATE_TEXT
;
2093 case MW_COLON_STATE_TAGSLASH
:
2095 // Yes, a self-closed tag <blah/>
2096 $state = MW_COLON_STATE_TEXT
;
2098 // Probably we're jumping the gun, and this is an attribute
2099 $state = MW_COLON_STATE_TAG
;
2102 case 5: // MW_COLON_STATE_COMMENT:
2104 $state = MW_COLON_STATE_COMMENTDASH
;
2107 case MW_COLON_STATE_COMMENTDASH
:
2109 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2111 $state = MW_COLON_STATE_COMMENT
;
2114 case MW_COLON_STATE_COMMENTDASHDASH
:
2116 $state = MW_COLON_STATE_TEXT
;
2118 $state = MW_COLON_STATE_COMMENT
;
2122 wfDebugDieBacktrace( "State machine error in $fname" );
2126 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2129 wfProfileOut( $fname );
2134 * Return value of a magic variable (like PAGENAME)
2138 function getVariableValue( $index ) {
2139 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2142 * Some of these require message or data lookups and can be
2143 * expensive to check many times.
2145 static $varCache = array();
2146 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2147 if ( isset( $varCache[$index] ) )
2148 return $varCache[$index];
2151 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2154 case MAG_CURRENTMONTH
:
2155 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2156 case MAG_CURRENTMONTHNAME
:
2157 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2158 case MAG_CURRENTMONTHNAMEGEN
:
2159 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2160 case MAG_CURRENTMONTHABBREV
:
2161 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2162 case MAG_CURRENTDAY
:
2163 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2164 case MAG_CURRENTDAY2
:
2165 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2167 return $this->mTitle
->getText();
2169 return $this->mTitle
->getPartialURL();
2170 case MAG_FULLPAGENAME
:
2171 return $this->mTitle
->getPrefixedText();
2172 case MAG_FULLPAGENAMEE
:
2173 return $this->mTitle
->getPrefixedURL();
2174 case MAG_SUBPAGENAME
:
2175 return $this->mTitle
->getSubpageText();
2176 case MAG_SUBPAGENAMEE
:
2177 return $this->mTitle
->getSubpageUrlForm();
2178 case MAG_BASEPAGENAME
:
2179 return $this->mTitle
->getBaseText();
2180 case MAG_BASEPAGENAMEE
:
2181 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2182 case MAG_TALKPAGENAME
:
2183 if( $this->mTitle
->canTalk() ) {
2184 $talkPage = $this->mTitle
->getTalkPage();
2185 return $talkPage->getPrefixedText();
2189 case MAG_TALKPAGENAMEE
:
2190 if( $this->mTitle
->canTalk() ) {
2191 $talkPage = $this->mTitle
->getTalkPage();
2192 return $talkPage->getPrefixedUrl();
2196 case MAG_SUBJECTPAGENAME
:
2197 $subjPage = $this->mTitle
->getSubjectPage();
2198 return $subjPage->getPrefixedText();
2199 case MAG_SUBJECTPAGENAMEE
:
2200 $subjPage = $this->mTitle
->getSubjectPage();
2201 return $subjPage->getPrefixedUrl();
2202 case MAG_REVISIONID
:
2203 return $this->mRevisionId
;
2205 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2206 case MAG_NAMESPACEE
:
2207 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2209 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2210 case MAG_TALKSPACEE
:
2211 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2212 case MAG_SUBJECTSPACE
:
2213 return $this->mTitle
->getSubjectNsText();
2214 case MAG_SUBJECTSPACEE
:
2215 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2216 case MAG_CURRENTDAYNAME
:
2217 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2218 case MAG_CURRENTYEAR
:
2219 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2220 case MAG_CURRENTTIME
:
2221 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2222 case MAG_CURRENTWEEK
:
2223 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2224 // int to remove the padding
2225 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2226 case MAG_CURRENTDOW
:
2227 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2228 case MAG_NUMBEROFARTICLES
:
2229 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2230 case MAG_NUMBEROFFILES
:
2231 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2232 case MAG_NUMBEROFUSERS
:
2233 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2234 case MAG_NUMBEROFPAGES
:
2235 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2236 case MAG_CURRENTTIMESTAMP
:
2237 return $varCache[$index] = wfTimestampNow();
2238 case MAG_CURRENTVERSION
:
2245 case MAG_SERVERNAME
:
2246 return $wgServerName;
2247 case MAG_SCRIPTPATH
:
2248 return $wgScriptPath;
2249 case MAG_DIRECTIONMARK
:
2250 return $wgContLang->getDirMark();
2253 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2261 * initialise the magic variables (like CURRENTMONTHNAME)
2265 function initialiseVariables() {
2266 $fname = 'Parser::initialiseVariables';
2267 wfProfileIn( $fname );
2268 global $wgVariableIDs;
2269 $this->mVariables
= array();
2270 foreach ( $wgVariableIDs as $id ) {
2271 $mw =& MagicWord
::get( $id );
2272 $mw->addToArray( $this->mVariables
, $id );
2274 wfProfileOut( $fname );
2278 * parse any parentheses in format ((title|part|part))
2279 * and call callbacks to get a replacement text for any found piece
2281 * @param string $text The text to parse
2282 * @param array $callbacks rules in form:
2283 * '{' => array( # opening parentheses
2284 * 'end' => '}', # closing parentheses
2285 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2286 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2291 function replace_callback ($text, $callbacks) {
2292 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2293 $lastOpeningBrace = -1; # last not closed parentheses
2295 for ($i = 0; $i < strlen($text); $i++
) {
2296 # check for any opening brace
2299 foreach ($callbacks as $key => $value) {
2300 $pos = strpos ($text, $key, $i);
2301 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2307 if ($lastOpeningBrace >= 0) {
2308 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2310 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2315 $pos = strpos ($text, '|', $i);
2317 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2328 # found openning brace, lets add it to parentheses stack
2329 if (null != $rule) {
2330 $piece = array('brace' => $text[$i],
2331 'braceEnd' => $rule['end'],
2336 # count openning brace characters
2337 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2342 $piece['startAt'] = $i+
1;
2343 $piece['partStart'] = $i+
1;
2345 # we need to add to stack only if openning brace count is enough for any given rule
2346 foreach ($rule['cb'] as $cnt => $fn) {
2347 if ($piece['count'] >= $cnt) {
2348 $lastOpeningBrace ++
;
2349 $openingBraceStack[$lastOpeningBrace] = $piece;
2356 else if ($lastOpeningBrace >= 0) {
2357 # first check if it is a closing brace
2358 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2359 # lets check if it is enough characters for closing brace
2361 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2364 # if there are more closing parentheses than opening ones, we parse less
2365 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2366 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2368 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2370 $matchingCallback = null;
2371 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2372 if ($count >= $cnt && $matchingCount < $cnt) {
2373 $matchingCount = $cnt;
2374 $matchingCallback = $fn;
2378 if ($matchingCount == 0) {
2383 # lets set a title or last part (if '|' was found)
2384 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2385 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2387 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2389 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2390 $pieceEnd = $i +
$matchingCount;
2392 if( is_callable( $matchingCallback ) ) {
2394 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2395 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2396 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2397 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2399 # finally we can call a user callback and replace piece of text
2400 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2401 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2402 $i = $pieceStart +
strlen($replaceWith) - 1;
2405 # null value for callback means that parentheses should be parsed, but not replaced
2406 $i +
= $matchingCount - 1;
2409 # reset last openning parentheses, but keep it in case there are unused characters
2410 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2411 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2412 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2415 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2416 $openingBraceStack[$lastOpeningBrace--] = null;
2418 if ($matchingCount < $piece['count']) {
2419 $piece['count'] -= $matchingCount;
2420 $piece['startAt'] -= $matchingCount;
2421 $piece['partStart'] = $piece['startAt'];
2422 # do we still qualify for any callback with remaining count?
2423 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2424 if ($piece['count'] >= $cnt) {
2425 $lastOpeningBrace ++
;
2426 $openingBraceStack[$lastOpeningBrace] = $piece;
2434 # lets set a title if it is a first separator, or next part otherwise
2435 if ($text[$i] == '|') {
2436 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2437 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2438 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2441 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2443 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2452 * Replace magic variables, templates, and template arguments
2453 * with the appropriate text. Templates are substituted recursively,
2454 * taking care to avoid infinite loops.
2456 * Note that the substitution depends on value of $mOutputType:
2457 * OT_WIKI: only {{subst:}} templates
2458 * OT_MSG: only magic variables
2459 * OT_HTML: all templates and magic variables
2461 * @param string $tex The text to transform
2462 * @param array $args Key-value pairs representing template parameters to substitute
2463 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2466 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2467 # Prevent too big inclusions
2468 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2472 $fname = 'Parser::replaceVariables';
2473 wfProfileIn( $fname );
2475 # This function is called recursively. To keep track of arguments we need a stack:
2476 array_push( $this->mArgStack
, $args );
2478 $braceCallbacks = array();
2480 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2482 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2483 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2485 $callbacks = array();
2486 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2487 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2488 $text = $this->replace_callback ($text, $callbacks);
2490 array_pop( $this->mArgStack
);
2492 wfProfileOut( $fname );
2497 * Replace magic variables
2500 function variableSubstitution( $matches ) {
2501 $fname = 'Parser::variableSubstitution';
2502 $varname = $matches[1];
2503 wfProfileIn( $fname );
2504 if ( !$this->mVariables
) {
2505 $this->initialiseVariables();
2508 if ( $this->mOutputType
== OT_WIKI
) {
2509 # Do only magic variables prefixed by SUBST
2510 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2511 if (!$mwSubst->matchStartAndRemove( $varname ))
2513 # Note that if we don't substitute the variable below,
2514 # we don't remove the {{subst:}} magic word, in case
2515 # it is a template rather than a magic variable.
2517 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2518 $id = $this->mVariables
[$varname];
2519 $text = $this->getVariableValue( $id );
2520 $this->mOutput
->mContainsOldMagic
= true;
2522 $text = $matches[0];
2524 wfProfileOut( $fname );
2528 # Split template arguments
2529 function getTemplateArgs( $argsString ) {
2530 if ( $argsString === '' ) {
2534 $args = explode( '|', substr( $argsString, 1 ) );
2536 # If any of the arguments contains a '[[' but no ']]', it needs to be
2537 # merged with the next arg because the '|' character between belongs
2538 # to the link syntax and not the template parameter syntax.
2539 $argc = count($args);
2541 for ( $i = 0; $i < $argc-1; $i++
) {
2542 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2543 $args[$i] .= '|'.$args[$i+
1];
2544 array_splice($args, $i+
1, 1);
2554 * Return the text of a template, after recursively
2555 * replacing any variables or templates within the template.
2557 * @param array $piece The parts of the template
2558 * $piece['text']: matched text
2559 * $piece['title']: the title, i.e. the part before the |
2560 * $piece['parts']: the parameter array
2561 * @return string the text of the template
2564 function braceSubstitution( $piece ) {
2565 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2566 $fname = 'Parser::braceSubstitution';
2567 wfProfileIn( $fname );
2570 $found = false; # $text has been filled
2571 $nowiki = false; # wiki markup in $text should be escaped
2572 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2573 $noargs = false; # Don't replace triple-brace arguments in $text
2574 $replaceHeadings = false; # Make the edit section links go to the template not the article
2575 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2576 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2578 # Title object, where $text came from
2583 # $part1 is the bit before the first |, and must contain only title characters
2584 # $args is a list of arguments, starting from index 0, not including $part1
2586 $part1 = $piece['title'];
2587 # If the third subpattern matched anything, it will start with |
2589 if (null == $piece['parts']) {
2590 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2591 if ($replaceWith != $piece['text']) {
2592 $text = $replaceWith;
2599 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2600 $argc = count( $args );
2604 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2605 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2606 # One of two possibilities is true:
2607 # 1) Found SUBST but not in the PST phase
2608 # 2) Didn't find SUBST and in the PST phase
2609 # In either case, return without further processing
2610 $text = $piece['text'];
2617 # MSG, MSGNW, INT and RAW
2620 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2621 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2624 # Remove obsolete MSG:
2625 $mwMsg =& MagicWord
::get( MAG_MSG
);
2626 $mwMsg->matchStartAndRemove( $part1 );
2630 $mwRaw =& MagicWord
::get( MAG_RAW
);
2631 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2632 $forceRawInterwiki = true;
2635 # Check if it is an internal message
2636 $mwInt =& MagicWord
::get( MAG_INT
);
2637 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2638 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2639 $text = $linestart . wfMsgReal( $part1, $args, true );
2647 # Check for NS: (namespace expansion)
2648 $mwNs = MagicWord
::get( MAG_NS
);
2649 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2650 if ( intval( $part1 ) ||
$part1 == "0" ) {
2651 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2654 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2655 if ( !is_null( $index ) ) {
2656 $text = $linestart . $wgContLang->getNsText( $index );
2665 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2666 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2667 $text = $linestart . urlencode( $part1 );
2672 # LCFIRST, UCFIRST, LC and UC
2674 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2675 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2676 $lc =& MagicWord
::get( MAG_LC
);
2677 $uc =& MagicWord
::get( MAG_UC
);
2678 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2679 $text = $linestart . $wgContLang->lcfirst( $part1 );
2681 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2682 $text = $linestart . $wgContLang->ucfirst( $part1 );
2684 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2685 $text = $linestart . $wgContLang->lc( $part1 );
2687 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2688 $text = $linestart . $wgContLang->uc( $part1 );
2693 # LOCALURL and FULLURL
2695 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2696 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2697 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2698 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2701 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2702 $func = 'getLocalURL';
2703 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2704 $func = 'escapeLocalURL';
2705 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2706 $func = 'getFullURL';
2707 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2708 $func = 'escapeFullURL';
2713 if ( $func !== false ) {
2714 $title = Title
::newFromText( $part1 );
2715 # Due to order of execution of a lot of bits, the values might be encoded
2716 # before arriving here; if that's true, then the title can't be created
2717 # and the variable will fail. If we can't get a decent title from the first
2718 # attempt, url-decode and try for a second.
2719 if( is_null( $title ) )
2720 $title = Title
::newFromUrl( urldecode( $part1 ) );
2721 if ( !is_null( $title ) ) {
2723 $text = $linestart . $title->$func( $args[0] );
2725 $text = $linestart . $title->$func();
2732 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2734 if ( !$found && $argc == 1 ) {
2735 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2736 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2737 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2743 if ( !$found && $argc >= 2 ) {
2744 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2745 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2746 if ($argc==2) {$args[2]=$args[1];}
2747 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2753 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2754 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2755 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2757 # Set title in parser output object
2759 $parserOptions = new ParserOptions
;
2760 $local_parser = new Parser ();
2761 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2762 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2765 $t = $this->mTitle
->getPrefixedText();
2766 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2772 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2774 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2775 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2776 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2777 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2778 foreach( $mwWordsToCheck as $word => $func ) {
2779 $mwCurrentWord =& MagicWord
::get( $word );
2780 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2781 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2782 if( $mwRawSuffix->match( $args[0] ) ) {
2783 # Raw and unformatted
2784 $text = $linestart . call_user_func( $func );
2786 # Formatted according to the content default
2787 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2796 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2797 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2798 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2799 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2805 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2806 $colonPos = strpos( $part1, ':' );
2807 if ( $colonPos !== false ) {
2808 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2809 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2810 $funcArgs = array_map( 'trim', $args );
2811 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2812 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2815 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2819 if ( is_array( $result ) ) {
2820 $text = $linestart . $result[0];
2821 unset( $result[0] );
2823 // Extract flags into the local scope
2824 // This allows callers to set flags such as nowiki, noparse, found, etc.
2827 $text = $linestart . $result;
2833 # Template table test
2835 # Did we encounter this template already? If yes, it is in the cache
2836 # and we need to check for loops.
2837 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2840 # Infinite loop test
2841 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2845 $text = $linestart .
2846 '{{' . $part1 . '}}' .
2847 '<!-- WARNING: template loop detected -->';
2848 wfDebug( "$fname: template loop broken at '$part1'\n" );
2850 # set $text to cached message.
2851 $text = $linestart . $this->mTemplates
[$piece['title']];
2855 # Load from database
2856 $lastPathLevel = $this->mTemplatePath
;
2859 # declaring $subpage directly in the function call
2860 # does not work correctly with references and breaks
2861 # {{/subpage}}-style inclusions
2863 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2864 if ($subpage !== '') {
2865 $ns = $this->mTitle
->getNamespace();
2867 $title = Title
::newFromText( $part1, $ns );
2869 if ( !is_null( $title ) ) {
2870 if ( !$title->isExternal() ) {
2871 # Check for excessive inclusion
2872 $dbk = $title->getPrefixedDBkey();
2873 if ( $this->incrementIncludeCount( $dbk ) ) {
2874 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2875 $text = SpecialPage
::capturePath( $title );
2876 if ( is_string( $text ) ) {
2881 $this->disableCache();
2884 $articleContent = $this->fetchTemplate( $title );
2885 if ( $articleContent !== false ) {
2887 $text = $articleContent;
2888 $replaceHeadings = true;
2893 # If the title is valid but undisplayable, make a link to it
2894 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2895 $text = '[['.$title->getPrefixedText().']]';
2898 } elseif ( $title->isTrans() ) {
2899 // Interwiki transclusion
2900 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2901 $text = $this->interwikiTransclude( $title, 'render' );
2905 $text = $this->interwikiTransclude( $title, 'raw' );
2906 $replaceHeadings = true;
2911 # Template cache array insertion
2912 # Use the original $piece['title'] not the mangled $part1, so that
2913 # modifiers such as RAW: produce separate cache entries
2916 // A special page; don't store it in the template cache.
2918 $this->mTemplates
[$piece['title']] = $text;
2920 $text = $linestart . $text;
2925 # Recursive parsing, escaping and link table handling
2926 # Only for HTML output
2927 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2928 $text = wfEscapeWikiText( $text );
2929 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2931 $assocArgs = array();
2933 # Clean up argument array
2934 $assocArgs = array();
2936 foreach( $args as $arg ) {
2937 $eqpos = strpos( $arg, '=' );
2938 if ( $eqpos === false ) {
2939 $assocArgs[$index++
] = $arg;
2941 $name = trim( substr( $arg, 0, $eqpos ) );
2942 $value = trim( substr( $arg, $eqpos+
1 ) );
2943 if ( $value === false ) {
2946 if ( $name !== false ) {
2947 $assocArgs[$name] = $value;
2952 # Add a new element to the templace recursion path
2953 $this->mTemplatePath
[$part1] = 1;
2957 # If there are any <onlyinclude> tags, only include them
2958 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2959 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2961 foreach ($m[1] as $piece)
2964 # Remove <noinclude> sections and <includeonly> tags
2965 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2966 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2968 if( $this->mOutputType
== OT_HTML
) {
2969 # Strip <nowiki>, <pre>, etc.
2970 $text = $this->strip( $text, $this->mStripState
);
2971 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2973 $text = $this->replaceVariables( $text, $assocArgs );
2975 # If the template begins with a table or block-level
2976 # element, it should be treated as beginning a new line.
2977 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2978 $text = "\n" . $text;
2980 } elseif ( !$noargs ) {
2981 # $noparse and !$noargs
2982 # Just replace the arguments, not any double-brace items
2983 # This is used for rendered interwiki transclusion
2984 $text = $this->replaceVariables( $text, $assocArgs, true );
2987 # Prune lower levels off the recursion check path
2988 $this->mTemplatePath
= $lastPathLevel;
2991 wfProfileOut( $fname );
2992 return $piece['text'];
2995 # Replace raw HTML by a placeholder
2996 # Add a blank line preceding, to prevent it from mucking up
2997 # immediately preceding headings
2998 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3000 # replace ==section headers==
3001 # XXX this needs to go away once we have a better parser.
3002 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3003 if( !is_null( $title ) )
3004 $encodedname = base64_encode($title->getPrefixedDBkey());
3006 $encodedname = base64_encode("");
3007 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3008 PREG_SPLIT_DELIM_CAPTURE
);
3011 for( $i = 0; $i < count($m); $i +
= 2 ) {
3013 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3015 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3019 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3020 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3021 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3029 # Prune lower levels off the recursion check path
3030 $this->mTemplatePath
= $lastPathLevel;
3033 wfProfileOut( $fname );
3034 return $piece['text'];
3036 wfProfileOut( $fname );
3042 * Fetch the unparsed text of a template and register a reference to it.
3044 function fetchTemplate( $title ) {
3046 // Loop to fetch the article, with up to 1 redirect
3047 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3048 $rev = Revision
::newFromTitle( $title );
3049 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3053 $text = $rev->getText();
3054 if ( $text === false ) {
3058 $title = Title
::newFromRedirect( $text );
3064 * Transclude an interwiki link.
3066 function interwikiTransclude( $title, $action ) {
3067 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3069 if (!$wgEnableScaryTranscluding)
3070 return wfMsg('scarytranscludedisabled');
3072 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3073 // But we'll handle it generally anyway
3074 if ( $title->getNamespace() ) {
3075 // Use the canonical namespace, which should work anywhere
3076 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3078 $articleName = $title->getDBkey();
3081 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3082 $url .= "?action=$action";
3083 if (strlen($url) > 255)
3084 return wfMsg('scarytranscludetoolong');
3085 return $this->fetchScaryTemplateMaybeFromCache($url);
3088 function fetchScaryTemplateMaybeFromCache($url) {
3089 global $wgTranscludeCacheExpiry;
3090 $dbr =& wfGetDB(DB_SLAVE
);
3091 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3092 array('tc_url' => $url));
3094 $time = $obj->tc_time
;
3095 $text = $obj->tc_contents
;
3096 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3101 $text = wfGetHTTP($url);
3103 return wfMsg('scarytranscludefailed', $url);
3105 $dbw =& wfGetDB(DB_MASTER
);
3106 $dbw->replace('transcache', array('tc_url'), array(
3108 'tc_time' => time(),
3109 'tc_contents' => $text));
3115 * Triple brace replacement -- used for template arguments
3118 function argSubstitution( $matches ) {
3119 $arg = trim( $matches['title'] );
3120 $text = $matches['text'];
3121 $inputArgs = end( $this->mArgStack
);
3123 if ( array_key_exists( $arg, $inputArgs ) ) {
3124 $text = $inputArgs[$arg];
3125 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3126 $text = $matches['parts'][0];
3133 * Returns true if the function is allowed to include this entity
3136 function incrementIncludeCount( $dbk ) {
3137 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3138 $this->mIncludeCount
[$dbk] = 0;
3140 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3148 * Detect __TOC__ magic word and set a placeholder
3150 function stripToc( $text ) {
3151 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3153 $mw = MagicWord
::get( MAG_NOTOC
);
3154 if( $mw->matchAndRemove( $text ) ) {
3155 $this->mShowToc
= false;
3158 $mw = MagicWord
::get( MAG_TOC
);
3159 if( $mw->match( $text ) ) {
3160 $this->mShowToc
= true;
3161 $this->mForceTocPosition
= true;
3163 // Set a placeholder. At the end we'll fill it in with the TOC.
3164 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3166 // Only keep the first one.
3167 $text = $mw->replace( '', $text );
3173 * This function accomplishes several tasks:
3174 * 1) Auto-number headings if that option is enabled
3175 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3176 * 3) Add a Table of contents on the top for users who have enabled the option
3177 * 4) Auto-anchor headings
3179 * It loops through all headlines, collects the necessary data, then splits up the
3180 * string and re-inserts the newly formatted headlines.
3182 * @param string $text
3183 * @param boolean $isMain
3186 function formatHeadings( $text, $isMain=true ) {
3187 global $wgMaxTocLevel, $wgContLang;
3189 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3190 if( !$this->mTitle
->userCanEdit() ) {
3193 $showEditLink = $this->mOptions
->getEditSection();
3196 # Inhibit editsection links if requested in the page
3197 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3198 if( $esw->matchAndRemove( $text ) ) {
3202 # Get all headlines for numbering them and adding funky stuff like [edit]
3203 # links - this is for later, but we need the number of headlines right now
3204 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3206 # if there are fewer than 4 headlines in the article, do not show TOC
3207 # unless it's been explicitly enabled.
3208 $enoughToc = $this->mShowToc
&&
3209 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3211 # Allow user to stipulate that a page should have a "new section"
3212 # link added via __NEWSECTIONLINK__
3213 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3214 if( $mw->matchAndRemove( $text ) )
3215 $this->mOutput
->setNewSection( true );
3217 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3218 # override above conditions and always show TOC above first header
3219 $mw =& MagicWord
::get( MAG_FORCETOC
);
3220 if ($mw->matchAndRemove( $text ) ) {
3221 $this->mShowToc
= true;
3225 # Never ever show TOC if no headers
3226 if( $numMatches < 1 ) {
3230 # We need this to perform operations on the HTML
3231 $sk =& $this->mOptions
->getSkin();
3235 $sectionCount = 0; # headlineCount excluding template sections
3237 # Ugh .. the TOC should have neat indentation levels which can be
3238 # passed to the skin functions. These are determined here
3242 $sublevelCount = array();
3243 $levelCount = array();
3250 foreach( $matches[3] as $headline ) {
3252 $templatetitle = '';
3253 $templatesection = 0;
3256 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3258 $templatetitle = base64_decode($mat[1]);
3259 $templatesection = 1 +
(int)base64_decode($mat[2]);
3260 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3264 $prevlevel = $level;
3265 $prevtoclevel = $toclevel;
3267 $level = $matches[1][$headlineCount];
3269 if( $doNumberHeadings ||
$enoughToc ) {
3271 if ( $level > $prevlevel ) {
3272 # Increase TOC level
3274 $sublevelCount[$toclevel] = 0;
3275 if( $toclevel<$wgMaxTocLevel ) {
3276 $toc .= $sk->tocIndent();
3279 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3280 # Decrease TOC level, find level to jump to
3282 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3283 # Can only go down to level 1
3286 for ($i = $toclevel; $i > 0; $i--) {
3287 if ( $levelCount[$i] == $level ) {
3288 # Found last matching level
3292 elseif ( $levelCount[$i] < $level ) {
3293 # Found first matching level below current level
3299 if( $toclevel<$wgMaxTocLevel ) {
3300 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3304 # No change in level, end TOC line
3305 if( $toclevel<$wgMaxTocLevel ) {
3306 $toc .= $sk->tocLineEnd();
3310 $levelCount[$toclevel] = $level;
3312 # count number of headlines for each level
3313 @$sublevelCount[$toclevel]++
;
3315 for( $i = 1; $i <= $toclevel; $i++
) {
3316 if( !empty( $sublevelCount[$i] ) ) {
3320 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3326 # The canonized header is a version of the header text safe to use for links
3327 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3328 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3329 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3331 # Remove link placeholders by the link text.
3332 # <!--LINK number-->
3334 # link text with suffix
3335 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3336 "\$this->mLinkHolders['texts'][\$1]",
3337 $canonized_headline );
3338 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3339 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3340 $canonized_headline );
3343 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3344 $tocline = trim( $canonized_headline );
3345 # Save headline for section edit hint before it's escaped
3346 $headline_hint = trim( $canonized_headline );
3347 $canonized_headline = Sanitizer
::escapeId( $tocline );
3348 $refers[$headlineCount] = $canonized_headline;
3350 # count how many in assoc. array so we can track dupes in anchors
3351 @$refers[$canonized_headline]++
;
3352 $refcount[$headlineCount]=$refers[$canonized_headline];
3354 # Don't number the heading if it is the only one (looks silly)
3355 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3356 # the two are different if the line contains a link
3357 $headline=$numbering . ' ' . $headline;
3360 # Create the anchor for linking from the TOC to the section
3361 $anchor = $canonized_headline;
3362 if($refcount[$headlineCount] > 1 ) {
3363 $anchor .= '_' . $refcount[$headlineCount];
3365 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3366 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3368 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3369 if ( empty( $head[$headlineCount] ) ) {
3370 $head[$headlineCount] = '';
3373 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3375 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3378 # give headline the correct <h#> tag
3379 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3387 if( $toclevel<$wgMaxTocLevel ) {
3388 $toc .= $sk->tocUnindent( $toclevel - 1 );
3390 $toc = $sk->tocList( $toc );
3393 # split up and insert constructed headlines
3395 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3398 foreach( $blocks as $block ) {
3399 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3400 # This is the [edit] link that appears for the top block of text when
3401 # section editing is enabled
3403 # Disabled because it broke block formatting
3404 # For example, a bullet point in the top line
3405 # $full .= $sk->editSectionLink(0);
3408 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3409 # Top anchor now in skin
3413 if( !empty( $head[$i] ) ) {
3418 if( $this->mForceTocPosition
) {
3419 return str_replace( '<!--MWTOC-->', $toc, $full );
3426 * Return an HTML link for the "ISBN 123456" text
3429 function magicISBN( $text ) {
3430 $fname = 'Parser::magicISBN';
3431 wfProfileIn( $fname );
3433 $a = split( 'ISBN ', ' '.$text );
3434 if ( count ( $a ) < 2 ) {
3435 wfProfileOut( $fname );
3438 $text = substr( array_shift( $a ), 1);
3439 $valid = '0123456789-Xx';
3441 foreach ( $a as $x ) {
3442 # hack: don't replace inside thumbnail title/alt
3444 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3449 $isbn = $blank = '' ;
3450 while ( ' ' == $x{0} ) {
3452 $x = substr( $x, 1 );
3454 if ( $x == '' ) { # blank isbn
3455 $text .= "ISBN $blank";
3458 while ( strstr( $valid, $x{0} ) != false ) {
3460 $x = substr( $x, 1 );
3462 $num = str_replace( '-', '', $isbn );
3463 $num = str_replace( ' ', '', $num );
3464 $num = str_replace( 'x', 'X', $num );
3467 $text .= "ISBN $blank$x";
3469 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3470 $text .= '<a href="' .
3471 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3472 "\" class=\"internal\">ISBN $isbn</a>";
3476 wfProfileOut( $fname );
3481 * Return an HTML link for the "RFC 1234" text
3484 * @param string $text Text to be processed
3485 * @param string $keyword Magic keyword to use (default RFC)
3486 * @param string $urlmsg Interface message to use (default rfcurl)
3489 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3491 $valid = '0123456789';
3494 $a = split( $keyword, ' '.$text );
3495 if ( count ( $a ) < 2 ) {
3498 $text = substr( array_shift( $a ), 1);
3500 /* Check if keyword is preceed by [[.
3501 * This test is made here cause of the array_shift above
3502 * that prevent the test to be done in the foreach.
3504 if ( substr( $text, -2 ) == '[[' ) {
3508 foreach ( $a as $x ) {
3509 /* token might be empty if we have RFC RFC 1234 */
3515 # hack: don't replace inside thumbnail title/alt
3517 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3518 $text .= $keyword . $x;
3524 /** remove and save whitespaces in $blank */
3525 while ( $x{0} == ' ' ) {
3527 $x = substr( $x, 1 );
3530 /** remove and save the rfc number in $id */
3531 while ( strstr( $valid, $x{0} ) != false ) {
3533 $x = substr( $x, 1 );
3537 /* call back stripped spaces*/
3538 $text .= $keyword.$blank.$x;
3539 } elseif( $internal ) {
3541 $text .= $keyword.$id.$x;
3543 /* build the external link*/
3544 $url = wfMsg( $urlmsg, $id);
3545 $sk =& $this->mOptions
->getSkin();
3546 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3547 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3550 /* Check if the next RFC keyword is preceed by [[ */
3551 $internal = ( substr($x,-2) == '[[' );
3557 * Transform wiki markup when saving a page by doing \r\n -> \n
3558 * conversion, substitting signatures, {{subst:}} templates, etc.
3560 * @param string $text the text to transform
3561 * @param Title &$title the Title object for the current article
3562 * @param User &$user the User object describing the current user
3563 * @param ParserOptions $options parsing options
3564 * @param bool $clearState whether to clear the parser state first
3565 * @return string the altered wiki markup
3568 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3569 $this->mOptions
= $options;
3570 $this->mTitle
=& $title;
3571 $this->mOutputType
= OT_WIKI
;
3573 if ( $clearState ) {
3574 $this->clearState();
3577 $stripState = false;
3581 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3582 $text = $this->strip( $text, $stripState, true );
3583 $text = $this->pstPass2( $text, $stripState, $user );
3584 $text = $this->unstrip( $text, $stripState );
3585 $text = $this->unstripNoWiki( $text, $stripState );
3590 * Pre-save transform helper function
3593 function pstPass2( $text, &$stripState, &$user ) {
3594 global $wgContLang, $wgLocaltimezone;
3596 /* Note: This is the timestamp saved as hardcoded wikitext to
3597 * the database, we use $wgContLang here in order to give
3598 * everyone the same signature and use the default one rather
3599 * than the one selected in each user's preferences.
3601 if ( isset( $wgLocaltimezone ) ) {
3602 $oldtz = getenv( 'TZ' );
3603 putenv( 'TZ='.$wgLocaltimezone );
3605 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3606 ' (' . date( 'T' ) . ')';
3607 if ( isset( $wgLocaltimezone ) ) {
3608 putenv( 'TZ='.$oldtz );
3611 # Variable replacement
3612 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3613 $text = $this->replaceVariables( $text );
3615 # Strip out <nowiki> etc. added via replaceVariables
3616 $text = $this->strip( $text, $stripState );
3619 $sigText = $this->getUserSig( $user );
3620 $text = strtr( $text, array(
3622 '~~~~' => "$sigText $d",
3626 # Context links: [[|name]] and [[name (context)|]]
3628 global $wgLegalTitleChars;
3629 $tc = "[$wgLegalTitleChars]";
3630 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3632 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3633 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3635 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3636 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3637 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3638 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3640 $t = $this->mTitle
->getText();
3641 if ( preg_match( $conpat, $t, $m ) ) {
3644 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3645 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3646 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3648 if ( '' == $context ) {
3649 $text = preg_replace( $p2, '[[\\1]]', $text );
3651 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3654 # Trim trailing whitespace
3655 # MAG_END (__END__) tag allows for trailing
3656 # whitespace to be deliberately included
3657 $text = rtrim( $text );
3658 $mw =& MagicWord
::get( MAG_END
);
3659 $mw->matchAndRemove( $text );
3665 * Fetch the user's signature text, if any, and normalize to
3666 * validated, ready-to-insert wikitext.
3672 function getUserSig( &$user ) {
3673 $username = $user->getName();
3674 $nickname = $user->getOption( 'nickname' );
3675 $nickname = $nickname === '' ?
$username : $nickname;
3677 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3678 # Sig. might contain markup; validate this
3679 if( $this->validateSig( $nickname ) !== false ) {
3680 # Validated; clean up (if needed) and return it
3681 return $this->cleanSig( $nickname, true );
3683 # Failed to validate; fall back to the default
3684 $nickname = $username;
3685 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3689 # If we're still here, make it a link to the user page
3690 $userpage = $user->getUserPage();
3691 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3695 * Check that the user's signature contains no bad XML
3697 * @param string $text
3698 * @return mixed An expanded string, or false if invalid.
3700 function validateSig( $text ) {
3701 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3705 * Clean up signature text
3707 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3708 * 2) Substitute all transclusions
3710 * @param string $text
3711 * @param $parsing Whether we're cleaning (preferences save) or parsing
3712 * @return string Signature text
3714 function cleanSig( $text, $parsing = false ) {
3716 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3718 $substWord = MagicWord
::get( MAG_SUBST
);
3719 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3720 $substText = '{{' . $substWord->getSynonym( 0 );
3722 $text = preg_replace( $substRegex, $substText, $text );
3723 $text = preg_replace( '/~{3,5}/', '', $text );
3724 $text = $this->replaceVariables( $text );
3726 $this->clearState();
3731 * Set up some variables which are usually set up in parse()
3732 * so that an external function can call some class members with confidence
3735 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3736 $this->mTitle
=& $title;
3737 $this->mOptions
= $options;
3738 $this->mOutputType
= $outputType;
3739 if ( $clearState ) {
3740 $this->clearState();
3745 * Transform a MediaWiki message by replacing magic variables.
3747 * @param string $text the text to transform
3748 * @param ParserOptions $options options
3749 * @return string the text with variables substituted
3752 function transformMsg( $text, $options ) {
3754 static $executing = false;
3756 $fname = "Parser::transformMsg";
3758 # Guard against infinite recursion
3764 wfProfileIn($fname);
3766 $this->mTitle
= $wgTitle;
3767 $this->mOptions
= $options;
3768 $this->mOutputType
= OT_MSG
;
3769 $this->clearState();
3770 $text = $this->replaceVariables( $text );
3773 wfProfileOut($fname);
3778 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3779 * The callback should have the following form:
3780 * function myParserHook( $text, $params, &$parser ) { ... }
3782 * Transform and return $text. Use $parser for any required context, e.g. use
3783 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3787 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3788 * @param mixed $callback The callback function (and object) to use for the tag
3790 * @return The old value of the mTagHooks array associated with the hook
3792 function setHook( $tag, $callback ) {
3793 $tag = strtolower( $tag );
3794 $oldVal = @$this->mTagHooks
[$tag];
3795 $this->mTagHooks
[$tag] = $callback;
3801 * Create a function, e.g. {{sum:1|2|3}}
3802 * The callback function should have the form:
3803 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3805 * The callback may either return the text result of the function, or an array with the text
3806 * in element 0, and a number of flags in the other elements. The names of the flags are
3807 * specified in the keys. Valid flags are:
3808 * found The text returned is valid, stop processing the template. This
3810 * nowiki Wiki markup in the return value should be escaped
3811 * noparse Unsafe HTML tags should not be stripped, etc.
3812 * noargs Don't replace triple-brace arguments in the return value
3813 * isHTML The returned text is HTML, armour it against wikitext transformation
3817 * @param string $name The function name. Function names are case-insensitive.
3818 * @param mixed $callback The callback function (and object) to use
3820 * @return The old callback function for this name, if any
3822 function setFunctionHook( $name, $callback ) {
3823 $name = strtolower( $name );
3824 $oldVal = @$this->mFunctionHooks
[$name];
3825 $this->mFunctionHooks
[$name] = $callback;
3830 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3831 * Placeholders created in Skin::makeLinkObj()
3832 * Returns an array of links found, indexed by PDBK:
3836 * $options is a bit field, RLH_FOR_UPDATE to select for update
3838 function replaceLinkHolders( &$text, $options = 0 ) {
3840 global $wgOutputReplace;
3842 $fname = 'Parser::replaceLinkHolders';
3843 wfProfileIn( $fname );
3847 $sk =& $this->mOptions
->getSkin();
3848 $linkCache =& LinkCache
::singleton();
3850 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3851 wfProfileIn( $fname.'-check' );
3852 $dbr =& wfGetDB( DB_SLAVE
);
3853 $page = $dbr->tableName( 'page' );
3854 $threshold = $wgUser->getOption('stubthreshold');
3857 asort( $this->mLinkHolders
['namespaces'] );
3861 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3863 $title = $this->mLinkHolders
['titles'][$key];
3865 # Skip invalid entries.
3866 # Result will be ugly, but prevents crash.
3867 if ( is_null( $title ) ) {
3870 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3872 # Check if it's a static known link, e.g. interwiki
3873 if ( $title->isAlwaysKnown() ) {
3874 $colours[$pdbk] = 1;
3875 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3876 $colours[$pdbk] = 1;
3877 $this->mOutput
->addLink( $title, $id );
3878 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3879 $colours[$pdbk] = 0;
3881 # Not in the link cache, add it to the query
3882 if ( !isset( $current ) ) {
3884 $query = "SELECT page_id, page_namespace, page_title";
3885 if ( $threshold > 0 ) {
3886 $query .= ', page_len, page_is_redirect';
3888 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3889 } elseif ( $current != $ns ) {
3891 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3896 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3901 if ( $options & RLH_FOR_UPDATE
) {
3902 $query .= ' FOR UPDATE';
3905 $res = $dbr->query( $query, $fname );
3907 # Fetch data and form into an associative array
3908 # non-existent = broken
3911 while ( $s = $dbr->fetchObject($res) ) {
3912 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3913 $pdbk = $title->getPrefixedDBkey();
3914 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3915 $this->mOutput
->addLink( $title, $s->page_id
);
3917 if ( $threshold > 0 ) {
3918 $size = $s->page_len
;
3919 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3920 $colours[$pdbk] = 1;
3922 $colours[$pdbk] = 2;
3925 $colours[$pdbk] = 1;
3929 wfProfileOut( $fname.'-check' );
3931 # Construct search and replace arrays
3932 wfProfileIn( $fname.'-construct' );
3933 $wgOutputReplace = array();
3934 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3935 $pdbk = $pdbks[$key];
3936 $searchkey = "<!--LINK $key-->";
3937 $title = $this->mLinkHolders
['titles'][$key];
3938 if ( empty( $colours[$pdbk] ) ) {
3939 $linkCache->addBadLinkObj( $title );
3940 $colours[$pdbk] = 0;
3941 $this->mOutput
->addLink( $title, 0 );
3942 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3943 $this->mLinkHolders
['texts'][$key],
3944 $this->mLinkHolders
['queries'][$key] );
3945 } elseif ( $colours[$pdbk] == 1 ) {
3946 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3947 $this->mLinkHolders
['texts'][$key],
3948 $this->mLinkHolders
['queries'][$key] );
3949 } elseif ( $colours[$pdbk] == 2 ) {
3950 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3951 $this->mLinkHolders
['texts'][$key],
3952 $this->mLinkHolders
['queries'][$key] );
3955 wfProfileOut( $fname.'-construct' );
3958 wfProfileIn( $fname.'-replace' );
3960 $text = preg_replace_callback(
3961 '/(<!--LINK .*?-->)/',
3962 "wfOutputReplaceMatches",
3965 wfProfileOut( $fname.'-replace' );
3968 # Now process interwiki link holders
3969 # This is quite a bit simpler than internal links
3970 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3971 wfProfileIn( $fname.'-interwiki' );
3972 # Make interwiki link HTML
3973 $wgOutputReplace = array();
3974 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3975 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3976 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3979 $text = preg_replace_callback(
3980 '/<!--IWLINK (.*?)-->/',
3981 "wfOutputReplaceMatches",
3983 wfProfileOut( $fname.'-interwiki' );
3986 wfProfileOut( $fname );
3991 * Replace <!--LINK--> link placeholders with plain text of links
3992 * (not HTML-formatted).
3993 * @param string $text
3996 function replaceLinkHoldersText( $text ) {
3997 $fname = 'Parser::replaceLinkHoldersText';
3998 wfProfileIn( $fname );
4000 $text = preg_replace_callback(
4001 '/<!--(LINK|IWLINK) (.*?)-->/',
4002 array( &$this, 'replaceLinkHoldersTextCallback' ),
4005 wfProfileOut( $fname );
4010 * @param array $matches
4014 function replaceLinkHoldersTextCallback( $matches ) {
4015 $type = $matches[1];
4017 if( $type == 'LINK' ) {
4018 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4019 return $this->mLinkHolders
['texts'][$key];
4021 } elseif( $type == 'IWLINK' ) {
4022 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4023 return $this->mInterwikiLinkHolders
['texts'][$key];
4030 * Tag hook handler for 'pre'.
4032 function renderPreTag( $text, $attribs, $parser ) {
4033 // Backwards-compatibility hack
4034 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4036 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4037 return wfOpenElement( 'pre', $attribs ) .
4038 wfEscapeHTMLTagsOnly( $content ) .
4043 * Renders an image gallery from a text with one line per image.
4044 * text labels may be given by using |-style alternative text. E.g.
4045 * Image:one.jpg|The number "1"
4046 * Image:tree.jpg|A tree
4047 * given as text will return the HTML of a gallery with two images,
4048 * labeled 'The number "1"' and
4051 function renderImageGallery( $text ) {
4052 $ig = new ImageGallery();
4053 $ig->setShowBytes( false );
4054 $ig->setShowFilename( false );
4056 $lines = explode( "\n", $text );
4058 foreach ( $lines as $line ) {
4059 # match lines like these:
4060 # Image:someimage.jpg|This is some image
4061 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4063 if ( count( $matches ) == 0 ) {
4066 $nt =& Title
::newFromText( $matches[1] );
4067 if( is_null( $nt ) ) {
4068 # Bogus title. Ignore these so we don't bomb out later.
4071 if ( isset( $matches[3] ) ) {
4072 $label = $matches[3];
4077 $pout = $this->parse( $label,
4080 false, // Strip whitespace...?
4081 false // Don't clear state!
4083 $html = $pout->getText();
4085 $ig->add( new Image( $nt ), $html );
4087 # Only add real images (bug #5586)
4088 if ( $nt->getNamespace() == NS_IMAGE
) {
4089 $this->mOutput
->addImage( $nt->getDBkey() );
4092 return $ig->toHTML();
4096 * Parse image options text and use it to make an image
4098 function makeImage( &$nt, $options ) {
4099 global $wgUseImageResize;
4103 # Check if the options text is of the form "options|alt text"
4105 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4106 # * left no resizing, just left align. label is used for alt= only
4107 # * right same, but right aligned
4108 # * none same, but not aligned
4109 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4110 # * center center the image
4111 # * framed Keep original image size, no magnify-button.
4113 $part = explode( '|', $options);
4115 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4116 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4117 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4118 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4119 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4120 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4121 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4122 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4125 $width = $height = $framed = $thumb = false;
4126 $manual_thumb = '' ;
4128 foreach( $part as $key => $val ) {
4129 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4131 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4132 # use manually specified thumbnail
4134 $manual_thumb = $match;
4135 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4136 # remember to set an alignment, don't render immediately
4138 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4139 # remember to set an alignment, don't render immediately
4141 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4142 # remember to set an alignment, don't render immediately
4144 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4145 # remember to set an alignment, don't render immediately
4147 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4148 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4149 # $match is the image width in pixels
4150 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4151 $width = intval( $m[1] );
4152 $height = intval( $m[2] );
4154 $width = intval($match);
4156 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4162 # Strip bad stuff out of the alt text
4163 $alt = $this->replaceLinkHoldersText( $caption );
4165 # make sure there are no placeholders in thumbnail attributes
4166 # that are later expanded to html- so expand them now and
4168 $alt = $this->unstrip($alt, $this->mStripState
);
4169 $alt = Sanitizer
::stripAllTags( $alt );
4171 # Linker does the rest
4172 $sk =& $this->mOptions
->getSkin();
4173 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4177 * Set a flag in the output object indicating that the content is dynamic and
4178 * shouldn't be cached.
4180 function disableCache() {
4181 wfDebug( "Parser output marked as uncacheable.\n" );
4182 $this->mOutput
->mCacheTime
= -1;
4186 * Callback from the Sanitizer for expanding items found in HTML attribute
4187 * values, so they can be safely tested and escaped.
4188 * @param string $text
4189 * @param array $args
4193 function attributeStripCallback( &$text, $args ) {
4194 $text = $this->replaceVariables( $text, $args );
4195 $text = $this->unstripForHTML( $text );
4199 function unstripForHTML( $text ) {
4200 $text = $this->unstrip( $text, $this->mStripState
);
4201 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4209 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4210 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4211 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4217 function getTags() { return array_keys( $this->mTagHooks
); }
4222 * Break wikitext input into sections, and either pull or replace
4223 * some particular section's text.
4225 * External callers should use the getSection and replaceSection methods.
4227 * @param $text Page wikitext
4228 * @param $section Numbered section. 0 pulls the text before the first
4229 * heading; other numbers will pull the given section
4230 * along with its lower-level subsections.
4231 * @param $mode One of "get" or "replace"
4232 * @param $newtext Replacement text for section data.
4233 * @return string for "get", the extracted section text.
4234 * for "replace", the whole page with the section replaced.
4236 private function extractSections( $text, $section, $mode, $newtext='' ) {
4237 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4238 # comments to be stripped as well)
4239 $striparray = array();
4241 $oldOutputType = $this->mOutputType
;
4242 $oldOptions = $this->mOptions
;
4243 $this->mOptions
= new ParserOptions();
4244 $this->mOutputType
= OT_WIKI
;
4246 $striptext = $this->strip( $text, $striparray, true );
4248 $this->mOutputType
= $oldOutputType;
4249 $this->mOptions
= $oldOptions;
4251 # now that we can be sure that no pseudo-sections are in the source,
4252 # split it up by section
4253 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4254 $comment = "(?:$uniq-!--.*?QINU)";
4259 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4261 (=+) # Should this be limited to 6?
4262 .+? # Section title...
4263 \\2 # Ending = count must match start
4270 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4277 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4278 (=+) # Should this be limited to 6?
4279 .+? # Section title...
4280 \\2 # Ending = count must match start
4281 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4290 PREG_SPLIT_DELIM_CAPTURE
);
4292 if( $mode == "get" ) {
4293 if( $section == 0 ) {
4294 // "Section 0" returns the content before any other section.
4299 } elseif( $mode == "replace" ) {
4300 if( $section == 0 ) {
4301 $rv = $newtext . "\n\n";
4310 for( $index = 1; $index < count( $secs ); ) {
4311 $headerLine = $secs[$index++
];
4312 if( $secs[$index] ) {
4314 $headerLevel = strlen( $secs[$index++
] );
4318 $headerLevel = intval( $secs[$index++
] );
4320 $content = $secs[$index++
];
4323 if( $mode == "get" ) {
4324 if( $count == $section ) {
4325 $rv = $headerLine . $content;
4326 $sectionLevel = $headerLevel;
4327 } elseif( $count > $section ) {
4328 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4329 $rv .= $headerLine . $content;
4331 // Broke out to a higher-level section
4335 } elseif( $mode == "replace" ) {
4336 if( $count < $section ) {
4337 $rv .= $headerLine . $content;
4338 } elseif( $count == $section ) {
4339 $rv .= $newtext . "\n\n";
4340 $sectionLevel = $headerLevel;
4341 } elseif( $count > $section ) {
4342 if( $headerLevel <= $sectionLevel ) {
4343 // Passed the section's sub-parts.
4347 $rv .= $headerLine . $content;
4352 # reinsert stripped tags
4353 $rv = $this->unstrip( $rv, $striparray );
4354 $rv = $this->unstripNoWiki( $rv, $striparray );
4360 * This function returns the text of a section, specified by a number ($section).
4361 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4362 * the first section before any such heading (section 0).
4364 * If a section contains subsections, these are also returned.
4366 * @param $text String: text to look in
4367 * @param $section Integer: section number
4368 * @return string text of the requested section
4370 function getSection( $text, $section ) {
4371 return $this->extractSections( $text, $section, "get" );
4374 function replaceSection( $oldtext, $section, $text ) {
4375 return $this->extractSections( $oldtext, $section, "replace", $text );
4382 * @package MediaWiki
4386 var $mText, # The output text
4387 $mLanguageLinks, # List of the full text of language links, in the order they appear
4388 $mCategories, # Map of category names to sort keys
4389 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4390 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4391 $mVersion, # Compatibility check
4392 $mTitleText, # title text of the chosen language variant
4393 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4394 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4395 $mImages, # DB keys of the images used, in the array key only
4396 $mExternalLinks, # External link URLs, in the key only
4397 $mHTMLtitle, # Display HTML title
4398 $mSubtitle, # Additional subtitle
4399 $mNewSection; # Show a new section link?
4401 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4402 $containsOldMagic = false, $titletext = '' )
4404 $this->mText
= $text;
4405 $this->mLanguageLinks
= $languageLinks;
4406 $this->mCategories
= $categoryLinks;
4407 $this->mContainsOldMagic
= $containsOldMagic;
4408 $this->mCacheTime
= '';
4409 $this->mVersion
= MW_PARSER_VERSION
;
4410 $this->mTitleText
= $titletext;
4411 $this->mLinks
= array();
4412 $this->mTemplates
= array();
4413 $this->mImages
= array();
4414 $this->mExternalLinks
= array();
4415 $this->mHTMLtitle
= "" ;
4416 $this->mSubtitle
= "" ;
4417 $this->mNewSection
= false;
4420 function getText() { return $this->mText
; }
4421 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4422 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4423 function &getCategories() { return $this->mCategories
; }
4424 function getCacheTime() { return $this->mCacheTime
; }
4425 function getTitleText() { return $this->mTitleText
; }
4426 function &getLinks() { return $this->mLinks
; }
4427 function &getTemplates() { return $this->mTemplates
; }
4428 function &getImages() { return $this->mImages
; }
4429 function &getExternalLinks() { return $this->mExternalLinks
; }
4431 function containsOldMagic() { return $this->mContainsOldMagic
; }
4432 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4433 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4434 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4435 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4436 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4437 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4439 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4440 function addImage( $name ) { $this->mImages
[$name] = 1; }
4441 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4442 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4444 function setNewSection( $value ) {
4445 $this->mNewSection
= (bool)$value;
4447 function getNewSection() {
4448 return (bool)$this->mNewSection
;
4451 function addLink( $title, $id ) {
4452 $ns = $title->getNamespace();
4453 $dbk = $title->getDBkey();
4454 if ( !isset( $this->mLinks
[$ns] ) ) {
4455 $this->mLinks
[$ns] = array();
4457 $this->mLinks
[$ns][$dbk] = $id;
4460 function addTemplate( $title, $id ) {
4461 $ns = $title->getNamespace();
4462 $dbk = $title->getDBkey();
4463 if ( !isset( $this->mTemplates
[$ns] ) ) {
4464 $this->mTemplates
[$ns] = array();
4466 $this->mTemplates
[$ns][$dbk] = $id;
4470 * Return true if this cached output object predates the global or
4471 * per-article cache invalidation timestamps, or if it comes from
4472 * an incompatible older version.
4474 * @param string $touched the affected article's last touched timestamp
4478 function expired( $touched ) {
4479 global $wgCacheEpoch;
4480 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4481 $this->getCacheTime() < $touched ||
4482 $this->getCacheTime() <= $wgCacheEpoch ||
4483 !isset( $this->mVersion
) ||
4484 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4489 * Set options of the Parser
4491 * @package MediaWiki
4495 # All variables are private
4496 var $mUseTeX; # Use texvc to expand <math> tags
4497 var $mUseDynamicDates; # Use DateFormatter to format dates
4498 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4499 var $mAllowExternalImages; # Allow external images inline
4500 var $mAllowExternalImagesFrom; # If not, any exception?
4501 var $mSkin; # Reference to the preferred skin
4502 var $mDateFormat; # Date format index
4503 var $mEditSection; # Create "edit section" links
4504 var $mNumberHeadings; # Automatically number headings
4505 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4506 var $mTidy; # Ask for tidy cleanup
4507 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4509 function getUseTeX() { return $this->mUseTeX
; }
4510 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4511 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4512 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4513 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4514 function &getSkin() { return $this->mSkin
; }
4515 function getDateFormat() { return $this->mDateFormat
; }
4516 function getEditSection() { return $this->mEditSection
; }
4517 function getNumberHeadings() { return $this->mNumberHeadings
; }
4518 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4519 function getTidy() { return $this->mTidy
; }
4520 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4522 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4523 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4524 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4525 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4526 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4527 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4528 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4529 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4530 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4531 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4532 function setSkin( &$x ) { $this->mSkin
=& $x; }
4533 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4535 function ParserOptions() {
4537 $this->initialiseFromUser( $wgUser );
4541 * Get parser options
4544 function newFromUser( &$user ) {
4545 $popts = new ParserOptions
;
4546 $popts->initialiseFromUser( $user );
4550 /** Get user options */
4551 function initialiseFromUser( &$userInput ) {
4552 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4553 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4554 $fname = 'ParserOptions::initialiseFromUser';
4555 wfProfileIn( $fname );
4556 if ( !$userInput ) {
4558 $user->setLoaded( true );
4560 $user =& $userInput;
4563 $this->mUseTeX
= $wgUseTeX;
4564 $this->mUseDynamicDates
= $wgUseDynamicDates;
4565 $this->mInterwikiMagic
= $wgInterwikiMagic;
4566 $this->mAllowExternalImages
= $wgAllowExternalImages;
4567 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4568 wfProfileIn( $fname.'-skin' );
4569 $this->mSkin
=& $user->getSkin();
4570 wfProfileOut( $fname.'-skin' );
4571 $this->mDateFormat
= $user->getOption( 'date' );
4572 $this->mEditSection
= true;
4573 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4574 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4575 $this->mTidy
= false;
4576 $this->mInterfaceMessage
= false;
4577 wfProfileOut( $fname );
4582 * Callback function used by Parser::replaceLinkHolders()
4583 * to substitute link placeholders.
4585 function &wfOutputReplaceMatches( $matches ) {
4586 global $wgOutputReplace;
4587 return $wgOutputReplace[$matches[1]];
4591 * Return the total number of articles
4593 function wfNumberOfArticles() {
4594 global $wgNumberOfArticles;
4597 return $wgNumberOfArticles;
4601 * Return the number of files
4603 function wfNumberOfFiles() {
4604 $fname = 'wfNumberOfFiles';
4606 wfProfileIn( $fname );
4607 $dbr =& wfGetDB( DB_SLAVE
);
4608 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4609 wfProfileOut( $fname );
4615 * Return the number of user accounts
4618 function wfNumberOfUsers() {
4619 wfProfileIn( 'wfNumberOfUsers' );
4620 $dbr =& wfGetDB( DB_SLAVE
);
4621 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4622 wfProfileOut( 'wfNumberOfUsers' );
4627 * Return the total number of pages
4630 function wfNumberOfPages() {
4631 wfProfileIn( 'wfNumberOfPages' );
4632 $dbr =& wfGetDB( DB_SLAVE
);
4633 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4634 wfProfileOut( 'wfNumberOfPages' );
4639 * Get various statistics from the database
4642 function wfLoadSiteStats() {
4643 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4644 $fname = 'wfLoadSiteStats';
4646 if ( -1 != $wgNumberOfArticles ) return;
4647 $dbr =& wfGetDB( DB_SLAVE
);
4648 $s = $dbr->selectRow( 'site_stats',
4649 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4650 array( 'ss_row_id' => 1 ), $fname
4653 if ( $s === false ) {
4656 $wgTotalViews = $s->ss_total_views
;
4657 $wgTotalEdits = $s->ss_total_edits
;
4658 $wgNumberOfArticles = $s->ss_good_articles
;
4664 * Basically replacing " > and < with HTML entities ( ", >, <)
4666 * @param $in String: text that might contain HTML tags.
4667 * @return string Escaped string
4669 function wfEscapeHTMLTagsOnly( $in ) {
4671 array( '"', '>', '<' ),
4672 array( '"', '>', '<' ),