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();
142 function clearState() {
143 $this->mOutput
= new ParserOutput
;
144 $this->mAutonumber
= 0;
145 $this->mLastSection
= '';
146 $this->mDTopen
= false;
147 $this->mVariables
= false;
148 $this->mIncludeCount
= array();
149 $this->mStripState
= array();
150 $this->mArgStack
= array();
151 $this->mInPre
= false;
152 $this->mInterwikiLinkHolders
= array(
156 $this->mLinkHolders
= array(
157 'namespaces' => array(),
159 'queries' => array(),
163 $this->mRevisionId
= null;
166 * Prefix for temporary replacement strings for the multipass parser.
167 * \x07 should never appear in input as it's disallowed in XML.
168 * Using it at the front also gives us a little extra robustness
169 * since it shouldn't match when butted up against identifier-like
172 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
174 # Clear these on every parse, bug 4549
175 $this->mTemplates
= array();
176 $this->mTemplatePath
= array();
178 $this->mShowToc
= true;
179 $this->mForceTocPosition
= false;
181 wfRunHooks( 'ParserClearState', array( &$this ) );
185 * Accessor for mUniqPrefix.
189 function UniqPrefix() {
190 return $this->mUniqPrefix
;
194 * Convert wikitext to HTML
195 * Do not call this function recursively.
198 * @param string $text Text we want to parse
199 * @param Title &$title A title object
200 * @param array $options
201 * @param boolean $linestart
202 * @param boolean $clearState
203 * @param int $revid number to pass in {{REVISIONID}}
204 * @return ParserOutput a ParserOutput
206 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
208 * First pass--just handle <nowiki> sections, pass the rest off
209 * to internalParse() which does all the real work.
212 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
213 $fname = 'Parser::parse';
214 wfProfileIn( $fname );
220 $this->mOptions
= $options;
221 $this->mTitle
=& $title;
222 $this->mRevisionId
= $revid;
223 $this->mOutputType
= OT_HTML
;
225 //$text = $this->strip( $text, $this->mStripState );
226 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
227 $x =& $this->mStripState
;
229 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
230 $text = $this->strip( $text, $x );
231 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
233 # Hook to suspend the parser in this state
234 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
235 wfProfileOut( $fname );
239 $text = $this->internalParse( $text );
241 $text = $this->unstrip( $text, $this->mStripState
);
243 # Clean up special characters, only run once, next-to-last before doBlockLevels
245 # french spaces, last one Guillemet-left
246 # only if there is something before the space
247 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
248 # french spaces, Guillemet-right
249 '/(\\302\\253) /' => '\\1 ',
250 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
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', 'pre', '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 // Backwards-compatibility hack
468 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $content );
469 $output = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
472 $output = $this->renderImageGallery( $content );
475 if( isset( $this->mTagHooks
[$tagName] ) ) {
476 $output = call_user_func_array( $this->mTagHooks
[$tagName],
477 array( $content, $params, $this ) );
479 wfDebugDieBacktrace( "Invalid call hook $element" );
483 // Just stripping tags; keep the source
486 if( !$stripcomments && $element == '!--' ) {
487 $commentState[$marker] = $output;
489 $state[$element][$marker] = $output;
493 # Unstrip comments unless explicitly told otherwise.
494 # (The comments are always stripped prior to this point, so as to
495 # not invoke any extension tags / parser hooks contained within
497 if ( !$stripcomments ) {
498 // Put them all back and forget them
499 $text = strtr( $text, $commentState );
506 * Restores pre, math, and other extensions removed by strip()
508 * always call unstripNoWiki() after this one
511 function unstrip( $text, &$state ) {
512 if ( !is_array( $state ) ) {
516 $replacements = array();
517 foreach( $state as $tag => $contentDict ) {
518 if( $tag != 'nowiki' && $tag != 'html' ) {
519 foreach( $contentDict as $uniq => $content ) {
520 $replacements[$uniq] = $content;
524 $text = strtr( $text, $replacements );
530 * Always call this after unstrip() to preserve the order
534 function unstripNoWiki( $text, &$state ) {
535 if ( !is_array( $state ) ) {
539 $replacements = array();
540 foreach( $state as $tag => $contentDict ) {
541 if( $tag == 'nowiki' ||
$tag == 'html' ) {
542 foreach( $contentDict as $uniq => $content ) {
543 $replacements[$uniq] = $content;
547 $text = strtr( $text, $replacements );
553 * Add an item to the strip state
554 * Returns the unique tag which must be inserted into the stripped text
555 * The tag will be replaced with the original text in unstrip()
559 function insertStripItem( $text, &$state ) {
560 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
564 $state['item'][$rnd] = $text;
569 * Interface with html tidy, used if $wgUseTidy = true.
570 * If tidy isn't able to correct the markup, the original will be
571 * returned in all its glory with a warning comment appended.
573 * Either the external tidy program or the in-process tidy extension
574 * will be used depending on availability. Override the default
575 * $wgTidyInternal setting to disable the internal if it's not working.
577 * @param string $text Hideous HTML input
578 * @return string Corrected HTML output
582 function tidy( $text ) {
583 global $wgTidyInternal;
584 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
585 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
586 '<head><title>test</title></head><body>'.$text.'</body></html>';
587 if( $wgTidyInternal ) {
588 $correctedtext = Parser
::internalTidy( $wrappedtext );
590 $correctedtext = Parser
::externalTidy( $wrappedtext );
592 if( is_null( $correctedtext ) ) {
593 wfDebug( "Tidy error detected!\n" );
594 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
596 return $correctedtext;
600 * Spawn an external HTML tidy process and get corrected markup back from it.
605 function externalTidy( $text ) {
606 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
607 $fname = 'Parser::externalTidy';
608 wfProfileIn( $fname );
613 $descriptorspec = array(
614 0 => array('pipe', 'r'),
615 1 => array('pipe', 'w'),
616 2 => array('file', '/dev/null', 'a')
619 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
620 if (is_resource($process)) {
621 // Theoretically, this style of communication could cause a deadlock
622 // here. If the stdout buffer fills up, then writes to stdin could
623 // block. This doesn't appear to happen with tidy, because tidy only
624 // writes to stdout after it's finished reading from stdin. Search
625 // for tidyParseStdin and tidySaveStdout in console/tidy.c
626 fwrite($pipes[0], $text);
628 while (!feof($pipes[1])) {
629 $cleansource .= fgets($pipes[1], 1024);
632 proc_close($process);
635 wfProfileOut( $fname );
637 if( $cleansource == '' && $text != '') {
638 // Some kind of error happened, so we couldn't get the corrected text.
639 // Just give up; we'll use the source text and append a warning.
647 * Use the HTML tidy PECL extension to use the tidy library in-process,
648 * saving the overhead of spawning a new process. Currently written to
649 * the PHP 4.3.x version of the extension, may not work on PHP 5.
651 * 'pear install tidy' should be able to compile the extension module.
656 function internalTidy( $text ) {
658 $fname = 'Parser::internalTidy';
659 wfProfileIn( $fname );
661 tidy_load_config( $wgTidyConf );
662 tidy_set_encoding( 'utf8' );
663 tidy_parse_string( $text );
665 if( tidy_get_status() == 2 ) {
666 // 2 is magic number for fatal error
667 // http://www.php.net/manual/en/function.tidy-get-status.php
670 $cleansource = tidy_get_output();
672 wfProfileOut( $fname );
677 * parse the wiki syntax used to render tables
681 function doTableStuff ( $t ) {
682 $fname = 'Parser::doTableStuff';
683 wfProfileIn( $fname );
685 $t = explode ( "\n" , $t ) ;
686 $td = array () ; # Is currently a td tag open?
687 $ltd = array () ; # Was it TD or TH?
688 $tr = array () ; # Is currently a tr tag open?
689 $ltr = array () ; # tr attributes
690 $has_opened_tr = array(); # Did this table open a <tr> element?
691 $indent_level = 0; # indent level of the table
692 foreach ( $t AS $k => $x )
695 $fc = substr ( $x , 0 , 1 ) ;
696 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
697 $indent_level = strlen( $matches[1] );
699 $attributes = $this->unstripForHTML( $matches[2] );
701 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
702 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
703 array_push ( $td , false ) ;
704 array_push ( $ltd , '' ) ;
705 array_push ( $tr , false ) ;
706 array_push ( $ltr , '' ) ;
707 array_push ( $has_opened_tr, false );
709 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
710 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
711 $z = "</table>" . substr ( $x , 2);
712 $l = array_pop ( $ltd ) ;
713 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
714 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
715 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
717 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
719 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
720 $x = substr ( $x , 1 ) ;
721 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
723 $l = array_pop ( $ltd ) ;
724 array_pop ( $has_opened_tr );
725 array_push ( $has_opened_tr , true ) ;
726 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
727 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
730 array_push ( $tr , false ) ;
731 array_push ( $td , false ) ;
732 array_push ( $ltd , '' ) ;
733 $attributes = $this->unstripForHTML( $x );
734 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
736 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
738 if ( '|+' == substr ( $x , 0 , 2 ) ) {
740 $x = substr ( $x , 1 ) ;
742 $after = substr ( $x , 1 ) ;
743 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
745 // Split up multiple cells on the same line.
746 // FIXME: This can result in improper nesting of tags processed
747 // by earlier parser steps, but should avoid splitting up eg
748 // attribute values containing literal "||".
749 $after = wfExplodeMarkup( '||', $after );
753 # Loop through each table cell
754 foreach ( $after AS $theline )
759 $tra = array_pop ( $ltr ) ;
760 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
761 array_push ( $tr , true ) ;
762 array_push ( $ltr , '' ) ;
763 array_pop ( $has_opened_tr );
764 array_push ( $has_opened_tr , true ) ;
767 $l = array_pop ( $ltd ) ;
768 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
769 if ( $fc == '|' ) $l = 'td' ;
770 else if ( $fc == '!' ) $l = 'th' ;
771 else if ( $fc == '+' ) $l = 'caption' ;
773 array_push ( $ltd , $l ) ;
776 $y = explode ( '|' , $theline , 2 ) ;
777 # Note that a '|' inside an invalid link should not
778 # be mistaken as delimiting cell parameters
779 if ( strpos( $y[0], '[[' ) !== false ) {
780 $y = array ($theline);
782 if ( count ( $y ) == 1 )
783 $y = "{$z}<{$l}>{$y[0]}" ;
785 $attributes = $this->unstripForHTML( $y[0] );
786 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
789 array_push ( $td , true ) ;
794 # Closing open td, tr && table
795 while ( count ( $td ) > 0 )
797 $l = array_pop ( $ltd ) ;
798 if ( array_pop ( $td ) ) $t[] = '</td>' ;
799 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
800 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
804 $t = implode ( "\n" , $t ) ;
805 # special case: don't return empty table
806 if($t == "<table>\n<tr><td></td></tr>\n</table>")
808 wfProfileOut( $fname );
813 * Helper function for parse() that transforms wiki markup into
814 * HTML. Only called for $mOutputType == OT_HTML.
818 function internalParse( $text ) {
821 $fname = 'Parser::internalParse';
822 wfProfileIn( $fname );
824 # Remove <noinclude> tags and <includeonly> sections
825 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
826 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
827 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
829 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
831 $text = $this->replaceVariables( $text, $args );
833 // Tables need to come after variable replacement for things to work
834 // properly; putting them before other transformations should keep
835 // exciting things like link expansions from showing up in surprising
837 $text = $this->doTableStuff( $text );
839 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
841 $text = $this->stripToc( $text );
842 $text = $this->doHeadings( $text );
843 if($this->mOptions
->getUseDynamicDates()) {
844 $df =& DateFormatter
::getInstance();
845 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
847 $text = $this->doAllQuotes( $text );
848 $text = $this->replaceInternalLinks( $text );
849 $text = $this->replaceExternalLinks( $text );
851 # replaceInternalLinks may sometimes leave behind
852 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
853 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
855 $text = $this->doMagicLinks( $text );
856 $text = $this->formatHeadings( $text, $isMain );
858 wfProfileOut( $fname );
863 * Replace special strings like "ISBN xxx" and "RFC xxx" with
864 * magic external links.
868 function &doMagicLinks( &$text ) {
869 $text = $this->magicISBN( $text );
870 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
871 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
876 * Parse headers and return html
880 function doHeadings( $text ) {
881 $fname = 'Parser::doHeadings';
882 wfProfileIn( $fname );
883 for ( $i = 6; $i >= 1; --$i ) {
884 $h = str_repeat( '=', $i );
885 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
886 "<h{$i}>\\1</h{$i}>\\2", $text );
888 wfProfileOut( $fname );
893 * Replace single quotes with HTML markup
895 * @return string the altered text
897 function doAllQuotes( $text ) {
898 $fname = 'Parser::doAllQuotes';
899 wfProfileIn( $fname );
901 $lines = explode( "\n", $text );
902 foreach ( $lines as $line ) {
903 $outtext .= $this->doQuotes ( $line ) . "\n";
905 $outtext = substr($outtext, 0,-1);
906 wfProfileOut( $fname );
911 * Helper function for doAllQuotes()
914 function doQuotes( $text ) {
915 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
916 if ( count( $arr ) == 1 )
920 # First, do some preliminary work. This may shift some apostrophes from
921 # being mark-up to being text. It also counts the number of occurrences
922 # of bold and italics mark-ups.
926 foreach ( $arr as $r )
928 if ( ( $i %
2 ) == 1 )
930 # If there are ever four apostrophes, assume the first is supposed to
931 # be text, and the remaining three constitute mark-up for bold text.
932 if ( strlen( $arr[$i] ) == 4 )
937 # If there are more than 5 apostrophes in a row, assume they're all
938 # text except for the last 5.
939 else if ( strlen( $arr[$i] ) > 5 )
941 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
944 # Count the number of occurrences of bold and italics mark-ups.
945 # We are not counting sequences of five apostrophes.
946 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
947 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
948 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
953 # If there is an odd number of both bold and italics, it is likely
954 # that one of the bold ones was meant to be an apostrophe followed
955 # by italics. Which one we cannot know for certain, but it is more
956 # likely to be one that has a single-letter word before it.
957 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
960 $firstsingleletterword = -1;
961 $firstmultiletterword = -1;
963 foreach ( $arr as $r )
965 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
967 $x1 = substr ($arr[$i-1], -1);
968 $x2 = substr ($arr[$i-1], -2, 1);
970 if ($firstspace == -1) $firstspace = $i;
971 } else if ($x2 == ' ') {
972 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
974 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
980 # If there is a single-letter word, use it!
981 if ($firstsingleletterword > -1)
983 $arr [ $firstsingleletterword ] = "''";
984 $arr [ $firstsingleletterword-1 ] .= "'";
986 # If not, but there's a multi-letter word, use that one.
987 else if ($firstmultiletterword > -1)
989 $arr [ $firstmultiletterword ] = "''";
990 $arr [ $firstmultiletterword-1 ] .= "'";
992 # ... otherwise use the first one that has neither.
993 # (notice that it is possible for all three to be -1 if, for example,
994 # there is only one pentuple-apostrophe in the line)
995 else if ($firstspace > -1)
997 $arr [ $firstspace ] = "''";
998 $arr [ $firstspace-1 ] .= "'";
1002 # Now let's actually convert our apostrophic mush to HTML!
1007 foreach ($arr as $r)
1011 if ($state == 'both')
1018 if (strlen ($r) == 2)
1021 { $output .= '</i>'; $state = ''; }
1022 else if ($state == 'bi')
1023 { $output .= '</i>'; $state = 'b'; }
1024 else if ($state == 'ib')
1025 { $output .= '</b></i><b>'; $state = 'b'; }
1026 else if ($state == 'both')
1027 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1028 else # $state can be 'b' or ''
1029 { $output .= '<i>'; $state .= 'i'; }
1031 else if (strlen ($r) == 3)
1034 { $output .= '</b>'; $state = ''; }
1035 else if ($state == 'bi')
1036 { $output .= '</i></b><i>'; $state = 'i'; }
1037 else if ($state == 'ib')
1038 { $output .= '</b>'; $state = 'i'; }
1039 else if ($state == 'both')
1040 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1041 else # $state can be 'i' or ''
1042 { $output .= '<b>'; $state .= 'b'; }
1044 else if (strlen ($r) == 5)
1047 { $output .= '</b><i>'; $state = 'i'; }
1048 else if ($state == 'i')
1049 { $output .= '</i><b>'; $state = 'b'; }
1050 else if ($state == 'bi')
1051 { $output .= '</i></b>'; $state = ''; }
1052 else if ($state == 'ib')
1053 { $output .= '</b></i>'; $state = ''; }
1054 else if ($state == 'both')
1055 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1056 else # ($state == '')
1057 { $buffer = ''; $state = 'both'; }
1062 # Now close all remaining tags. Notice that the order is important.
1063 if ($state == 'b' ||
$state == 'ib')
1065 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1069 if ($state == 'both')
1070 $output .= '<b><i>'.$buffer.'</i></b>';
1076 * Replace external links
1078 * Note: this is all very hackish and the order of execution matters a lot.
1079 * Make sure to run maintenance/parserTests.php if you change this code.
1083 function replaceExternalLinks( $text ) {
1085 $fname = 'Parser::replaceExternalLinks';
1086 wfProfileIn( $fname );
1088 $sk =& $this->mOptions
->getSkin();
1090 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1092 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1095 while ( $i<count( $bits ) ) {
1097 $protocol = $bits[$i++
];
1098 $text = $bits[$i++
];
1099 $trail = $bits[$i++
];
1101 # The characters '<' and '>' (which were escaped by
1102 # removeHTMLtags()) should not be included in
1103 # URLs, per RFC 2396.
1104 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1105 $text = substr($url, $m2[0][1]) . ' ' . $text;
1106 $url = substr($url, 0, $m2[0][1]);
1109 # If the link text is an image URL, replace it with an <img> tag
1110 # This happened by accident in the original parser, but some people used it extensively
1111 $img = $this->maybeMakeExternalImage( $text );
1112 if ( $img !== false ) {
1118 # Set linktype for CSS - if URL==text, link is essentially free
1119 $linktype = ($text == $url) ?
'free' : 'text';
1121 # No link text, e.g. [http://domain.tld/some.link]
1122 if ( $text == '' ) {
1123 # Autonumber if allowed. See bug #5918
1124 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1125 $text = '[' . ++
$this->mAutonumber
. ']';
1126 $linktype = 'autonumber';
1128 # Otherwise just use the URL
1129 $text = htmlspecialchars( $url );
1133 # Have link text, e.g. [http://domain.tld/some.link text]s
1135 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1138 $text = $wgContLang->markNoConversion($text);
1140 # Normalize any HTML entities in input. They will be
1141 # re-escaped by makeExternalLink().
1142 $url = Sanitizer
::decodeCharReferences( $url );
1144 # Process the trail (i.e. everything after this link up until start of the next link),
1145 # replacing any non-bracketed links
1146 $trail = $this->replaceFreeExternalLinks( $trail );
1148 # Use the encoded URL
1149 # This means that users can paste URLs directly into the text
1150 # Funny characters like ö aren't valid in URLs anyway
1151 # This was changed in August 2004
1152 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1154 # Register link in the output object.
1155 # Replace unnecessary URL escape codes with the referenced character
1156 # This prevents spammers from hiding links from the filters
1157 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1158 $this->mOutput
->addExternalLink( $pasteurized );
1161 wfProfileOut( $fname );
1166 * Replace anything that looks like a URL with a link
1169 function replaceFreeExternalLinks( $text ) {
1171 $fname = 'Parser::replaceFreeExternalLinks';
1172 wfProfileIn( $fname );
1174 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1175 $s = array_shift( $bits );
1178 $sk =& $this->mOptions
->getSkin();
1180 while ( $i < count( $bits ) ){
1181 $protocol = $bits[$i++
];
1182 $remainder = $bits[$i++
];
1184 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1185 # Found some characters after the protocol that look promising
1186 $url = $protocol . $m[1];
1189 # special case: handle urls as url args:
1190 # http://www.example.com/foo?=http://www.example.com/bar
1191 if(strlen($trail) == 0 &&
1193 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1194 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1197 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1202 # The characters '<' and '>' (which were escaped by
1203 # removeHTMLtags()) should not be included in
1204 # URLs, per RFC 2396.
1205 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1206 $trail = substr($url, $m2[0][1]) . $trail;
1207 $url = substr($url, 0, $m2[0][1]);
1210 # Move trailing punctuation to $trail
1212 # If there is no left bracket, then consider right brackets fair game too
1213 if ( strpos( $url, '(' ) === false ) {
1217 $numSepChars = strspn( strrev( $url ), $sep );
1218 if ( $numSepChars ) {
1219 $trail = substr( $url, -$numSepChars ) . $trail;
1220 $url = substr( $url, 0, -$numSepChars );
1223 # Normalize any HTML entities in input. They will be
1224 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1225 $url = Sanitizer
::decodeCharReferences( $url );
1227 # Is this an external image?
1228 $text = $this->maybeMakeExternalImage( $url );
1229 if ( $text === false ) {
1230 # Not an image, make a link
1231 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1232 # Register it in the output object...
1233 # Replace unnecessary URL escape codes with their equivalent characters
1234 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1235 $this->mOutput
->addExternalLink( $pasteurized );
1237 $s .= $text . $trail;
1239 $s .= $protocol . $remainder;
1242 wfProfileOut( $fname );
1247 * Replace unusual URL escape codes with their equivalent characters
1251 * @fixme This can merge genuinely required bits in the path or query string,
1252 * breaking legit URLs. A proper fix would treat the various parts of
1253 * the URL differently; as a workaround, just use the output for
1254 * statistical records, not for actual linking/output.
1256 function replaceUnusualEscapes( $url ) {
1257 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1258 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1262 * Callback function used in replaceUnusualEscapes().
1263 * Replaces unusual URL escape codes with their equivalent character
1267 function replaceUnusualEscapesCallback( $matches ) {
1268 $char = urldecode( $matches[0] );
1269 $ord = ord( $char );
1270 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1271 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1272 // No, shouldn't be escaped
1275 // Yes, leave it escaped
1281 * make an image if it's allowed, either through the global
1282 * option or through the exception
1285 function maybeMakeExternalImage( $url ) {
1286 $sk =& $this->mOptions
->getSkin();
1287 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1288 $imagesexception = !empty($imagesfrom);
1290 if ( $this->mOptions
->getAllowExternalImages()
1291 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1292 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1294 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1301 * Process [[ ]] wikilinks
1305 function replaceInternalLinks( $s ) {
1307 static $fname = 'Parser::replaceInternalLinks' ;
1309 wfProfileIn( $fname );
1311 wfProfileIn( $fname.'-setup' );
1313 # the % is needed to support urlencoded titles as well
1314 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1316 $sk =& $this->mOptions
->getSkin();
1318 #split the entire text string on occurences of [[
1319 $a = explode( '[[', ' ' . $s );
1320 #get the first element (all text up to first [[), and remove the space we added
1321 $s = array_shift( $a );
1322 $s = substr( $s, 1 );
1324 # Match a link having the form [[namespace:link|alternate]]trail
1326 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1327 # Match cases where there is no "]]", which might still be images
1328 static $e1_img = FALSE;
1329 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1330 # Match the end of a line for a word that's not followed by whitespace,
1331 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1332 $e2 = wfMsgForContent( 'linkprefix' );
1334 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1336 if( is_null( $this->mTitle
) ) {
1337 wfDebugDieBacktrace( 'nooo' );
1339 $nottalk = !$this->mTitle
->isTalkPage();
1341 if ( $useLinkPrefixExtension ) {
1342 if ( preg_match( $e2, $s, $m ) ) {
1343 $first_prefix = $m[2];
1345 $first_prefix = false;
1351 $selflink = $this->mTitle
->getPrefixedText();
1352 wfProfileOut( $fname.'-setup' );
1354 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1355 $useSubpages = $this->areSubpagesAllowed();
1357 # Loop for each link
1358 for ($k = 0; isset( $a[$k] ); $k++
) {
1360 if ( $useLinkPrefixExtension ) {
1361 wfProfileIn( $fname.'-prefixhandling' );
1362 if ( preg_match( $e2, $s, $m ) ) {
1370 $prefix = $first_prefix;
1371 $first_prefix = false;
1373 wfProfileOut( $fname.'-prefixhandling' );
1376 $might_be_img = false;
1378 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1380 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1381 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1382 # the real problem is with the $e1 regex
1385 # Still some problems for cases where the ] is meant to be outside punctuation,
1386 # and no image is in sight. See bug 2095.
1389 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1390 strpos($text, '[') !== false
1393 $text .= ']'; # so that replaceExternalLinks($text) works later
1396 # fix up urlencoded title texts
1397 if(preg_match('/%/', $m[1] ))
1398 # Should anchors '#' also be rejected?
1399 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1401 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1402 $might_be_img = true;
1404 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1406 } else { # Invalid form; output directly
1407 $s .= $prefix . '[[' . $line ;
1411 # Don't allow internal links to pages containing
1412 # PROTO: where PROTO is a valid URL protocol; these
1413 # should be external links.
1414 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1415 $s .= $prefix . '[[' . $line ;
1419 # Make subpage if necessary
1420 if( $useSubpages ) {
1421 $link = $this->maybeDoSubpageLink( $m[1], $text );
1426 $noforce = (substr($m[1], 0, 1) != ':');
1428 # Strip off leading ':'
1429 $link = substr($link, 1);
1432 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1434 $s .= $prefix . '[[' . $line;
1438 #check other language variants of the link
1439 #if the article does not exist
1440 if( $checkVariantLink
1441 && $nt->getArticleID() == 0 ) {
1442 $wgContLang->findVariantLink($link, $nt);
1445 $ns = $nt->getNamespace();
1446 $iw = $nt->getInterWiki();
1448 if ($might_be_img) { # if this is actually an invalid link
1449 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1451 while (isset ($a[$k+
1]) ) {
1452 #look at the next 'line' to see if we can close it there
1453 $spliced = array_splice( $a, $k +
1, 1 );
1454 $next_line = array_shift( $spliced );
1455 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1456 # the first ]] closes the inner link, the second the image
1458 $text .= '[[' . $m[1];
1461 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1462 #if there's exactly one ]] that's fine, we'll keep looking
1463 $text .= '[[' . $m[0];
1465 #if $next_line is invalid too, we need look no further
1466 $text .= '[[' . $next_line;
1471 # we couldn't find the end of this imageLink, so output it raw
1472 #but don't ignore what might be perfectly normal links in the text we've examined
1473 $text = $this->replaceInternalLinks($text);
1474 $s .= $prefix . '[[' . $link . '|' . $text;
1475 # note: no $trail, because without an end, there *is* no trail
1478 } else { #it's not an image, so output it raw
1479 $s .= $prefix . '[[' . $link . '|' . $text;
1480 # note: no $trail, because without an end, there *is* no trail
1485 $wasblank = ( '' == $text );
1486 if( $wasblank ) $text = $link;
1489 # Link not escaped by : , create the various objects
1493 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1494 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1495 $s = rtrim($s . "\n");
1496 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1500 if ( $ns == NS_IMAGE
) {
1501 wfProfileIn( "$fname-image" );
1502 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1503 # recursively parse links inside the image caption
1504 # actually, this will parse them in any other parameters, too,
1505 # but it might be hard to fix that, and it doesn't matter ATM
1506 $text = $this->replaceExternalLinks($text);
1507 $text = $this->replaceInternalLinks($text);
1509 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1510 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1511 $this->mOutput
->addImage( $nt->getDBkey() );
1513 wfProfileOut( "$fname-image" );
1516 wfProfileOut( "$fname-image" );
1520 if ( $ns == NS_CATEGORY
) {
1521 wfProfileIn( "$fname-category" );
1522 $s = rtrim($s . "\n"); # bug 87
1525 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1526 $sortkey = $this->mTitle
->getText();
1528 $sortkey = $this->mTitle
->getPrefixedText();
1533 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1534 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1535 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1538 * Strip the whitespace Category links produce, see bug 87
1539 * @todo We might want to use trim($tmp, "\n") here.
1541 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1543 wfProfileOut( "$fname-category" );
1548 if( ( $nt->getPrefixedText() === $selflink ) &&
1549 ( $nt->getFragment() === '' ) ) {
1550 # Self-links are handled specially; generally de-link and change to bold.
1551 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1555 # Special and Media are pseudo-namespaces; no pages actually exist in them
1556 if( $ns == NS_MEDIA
) {
1557 $link = $sk->makeMediaLinkObj( $nt, $text );
1558 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1559 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1560 $this->mOutput
->addImage( $nt->getDBkey() );
1562 } elseif( $ns == NS_SPECIAL
) {
1563 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1565 } elseif( $ns == NS_IMAGE
) {
1566 $img = Image
::newFromTitle( $nt );
1567 if( $img->exists() ) {
1568 // Force a blue link if the file exists; may be a remote
1569 // upload on the shared repository, and we want to see its
1570 // auto-generated page.
1571 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1575 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1577 wfProfileOut( $fname );
1582 * Make a link placeholder. The text returned can be later resolved to a real link with
1583 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1584 * parsing of interwiki links, and secondly to allow all extistence checks and
1585 * article length checks (for stub links) to be bundled into a single query.
1588 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1589 if ( ! is_object($nt) ) {
1591 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1593 # Separate the link trail from the rest of the link
1594 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1596 if ( $nt->isExternal() ) {
1597 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1598 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1599 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1601 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1602 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1603 $this->mLinkHolders
['queries'][] = $query;
1604 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1605 $this->mLinkHolders
['titles'][] = $nt;
1607 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1614 * Render a forced-blue link inline; protect against double expansion of
1615 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1616 * Since this little disaster has to split off the trail text to avoid
1617 * breaking URLs in the following text without breaking trails on the
1618 * wiki links, it's been made into a horrible function.
1621 * @param string $text
1622 * @param string $query
1623 * @param string $trail
1624 * @param string $prefix
1625 * @return string HTML-wikitext mix oh yuck
1627 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1628 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1629 $sk =& $this->mOptions
->getSkin();
1630 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1631 return $this->armorLinks( $link ) . $trail;
1635 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1636 * going to go through further parsing steps before inline URL expansion.
1638 * In particular this is important when using action=render, which causes
1639 * full URLs to be included.
1641 * Oh man I hate our multi-layer parser!
1643 * @param string more-or-less HTML
1644 * @return string less-or-more HTML with NOPARSE bits
1646 function armorLinks( $text ) {
1647 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1648 "{$this->mUniqPrefix}NOPARSE$1", $text );
1652 * Return true if subpage links should be expanded on this page.
1655 function areSubpagesAllowed() {
1656 # Some namespaces don't allow subpages
1657 global $wgNamespacesWithSubpages;
1658 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1662 * Handle link to subpage if necessary
1663 * @param string $target the source of the link
1664 * @param string &$text the link text, modified as necessary
1665 * @return string the full name of the link
1668 function maybeDoSubpageLink($target, &$text) {
1671 # :Foobar -- override special treatment of prefix (images, language links)
1672 # /Foobar -- convert to CurrentPage/Foobar
1673 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1674 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1675 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1677 $fname = 'Parser::maybeDoSubpageLink';
1678 wfProfileIn( $fname );
1679 $ret = $target; # default return value is no change
1681 # Some namespaces don't allow subpages,
1682 # so only perform processing if subpages are allowed
1683 if( $this->areSubpagesAllowed() ) {
1684 # Look at the first character
1685 if( $target != '' && $target{0} == '/' ) {
1686 # / at end means we don't want the slash to be shown
1687 if( substr( $target, -1, 1 ) == '/' ) {
1688 $target = substr( $target, 1, -1 );
1691 $noslash = substr( $target, 1 );
1694 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1695 if( '' === $text ) {
1697 } # this might be changed for ugliness reasons
1699 # check for .. subpage backlinks
1701 $nodotdot = $target;
1702 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1704 $nodotdot = substr( $nodotdot, 3 );
1706 if($dotdotcount > 0) {
1707 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1708 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1709 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1710 # / at the end means don't show full path
1711 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1712 $nodotdot = substr( $nodotdot, 0, -1 );
1713 if( '' === $text ) {
1717 $nodotdot = trim( $nodotdot );
1718 if( $nodotdot != '' ) {
1719 $ret .= '/' . $nodotdot;
1726 wfProfileOut( $fname );
1731 * Used by doBlockLevels()
1734 /* private */ function closeParagraph() {
1736 if ( '' != $this->mLastSection
) {
1737 $result = '</' . $this->mLastSection
. ">\n";
1739 $this->mInPre
= false;
1740 $this->mLastSection
= '';
1743 # getCommon() returns the length of the longest common substring
1744 # of both arguments, starting at the beginning of both.
1746 /* private */ function getCommon( $st1, $st2 ) {
1747 $fl = strlen( $st1 );
1748 $shorter = strlen( $st2 );
1749 if ( $fl < $shorter ) { $shorter = $fl; }
1751 for ( $i = 0; $i < $shorter; ++
$i ) {
1752 if ( $st1{$i} != $st2{$i} ) { break; }
1756 # These next three functions open, continue, and close the list
1757 # element appropriate to the prefix character passed into them.
1759 /* private */ function openList( $char ) {
1760 $result = $this->closeParagraph();
1762 if ( '*' == $char ) { $result .= '<ul><li>'; }
1763 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1764 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1765 else if ( ';' == $char ) {
1766 $result .= '<dl><dt>';
1767 $this->mDTopen
= true;
1769 else { $result = '<!-- ERR 1 -->'; }
1774 /* private */ function nextItem( $char ) {
1775 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1776 else if ( ':' == $char ||
';' == $char ) {
1778 if ( $this->mDTopen
) { $close = '</dt>'; }
1779 if ( ';' == $char ) {
1780 $this->mDTopen
= true;
1781 return $close . '<dt>';
1783 $this->mDTopen
= false;
1784 return $close . '<dd>';
1787 return '<!-- ERR 2 -->';
1790 /* private */ function closeList( $char ) {
1791 if ( '*' == $char ) { $text = '</li></ul>'; }
1792 else if ( '#' == $char ) { $text = '</li></ol>'; }
1793 else if ( ':' == $char ) {
1794 if ( $this->mDTopen
) {
1795 $this->mDTopen
= false;
1796 $text = '</dt></dl>';
1798 $text = '</dd></dl>';
1801 else { return '<!-- ERR 3 -->'; }
1807 * Make lists from lines starting with ':', '*', '#', etc.
1810 * @return string the lists rendered as HTML
1812 function doBlockLevels( $text, $linestart ) {
1813 $fname = 'Parser::doBlockLevels';
1814 wfProfileIn( $fname );
1816 # Parsing through the text line by line. The main thing
1817 # happening here is handling of block-level elements p, pre,
1818 # and making lists from lines starting with * # : etc.
1820 $textLines = explode( "\n", $text );
1822 $lastPrefix = $output = '';
1823 $this->mDTopen
= $inBlockElem = false;
1825 $paragraphStack = false;
1827 if ( !$linestart ) {
1828 $output .= array_shift( $textLines );
1830 foreach ( $textLines as $oLine ) {
1831 $lastPrefixLength = strlen( $lastPrefix );
1832 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1833 $preOpenMatch = preg_match('/<pre/i', $oLine );
1834 if ( !$this->mInPre
) {
1835 # Multiple prefixes may abut each other for nested lists.
1836 $prefixLength = strspn( $oLine, '*#:;' );
1837 $pref = substr( $oLine, 0, $prefixLength );
1840 $pref2 = str_replace( ';', ':', $pref );
1841 $t = substr( $oLine, $prefixLength );
1842 $this->mInPre
= !empty($preOpenMatch);
1844 # Don't interpret any other prefixes in preformatted text
1846 $pref = $pref2 = '';
1851 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1852 # Same as the last item, so no need to deal with nesting or opening stuff
1853 $output .= $this->nextItem( substr( $pref, -1 ) );
1854 $paragraphStack = false;
1856 if ( substr( $pref, -1 ) == ';') {
1857 # The one nasty exception: definition lists work like this:
1858 # ; title : definition text
1859 # So we check for : in the remainder text to split up the
1860 # title and definition, without b0rking links.
1862 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1864 $output .= $term . $this->nextItem( ':' );
1867 } elseif( $prefixLength ||
$lastPrefixLength ) {
1868 # Either open or close a level...
1869 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1870 $paragraphStack = false;
1872 while( $commonPrefixLength < $lastPrefixLength ) {
1873 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1874 --$lastPrefixLength;
1876 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1877 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1879 while ( $prefixLength > $commonPrefixLength ) {
1880 $char = substr( $pref, $commonPrefixLength, 1 );
1881 $output .= $this->openList( $char );
1883 if ( ';' == $char ) {
1884 # FIXME: This is dupe of code above
1885 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1887 $output .= $term . $this->nextItem( ':' );
1890 ++
$commonPrefixLength;
1892 $lastPrefix = $pref2;
1894 if( 0 == $prefixLength ) {
1895 wfProfileIn( "$fname-paragraph" );
1896 # No prefix (not in list)--go to paragraph mode
1897 // XXX: use a stack for nestable elements like span, table and div
1898 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1899 $closematch = preg_match(
1900 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1901 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol)/iS', $t );
1902 if ( $openmatch or $closematch ) {
1903 $paragraphStack = false;
1904 #Â TODO bug 5718: paragraph closed
1905 $output .= $this->closeParagraph();
1906 if ( $preOpenMatch and !$preCloseMatch ) {
1907 $this->mInPre
= true;
1909 if ( $closematch ) {
1910 $inBlockElem = false;
1912 $inBlockElem = true;
1914 } else if ( !$inBlockElem && !$this->mInPre
) {
1915 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1917 if ($this->mLastSection
!= 'pre') {
1918 $paragraphStack = false;
1919 $output .= $this->closeParagraph().'<pre>';
1920 $this->mLastSection
= 'pre';
1922 $t = substr( $t, 1 );
1925 if ( '' == trim($t) ) {
1926 if ( $paragraphStack ) {
1927 $output .= $paragraphStack.'<br />';
1928 $paragraphStack = false;
1929 $this->mLastSection
= 'p';
1931 if ($this->mLastSection
!= 'p' ) {
1932 $output .= $this->closeParagraph();
1933 $this->mLastSection
= '';
1934 $paragraphStack = '<p>';
1936 $paragraphStack = '</p><p>';
1940 if ( $paragraphStack ) {
1941 $output .= $paragraphStack;
1942 $paragraphStack = false;
1943 $this->mLastSection
= 'p';
1944 } else if ($this->mLastSection
!= 'p') {
1945 $output .= $this->closeParagraph().'<p>';
1946 $this->mLastSection
= 'p';
1951 wfProfileOut( "$fname-paragraph" );
1953 // somewhere above we forget to get out of pre block (bug 785)
1954 if($preCloseMatch && $this->mInPre
) {
1955 $this->mInPre
= false;
1957 if ($paragraphStack === false) {
1961 while ( $prefixLength ) {
1962 $output .= $this->closeList( $pref2{$prefixLength-1} );
1965 if ( '' != $this->mLastSection
) {
1966 $output .= '</' . $this->mLastSection
. '>';
1967 $this->mLastSection
= '';
1970 wfProfileOut( $fname );
1975 * Split up a string on ':', ignoring any occurences inside tags
1976 * to prevent illegal overlapping.
1977 * @param string $str the string to split
1978 * @param string &$before set to everything before the ':'
1979 * @param string &$after set to everything after the ':'
1980 * return string the position of the ':', or false if none found
1982 function findColonNoLinks($str, &$before, &$after) {
1983 $fname = 'Parser::findColonNoLinks';
1984 wfProfileIn( $fname );
1986 $pos = strpos( $str, ':' );
1987 if( $pos === false ) {
1989 wfProfileOut( $fname );
1993 $lt = strpos( $str, '<' );
1994 if( $lt === false ||
$lt > $pos ) {
1995 // Easy; no tag nesting to worry about
1996 $before = substr( $str, 0, $pos );
1997 $after = substr( $str, $pos+
1 );
1998 wfProfileOut( $fname );
2002 // Ugly state machine to walk through avoiding tags.
2003 $state = MW_COLON_STATE_TEXT
;
2005 $len = strlen( $str );
2006 for( $i = 0; $i < $len; $i++
) {
2010 // (Using the number is a performance hack for common cases)
2011 case 0: // MW_COLON_STATE_TEXT:
2014 // Could be either a <start> tag or an </end> tag
2015 $state = MW_COLON_STATE_TAGSTART
;
2020 $before = substr( $str, 0, $i );
2021 $after = substr( $str, $i +
1 );
2022 wfProfileOut( $fname );
2025 // Embedded in a tag; don't break it.
2028 // Skip ahead looking for something interesting
2029 $colon = strpos( $str, ':', $i );
2030 if( $colon === false ) {
2031 // Nothing else interesting
2032 wfProfileOut( $fname );
2035 $lt = strpos( $str, '<', $i );
2036 if( $stack === 0 ) {
2037 if( $lt === false ||
$colon < $lt ) {
2039 $before = substr( $str, 0, $colon );
2040 $after = substr( $str, $colon +
1 );
2041 wfProfileOut( $fname );
2045 if( $lt === false ) {
2046 // Nothing else interesting to find; abort!
2047 // We're nested, but there's no close tags left. Abort!
2050 // Skip ahead to next tag start
2052 $state = MW_COLON_STATE_TAGSTART
;
2055 case 1: // MW_COLON_STATE_TAG:
2060 $state = MW_COLON_STATE_TEXT
;
2063 // Slash may be followed by >?
2064 $state = MW_COLON_STATE_TAGSLASH
;
2070 case 2: // MW_COLON_STATE_TAGSTART:
2073 $state = MW_COLON_STATE_CLOSETAG
;
2076 $state = MW_COLON_STATE_COMMENT
;
2079 // Illegal early close? This shouldn't happen D:
2080 $state = MW_COLON_STATE_TEXT
;
2083 $state = MW_COLON_STATE_TAG
;
2086 case 3: // MW_COLON_STATE_CLOSETAG:
2091 wfDebug( "Invalid input in $fname; too many close tags\n" );
2092 wfProfileOut( $fname );
2095 $state = MW_COLON_STATE_TEXT
;
2098 case MW_COLON_STATE_TAGSLASH
:
2100 // Yes, a self-closed tag <blah/>
2101 $state = MW_COLON_STATE_TEXT
;
2103 // Probably we're jumping the gun, and this is an attribute
2104 $state = MW_COLON_STATE_TAG
;
2107 case 5: // MW_COLON_STATE_COMMENT:
2109 $state = MW_COLON_STATE_COMMENTDASH
;
2112 case MW_COLON_STATE_COMMENTDASH
:
2114 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2116 $state = MW_COLON_STATE_COMMENT
;
2119 case MW_COLON_STATE_COMMENTDASHDASH
:
2121 $state = MW_COLON_STATE_TEXT
;
2123 $state = MW_COLON_STATE_COMMENT
;
2127 wfDebugDieBacktrace( "State machine error in $fname" );
2131 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2134 wfProfileOut( $fname );
2139 * Return value of a magic variable (like PAGENAME)
2143 function getVariableValue( $index ) {
2144 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2147 * Some of these require message or data lookups and can be
2148 * expensive to check many times.
2150 static $varCache = array();
2151 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2152 if ( isset( $varCache[$index] ) )
2153 return $varCache[$index];
2156 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2159 case MAG_CURRENTMONTH
:
2160 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2161 case MAG_CURRENTMONTHNAME
:
2162 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2163 case MAG_CURRENTMONTHNAMEGEN
:
2164 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2165 case MAG_CURRENTMONTHABBREV
:
2166 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2167 case MAG_CURRENTDAY
:
2168 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2169 case MAG_CURRENTDAY2
:
2170 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2172 return $this->mTitle
->getText();
2174 return $this->mTitle
->getPartialURL();
2175 case MAG_FULLPAGENAME
:
2176 return $this->mTitle
->getPrefixedText();
2177 case MAG_FULLPAGENAMEE
:
2178 return $this->mTitle
->getPrefixedURL();
2179 case MAG_SUBPAGENAME
:
2180 return $this->mTitle
->getSubpageText();
2181 case MAG_SUBPAGENAMEE
:
2182 return $this->mTitle
->getSubpageUrlForm();
2183 case MAG_BASEPAGENAME
:
2184 return $this->mTitle
->getBaseText();
2185 case MAG_BASEPAGENAMEE
:
2186 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2187 case MAG_TALKPAGENAME
:
2188 if( $this->mTitle
->canTalk() ) {
2189 $talkPage = $this->mTitle
->getTalkPage();
2190 return $talkPage->getPrefixedText();
2194 case MAG_TALKPAGENAMEE
:
2195 if( $this->mTitle
->canTalk() ) {
2196 $talkPage = $this->mTitle
->getTalkPage();
2197 return $talkPage->getPrefixedUrl();
2201 case MAG_SUBJECTPAGENAME
:
2202 $subjPage = $this->mTitle
->getSubjectPage();
2203 return $subjPage->getPrefixedText();
2204 case MAG_SUBJECTPAGENAMEE
:
2205 $subjPage = $this->mTitle
->getSubjectPage();
2206 return $subjPage->getPrefixedUrl();
2207 case MAG_REVISIONID
:
2208 return $this->mRevisionId
;
2210 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2211 case MAG_NAMESPACEE
:
2212 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2214 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2215 case MAG_TALKSPACEE
:
2216 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2217 case MAG_SUBJECTSPACE
:
2218 return $this->mTitle
->getSubjectNsText();
2219 case MAG_SUBJECTSPACEE
:
2220 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2221 case MAG_CURRENTDAYNAME
:
2222 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2223 case MAG_CURRENTYEAR
:
2224 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2225 case MAG_CURRENTTIME
:
2226 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2227 case MAG_CURRENTWEEK
:
2228 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2229 // int to remove the padding
2230 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2231 case MAG_CURRENTDOW
:
2232 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2233 case MAG_NUMBEROFARTICLES
:
2234 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2235 case MAG_NUMBEROFFILES
:
2236 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2237 case MAG_NUMBEROFUSERS
:
2238 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2239 case MAG_NUMBEROFPAGES
:
2240 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2241 case MAG_CURRENTTIMESTAMP
:
2242 return $varCache[$index] = wfTimestampNow();
2243 case MAG_CURRENTVERSION
:
2250 case MAG_SERVERNAME
:
2251 return $wgServerName;
2252 case MAG_SCRIPTPATH
:
2253 return $wgScriptPath;
2254 case MAG_DIRECTIONMARK
:
2255 return $wgContLang->getDirMark();
2258 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2266 * initialise the magic variables (like CURRENTMONTHNAME)
2270 function initialiseVariables() {
2271 $fname = 'Parser::initialiseVariables';
2272 wfProfileIn( $fname );
2273 global $wgVariableIDs;
2274 $this->mVariables
= array();
2275 foreach ( $wgVariableIDs as $id ) {
2276 $mw =& MagicWord
::get( $id );
2277 $mw->addToArray( $this->mVariables
, $id );
2279 wfProfileOut( $fname );
2283 * parse any parentheses in format ((title|part|part))
2284 * and call callbacks to get a replacement text for any found piece
2286 * @param string $text The text to parse
2287 * @param array $callbacks rules in form:
2288 * '{' => array( # opening parentheses
2289 * 'end' => '}', # closing parentheses
2290 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2291 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2296 function replace_callback ($text, $callbacks) {
2297 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2298 $lastOpeningBrace = -1; # last not closed parentheses
2300 for ($i = 0; $i < strlen($text); $i++
) {
2301 # check for any opening brace
2304 foreach ($callbacks as $key => $value) {
2305 $pos = strpos ($text, $key, $i);
2306 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2312 if ($lastOpeningBrace >= 0) {
2313 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2315 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2320 $pos = strpos ($text, '|', $i);
2322 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2333 # found openning brace, lets add it to parentheses stack
2334 if (null != $rule) {
2335 $piece = array('brace' => $text[$i],
2336 'braceEnd' => $rule['end'],
2341 # count openning brace characters
2342 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2347 $piece['startAt'] = $i+
1;
2348 $piece['partStart'] = $i+
1;
2350 # we need to add to stack only if openning brace count is enough for any given rule
2351 foreach ($rule['cb'] as $cnt => $fn) {
2352 if ($piece['count'] >= $cnt) {
2353 $lastOpeningBrace ++
;
2354 $openingBraceStack[$lastOpeningBrace] = $piece;
2361 else if ($lastOpeningBrace >= 0) {
2362 # first check if it is a closing brace
2363 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2364 # lets check if it is enough characters for closing brace
2366 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2369 # if there are more closing parentheses than opening ones, we parse less
2370 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2371 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2373 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2375 $matchingCallback = null;
2376 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2377 if ($count >= $cnt && $matchingCount < $cnt) {
2378 $matchingCount = $cnt;
2379 $matchingCallback = $fn;
2383 if ($matchingCount == 0) {
2388 # lets set a title or last part (if '|' was found)
2389 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2390 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2392 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2394 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2395 $pieceEnd = $i +
$matchingCount;
2397 if( is_callable( $matchingCallback ) ) {
2399 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2400 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2401 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2402 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2404 # finally we can call a user callback and replace piece of text
2405 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2406 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2407 $i = $pieceStart +
strlen($replaceWith) - 1;
2410 # null value for callback means that parentheses should be parsed, but not replaced
2411 $i +
= $matchingCount - 1;
2414 # reset last openning parentheses, but keep it in case there are unused characters
2415 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2416 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2417 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2420 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2421 $openingBraceStack[$lastOpeningBrace--] = null;
2423 if ($matchingCount < $piece['count']) {
2424 $piece['count'] -= $matchingCount;
2425 $piece['startAt'] -= $matchingCount;
2426 $piece['partStart'] = $piece['startAt'];
2427 # do we still qualify for any callback with remaining count?
2428 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2429 if ($piece['count'] >= $cnt) {
2430 $lastOpeningBrace ++
;
2431 $openingBraceStack[$lastOpeningBrace] = $piece;
2439 # lets set a title if it is a first separator, or next part otherwise
2440 if ($text[$i] == '|') {
2441 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2442 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2443 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2446 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2448 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2457 * Replace magic variables, templates, and template arguments
2458 * with the appropriate text. Templates are substituted recursively,
2459 * taking care to avoid infinite loops.
2461 * Note that the substitution depends on value of $mOutputType:
2462 * OT_WIKI: only {{subst:}} templates
2463 * OT_MSG: only magic variables
2464 * OT_HTML: all templates and magic variables
2466 * @param string $tex The text to transform
2467 * @param array $args Key-value pairs representing template parameters to substitute
2468 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2471 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2472 # Prevent too big inclusions
2473 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2477 $fname = 'Parser::replaceVariables';
2478 wfProfileIn( $fname );
2480 # This function is called recursively. To keep track of arguments we need a stack:
2481 array_push( $this->mArgStack
, $args );
2483 $braceCallbacks = array();
2485 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2487 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2488 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2490 $callbacks = array();
2491 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2492 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2493 $text = $this->replace_callback ($text, $callbacks);
2495 array_pop( $this->mArgStack
);
2497 wfProfileOut( $fname );
2502 * Replace magic variables
2505 function variableSubstitution( $matches ) {
2506 $fname = 'Parser::variableSubstitution';
2507 $varname = $matches[1];
2508 wfProfileIn( $fname );
2509 if ( !$this->mVariables
) {
2510 $this->initialiseVariables();
2513 if ( $this->mOutputType
== OT_WIKI
) {
2514 # Do only magic variables prefixed by SUBST
2515 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2516 if (!$mwSubst->matchStartAndRemove( $varname ))
2518 # Note that if we don't substitute the variable below,
2519 # we don't remove the {{subst:}} magic word, in case
2520 # it is a template rather than a magic variable.
2522 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2523 $id = $this->mVariables
[$varname];
2524 $text = $this->getVariableValue( $id );
2525 $this->mOutput
->mContainsOldMagic
= true;
2527 $text = $matches[0];
2529 wfProfileOut( $fname );
2533 # Split template arguments
2534 function getTemplateArgs( $argsString ) {
2535 if ( $argsString === '' ) {
2539 $args = explode( '|', substr( $argsString, 1 ) );
2541 # If any of the arguments contains a '[[' but no ']]', it needs to be
2542 # merged with the next arg because the '|' character between belongs
2543 # to the link syntax and not the template parameter syntax.
2544 $argc = count($args);
2546 for ( $i = 0; $i < $argc-1; $i++
) {
2547 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2548 $args[$i] .= '|'.$args[$i+
1];
2549 array_splice($args, $i+
1, 1);
2559 * Return the text of a template, after recursively
2560 * replacing any variables or templates within the template.
2562 * @param array $piece The parts of the template
2563 * $piece['text']: matched text
2564 * $piece['title']: the title, i.e. the part before the |
2565 * $piece['parts']: the parameter array
2566 * @return string the text of the template
2569 function braceSubstitution( $piece ) {
2570 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2571 $fname = 'Parser::braceSubstitution';
2572 wfProfileIn( $fname );
2575 $found = false; # $text has been filled
2576 $nowiki = false; # wiki markup in $text should be escaped
2577 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2578 $noargs = false; # Don't replace triple-brace arguments in $text
2579 $replaceHeadings = false; # Make the edit section links go to the template not the article
2580 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2581 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2583 # Title object, where $text came from
2588 # $part1 is the bit before the first |, and must contain only title characters
2589 # $args is a list of arguments, starting from index 0, not including $part1
2591 $part1 = $piece['title'];
2592 # If the third subpattern matched anything, it will start with |
2594 if (null == $piece['parts']) {
2595 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2596 if ($replaceWith != $piece['text']) {
2597 $text = $replaceWith;
2604 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2605 $argc = count( $args );
2609 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2610 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2611 # One of two possibilities is true:
2612 # 1) Found SUBST but not in the PST phase
2613 # 2) Didn't find SUBST and in the PST phase
2614 # In either case, return without further processing
2615 $text = $piece['text'];
2622 # MSG, MSGNW, INT and RAW
2625 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2626 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2629 # Remove obsolete MSG:
2630 $mwMsg =& MagicWord
::get( MAG_MSG
);
2631 $mwMsg->matchStartAndRemove( $part1 );
2635 $mwRaw =& MagicWord
::get( MAG_RAW
);
2636 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2637 $forceRawInterwiki = true;
2640 # Check if it is an internal message
2641 $mwInt =& MagicWord
::get( MAG_INT
);
2642 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2643 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2644 $text = $linestart . wfMsgReal( $part1, $args, true );
2652 # Check for NS: (namespace expansion)
2653 $mwNs = MagicWord
::get( MAG_NS
);
2654 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2655 if ( intval( $part1 ) ||
$part1 == "0" ) {
2656 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2659 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2660 if ( !is_null( $index ) ) {
2661 $text = $linestart . $wgContLang->getNsText( $index );
2670 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2671 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2672 $text = $linestart . urlencode( $part1 );
2677 # LCFIRST, UCFIRST, LC and UC
2679 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2680 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2681 $lc =& MagicWord
::get( MAG_LC
);
2682 $uc =& MagicWord
::get( MAG_UC
);
2683 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2684 $text = $linestart . $wgContLang->lcfirst( $part1 );
2686 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2687 $text = $linestart . $wgContLang->ucfirst( $part1 );
2689 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2690 $text = $linestart . $wgContLang->lc( $part1 );
2692 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2693 $text = $linestart . $wgContLang->uc( $part1 );
2698 # LOCALURL and FULLURL
2700 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2701 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2702 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2703 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2706 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2707 $func = 'getLocalURL';
2708 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2709 $func = 'escapeLocalURL';
2710 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2711 $func = 'getFullURL';
2712 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2713 $func = 'escapeFullURL';
2718 if ( $func !== false ) {
2719 $title = Title
::newFromText( $part1 );
2720 # Due to order of execution of a lot of bits, the values might be encoded
2721 # before arriving here; if that's true, then the title can't be created
2722 # and the variable will fail. If we can't get a decent title from the first
2723 # attempt, url-decode and try for a second.
2724 if( is_null( $title ) )
2725 $title = Title
::newFromUrl( urldecode( $part1 ) );
2726 if ( !is_null( $title ) ) {
2728 $text = $linestart . $title->$func( $args[0] );
2730 $text = $linestart . $title->$func();
2737 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2739 if ( !$found && $argc == 1 ) {
2740 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2741 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2742 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2748 if ( !$found && $argc >= 2 ) {
2749 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2750 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2751 if ($argc==2) {$args[2]=$args[1];}
2752 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2758 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2759 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2760 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2762 # Set title in parser output object
2764 $parserOptions = new ParserOptions
;
2765 $local_parser = new Parser ();
2766 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2767 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2770 $t = $this->mTitle
->getPrefixedText();
2771 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2777 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2779 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2780 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2781 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2782 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2783 foreach( $mwWordsToCheck as $word => $func ) {
2784 $mwCurrentWord =& MagicWord
::get( $word );
2785 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2786 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2787 if( $mwRawSuffix->match( $args[0] ) ) {
2788 # Raw and unformatted
2789 $text = $linestart . call_user_func( $func );
2791 # Formatted according to the content default
2792 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2801 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2802 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2803 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2804 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2810 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2811 $colonPos = strpos( $part1, ':' );
2812 if ( $colonPos !== false ) {
2813 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2814 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2815 $funcArgs = array_map( 'trim', $args );
2816 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2817 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2820 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2824 if ( is_array( $result ) ) {
2825 $text = $linestart . $result[0];
2826 unset( $result[0] );
2828 // Extract flags into the local scope
2829 // This allows callers to set flags such as nowiki, noparse, found, etc.
2832 $text = $linestart . $result;
2838 # Template table test
2840 # Did we encounter this template already? If yes, it is in the cache
2841 # and we need to check for loops.
2842 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2845 # Infinite loop test
2846 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2850 $text = $linestart .
2851 '{{' . $part1 . '}}' .
2852 '<!-- WARNING: template loop detected -->';
2853 wfDebug( "$fname: template loop broken at '$part1'\n" );
2855 # set $text to cached message.
2856 $text = $linestart . $this->mTemplates
[$piece['title']];
2860 # Load from database
2861 $lastPathLevel = $this->mTemplatePath
;
2864 # declaring $subpage directly in the function call
2865 # does not work correctly with references and breaks
2866 # {{/subpage}}-style inclusions
2868 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2869 if ($subpage !== '') {
2870 $ns = $this->mTitle
->getNamespace();
2872 $title = Title
::newFromText( $part1, $ns );
2874 if ( !is_null( $title ) ) {
2875 if ( !$title->isExternal() ) {
2876 # Check for excessive inclusion
2877 $dbk = $title->getPrefixedDBkey();
2878 if ( $this->incrementIncludeCount( $dbk ) ) {
2879 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2880 $text = SpecialPage
::capturePath( $title );
2881 if ( is_string( $text ) ) {
2886 $this->disableCache();
2889 $articleContent = $this->fetchTemplate( $title );
2890 if ( $articleContent !== false ) {
2892 $text = $articleContent;
2893 $replaceHeadings = true;
2898 # If the title is valid but undisplayable, make a link to it
2899 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2900 $text = '[['.$title->getPrefixedText().']]';
2903 } elseif ( $title->isTrans() ) {
2904 // Interwiki transclusion
2905 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2906 $text = $this->interwikiTransclude( $title, 'render' );
2910 $text = $this->interwikiTransclude( $title, 'raw' );
2911 $replaceHeadings = true;
2916 # Template cache array insertion
2917 # Use the original $piece['title'] not the mangled $part1, so that
2918 # modifiers such as RAW: produce separate cache entries
2921 // A special page; don't store it in the template cache.
2923 $this->mTemplates
[$piece['title']] = $text;
2925 $text = $linestart . $text;
2930 # Recursive parsing, escaping and link table handling
2931 # Only for HTML output
2932 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2933 $text = wfEscapeWikiText( $text );
2934 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2936 $assocArgs = array();
2938 # Clean up argument array
2939 $assocArgs = array();
2941 foreach( $args as $arg ) {
2942 $eqpos = strpos( $arg, '=' );
2943 if ( $eqpos === false ) {
2944 $assocArgs[$index++
] = $arg;
2946 $name = trim( substr( $arg, 0, $eqpos ) );
2947 $value = trim( substr( $arg, $eqpos+
1 ) );
2948 if ( $value === false ) {
2951 if ( $name !== false ) {
2952 $assocArgs[$name] = $value;
2957 # Add a new element to the templace recursion path
2958 $this->mTemplatePath
[$part1] = 1;
2962 # If there are any <onlyinclude> tags, only include them
2963 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2964 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2966 foreach ($m[1] as $piece)
2969 # Remove <noinclude> sections and <includeonly> tags
2970 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2971 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2973 if( $this->mOutputType
== OT_HTML
) {
2974 # Strip <nowiki>, <pre>, etc.
2975 $text = $this->strip( $text, $this->mStripState
);
2976 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2978 $text = $this->replaceVariables( $text, $assocArgs );
2980 # If the template begins with a table or block-level
2981 # element, it should be treated as beginning a new line.
2982 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2983 $text = "\n" . $text;
2985 } elseif ( !$noargs ) {
2986 # $noparse and !$noargs
2987 # Just replace the arguments, not any double-brace items
2988 # This is used for rendered interwiki transclusion
2989 $text = $this->replaceVariables( $text, $assocArgs, true );
2992 # Prune lower levels off the recursion check path
2993 $this->mTemplatePath
= $lastPathLevel;
2996 wfProfileOut( $fname );
2997 return $piece['text'];
3000 # Replace raw HTML by a placeholder
3001 # Add a blank line preceding, to prevent it from mucking up
3002 # immediately preceding headings
3003 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3005 # replace ==section headers==
3006 # XXX this needs to go away once we have a better parser.
3007 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3008 if( !is_null( $title ) )
3009 $encodedname = base64_encode($title->getPrefixedDBkey());
3011 $encodedname = base64_encode("");
3012 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3013 PREG_SPLIT_DELIM_CAPTURE
);
3016 for( $i = 0; $i < count($m); $i +
= 2 ) {
3018 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3020 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3024 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3025 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3026 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3034 # Prune lower levels off the recursion check path
3035 $this->mTemplatePath
= $lastPathLevel;
3038 wfProfileOut( $fname );
3039 return $piece['text'];
3041 wfProfileOut( $fname );
3047 * Fetch the unparsed text of a template and register a reference to it.
3049 function fetchTemplate( $title ) {
3051 // Loop to fetch the article, with up to 1 redirect
3052 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3053 $rev = Revision
::newFromTitle( $title );
3054 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3058 $text = $rev->getText();
3059 if ( $text === false ) {
3063 $title = Title
::newFromRedirect( $text );
3069 * Transclude an interwiki link.
3071 function interwikiTransclude( $title, $action ) {
3072 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3074 if (!$wgEnableScaryTranscluding)
3075 return wfMsg('scarytranscludedisabled');
3077 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3078 // But we'll handle it generally anyway
3079 if ( $title->getNamespace() ) {
3080 // Use the canonical namespace, which should work anywhere
3081 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3083 $articleName = $title->getDBkey();
3086 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3087 $url .= "?action=$action";
3088 if (strlen($url) > 255)
3089 return wfMsg('scarytranscludetoolong');
3090 return $this->fetchScaryTemplateMaybeFromCache($url);
3093 function fetchScaryTemplateMaybeFromCache($url) {
3094 global $wgTranscludeCacheExpiry;
3095 $dbr =& wfGetDB(DB_SLAVE
);
3096 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3097 array('tc_url' => $url));
3099 $time = $obj->tc_time
;
3100 $text = $obj->tc_contents
;
3101 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3106 $text = wfGetHTTP($url);
3108 return wfMsg('scarytranscludefailed', $url);
3110 $dbw =& wfGetDB(DB_MASTER
);
3111 $dbw->replace('transcache', array('tc_url'), array(
3113 'tc_time' => time(),
3114 'tc_contents' => $text));
3120 * Triple brace replacement -- used for template arguments
3123 function argSubstitution( $matches ) {
3124 $arg = trim( $matches['title'] );
3125 $text = $matches['text'];
3126 $inputArgs = end( $this->mArgStack
);
3128 if ( array_key_exists( $arg, $inputArgs ) ) {
3129 $text = $inputArgs[$arg];
3130 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3131 $text = $matches['parts'][0];
3138 * Returns true if the function is allowed to include this entity
3141 function incrementIncludeCount( $dbk ) {
3142 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3143 $this->mIncludeCount
[$dbk] = 0;
3145 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3153 * Detect __TOC__ magic word and set a placeholder
3155 function stripToc( $text ) {
3156 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3158 $mw = MagicWord
::get( MAG_NOTOC
);
3159 if( $mw->matchAndRemove( $text ) ) {
3160 $this->mShowToc
= false;
3163 $mw = MagicWord
::get( MAG_TOC
);
3164 if( $mw->match( $text ) ) {
3165 $this->mShowToc
= true;
3166 $this->mForceTocPosition
= true;
3168 // Set a placeholder. At the end we'll fill it in with the TOC.
3169 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3171 // Only keep the first one.
3172 $text = $mw->replace( '', $text );
3178 * This function accomplishes several tasks:
3179 * 1) Auto-number headings if that option is enabled
3180 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3181 * 3) Add a Table of contents on the top for users who have enabled the option
3182 * 4) Auto-anchor headings
3184 * It loops through all headlines, collects the necessary data, then splits up the
3185 * string and re-inserts the newly formatted headlines.
3187 * @param string $text
3188 * @param boolean $isMain
3191 function formatHeadings( $text, $isMain=true ) {
3192 global $wgMaxTocLevel, $wgContLang;
3194 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3195 if( !$this->mTitle
->userCanEdit() ) {
3198 $showEditLink = $this->mOptions
->getEditSection();
3201 # Inhibit editsection links if requested in the page
3202 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3203 if( $esw->matchAndRemove( $text ) ) {
3207 # Get all headlines for numbering them and adding funky stuff like [edit]
3208 # links - this is for later, but we need the number of headlines right now
3209 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3211 # if there are fewer than 4 headlines in the article, do not show TOC
3212 # unless it's been explicitly enabled.
3213 $enoughToc = $this->mShowToc
&&
3214 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3216 # Allow user to stipulate that a page should have a "new section"
3217 # link added via __NEWSECTIONLINK__
3218 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3219 if( $mw->matchAndRemove( $text ) )
3220 $this->mOutput
->setNewSection( true );
3222 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3223 # override above conditions and always show TOC above first header
3224 $mw =& MagicWord
::get( MAG_FORCETOC
);
3225 if ($mw->matchAndRemove( $text ) ) {
3226 $this->mShowToc
= true;
3230 # Never ever show TOC if no headers
3231 if( $numMatches < 1 ) {
3235 # We need this to perform operations on the HTML
3236 $sk =& $this->mOptions
->getSkin();
3240 $sectionCount = 0; # headlineCount excluding template sections
3242 # Ugh .. the TOC should have neat indentation levels which can be
3243 # passed to the skin functions. These are determined here
3247 $sublevelCount = array();
3248 $levelCount = array();
3255 foreach( $matches[3] as $headline ) {
3257 $templatetitle = '';
3258 $templatesection = 0;
3261 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3263 $templatetitle = base64_decode($mat[1]);
3264 $templatesection = 1 +
(int)base64_decode($mat[2]);
3265 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3269 $prevlevel = $level;
3270 $prevtoclevel = $toclevel;
3272 $level = $matches[1][$headlineCount];
3274 if( $doNumberHeadings ||
$enoughToc ) {
3276 if ( $level > $prevlevel ) {
3277 # Increase TOC level
3279 $sublevelCount[$toclevel] = 0;
3280 if( $toclevel<$wgMaxTocLevel ) {
3281 $toc .= $sk->tocIndent();
3284 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3285 # Decrease TOC level, find level to jump to
3287 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3288 # Can only go down to level 1
3291 for ($i = $toclevel; $i > 0; $i--) {
3292 if ( $levelCount[$i] == $level ) {
3293 # Found last matching level
3297 elseif ( $levelCount[$i] < $level ) {
3298 # Found first matching level below current level
3304 if( $toclevel<$wgMaxTocLevel ) {
3305 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3309 # No change in level, end TOC line
3310 if( $toclevel<$wgMaxTocLevel ) {
3311 $toc .= $sk->tocLineEnd();
3315 $levelCount[$toclevel] = $level;
3317 # count number of headlines for each level
3318 @$sublevelCount[$toclevel]++
;
3320 for( $i = 1; $i <= $toclevel; $i++
) {
3321 if( !empty( $sublevelCount[$i] ) ) {
3325 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3331 # The canonized header is a version of the header text safe to use for links
3332 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3333 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3334 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3336 # Remove link placeholders by the link text.
3337 # <!--LINK number-->
3339 # link text with suffix
3340 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3341 "\$this->mLinkHolders['texts'][\$1]",
3342 $canonized_headline );
3343 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3344 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3345 $canonized_headline );
3348 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3349 $tocline = trim( $canonized_headline );
3350 # Save headline for section edit hint before it's escaped
3351 $headline_hint = trim( $canonized_headline );
3352 $canonized_headline = Sanitizer
::escapeId( $tocline );
3353 $refers[$headlineCount] = $canonized_headline;
3355 # count how many in assoc. array so we can track dupes in anchors
3356 @$refers[$canonized_headline]++
;
3357 $refcount[$headlineCount]=$refers[$canonized_headline];
3359 # Don't number the heading if it is the only one (looks silly)
3360 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3361 # the two are different if the line contains a link
3362 $headline=$numbering . ' ' . $headline;
3365 # Create the anchor for linking from the TOC to the section
3366 $anchor = $canonized_headline;
3367 if($refcount[$headlineCount] > 1 ) {
3368 $anchor .= '_' . $refcount[$headlineCount];
3370 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3371 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3373 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3374 if ( empty( $head[$headlineCount] ) ) {
3375 $head[$headlineCount] = '';
3378 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3380 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3383 # give headline the correct <h#> tag
3384 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3392 if( $toclevel<$wgMaxTocLevel ) {
3393 $toc .= $sk->tocUnindent( $toclevel - 1 );
3395 $toc = $sk->tocList( $toc );
3398 # split up and insert constructed headlines
3400 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3403 foreach( $blocks as $block ) {
3404 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3405 # This is the [edit] link that appears for the top block of text when
3406 # section editing is enabled
3408 # Disabled because it broke block formatting
3409 # For example, a bullet point in the top line
3410 # $full .= $sk->editSectionLink(0);
3413 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3414 # Top anchor now in skin
3418 if( !empty( $head[$i] ) ) {
3423 if( $this->mForceTocPosition
) {
3424 return str_replace( '<!--MWTOC-->', $toc, $full );
3431 * Return an HTML link for the "ISBN 123456" text
3434 function magicISBN( $text ) {
3435 $fname = 'Parser::magicISBN';
3436 wfProfileIn( $fname );
3438 $a = split( 'ISBN ', ' '.$text );
3439 if ( count ( $a ) < 2 ) {
3440 wfProfileOut( $fname );
3443 $text = substr( array_shift( $a ), 1);
3444 $valid = '0123456789-Xx';
3446 foreach ( $a as $x ) {
3447 # hack: don't replace inside thumbnail title/alt
3449 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3454 $isbn = $blank = '' ;
3455 while ( ' ' == $x{0} ) {
3457 $x = substr( $x, 1 );
3459 if ( $x == '' ) { # blank isbn
3460 $text .= "ISBN $blank";
3463 while ( strstr( $valid, $x{0} ) != false ) {
3465 $x = substr( $x, 1 );
3467 $num = str_replace( '-', '', $isbn );
3468 $num = str_replace( ' ', '', $num );
3469 $num = str_replace( 'x', 'X', $num );
3472 $text .= "ISBN $blank$x";
3474 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3475 $text .= '<a href="' .
3476 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3477 "\" class=\"internal\">ISBN $isbn</a>";
3481 wfProfileOut( $fname );
3486 * Return an HTML link for the "RFC 1234" text
3489 * @param string $text Text to be processed
3490 * @param string $keyword Magic keyword to use (default RFC)
3491 * @param string $urlmsg Interface message to use (default rfcurl)
3494 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3496 $valid = '0123456789';
3499 $a = split( $keyword, ' '.$text );
3500 if ( count ( $a ) < 2 ) {
3503 $text = substr( array_shift( $a ), 1);
3505 /* Check if keyword is preceed by [[.
3506 * This test is made here cause of the array_shift above
3507 * that prevent the test to be done in the foreach.
3509 if ( substr( $text, -2 ) == '[[' ) {
3513 foreach ( $a as $x ) {
3514 /* token might be empty if we have RFC RFC 1234 */
3520 # hack: don't replace inside thumbnail title/alt
3522 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3523 $text .= $keyword . $x;
3529 /** remove and save whitespaces in $blank */
3530 while ( $x{0} == ' ' ) {
3532 $x = substr( $x, 1 );
3535 /** remove and save the rfc number in $id */
3536 while ( strstr( $valid, $x{0} ) != false ) {
3538 $x = substr( $x, 1 );
3542 /* call back stripped spaces*/
3543 $text .= $keyword.$blank.$x;
3544 } elseif( $internal ) {
3546 $text .= $keyword.$id.$x;
3548 /* build the external link*/
3549 $url = wfMsg( $urlmsg, $id);
3550 $sk =& $this->mOptions
->getSkin();
3551 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3552 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3555 /* Check if the next RFC keyword is preceed by [[ */
3556 $internal = ( substr($x,-2) == '[[' );
3562 * Transform wiki markup when saving a page by doing \r\n -> \n
3563 * conversion, substitting signatures, {{subst:}} templates, etc.
3565 * @param string $text the text to transform
3566 * @param Title &$title the Title object for the current article
3567 * @param User &$user the User object describing the current user
3568 * @param ParserOptions $options parsing options
3569 * @param bool $clearState whether to clear the parser state first
3570 * @return string the altered wiki markup
3573 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3574 $this->mOptions
= $options;
3575 $this->mTitle
=& $title;
3576 $this->mOutputType
= OT_WIKI
;
3578 if ( $clearState ) {
3579 $this->clearState();
3582 $stripState = false;
3586 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3587 $text = $this->strip( $text, $stripState, true );
3588 $text = $this->pstPass2( $text, $stripState, $user );
3589 $text = $this->unstrip( $text, $stripState );
3590 $text = $this->unstripNoWiki( $text, $stripState );
3595 * Pre-save transform helper function
3598 function pstPass2( $text, &$stripState, &$user ) {
3599 global $wgContLang, $wgLocaltimezone;
3601 /* Note: This is the timestamp saved as hardcoded wikitext to
3602 * the database, we use $wgContLang here in order to give
3603 * everyone the same signature and use the default one rather
3604 * than the one selected in each user's preferences.
3606 if ( isset( $wgLocaltimezone ) ) {
3607 $oldtz = getenv( 'TZ' );
3608 putenv( 'TZ='.$wgLocaltimezone );
3610 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3611 ' (' . date( 'T' ) . ')';
3612 if ( isset( $wgLocaltimezone ) ) {
3613 putenv( 'TZ='.$oldtz );
3616 # Variable replacement
3617 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3618 $text = $this->replaceVariables( $text );
3620 # Strip out <nowiki> etc. added via replaceVariables
3621 $text = $this->strip( $text, $stripState );
3624 $sigText = $this->getUserSig( $user );
3625 $text = strtr( $text, array(
3627 '~~~~' => "$sigText $d",
3631 # Context links: [[|name]] and [[name (context)|]]
3633 global $wgLegalTitleChars;
3634 $tc = "[$wgLegalTitleChars]";
3635 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3637 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3638 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3640 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3641 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3642 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3643 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3645 $t = $this->mTitle
->getText();
3646 if ( preg_match( $conpat, $t, $m ) ) {
3649 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3650 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3651 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3653 if ( '' == $context ) {
3654 $text = preg_replace( $p2, '[[\\1]]', $text );
3656 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3659 # Trim trailing whitespace
3660 # MAG_END (__END__) tag allows for trailing
3661 # whitespace to be deliberately included
3662 $text = rtrim( $text );
3663 $mw =& MagicWord
::get( MAG_END
);
3664 $mw->matchAndRemove( $text );
3670 * Fetch the user's signature text, if any, and normalize to
3671 * validated, ready-to-insert wikitext.
3677 function getUserSig( &$user ) {
3678 $username = $user->getName();
3679 $nickname = $user->getOption( 'nickname' );
3680 $nickname = $nickname === '' ?
$username : $nickname;
3682 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3683 # Sig. might contain markup; validate this
3684 if( $this->validateSig( $nickname ) !== false ) {
3685 # Validated; clean up (if needed) and return it
3686 return $this->cleanSig( $nickname, true );
3688 # Failed to validate; fall back to the default
3689 $nickname = $username;
3690 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3694 # If we're still here, make it a link to the user page
3695 $userpage = $user->getUserPage();
3696 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3700 * Check that the user's signature contains no bad XML
3702 * @param string $text
3703 * @return mixed An expanded string, or false if invalid.
3705 function validateSig( $text ) {
3706 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3710 * Clean up signature text
3712 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3713 * 2) Substitute all transclusions
3715 * @param string $text
3716 * @param $parsing Whether we're cleaning (preferences save) or parsing
3717 * @return string Signature text
3719 function cleanSig( $text, $parsing = false ) {
3721 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3723 $substWord = MagicWord
::get( MAG_SUBST
);
3724 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3725 $substText = '{{' . $substWord->getSynonym( 0 );
3727 $text = preg_replace( $substRegex, $substText, $text );
3728 $text = preg_replace( '/~{3,5}/', '', $text );
3729 $text = $this->replaceVariables( $text );
3731 $this->clearState();
3736 * Set up some variables which are usually set up in parse()
3737 * so that an external function can call some class members with confidence
3740 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3741 $this->mTitle
=& $title;
3742 $this->mOptions
= $options;
3743 $this->mOutputType
= $outputType;
3744 if ( $clearState ) {
3745 $this->clearState();
3750 * Transform a MediaWiki message by replacing magic variables.
3752 * @param string $text the text to transform
3753 * @param ParserOptions $options options
3754 * @return string the text with variables substituted
3757 function transformMsg( $text, $options ) {
3759 static $executing = false;
3761 $fname = "Parser::transformMsg";
3763 # Guard against infinite recursion
3769 wfProfileIn($fname);
3771 $this->mTitle
= $wgTitle;
3772 $this->mOptions
= $options;
3773 $this->mOutputType
= OT_MSG
;
3774 $this->clearState();
3775 $text = $this->replaceVariables( $text );
3778 wfProfileOut($fname);
3783 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3784 * The callback should have the following form:
3785 * function myParserHook( $text, $params, &$parser ) { ... }
3787 * Transform and return $text. Use $parser for any required context, e.g. use
3788 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3792 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3793 * @param mixed $callback The callback function (and object) to use for the tag
3795 * @return The old value of the mTagHooks array associated with the hook
3797 function setHook( $tag, $callback ) {
3798 $tag = strtolower( $tag );
3799 $oldVal = @$this->mTagHooks
[$tag];
3800 $this->mTagHooks
[$tag] = $callback;
3806 * Create a function, e.g. {{sum:1|2|3}}
3807 * The callback function should have the form:
3808 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3810 * The callback may either return the text result of the function, or an array with the text
3811 * in element 0, and a number of flags in the other elements. The names of the flags are
3812 * specified in the keys. Valid flags are:
3813 * found The text returned is valid, stop processing the template. This
3815 * nowiki Wiki markup in the return value should be escaped
3816 * noparse Unsafe HTML tags should not be stripped, etc.
3817 * noargs Don't replace triple-brace arguments in the return value
3818 * isHTML The returned text is HTML, armour it against wikitext transformation
3822 * @param string $name The function name. Function names are case-insensitive.
3823 * @param mixed $callback The callback function (and object) to use
3825 * @return The old callback function for this name, if any
3827 function setFunctionHook( $name, $callback ) {
3828 $name = strtolower( $name );
3829 $oldVal = @$this->mFunctionHooks
[$name];
3830 $this->mFunctionHooks
[$name] = $callback;
3835 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3836 * Placeholders created in Skin::makeLinkObj()
3837 * Returns an array of links found, indexed by PDBK:
3841 * $options is a bit field, RLH_FOR_UPDATE to select for update
3843 function replaceLinkHolders( &$text, $options = 0 ) {
3845 global $wgOutputReplace;
3847 $fname = 'Parser::replaceLinkHolders';
3848 wfProfileIn( $fname );
3852 $sk =& $this->mOptions
->getSkin();
3853 $linkCache =& LinkCache
::singleton();
3855 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3856 wfProfileIn( $fname.'-check' );
3857 $dbr =& wfGetDB( DB_SLAVE
);
3858 $page = $dbr->tableName( 'page' );
3859 $threshold = $wgUser->getOption('stubthreshold');
3862 asort( $this->mLinkHolders
['namespaces'] );
3866 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3868 $title = $this->mLinkHolders
['titles'][$key];
3870 # Skip invalid entries.
3871 # Result will be ugly, but prevents crash.
3872 if ( is_null( $title ) ) {
3875 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3877 # Check if it's a static known link, e.g. interwiki
3878 if ( $title->isAlwaysKnown() ) {
3879 $colours[$pdbk] = 1;
3880 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3881 $colours[$pdbk] = 1;
3882 $this->mOutput
->addLink( $title, $id );
3883 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3884 $colours[$pdbk] = 0;
3886 # Not in the link cache, add it to the query
3887 if ( !isset( $current ) ) {
3889 $query = "SELECT page_id, page_namespace, page_title";
3890 if ( $threshold > 0 ) {
3891 $query .= ', page_len, page_is_redirect';
3893 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3894 } elseif ( $current != $ns ) {
3896 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3901 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3906 if ( $options & RLH_FOR_UPDATE
) {
3907 $query .= ' FOR UPDATE';
3910 $res = $dbr->query( $query, $fname );
3912 # Fetch data and form into an associative array
3913 # non-existent = broken
3916 while ( $s = $dbr->fetchObject($res) ) {
3917 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3918 $pdbk = $title->getPrefixedDBkey();
3919 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3920 $this->mOutput
->addLink( $title, $s->page_id
);
3922 if ( $threshold > 0 ) {
3923 $size = $s->page_len
;
3924 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3925 $colours[$pdbk] = 1;
3927 $colours[$pdbk] = 2;
3930 $colours[$pdbk] = 1;
3934 wfProfileOut( $fname.'-check' );
3936 # Construct search and replace arrays
3937 wfProfileIn( $fname.'-construct' );
3938 $wgOutputReplace = array();
3939 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3940 $pdbk = $pdbks[$key];
3941 $searchkey = "<!--LINK $key-->";
3942 $title = $this->mLinkHolders
['titles'][$key];
3943 if ( empty( $colours[$pdbk] ) ) {
3944 $linkCache->addBadLinkObj( $title );
3945 $colours[$pdbk] = 0;
3946 $this->mOutput
->addLink( $title, 0 );
3947 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3948 $this->mLinkHolders
['texts'][$key],
3949 $this->mLinkHolders
['queries'][$key] );
3950 } elseif ( $colours[$pdbk] == 1 ) {
3951 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3952 $this->mLinkHolders
['texts'][$key],
3953 $this->mLinkHolders
['queries'][$key] );
3954 } elseif ( $colours[$pdbk] == 2 ) {
3955 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3956 $this->mLinkHolders
['texts'][$key],
3957 $this->mLinkHolders
['queries'][$key] );
3960 wfProfileOut( $fname.'-construct' );
3963 wfProfileIn( $fname.'-replace' );
3965 $text = preg_replace_callback(
3966 '/(<!--LINK .*?-->)/',
3967 "wfOutputReplaceMatches",
3970 wfProfileOut( $fname.'-replace' );
3973 # Now process interwiki link holders
3974 # This is quite a bit simpler than internal links
3975 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3976 wfProfileIn( $fname.'-interwiki' );
3977 # Make interwiki link HTML
3978 $wgOutputReplace = array();
3979 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3980 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3981 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3984 $text = preg_replace_callback(
3985 '/<!--IWLINK (.*?)-->/',
3986 "wfOutputReplaceMatches",
3988 wfProfileOut( $fname.'-interwiki' );
3991 wfProfileOut( $fname );
3996 * Replace <!--LINK--> link placeholders with plain text of links
3997 * (not HTML-formatted).
3998 * @param string $text
4001 function replaceLinkHoldersText( $text ) {
4002 $fname = 'Parser::replaceLinkHoldersText';
4003 wfProfileIn( $fname );
4005 $text = preg_replace_callback(
4006 '/<!--(LINK|IWLINK) (.*?)-->/',
4007 array( &$this, 'replaceLinkHoldersTextCallback' ),
4010 wfProfileOut( $fname );
4015 * @param array $matches
4019 function replaceLinkHoldersTextCallback( $matches ) {
4020 $type = $matches[1];
4022 if( $type == 'LINK' ) {
4023 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4024 return $this->mLinkHolders
['texts'][$key];
4026 } elseif( $type == 'IWLINK' ) {
4027 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4028 return $this->mInterwikiLinkHolders
['texts'][$key];
4035 * Renders an image gallery from a text with one line per image.
4036 * text labels may be given by using |-style alternative text. E.g.
4037 * Image:one.jpg|The number "1"
4038 * Image:tree.jpg|A tree
4039 * given as text will return the HTML of a gallery with two images,
4040 * labeled 'The number "1"' and
4043 function renderImageGallery( $text ) {
4044 $ig = new ImageGallery();
4045 $ig->setShowBytes( false );
4046 $ig->setShowFilename( false );
4048 $lines = explode( "\n", $text );
4050 foreach ( $lines as $line ) {
4051 # match lines like these:
4052 # Image:someimage.jpg|This is some image
4053 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4055 if ( count( $matches ) == 0 ) {
4058 $nt =& Title
::newFromText( $matches[1] );
4059 if( is_null( $nt ) ) {
4060 # Bogus title. Ignore these so we don't bomb out later.
4063 if ( isset( $matches[3] ) ) {
4064 $label = $matches[3];
4069 $pout = $this->parse( $label,
4072 false, // Strip whitespace...?
4073 false // Don't clear state!
4075 $html = $pout->getText();
4077 $ig->add( new Image( $nt ), $html );
4079 # Only add real images (bug #5586)
4080 if ( $nt->getNamespace() == NS_IMAGE
) {
4081 $this->mOutput
->addImage( $nt->getDBkey() );
4084 return $ig->toHTML();
4088 * Parse image options text and use it to make an image
4090 function makeImage( &$nt, $options ) {
4091 global $wgUseImageResize;
4095 # Check if the options text is of the form "options|alt text"
4097 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4098 # * left no resizing, just left align. label is used for alt= only
4099 # * right same, but right aligned
4100 # * none same, but not aligned
4101 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4102 # * center center the image
4103 # * framed Keep original image size, no magnify-button.
4105 $part = explode( '|', $options);
4107 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4108 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4109 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4110 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4111 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4112 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4113 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4114 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4117 $width = $height = $framed = $thumb = false;
4118 $manual_thumb = '' ;
4120 foreach( $part as $key => $val ) {
4121 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4123 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4124 # use manually specified thumbnail
4126 $manual_thumb = $match;
4127 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4128 # remember to set an alignment, don't render immediately
4130 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4131 # remember to set an alignment, don't render immediately
4133 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4134 # remember to set an alignment, don't render immediately
4136 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4137 # remember to set an alignment, don't render immediately
4139 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4140 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4141 # $match is the image width in pixels
4142 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4143 $width = intval( $m[1] );
4144 $height = intval( $m[2] );
4146 $width = intval($match);
4148 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4154 # Strip bad stuff out of the alt text
4155 $alt = $this->replaceLinkHoldersText( $caption );
4157 # make sure there are no placeholders in thumbnail attributes
4158 # that are later expanded to html- so expand them now and
4160 $alt = $this->unstrip($alt, $this->mStripState
);
4161 $alt = Sanitizer
::stripAllTags( $alt );
4163 # Linker does the rest
4164 $sk =& $this->mOptions
->getSkin();
4165 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4169 * Set a flag in the output object indicating that the content is dynamic and
4170 * shouldn't be cached.
4172 function disableCache() {
4173 wfDebug( "Parser output marked as uncacheable.\n" );
4174 $this->mOutput
->mCacheTime
= -1;
4178 * Callback from the Sanitizer for expanding items found in HTML attribute
4179 * values, so they can be safely tested and escaped.
4180 * @param string $text
4181 * @param array $args
4185 function attributeStripCallback( &$text, $args ) {
4186 $text = $this->replaceVariables( $text, $args );
4187 $text = $this->unstripForHTML( $text );
4191 function unstripForHTML( $text ) {
4192 $text = $this->unstrip( $text, $this->mStripState
);
4193 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4201 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4202 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4203 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4209 function getTags() { return array_keys( $this->mTagHooks
); }
4214 * Break wikitext input into sections, and either pull or replace
4215 * some particular section's text.
4217 * External callers should use the getSection and replaceSection methods.
4219 * @param $text Page wikitext
4220 * @param $section Numbered section. 0 pulls the text before the first
4221 * heading; other numbers will pull the given section
4222 * along with its lower-level subsections.
4223 * @param $mode One of "get" or "replace"
4224 * @param $newtext Replacement text for section data.
4225 * @return string for "get", the extracted section text.
4226 * for "replace", the whole page with the section replaced.
4228 private function extractSections( $text, $section, $mode, $newtext='' ) {
4229 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4230 # comments to be stripped as well)
4231 $striparray = array();
4233 $oldOutputType = $this->mOutputType
;
4234 $oldOptions = $this->mOptions
;
4235 $this->mOptions
= new ParserOptions();
4236 $this->mOutputType
= OT_WIKI
;
4238 $striptext = $this->strip( $text, $striparray, true );
4240 $this->mOutputType
= $oldOutputType;
4241 $this->mOptions
= $oldOptions;
4243 # now that we can be sure that no pseudo-sections are in the source,
4244 # split it up by section
4245 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4246 $comment = "(?:$uniq-!--.*?QINU)";
4251 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4253 (=+) # Should this be limited to 6?
4254 .+? # Section title...
4255 \\2 # Ending = count must match start
4262 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4269 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4270 (=+) # Should this be limited to 6?
4271 .+? # Section title...
4272 \\2 # Ending = count must match start
4273 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4282 PREG_SPLIT_DELIM_CAPTURE
);
4284 if( $mode == "get" ) {
4285 if( $section == 0 ) {
4286 // "Section 0" returns the content before any other section.
4291 } elseif( $mode == "replace" ) {
4292 if( $section == 0 ) {
4293 $rv = $newtext . "\n\n";
4302 for( $index = 1; $index < count( $secs ); ) {
4303 $headerLine = $secs[$index++
];
4304 if( $secs[$index] ) {
4306 $headerLevel = strlen( $secs[$index++
] );
4310 $headerLevel = intval( $secs[$index++
] );
4312 $content = $secs[$index++
];
4315 if( $mode == "get" ) {
4316 if( $count == $section ) {
4317 $rv = $headerLine . $content;
4318 $sectionLevel = $headerLevel;
4319 } elseif( $count > $section ) {
4320 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4321 $rv .= $headerLine . $content;
4323 // Broke out to a higher-level section
4327 } elseif( $mode == "replace" ) {
4328 if( $count < $section ) {
4329 $rv .= $headerLine . $content;
4330 } elseif( $count == $section ) {
4331 $rv .= $newtext . "\n\n";
4332 $sectionLevel = $headerLevel;
4333 } elseif( $count > $section ) {
4334 if( $headerLevel <= $sectionLevel ) {
4335 // Passed the section's sub-parts.
4339 $rv .= $headerLine . $content;
4344 # reinsert stripped tags
4345 $rv = $this->unstrip( $rv, $striparray );
4346 $rv = $this->unstripNoWiki( $rv, $striparray );
4352 * This function returns the text of a section, specified by a number ($section).
4353 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4354 * the first section before any such heading (section 0).
4356 * If a section contains subsections, these are also returned.
4358 * @param $text String: text to look in
4359 * @param $section Integer: section number
4360 * @return string text of the requested section
4362 function getSection( $text, $section ) {
4363 return $this->extractSections( $text, $section, "get" );
4366 function replaceSection( $oldtext, $section, $text ) {
4367 return $this->extractSections( $oldtext, $section, "replace", $text );
4374 * @package MediaWiki
4378 var $mText, # The output text
4379 $mLanguageLinks, # List of the full text of language links, in the order they appear
4380 $mCategories, # Map of category names to sort keys
4381 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4382 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4383 $mVersion, # Compatibility check
4384 $mTitleText, # title text of the chosen language variant
4385 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4386 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4387 $mImages, # DB keys of the images used, in the array key only
4388 $mExternalLinks, # External link URLs, in the key only
4389 $mHTMLtitle, # Display HTML title
4390 $mSubtitle, # Additional subtitle
4391 $mNewSection; # Show a new section link?
4393 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4394 $containsOldMagic = false, $titletext = '' )
4396 $this->mText
= $text;
4397 $this->mLanguageLinks
= $languageLinks;
4398 $this->mCategories
= $categoryLinks;
4399 $this->mContainsOldMagic
= $containsOldMagic;
4400 $this->mCacheTime
= '';
4401 $this->mVersion
= MW_PARSER_VERSION
;
4402 $this->mTitleText
= $titletext;
4403 $this->mLinks
= array();
4404 $this->mTemplates
= array();
4405 $this->mImages
= array();
4406 $this->mExternalLinks
= array();
4407 $this->mHTMLtitle
= "" ;
4408 $this->mSubtitle
= "" ;
4409 $this->mNewSection
= false;
4412 function getText() { return $this->mText
; }
4413 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4414 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4415 function &getCategories() { return $this->mCategories
; }
4416 function getCacheTime() { return $this->mCacheTime
; }
4417 function getTitleText() { return $this->mTitleText
; }
4418 function &getLinks() { return $this->mLinks
; }
4419 function &getTemplates() { return $this->mTemplates
; }
4420 function &getImages() { return $this->mImages
; }
4421 function &getExternalLinks() { return $this->mExternalLinks
; }
4423 function containsOldMagic() { return $this->mContainsOldMagic
; }
4424 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4425 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4426 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4427 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4428 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4429 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4431 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4432 function addImage( $name ) { $this->mImages
[$name] = 1; }
4433 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4434 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4436 function setNewSection( $value ) {
4437 $this->mNewSection
= (bool)$value;
4439 function getNewSection() {
4440 return (bool)$this->mNewSection
;
4443 function addLink( $title, $id ) {
4444 $ns = $title->getNamespace();
4445 $dbk = $title->getDBkey();
4446 if ( !isset( $this->mLinks
[$ns] ) ) {
4447 $this->mLinks
[$ns] = array();
4449 $this->mLinks
[$ns][$dbk] = $id;
4452 function addTemplate( $title, $id ) {
4453 $ns = $title->getNamespace();
4454 $dbk = $title->getDBkey();
4455 if ( !isset( $this->mTemplates
[$ns] ) ) {
4456 $this->mTemplates
[$ns] = array();
4458 $this->mTemplates
[$ns][$dbk] = $id;
4462 * Return true if this cached output object predates the global or
4463 * per-article cache invalidation timestamps, or if it comes from
4464 * an incompatible older version.
4466 * @param string $touched the affected article's last touched timestamp
4470 function expired( $touched ) {
4471 global $wgCacheEpoch;
4472 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4473 $this->getCacheTime() < $touched ||
4474 $this->getCacheTime() <= $wgCacheEpoch ||
4475 !isset( $this->mVersion
) ||
4476 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4481 * Set options of the Parser
4483 * @package MediaWiki
4487 # All variables are private
4488 var $mUseTeX; # Use texvc to expand <math> tags
4489 var $mUseDynamicDates; # Use DateFormatter to format dates
4490 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4491 var $mAllowExternalImages; # Allow external images inline
4492 var $mAllowExternalImagesFrom; # If not, any exception?
4493 var $mSkin; # Reference to the preferred skin
4494 var $mDateFormat; # Date format index
4495 var $mEditSection; # Create "edit section" links
4496 var $mNumberHeadings; # Automatically number headings
4497 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4498 var $mTidy; # Ask for tidy cleanup
4499 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4501 function getUseTeX() { return $this->mUseTeX
; }
4502 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4503 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4504 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4505 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4506 function &getSkin() { return $this->mSkin
; }
4507 function getDateFormat() { return $this->mDateFormat
; }
4508 function getEditSection() { return $this->mEditSection
; }
4509 function getNumberHeadings() { return $this->mNumberHeadings
; }
4510 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4511 function getTidy() { return $this->mTidy
; }
4512 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4514 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4515 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4516 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4517 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4518 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4519 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4520 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4521 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4522 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4523 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4524 function setSkin( &$x ) { $this->mSkin
=& $x; }
4525 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4527 function ParserOptions() {
4529 $this->initialiseFromUser( $wgUser );
4533 * Get parser options
4536 function newFromUser( &$user ) {
4537 $popts = new ParserOptions
;
4538 $popts->initialiseFromUser( $user );
4542 /** Get user options */
4543 function initialiseFromUser( &$userInput ) {
4544 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4545 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4546 $fname = 'ParserOptions::initialiseFromUser';
4547 wfProfileIn( $fname );
4548 if ( !$userInput ) {
4550 $user->setLoaded( true );
4552 $user =& $userInput;
4555 $this->mUseTeX
= $wgUseTeX;
4556 $this->mUseDynamicDates
= $wgUseDynamicDates;
4557 $this->mInterwikiMagic
= $wgInterwikiMagic;
4558 $this->mAllowExternalImages
= $wgAllowExternalImages;
4559 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4560 wfProfileIn( $fname.'-skin' );
4561 $this->mSkin
=& $user->getSkin();
4562 wfProfileOut( $fname.'-skin' );
4563 $this->mDateFormat
= $user->getOption( 'date' );
4564 $this->mEditSection
= true;
4565 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4566 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4567 $this->mTidy
= false;
4568 $this->mInterfaceMessage
= false;
4569 wfProfileOut( $fname );
4574 * Callback function used by Parser::replaceLinkHolders()
4575 * to substitute link placeholders.
4577 function &wfOutputReplaceMatches( $matches ) {
4578 global $wgOutputReplace;
4579 return $wgOutputReplace[$matches[1]];
4583 * Return the total number of articles
4585 function wfNumberOfArticles() {
4586 global $wgNumberOfArticles;
4589 return $wgNumberOfArticles;
4593 * Return the number of files
4595 function wfNumberOfFiles() {
4596 $fname = 'wfNumberOfFiles';
4598 wfProfileIn( $fname );
4599 $dbr =& wfGetDB( DB_SLAVE
);
4600 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4601 wfProfileOut( $fname );
4607 * Return the number of user accounts
4610 function wfNumberOfUsers() {
4611 wfProfileIn( 'wfNumberOfUsers' );
4612 $dbr =& wfGetDB( DB_SLAVE
);
4613 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4614 wfProfileOut( 'wfNumberOfUsers' );
4619 * Return the total number of pages
4622 function wfNumberOfPages() {
4623 wfProfileIn( 'wfNumberOfPages' );
4624 $dbr =& wfGetDB( DB_SLAVE
);
4625 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4626 wfProfileOut( 'wfNumberOfPages' );
4631 * Get various statistics from the database
4634 function wfLoadSiteStats() {
4635 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4636 $fname = 'wfLoadSiteStats';
4638 if ( -1 != $wgNumberOfArticles ) return;
4639 $dbr =& wfGetDB( DB_SLAVE
);
4640 $s = $dbr->selectRow( 'site_stats',
4641 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4642 array( 'ss_row_id' => 1 ), $fname
4645 if ( $s === false ) {
4648 $wgTotalViews = $s->ss_total_views
;
4649 $wgTotalEdits = $s->ss_total_edits
;
4650 $wgNumberOfArticles = $s->ss_good_articles
;
4656 * Basically replacing " > and < with HTML entities ( ", >, <)
4658 * @param $in String: text that might contain HTML tags.
4659 * @return string Escaped string
4661 function wfEscapeHTMLTagsOnly( $in ) {
4663 array( '"', '>', '<' ),
4664 array( '"', '>', '<' ),