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]' );
50 # Including space, but excluding newlines
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
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() . ')'.
55 EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
56 define( 'EXT_IMAGE_REGEX',
57 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
58 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
59 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
62 // State constants for the definition list colon extraction
63 define( 'MW_COLON_STATE_TEXT', 0 );
64 define( 'MW_COLON_STATE_TAG', 1 );
65 define( 'MW_COLON_STATE_TAGSTART', 2 );
66 define( 'MW_COLON_STATE_CLOSETAG', 3 );
67 define( 'MW_COLON_STATE_TAGSLASH', 4 );
68 define( 'MW_COLON_STATE_COMMENT', 5 );
69 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
70 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
75 * Processes wiki markup
78 * There are three main entry points into the Parser class:
80 * produces HTML output
82 * produces altered wiki markup.
84 * performs brace substitution on MediaWiki messages
87 * objects: $wgLang, $wgContLang
89 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
92 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
93 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
94 * $wgLocaltimezone, $wgAllowSpecialInclusion*
96 * * only within ParserOptions
107 var $mTagHooks, $mFunctionHooks;
109 # Cleared with clearState():
110 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
111 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
112 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
113 var $mTemplates, // cache of already loaded templates, avoids
114 // multiple SQL queries for the same string
115 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
116 // in this path. Used for loop detection.
119 # These are variables reset at least once per parse regardless of $clearState
120 var $mOptions, // ParserOptions object
121 $mTitle, // Title context, used for self-link rendering and similar things
122 $mOutputType, // Output type, one of the OT_xxx constants
123 $mRevisionId; // ID to display in {{REVISIONID}} tags
133 $this->mTagHooks
= array();
134 $this->mFunctionHooks
= array();
136 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
144 function clearState() {
145 $this->mOutput
= new ParserOutput
;
146 $this->mAutonumber
= 0;
147 $this->mLastSection
= '';
148 $this->mDTopen
= false;
149 $this->mVariables
= false;
150 $this->mIncludeCount
= array();
151 $this->mStripState
= array();
152 $this->mArgStack
= array();
153 $this->mInPre
= false;
154 $this->mInterwikiLinkHolders
= array(
158 $this->mLinkHolders
= array(
159 'namespaces' => array(),
161 'queries' => array(),
165 $this->mRevisionId
= null;
168 * Prefix for temporary replacement strings for the multipass parser.
169 * \x07 should never appear in input as it's disallowed in XML.
170 * Using it at the front also gives us a little extra robustness
171 * since it shouldn't match when butted up against identifier-like
174 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
176 # Clear these on every parse, bug 4549
177 $this->mTemplates
= array();
178 $this->mTemplatePath
= array();
180 $this->mShowToc
= true;
181 $this->mForceTocPosition
= false;
183 wfRunHooks( 'ParserClearState', array( &$this ) );
187 * Accessor for mUniqPrefix.
191 function UniqPrefix() {
192 return $this->mUniqPrefix
;
196 * Convert wikitext to HTML
197 * Do not call this function recursively.
200 * @param string $text Text we want to parse
201 * @param Title &$title A title object
202 * @param array $options
203 * @param boolean $linestart
204 * @param boolean $clearState
205 * @param int $revid number to pass in {{REVISIONID}}
206 * @return ParserOutput a ParserOutput
208 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
210 * First pass--just handle <nowiki> sections, pass the rest off
211 * to internalParse() which does all the real work.
214 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
215 $fname = 'Parser::parse';
216 wfProfileIn( $fname );
222 $this->mOptions
= $options;
223 $this->mTitle
=& $title;
224 $this->mRevisionId
= $revid;
225 $this->mOutputType
= OT_HTML
;
227 //$text = $this->strip( $text, $this->mStripState );
228 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
229 $x =& $this->mStripState
;
231 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
232 $text = $this->strip( $text, $x );
233 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
235 # Hook to suspend the parser in this state
236 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
237 wfProfileOut( $fname );
241 $text = $this->internalParse( $text );
243 $text = $this->unstrip( $text, $this->mStripState
);
245 # Clean up special characters, only run once, next-to-last before doBlockLevels
247 # french spaces, last one Guillemet-left
248 # only if there is something before the space
249 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
250 # french spaces, Guillemet-right
251 '/(\\302\\253) /' => '\\1 ',
253 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
256 $text = $this->doBlockLevels( $text, $linestart );
258 $this->replaceLinkHolders( $text );
260 # the position of the parserConvert() call should not be changed. it
261 # assumes that the links are all replaced and the only thing left
262 # is the <nowiki> mark.
263 # Side-effects: this calls $this->mOutput->setTitleText()
264 $text = $wgContLang->parserConvert( $text, $this );
266 $text = $this->unstripNoWiki( $text, $this->mStripState
);
268 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
270 $text = Sanitizer
::normalizeCharReferences( $text );
272 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
273 $text = Parser
::tidy($text);
275 # attempt to sanitize at least some nesting problems
276 # (bug #2702 and quite a few others)
278 # ''Something [http://www.cool.com cool''] -->
279 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
280 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
281 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
282 # fix up an anchor inside another anchor, only
283 # at least for a single single nested link (bug 3695)
284 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
285 '\\1\\2</a>\\3</a>\\1\\4</a>',
286 # fix div inside inline elements- doBlockLevels won't wrap a line which
287 # contains a div, so fix it up here; replace
288 # div with escaped text
289 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
290 '\\1\\3<div\\5>\\6</div>\\8\\9',
291 # remove empty italic or bold tag pairs, some
292 # introduced by rules above
293 '/<([bi])><\/\\1>/' => ''
296 $text = preg_replace(
297 array_keys( $tidyregs ),
298 array_values( $tidyregs ),
302 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
304 $this->mOutput
->setText( $text );
305 wfProfileOut( $fname );
307 return $this->mOutput
;
311 * Get a random string
316 function getRandomString() {
317 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
320 function &getTitle() { return $this->mTitle
; }
321 function getOptions() { return $this->mOptions
; }
324 * Replaces all occurrences of HTML-style comments and the given tags
325 * in the text with a random marker and returns teh next text. The output
326 * parameter $matches will be an associative array filled with data in
328 * 'UNIQ-xxxxx' => array(
331 * array( 'param' => 'x' ),
332 * '<element param="x">tag content</element>' ) )
334 * @param $elements list of element names. Comments are always extracted.
335 * @param $text Source text string.
336 * @param $uniq_prefix
341 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
342 $rand = Parser
::getRandomString();
347 $taglist = implode( '|', $elements );
348 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
350 while ( '' != $text ) {
351 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
353 if( count( $p ) < 5 ) {
356 if( count( $p ) > 5 ) {
370 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
) . '-QINU';
371 $stripped .= $marker;
373 if ( $close === '/>' ) {
374 // Empty element tag, <tag />
379 if( $element == '!--' ) {
382 $end = "/(<\\/$element\\s*>)/i";
384 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
386 if( count( $q ) < 3 ) {
387 # No end tag -- let it run out to the end of the text.
396 $matches[$marker] = array( $element,
398 Sanitizer
::decodeTagAttributes( $attributes ),
399 "<$element$attributes$close$content$tail" );
405 * Strips and renders nowiki, pre, math, hiero
406 * If $render is set, performs necessary rendering operations on plugins
407 * Returns the text, and fills an array with data needed in unstrip()
408 * If the $state is already a valid strip state, it adds to the state
410 * @param bool $stripcomments when set, HTML comments <!-- like this -->
411 * will be stripped in addition to other tags. This is important
412 * for section editing, where these comments cause confusion when
413 * counting the sections in the wikisource
417 function strip( $text, &$state, $stripcomments = false ) {
418 $render = ($this->mOutputType
== OT_HTML
);
420 # Replace any instances of the placeholders
421 $uniq_prefix = $this->mUniqPrefix
;
422 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
423 $commentState = array();
425 $elements = array_merge(
426 array( 'nowiki', 'gallery' ),
427 array_keys( $this->mTagHooks
) );
430 $elements[] = 'html';
432 if( $this->mOptions
->getUseTeX() ) {
433 $elements[] = 'math';
438 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
440 foreach( $matches as $marker => $data ) {
441 list( $element, $content, $params, $tag ) = $data;
443 $tagName = strtolower( $element );
447 if( substr( $tag, -3 ) == '-->' ) {
450 // Unclosed comment in input.
451 // Close it so later stripping can remove it
460 // Shouldn't happen otherwise. :)
462 $output = wfEscapeHTMLTagsOnly( $content );
465 $output = MathRenderer
::renderMath( $content );
468 $output = $this->renderImageGallery( $content );
471 if( isset( $this->mTagHooks
[$tagName] ) ) {
472 $output = call_user_func_array( $this->mTagHooks
[$tagName],
473 array( $content, $params, $this ) );
475 throw new MWException( "Invalid call hook $element" );
479 // Just stripping tags; keep the source
482 if( !$stripcomments && $element == '!--' ) {
483 $commentState[$marker] = $output;
485 $state[$element][$marker] = $output;
489 # Unstrip comments unless explicitly told otherwise.
490 # (The comments are always stripped prior to this point, so as to
491 # not invoke any extension tags / parser hooks contained within
493 if ( !$stripcomments ) {
494 // Put them all back and forget them
495 $text = strtr( $text, $commentState );
502 * Restores pre, math, and other extensions removed by strip()
504 * always call unstripNoWiki() after this one
507 function unstrip( $text, &$state ) {
508 if ( !is_array( $state ) ) {
512 $replacements = array();
513 foreach( $state as $tag => $contentDict ) {
514 if( $tag != 'nowiki' && $tag != 'html' ) {
515 foreach( $contentDict as $uniq => $content ) {
516 $replacements[$uniq] = $content;
520 $text = strtr( $text, $replacements );
526 * Always call this after unstrip() to preserve the order
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
535 $replacements = array();
536 foreach( $state as $tag => $contentDict ) {
537 if( $tag == 'nowiki' ||
$tag == 'html' ) {
538 foreach( $contentDict as $uniq => $content ) {
539 $replacements[$uniq] = $content;
543 $text = strtr( $text, $replacements );
549 * Add an item to the strip state
550 * Returns the unique tag which must be inserted into the stripped text
551 * The tag will be replaced with the original text in unstrip()
555 function insertStripItem( $text, &$state ) {
556 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
560 $state['item'][$rnd] = $text;
565 * Interface with html tidy, used if $wgUseTidy = true.
566 * If tidy isn't able to correct the markup, the original will be
567 * returned in all its glory with a warning comment appended.
569 * Either the external tidy program or the in-process tidy extension
570 * will be used depending on availability. Override the default
571 * $wgTidyInternal setting to disable the internal if it's not working.
573 * @param string $text Hideous HTML input
574 * @return string Corrected HTML output
578 function tidy( $text ) {
579 global $wgTidyInternal;
580 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
581 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
582 '<head><title>test</title></head><body>'.$text.'</body></html>';
583 if( $wgTidyInternal ) {
584 $correctedtext = Parser
::internalTidy( $wrappedtext );
586 $correctedtext = Parser
::externalTidy( $wrappedtext );
588 if( is_null( $correctedtext ) ) {
589 wfDebug( "Tidy error detected!\n" );
590 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
592 return $correctedtext;
596 * Spawn an external HTML tidy process and get corrected markup back from it.
601 function externalTidy( $text ) {
602 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
603 $fname = 'Parser::externalTidy';
604 wfProfileIn( $fname );
609 $descriptorspec = array(
610 0 => array('pipe', 'r'),
611 1 => array('pipe', 'w'),
612 2 => array('file', '/dev/null', 'a')
615 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
616 if (is_resource($process)) {
617 // Theoretically, this style of communication could cause a deadlock
618 // here. If the stdout buffer fills up, then writes to stdin could
619 // block. This doesn't appear to happen with tidy, because tidy only
620 // writes to stdout after it's finished reading from stdin. Search
621 // for tidyParseStdin and tidySaveStdout in console/tidy.c
622 fwrite($pipes[0], $text);
624 while (!feof($pipes[1])) {
625 $cleansource .= fgets($pipes[1], 1024);
628 proc_close($process);
631 wfProfileOut( $fname );
633 if( $cleansource == '' && $text != '') {
634 // Some kind of error happened, so we couldn't get the corrected text.
635 // Just give up; we'll use the source text and append a warning.
643 * Use the HTML tidy PECL extension to use the tidy library in-process,
644 * saving the overhead of spawning a new process. Currently written to
645 * the PHP 4.3.x version of the extension, may not work on PHP 5.
647 * 'pear install tidy' should be able to compile the extension module.
652 function internalTidy( $text ) {
654 $fname = 'Parser::internalTidy';
655 wfProfileIn( $fname );
657 tidy_load_config( $wgTidyConf );
658 tidy_set_encoding( 'utf8' );
659 tidy_parse_string( $text );
661 if( tidy_get_status() == 2 ) {
662 // 2 is magic number for fatal error
663 // http://www.php.net/manual/en/function.tidy-get-status.php
666 $cleansource = tidy_get_output();
668 wfProfileOut( $fname );
673 * parse the wiki syntax used to render tables
677 function doTableStuff ( $t ) {
678 $fname = 'Parser::doTableStuff';
679 wfProfileIn( $fname );
681 $t = explode ( "\n" , $t ) ;
682 $td = array () ; # Is currently a td tag open?
683 $ltd = array () ; # Was it TD or TH?
684 $tr = array () ; # Is currently a tr tag open?
685 $ltr = array () ; # tr attributes
686 $has_opened_tr = array(); # Did this table open a <tr> element?
687 $indent_level = 0; # indent level of the table
688 foreach ( $t AS $k => $x )
691 $fc = substr ( $x , 0 , 1 ) ;
692 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
693 $indent_level = strlen( $matches[1] );
695 $attributes = $this->unstripForHTML( $matches[2] );
697 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
698 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
699 array_push ( $td , false ) ;
700 array_push ( $ltd , '' ) ;
701 array_push ( $tr , false ) ;
702 array_push ( $ltr , '' ) ;
703 array_push ( $has_opened_tr, false );
705 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
706 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
707 $z = "</table>" . substr ( $x , 2);
708 $l = array_pop ( $ltd ) ;
709 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
710 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
711 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
713 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
715 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
716 $x = substr ( $x , 1 ) ;
717 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
719 $l = array_pop ( $ltd ) ;
720 array_pop ( $has_opened_tr );
721 array_push ( $has_opened_tr , true ) ;
722 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
723 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
726 array_push ( $tr , false ) ;
727 array_push ( $td , false ) ;
728 array_push ( $ltd , '' ) ;
729 $attributes = $this->unstripForHTML( $x );
730 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
732 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
734 if ( '|+' == substr ( $x , 0 , 2 ) ) {
736 $x = substr ( $x , 1 ) ;
738 $after = substr ( $x , 1 ) ;
739 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
741 // Split up multiple cells on the same line.
742 // FIXME: This can result in improper nesting of tags processed
743 // by earlier parser steps, but should avoid splitting up eg
744 // attribute values containing literal "||".
745 $after = wfExplodeMarkup( '||', $after );
749 # Loop through each table cell
750 foreach ( $after AS $theline )
755 $tra = array_pop ( $ltr ) ;
756 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
757 array_push ( $tr , true ) ;
758 array_push ( $ltr , '' ) ;
759 array_pop ( $has_opened_tr );
760 array_push ( $has_opened_tr , true ) ;
763 $l = array_pop ( $ltd ) ;
764 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
765 if ( $fc == '|' ) $l = 'td' ;
766 else if ( $fc == '!' ) $l = 'th' ;
767 else if ( $fc == '+' ) $l = 'caption' ;
769 array_push ( $ltd , $l ) ;
772 $y = explode ( '|' , $theline , 2 ) ;
773 # Note that a '|' inside an invalid link should not
774 # be mistaken as delimiting cell parameters
775 if ( strpos( $y[0], '[[' ) !== false ) {
776 $y = array ($theline);
778 if ( count ( $y ) == 1 )
779 $y = "{$z}<{$l}>{$y[0]}" ;
781 $attributes = $this->unstripForHTML( $y[0] );
782 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
785 array_push ( $td , true ) ;
790 # Closing open td, tr && table
791 while ( count ( $td ) > 0 )
793 $l = array_pop ( $ltd ) ;
794 if ( array_pop ( $td ) ) $t[] = '</td>' ;
795 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
796 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
800 $t = implode ( "\n" , $t ) ;
801 # special case: don't return empty table
802 if($t == "<table>\n<tr><td></td></tr>\n</table>")
804 wfProfileOut( $fname );
809 * Helper function for parse() that transforms wiki markup into
810 * HTML. Only called for $mOutputType == OT_HTML.
814 function internalParse( $text ) {
817 $fname = 'Parser::internalParse';
818 wfProfileIn( $fname );
820 # Remove <noinclude> tags and <includeonly> sections
821 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
822 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
823 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
825 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
827 $text = $this->replaceVariables( $text, $args );
829 // Tables need to come after variable replacement for things to work
830 // properly; putting them before other transformations should keep
831 // exciting things like link expansions from showing up in surprising
833 $text = $this->doTableStuff( $text );
835 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
837 $text = $this->stripToc( $text );
838 $text = $this->doHeadings( $text );
839 if($this->mOptions
->getUseDynamicDates()) {
840 $df =& DateFormatter
::getInstance();
841 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
843 $text = $this->doAllQuotes( $text );
844 $text = $this->replaceInternalLinks( $text );
845 $text = $this->replaceExternalLinks( $text );
847 # replaceInternalLinks may sometimes leave behind
848 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
849 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
851 $text = $this->doMagicLinks( $text );
852 $text = $this->formatHeadings( $text, $isMain );
854 wfProfileOut( $fname );
859 * Replace special strings like "ISBN xxx" and "RFC xxx" with
860 * magic external links.
864 function &doMagicLinks( &$text ) {
865 $text = $this->magicISBN( $text );
866 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
867 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
872 * Parse headers and return html
876 function doHeadings( $text ) {
877 $fname = 'Parser::doHeadings';
878 wfProfileIn( $fname );
879 for ( $i = 6; $i >= 1; --$i ) {
880 $h = str_repeat( '=', $i );
881 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
882 "<h{$i}>\\1</h{$i}>\\2", $text );
884 wfProfileOut( $fname );
889 * Replace single quotes with HTML markup
891 * @return string the altered text
893 function doAllQuotes( $text ) {
894 $fname = 'Parser::doAllQuotes';
895 wfProfileIn( $fname );
897 $lines = explode( "\n", $text );
898 foreach ( $lines as $line ) {
899 $outtext .= $this->doQuotes ( $line ) . "\n";
901 $outtext = substr($outtext, 0,-1);
902 wfProfileOut( $fname );
907 * Helper function for doAllQuotes()
910 function doQuotes( $text ) {
911 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
912 if ( count( $arr ) == 1 )
916 # First, do some preliminary work. This may shift some apostrophes from
917 # being mark-up to being text. It also counts the number of occurrences
918 # of bold and italics mark-ups.
922 foreach ( $arr as $r )
924 if ( ( $i %
2 ) == 1 )
926 # If there are ever four apostrophes, assume the first is supposed to
927 # be text, and the remaining three constitute mark-up for bold text.
928 if ( strlen( $arr[$i] ) == 4 )
933 # If there are more than 5 apostrophes in a row, assume they're all
934 # text except for the last 5.
935 else if ( strlen( $arr[$i] ) > 5 )
937 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
940 # Count the number of occurrences of bold and italics mark-ups.
941 # We are not counting sequences of five apostrophes.
942 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
943 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
944 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
949 # If there is an odd number of both bold and italics, it is likely
950 # that one of the bold ones was meant to be an apostrophe followed
951 # by italics. Which one we cannot know for certain, but it is more
952 # likely to be one that has a single-letter word before it.
953 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
956 $firstsingleletterword = -1;
957 $firstmultiletterword = -1;
959 foreach ( $arr as $r )
961 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
963 $x1 = substr ($arr[$i-1], -1);
964 $x2 = substr ($arr[$i-1], -2, 1);
966 if ($firstspace == -1) $firstspace = $i;
967 } else if ($x2 == ' ') {
968 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
970 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
976 # If there is a single-letter word, use it!
977 if ($firstsingleletterword > -1)
979 $arr [ $firstsingleletterword ] = "''";
980 $arr [ $firstsingleletterword-1 ] .= "'";
982 # If not, but there's a multi-letter word, use that one.
983 else if ($firstmultiletterword > -1)
985 $arr [ $firstmultiletterword ] = "''";
986 $arr [ $firstmultiletterword-1 ] .= "'";
988 # ... otherwise use the first one that has neither.
989 # (notice that it is possible for all three to be -1 if, for example,
990 # there is only one pentuple-apostrophe in the line)
991 else if ($firstspace > -1)
993 $arr [ $firstspace ] = "''";
994 $arr [ $firstspace-1 ] .= "'";
998 # Now let's actually convert our apostrophic mush to HTML!
1003 foreach ($arr as $r)
1007 if ($state == 'both')
1014 if (strlen ($r) == 2)
1017 { $output .= '</i>'; $state = ''; }
1018 else if ($state == 'bi')
1019 { $output .= '</i>'; $state = 'b'; }
1020 else if ($state == 'ib')
1021 { $output .= '</b></i><b>'; $state = 'b'; }
1022 else if ($state == 'both')
1023 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1024 else # $state can be 'b' or ''
1025 { $output .= '<i>'; $state .= 'i'; }
1027 else if (strlen ($r) == 3)
1030 { $output .= '</b>'; $state = ''; }
1031 else if ($state == 'bi')
1032 { $output .= '</i></b><i>'; $state = 'i'; }
1033 else if ($state == 'ib')
1034 { $output .= '</b>'; $state = 'i'; }
1035 else if ($state == 'both')
1036 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1037 else # $state can be 'i' or ''
1038 { $output .= '<b>'; $state .= 'b'; }
1040 else if (strlen ($r) == 5)
1043 { $output .= '</b><i>'; $state = 'i'; }
1044 else if ($state == 'i')
1045 { $output .= '</i><b>'; $state = 'b'; }
1046 else if ($state == 'bi')
1047 { $output .= '</i></b>'; $state = ''; }
1048 else if ($state == 'ib')
1049 { $output .= '</b></i>'; $state = ''; }
1050 else if ($state == 'both')
1051 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1052 else # ($state == '')
1053 { $buffer = ''; $state = 'both'; }
1058 # Now close all remaining tags. Notice that the order is important.
1059 if ($state == 'b' ||
$state == 'ib')
1061 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1065 if ($state == 'both')
1066 $output .= '<b><i>'.$buffer.'</i></b>';
1072 * Replace external links
1074 * Note: this is all very hackish and the order of execution matters a lot.
1075 * Make sure to run maintenance/parserTests.php if you change this code.
1079 function replaceExternalLinks( $text ) {
1081 $fname = 'Parser::replaceExternalLinks';
1082 wfProfileIn( $fname );
1084 $sk =& $this->mOptions
->getSkin();
1086 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1088 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1091 while ( $i<count( $bits ) ) {
1093 $protocol = $bits[$i++
];
1094 $text = $bits[$i++
];
1095 $trail = $bits[$i++
];
1097 # The characters '<' and '>' (which were escaped by
1098 # removeHTMLtags()) should not be included in
1099 # URLs, per RFC 2396.
1100 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1101 $text = substr($url, $m2[0][1]) . ' ' . $text;
1102 $url = substr($url, 0, $m2[0][1]);
1105 # If the link text is an image URL, replace it with an <img> tag
1106 # This happened by accident in the original parser, but some people used it extensively
1107 $img = $this->maybeMakeExternalImage( $text );
1108 if ( $img !== false ) {
1114 # Set linktype for CSS - if URL==text, link is essentially free
1115 $linktype = ($text == $url) ?
'free' : 'text';
1117 # No link text, e.g. [http://domain.tld/some.link]
1118 if ( $text == '' ) {
1119 # Autonumber if allowed. See bug #5918
1120 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1121 $text = '[' . ++
$this->mAutonumber
. ']';
1122 $linktype = 'autonumber';
1124 # Otherwise just use the URL
1125 $text = htmlspecialchars( $url );
1129 # Have link text, e.g. [http://domain.tld/some.link text]s
1131 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1134 $text = $wgContLang->markNoConversion($text);
1136 # Normalize any HTML entities in input. They will be
1137 # re-escaped by makeExternalLink().
1138 $url = Sanitizer
::decodeCharReferences( $url );
1140 # Process the trail (i.e. everything after this link up until start of the next link),
1141 # replacing any non-bracketed links
1142 $trail = $this->replaceFreeExternalLinks( $trail );
1144 # Use the encoded URL
1145 # This means that users can paste URLs directly into the text
1146 # Funny characters like ö aren't valid in URLs anyway
1147 # This was changed in August 2004
1148 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1150 # Register link in the output object.
1151 # Replace unnecessary URL escape codes with the referenced character
1152 # This prevents spammers from hiding links from the filters
1153 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1154 $this->mOutput
->addExternalLink( $pasteurized );
1157 wfProfileOut( $fname );
1162 * Replace anything that looks like a URL with a link
1165 function replaceFreeExternalLinks( $text ) {
1167 $fname = 'Parser::replaceFreeExternalLinks';
1168 wfProfileIn( $fname );
1170 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1171 $s = array_shift( $bits );
1174 $sk =& $this->mOptions
->getSkin();
1176 while ( $i < count( $bits ) ){
1177 $protocol = $bits[$i++
];
1178 $remainder = $bits[$i++
];
1180 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1181 # Found some characters after the protocol that look promising
1182 $url = $protocol . $m[1];
1185 # special case: handle urls as url args:
1186 # http://www.example.com/foo?=http://www.example.com/bar
1187 if(strlen($trail) == 0 &&
1189 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1190 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1193 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1198 # The characters '<' and '>' (which were escaped by
1199 # removeHTMLtags()) should not be included in
1200 # URLs, per RFC 2396.
1201 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1202 $trail = substr($url, $m2[0][1]) . $trail;
1203 $url = substr($url, 0, $m2[0][1]);
1206 # Move trailing punctuation to $trail
1208 # If there is no left bracket, then consider right brackets fair game too
1209 if ( strpos( $url, '(' ) === false ) {
1213 $numSepChars = strspn( strrev( $url ), $sep );
1214 if ( $numSepChars ) {
1215 $trail = substr( $url, -$numSepChars ) . $trail;
1216 $url = substr( $url, 0, -$numSepChars );
1219 # Normalize any HTML entities in input. They will be
1220 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1221 $url = Sanitizer
::decodeCharReferences( $url );
1223 # Is this an external image?
1224 $text = $this->maybeMakeExternalImage( $url );
1225 if ( $text === false ) {
1226 # Not an image, make a link
1227 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1228 # Register it in the output object...
1229 # Replace unnecessary URL escape codes with their equivalent characters
1230 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1231 $this->mOutput
->addExternalLink( $pasteurized );
1233 $s .= $text . $trail;
1235 $s .= $protocol . $remainder;
1238 wfProfileOut( $fname );
1243 * Replace unusual URL escape codes with their equivalent characters
1247 * @fixme This can merge genuinely required bits in the path or query string,
1248 * breaking legit URLs. A proper fix would treat the various parts of
1249 * the URL differently; as a workaround, just use the output for
1250 * statistical records, not for actual linking/output.
1252 function replaceUnusualEscapes( $url ) {
1253 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1254 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1258 * Callback function used in replaceUnusualEscapes().
1259 * Replaces unusual URL escape codes with their equivalent character
1263 function replaceUnusualEscapesCallback( $matches ) {
1264 $char = urldecode( $matches[0] );
1265 $ord = ord( $char );
1266 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1267 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1268 // No, shouldn't be escaped
1271 // Yes, leave it escaped
1277 * make an image if it's allowed, either through the global
1278 * option or through the exception
1281 function maybeMakeExternalImage( $url ) {
1282 $sk =& $this->mOptions
->getSkin();
1283 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1284 $imagesexception = !empty($imagesfrom);
1286 if ( $this->mOptions
->getAllowExternalImages()
1287 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1288 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1290 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1297 * Process [[ ]] wikilinks
1301 function replaceInternalLinks( $s ) {
1303 static $fname = 'Parser::replaceInternalLinks' ;
1305 wfProfileIn( $fname );
1307 wfProfileIn( $fname.'-setup' );
1309 # the % is needed to support urlencoded titles as well
1310 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1312 $sk =& $this->mOptions
->getSkin();
1314 #split the entire text string on occurences of [[
1315 $a = explode( '[[', ' ' . $s );
1316 #get the first element (all text up to first [[), and remove the space we added
1317 $s = array_shift( $a );
1318 $s = substr( $s, 1 );
1320 # Match a link having the form [[namespace:link|alternate]]trail
1322 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1323 # Match cases where there is no "]]", which might still be images
1324 static $e1_img = FALSE;
1325 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1326 # Match the end of a line for a word that's not followed by whitespace,
1327 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1328 $e2 = wfMsgForContent( 'linkprefix' );
1330 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1332 if( is_null( $this->mTitle
) ) {
1333 throw new MWException( 'nooo' );
1335 $nottalk = !$this->mTitle
->isTalkPage();
1337 if ( $useLinkPrefixExtension ) {
1338 if ( preg_match( $e2, $s, $m ) ) {
1339 $first_prefix = $m[2];
1341 $first_prefix = false;
1347 $selflink = $this->mTitle
->getPrefixedText();
1348 wfProfileOut( $fname.'-setup' );
1350 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1351 $useSubpages = $this->areSubpagesAllowed();
1353 # Loop for each link
1354 for ($k = 0; isset( $a[$k] ); $k++
) {
1356 if ( $useLinkPrefixExtension ) {
1357 wfProfileIn( $fname.'-prefixhandling' );
1358 if ( preg_match( $e2, $s, $m ) ) {
1366 $prefix = $first_prefix;
1367 $first_prefix = false;
1369 wfProfileOut( $fname.'-prefixhandling' );
1372 $might_be_img = false;
1374 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1376 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1377 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1378 # the real problem is with the $e1 regex
1381 # Still some problems for cases where the ] is meant to be outside punctuation,
1382 # and no image is in sight. See bug 2095.
1385 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1386 strpos($text, '[') !== false
1389 $text .= ']'; # so that replaceExternalLinks($text) works later
1392 # fix up urlencoded title texts
1393 if(preg_match('/%/', $m[1] ))
1394 # Should anchors '#' also be rejected?
1395 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1397 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1398 $might_be_img = true;
1400 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1402 } else { # Invalid form; output directly
1403 $s .= $prefix . '[[' . $line ;
1407 # Don't allow internal links to pages containing
1408 # PROTO: where PROTO is a valid URL protocol; these
1409 # should be external links.
1410 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1411 $s .= $prefix . '[[' . $line ;
1415 # Make subpage if necessary
1416 if( $useSubpages ) {
1417 $link = $this->maybeDoSubpageLink( $m[1], $text );
1422 $noforce = (substr($m[1], 0, 1) != ':');
1424 # Strip off leading ':'
1425 $link = substr($link, 1);
1428 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1430 $s .= $prefix . '[[' . $line;
1434 #check other language variants of the link
1435 #if the article does not exist
1436 if( $checkVariantLink
1437 && $nt->getArticleID() == 0 ) {
1438 $wgContLang->findVariantLink($link, $nt);
1441 $ns = $nt->getNamespace();
1442 $iw = $nt->getInterWiki();
1444 if ($might_be_img) { # if this is actually an invalid link
1445 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1447 while (isset ($a[$k+
1]) ) {
1448 #look at the next 'line' to see if we can close it there
1449 $spliced = array_splice( $a, $k +
1, 1 );
1450 $next_line = array_shift( $spliced );
1451 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1452 # the first ]] closes the inner link, the second the image
1454 $text .= '[[' . $m[1];
1457 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1458 #if there's exactly one ]] that's fine, we'll keep looking
1459 $text .= '[[' . $m[0];
1461 #if $next_line is invalid too, we need look no further
1462 $text .= '[[' . $next_line;
1467 # we couldn't find the end of this imageLink, so output it raw
1468 #but don't ignore what might be perfectly normal links in the text we've examined
1469 $text = $this->replaceInternalLinks($text);
1470 $s .= $prefix . '[[' . $link . '|' . $text;
1471 # note: no $trail, because without an end, there *is* no trail
1474 } else { #it's not an image, so output it raw
1475 $s .= $prefix . '[[' . $link . '|' . $text;
1476 # note: no $trail, because without an end, there *is* no trail
1481 $wasblank = ( '' == $text );
1482 if( $wasblank ) $text = $link;
1485 # Link not escaped by : , create the various objects
1489 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1490 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1491 $s = rtrim($s . "\n");
1492 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1496 if ( $ns == NS_IMAGE
) {
1497 wfProfileIn( "$fname-image" );
1498 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1499 # recursively parse links inside the image caption
1500 # actually, this will parse them in any other parameters, too,
1501 # but it might be hard to fix that, and it doesn't matter ATM
1502 $text = $this->replaceExternalLinks($text);
1503 $text = $this->replaceInternalLinks($text);
1505 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1506 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1507 $this->mOutput
->addImage( $nt->getDBkey() );
1509 wfProfileOut( "$fname-image" );
1512 wfProfileOut( "$fname-image" );
1516 if ( $ns == NS_CATEGORY
) {
1517 wfProfileIn( "$fname-category" );
1518 $s = rtrim($s . "\n"); # bug 87
1521 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1522 $sortkey = $this->mTitle
->getText();
1524 $sortkey = $this->mTitle
->getPrefixedText();
1529 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1530 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1531 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1534 * Strip the whitespace Category links produce, see bug 87
1535 * @todo We might want to use trim($tmp, "\n") here.
1537 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1539 wfProfileOut( "$fname-category" );
1544 if( ( $nt->getPrefixedText() === $selflink ) &&
1545 ( $nt->getFragment() === '' ) ) {
1546 # Self-links are handled specially; generally de-link and change to bold.
1547 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1551 # Special and Media are pseudo-namespaces; no pages actually exist in them
1552 if( $ns == NS_MEDIA
) {
1553 $link = $sk->makeMediaLinkObj( $nt, $text );
1554 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1555 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1556 $this->mOutput
->addImage( $nt->getDBkey() );
1558 } elseif( $ns == NS_SPECIAL
) {
1559 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1561 } elseif( $ns == NS_IMAGE
) {
1562 $img = Image
::newFromTitle( $nt );
1563 if( $img->exists() ) {
1564 // Force a blue link if the file exists; may be a remote
1565 // upload on the shared repository, and we want to see its
1566 // auto-generated page.
1567 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1571 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1573 wfProfileOut( $fname );
1578 * Make a link placeholder. The text returned can be later resolved to a real link with
1579 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1580 * parsing of interwiki links, and secondly to allow all extistence checks and
1581 * article length checks (for stub links) to be bundled into a single query.
1584 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1585 if ( ! is_object($nt) ) {
1587 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1589 # Separate the link trail from the rest of the link
1590 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1592 if ( $nt->isExternal() ) {
1593 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1594 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1595 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1597 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1598 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1599 $this->mLinkHolders
['queries'][] = $query;
1600 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1601 $this->mLinkHolders
['titles'][] = $nt;
1603 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1610 * Render a forced-blue link inline; protect against double expansion of
1611 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1612 * Since this little disaster has to split off the trail text to avoid
1613 * breaking URLs in the following text without breaking trails on the
1614 * wiki links, it's been made into a horrible function.
1617 * @param string $text
1618 * @param string $query
1619 * @param string $trail
1620 * @param string $prefix
1621 * @return string HTML-wikitext mix oh yuck
1623 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1624 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1625 $sk =& $this->mOptions
->getSkin();
1626 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1627 return $this->armorLinks( $link ) . $trail;
1631 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1632 * going to go through further parsing steps before inline URL expansion.
1634 * In particular this is important when using action=render, which causes
1635 * full URLs to be included.
1637 * Oh man I hate our multi-layer parser!
1639 * @param string more-or-less HTML
1640 * @return string less-or-more HTML with NOPARSE bits
1642 function armorLinks( $text ) {
1643 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1644 "{$this->mUniqPrefix}NOPARSE$1", $text );
1648 * Return true if subpage links should be expanded on this page.
1651 function areSubpagesAllowed() {
1652 # Some namespaces don't allow subpages
1653 global $wgNamespacesWithSubpages;
1654 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1658 * Handle link to subpage if necessary
1659 * @param string $target the source of the link
1660 * @param string &$text the link text, modified as necessary
1661 * @return string the full name of the link
1664 function maybeDoSubpageLink($target, &$text) {
1667 # :Foobar -- override special treatment of prefix (images, language links)
1668 # /Foobar -- convert to CurrentPage/Foobar
1669 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1670 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1671 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1673 $fname = 'Parser::maybeDoSubpageLink';
1674 wfProfileIn( $fname );
1675 $ret = $target; # default return value is no change
1677 # Some namespaces don't allow subpages,
1678 # so only perform processing if subpages are allowed
1679 if( $this->areSubpagesAllowed() ) {
1680 # Look at the first character
1681 if( $target != '' && $target{0} == '/' ) {
1682 # / at end means we don't want the slash to be shown
1683 if( substr( $target, -1, 1 ) == '/' ) {
1684 $target = substr( $target, 1, -1 );
1687 $noslash = substr( $target, 1 );
1690 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1691 if( '' === $text ) {
1693 } # this might be changed for ugliness reasons
1695 # check for .. subpage backlinks
1697 $nodotdot = $target;
1698 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1700 $nodotdot = substr( $nodotdot, 3 );
1702 if($dotdotcount > 0) {
1703 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1704 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1705 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1706 # / at the end means don't show full path
1707 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1708 $nodotdot = substr( $nodotdot, 0, -1 );
1709 if( '' === $text ) {
1713 $nodotdot = trim( $nodotdot );
1714 if( $nodotdot != '' ) {
1715 $ret .= '/' . $nodotdot;
1722 wfProfileOut( $fname );
1727 * Used by doBlockLevels()
1730 /* private */ function closeParagraph() {
1732 if ( '' != $this->mLastSection
) {
1733 $result = '</' . $this->mLastSection
. ">\n";
1735 $this->mInPre
= false;
1736 $this->mLastSection
= '';
1739 # getCommon() returns the length of the longest common substring
1740 # of both arguments, starting at the beginning of both.
1742 /* private */ function getCommon( $st1, $st2 ) {
1743 $fl = strlen( $st1 );
1744 $shorter = strlen( $st2 );
1745 if ( $fl < $shorter ) { $shorter = $fl; }
1747 for ( $i = 0; $i < $shorter; ++
$i ) {
1748 if ( $st1{$i} != $st2{$i} ) { break; }
1752 # These next three functions open, continue, and close the list
1753 # element appropriate to the prefix character passed into them.
1755 /* private */ function openList( $char ) {
1756 $result = $this->closeParagraph();
1758 if ( '*' == $char ) { $result .= '<ul><li>'; }
1759 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1760 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1761 else if ( ';' == $char ) {
1762 $result .= '<dl><dt>';
1763 $this->mDTopen
= true;
1765 else { $result = '<!-- ERR 1 -->'; }
1770 /* private */ function nextItem( $char ) {
1771 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1772 else if ( ':' == $char ||
';' == $char ) {
1774 if ( $this->mDTopen
) { $close = '</dt>'; }
1775 if ( ';' == $char ) {
1776 $this->mDTopen
= true;
1777 return $close . '<dt>';
1779 $this->mDTopen
= false;
1780 return $close . '<dd>';
1783 return '<!-- ERR 2 -->';
1786 /* private */ function closeList( $char ) {
1787 if ( '*' == $char ) { $text = '</li></ul>'; }
1788 else if ( '#' == $char ) { $text = '</li></ol>'; }
1789 else if ( ':' == $char ) {
1790 if ( $this->mDTopen
) {
1791 $this->mDTopen
= false;
1792 $text = '</dt></dl>';
1794 $text = '</dd></dl>';
1797 else { return '<!-- ERR 3 -->'; }
1803 * Make lists from lines starting with ':', '*', '#', etc.
1806 * @return string the lists rendered as HTML
1808 function doBlockLevels( $text, $linestart ) {
1809 $fname = 'Parser::doBlockLevels';
1810 wfProfileIn( $fname );
1812 # Parsing through the text line by line. The main thing
1813 # happening here is handling of block-level elements p, pre,
1814 # and making lists from lines starting with * # : etc.
1816 $textLines = explode( "\n", $text );
1818 $lastPrefix = $output = '';
1819 $this->mDTopen
= $inBlockElem = false;
1821 $paragraphStack = false;
1823 if ( !$linestart ) {
1824 $output .= array_shift( $textLines );
1826 foreach ( $textLines as $oLine ) {
1827 $lastPrefixLength = strlen( $lastPrefix );
1828 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1829 $preOpenMatch = preg_match('/<pre/i', $oLine );
1830 if ( !$this->mInPre
) {
1831 # Multiple prefixes may abut each other for nested lists.
1832 $prefixLength = strspn( $oLine, '*#:;' );
1833 $pref = substr( $oLine, 0, $prefixLength );
1836 $pref2 = str_replace( ';', ':', $pref );
1837 $t = substr( $oLine, $prefixLength );
1838 $this->mInPre
= !empty($preOpenMatch);
1840 # Don't interpret any other prefixes in preformatted text
1842 $pref = $pref2 = '';
1847 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1848 # Same as the last item, so no need to deal with nesting or opening stuff
1849 $output .= $this->nextItem( substr( $pref, -1 ) );
1850 $paragraphStack = false;
1852 if ( substr( $pref, -1 ) == ';') {
1853 # The one nasty exception: definition lists work like this:
1854 # ; title : definition text
1855 # So we check for : in the remainder text to split up the
1856 # title and definition, without b0rking links.
1858 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1860 $output .= $term . $this->nextItem( ':' );
1863 } elseif( $prefixLength ||
$lastPrefixLength ) {
1864 # Either open or close a level...
1865 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1866 $paragraphStack = false;
1868 while( $commonPrefixLength < $lastPrefixLength ) {
1869 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1870 --$lastPrefixLength;
1872 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1873 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1875 while ( $prefixLength > $commonPrefixLength ) {
1876 $char = substr( $pref, $commonPrefixLength, 1 );
1877 $output .= $this->openList( $char );
1879 if ( ';' == $char ) {
1880 # FIXME: This is dupe of code above
1881 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1883 $output .= $term . $this->nextItem( ':' );
1886 ++
$commonPrefixLength;
1888 $lastPrefix = $pref2;
1890 if( 0 == $prefixLength ) {
1891 wfProfileIn( "$fname-paragraph" );
1892 # No prefix (not in list)--go to paragraph mode
1893 // XXX: use a stack for nestable elements like span, table and div
1894 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1895 $closematch = preg_match(
1896 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1897 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1898 if ( $openmatch or $closematch ) {
1899 $paragraphStack = false;
1900 #Â TODO bug 5718: paragraph closed
1901 $output .= $this->closeParagraph();
1902 if ( $preOpenMatch and !$preCloseMatch ) {
1903 $this->mInPre
= true;
1905 if ( $closematch ) {
1906 $inBlockElem = false;
1908 $inBlockElem = true;
1910 } else if ( !$inBlockElem && !$this->mInPre
) {
1911 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1913 if ($this->mLastSection
!= 'pre') {
1914 $paragraphStack = false;
1915 $output .= $this->closeParagraph().'<pre>';
1916 $this->mLastSection
= 'pre';
1918 $t = substr( $t, 1 );
1921 if ( '' == trim($t) ) {
1922 if ( $paragraphStack ) {
1923 $output .= $paragraphStack.'<br />';
1924 $paragraphStack = false;
1925 $this->mLastSection
= 'p';
1927 if ($this->mLastSection
!= 'p' ) {
1928 $output .= $this->closeParagraph();
1929 $this->mLastSection
= '';
1930 $paragraphStack = '<p>';
1932 $paragraphStack = '</p><p>';
1936 if ( $paragraphStack ) {
1937 $output .= $paragraphStack;
1938 $paragraphStack = false;
1939 $this->mLastSection
= 'p';
1940 } else if ($this->mLastSection
!= 'p') {
1941 $output .= $this->closeParagraph().'<p>';
1942 $this->mLastSection
= 'p';
1947 wfProfileOut( "$fname-paragraph" );
1949 // somewhere above we forget to get out of pre block (bug 785)
1950 if($preCloseMatch && $this->mInPre
) {
1951 $this->mInPre
= false;
1953 if ($paragraphStack === false) {
1957 while ( $prefixLength ) {
1958 $output .= $this->closeList( $pref2{$prefixLength-1} );
1961 if ( '' != $this->mLastSection
) {
1962 $output .= '</' . $this->mLastSection
. '>';
1963 $this->mLastSection
= '';
1966 wfProfileOut( $fname );
1971 * Split up a string on ':', ignoring any occurences inside tags
1972 * to prevent illegal overlapping.
1973 * @param string $str the string to split
1974 * @param string &$before set to everything before the ':'
1975 * @param string &$after set to everything after the ':'
1976 * return string the position of the ':', or false if none found
1978 function findColonNoLinks($str, &$before, &$after) {
1979 $fname = 'Parser::findColonNoLinks';
1980 wfProfileIn( $fname );
1982 $pos = strpos( $str, ':' );
1983 if( $pos === false ) {
1985 wfProfileOut( $fname );
1989 $lt = strpos( $str, '<' );
1990 if( $lt === false ||
$lt > $pos ) {
1991 // Easy; no tag nesting to worry about
1992 $before = substr( $str, 0, $pos );
1993 $after = substr( $str, $pos+
1 );
1994 wfProfileOut( $fname );
1998 // Ugly state machine to walk through avoiding tags.
1999 $state = MW_COLON_STATE_TEXT
;
2001 $len = strlen( $str );
2002 for( $i = 0; $i < $len; $i++
) {
2006 // (Using the number is a performance hack for common cases)
2007 case 0: // MW_COLON_STATE_TEXT:
2010 // Could be either a <start> tag or an </end> tag
2011 $state = MW_COLON_STATE_TAGSTART
;
2016 $before = substr( $str, 0, $i );
2017 $after = substr( $str, $i +
1 );
2018 wfProfileOut( $fname );
2021 // Embedded in a tag; don't break it.
2024 // Skip ahead looking for something interesting
2025 $colon = strpos( $str, ':', $i );
2026 if( $colon === false ) {
2027 // Nothing else interesting
2028 wfProfileOut( $fname );
2031 $lt = strpos( $str, '<', $i );
2032 if( $stack === 0 ) {
2033 if( $lt === false ||
$colon < $lt ) {
2035 $before = substr( $str, 0, $colon );
2036 $after = substr( $str, $colon +
1 );
2037 wfProfileOut( $fname );
2041 if( $lt === false ) {
2042 // Nothing else interesting to find; abort!
2043 // We're nested, but there's no close tags left. Abort!
2046 // Skip ahead to next tag start
2048 $state = MW_COLON_STATE_TAGSTART
;
2051 case 1: // MW_COLON_STATE_TAG:
2056 $state = MW_COLON_STATE_TEXT
;
2059 // Slash may be followed by >?
2060 $state = MW_COLON_STATE_TAGSLASH
;
2066 case 2: // MW_COLON_STATE_TAGSTART:
2069 $state = MW_COLON_STATE_CLOSETAG
;
2072 $state = MW_COLON_STATE_COMMENT
;
2075 // Illegal early close? This shouldn't happen D:
2076 $state = MW_COLON_STATE_TEXT
;
2079 $state = MW_COLON_STATE_TAG
;
2082 case 3: // MW_COLON_STATE_CLOSETAG:
2087 wfDebug( "Invalid input in $fname; too many close tags\n" );
2088 wfProfileOut( $fname );
2091 $state = MW_COLON_STATE_TEXT
;
2094 case MW_COLON_STATE_TAGSLASH
:
2096 // Yes, a self-closed tag <blah/>
2097 $state = MW_COLON_STATE_TEXT
;
2099 // Probably we're jumping the gun, and this is an attribute
2100 $state = MW_COLON_STATE_TAG
;
2103 case 5: // MW_COLON_STATE_COMMENT:
2105 $state = MW_COLON_STATE_COMMENTDASH
;
2108 case MW_COLON_STATE_COMMENTDASH
:
2110 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2112 $state = MW_COLON_STATE_COMMENT
;
2115 case MW_COLON_STATE_COMMENTDASHDASH
:
2117 $state = MW_COLON_STATE_TEXT
;
2119 $state = MW_COLON_STATE_COMMENT
;
2123 throw new MWException( "State machine error in $fname" );
2127 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2130 wfProfileOut( $fname );
2135 * Return value of a magic variable (like PAGENAME)
2139 function getVariableValue( $index ) {
2140 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2143 * Some of these require message or data lookups and can be
2144 * expensive to check many times.
2146 static $varCache = array();
2147 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2148 if ( isset( $varCache[$index] ) )
2149 return $varCache[$index];
2152 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2155 case MAG_CURRENTMONTH
:
2156 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2157 case MAG_CURRENTMONTHNAME
:
2158 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2159 case MAG_CURRENTMONTHNAMEGEN
:
2160 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2161 case MAG_CURRENTMONTHABBREV
:
2162 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2163 case MAG_CURRENTDAY
:
2164 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2165 case MAG_CURRENTDAY2
:
2166 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2168 return $this->mTitle
->getText();
2170 return $this->mTitle
->getPartialURL();
2171 case MAG_FULLPAGENAME
:
2172 return $this->mTitle
->getPrefixedText();
2173 case MAG_FULLPAGENAMEE
:
2174 return $this->mTitle
->getPrefixedURL();
2175 case MAG_SUBPAGENAME
:
2176 return $this->mTitle
->getSubpageText();
2177 case MAG_SUBPAGENAMEE
:
2178 return $this->mTitle
->getSubpageUrlForm();
2179 case MAG_BASEPAGENAME
:
2180 return $this->mTitle
->getBaseText();
2181 case MAG_BASEPAGENAMEE
:
2182 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2183 case MAG_TALKPAGENAME
:
2184 if( $this->mTitle
->canTalk() ) {
2185 $talkPage = $this->mTitle
->getTalkPage();
2186 return $talkPage->getPrefixedText();
2190 case MAG_TALKPAGENAMEE
:
2191 if( $this->mTitle
->canTalk() ) {
2192 $talkPage = $this->mTitle
->getTalkPage();
2193 return $talkPage->getPrefixedUrl();
2197 case MAG_SUBJECTPAGENAME
:
2198 $subjPage = $this->mTitle
->getSubjectPage();
2199 return $subjPage->getPrefixedText();
2200 case MAG_SUBJECTPAGENAMEE
:
2201 $subjPage = $this->mTitle
->getSubjectPage();
2202 return $subjPage->getPrefixedUrl();
2203 case MAG_REVISIONID
:
2204 return $this->mRevisionId
;
2206 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2207 case MAG_NAMESPACEE
:
2208 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2210 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2211 case MAG_TALKSPACEE
:
2212 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2213 case MAG_SUBJECTSPACE
:
2214 return $this->mTitle
->getSubjectNsText();
2215 case MAG_SUBJECTSPACEE
:
2216 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2217 case MAG_CURRENTDAYNAME
:
2218 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2219 case MAG_CURRENTYEAR
:
2220 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2221 case MAG_CURRENTTIME
:
2222 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2223 case MAG_CURRENTWEEK
:
2224 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2225 // int to remove the padding
2226 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2227 case MAG_CURRENTDOW
:
2228 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2229 case MAG_NUMBEROFARTICLES
:
2230 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2231 case MAG_NUMBEROFFILES
:
2232 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2233 case MAG_NUMBEROFUSERS
:
2234 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2235 case MAG_NUMBEROFPAGES
:
2236 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2237 case MAG_CURRENTTIMESTAMP
:
2238 return $varCache[$index] = wfTimestampNow();
2239 case MAG_CURRENTVERSION
:
2246 case MAG_SERVERNAME
:
2247 return $wgServerName;
2248 case MAG_SCRIPTPATH
:
2249 return $wgScriptPath;
2250 case MAG_DIRECTIONMARK
:
2251 return $wgContLang->getDirMark();
2252 case MAG_CONTENTLANGUAGE
:
2253 global $wgContLanguageCode;
2254 return $wgContLanguageCode;
2257 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2265 * initialise the magic variables (like CURRENTMONTHNAME)
2269 function initialiseVariables() {
2270 $fname = 'Parser::initialiseVariables';
2271 wfProfileIn( $fname );
2272 global $wgVariableIDs;
2273 $this->mVariables
= array();
2274 foreach ( $wgVariableIDs as $id ) {
2275 $mw =& MagicWord
::get( $id );
2276 $mw->addToArray( $this->mVariables
, $id );
2278 wfProfileOut( $fname );
2282 * parse any parentheses in format ((title|part|part))
2283 * and call callbacks to get a replacement text for any found piece
2285 * @param string $text The text to parse
2286 * @param array $callbacks rules in form:
2287 * '{' => array( # opening parentheses
2288 * 'end' => '}', # closing parentheses
2289 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2290 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2295 function replace_callback ($text, $callbacks) {
2296 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2297 $lastOpeningBrace = -1; # last not closed parentheses
2299 for ($i = 0; $i < strlen($text); $i++
) {
2300 # check for any opening brace
2303 foreach ($callbacks as $key => $value) {
2304 $pos = strpos ($text, $key, $i);
2305 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2311 if ($lastOpeningBrace >= 0) {
2312 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2314 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2319 $pos = strpos ($text, '|', $i);
2321 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2332 # found openning brace, lets add it to parentheses stack
2333 if (null != $rule) {
2334 $piece = array('brace' => $text[$i],
2335 'braceEnd' => $rule['end'],
2340 # count openning brace characters
2341 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2346 $piece['startAt'] = $i+
1;
2347 $piece['partStart'] = $i+
1;
2349 # we need to add to stack only if openning brace count is enough for any given rule
2350 foreach ($rule['cb'] as $cnt => $fn) {
2351 if ($piece['count'] >= $cnt) {
2352 $lastOpeningBrace ++
;
2353 $openingBraceStack[$lastOpeningBrace] = $piece;
2360 else if ($lastOpeningBrace >= 0) {
2361 # first check if it is a closing brace
2362 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2363 # lets check if it is enough characters for closing brace
2365 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2368 # if there are more closing parentheses than opening ones, we parse less
2369 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2370 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2372 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2374 $matchingCallback = null;
2375 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2376 if ($count >= $cnt && $matchingCount < $cnt) {
2377 $matchingCount = $cnt;
2378 $matchingCallback = $fn;
2382 if ($matchingCount == 0) {
2387 # lets set a title or last part (if '|' was found)
2388 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2389 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2391 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2393 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2394 $pieceEnd = $i +
$matchingCount;
2396 if( is_callable( $matchingCallback ) ) {
2398 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2399 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2400 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2401 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2403 # finally we can call a user callback and replace piece of text
2404 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2405 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2406 $i = $pieceStart +
strlen($replaceWith) - 1;
2409 # null value for callback means that parentheses should be parsed, but not replaced
2410 $i +
= $matchingCount - 1;
2413 # reset last openning parentheses, but keep it in case there are unused characters
2414 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2415 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2416 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2419 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2420 $openingBraceStack[$lastOpeningBrace--] = null;
2422 if ($matchingCount < $piece['count']) {
2423 $piece['count'] -= $matchingCount;
2424 $piece['startAt'] -= $matchingCount;
2425 $piece['partStart'] = $piece['startAt'];
2426 # do we still qualify for any callback with remaining count?
2427 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2428 if ($piece['count'] >= $cnt) {
2429 $lastOpeningBrace ++
;
2430 $openingBraceStack[$lastOpeningBrace] = $piece;
2438 # lets set a title if it is a first separator, or next part otherwise
2439 if ($text[$i] == '|') {
2440 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2441 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2442 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2445 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2447 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2456 * Replace magic variables, templates, and template arguments
2457 * with the appropriate text. Templates are substituted recursively,
2458 * taking care to avoid infinite loops.
2460 * Note that the substitution depends on value of $mOutputType:
2461 * OT_WIKI: only {{subst:}} templates
2462 * OT_MSG: only magic variables
2463 * OT_HTML: all templates and magic variables
2465 * @param string $tex The text to transform
2466 * @param array $args Key-value pairs representing template parameters to substitute
2467 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2470 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2471 # Prevent too big inclusions
2472 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2476 $fname = 'Parser::replaceVariables';
2477 wfProfileIn( $fname );
2479 # This function is called recursively. To keep track of arguments we need a stack:
2480 array_push( $this->mArgStack
, $args );
2482 $braceCallbacks = array();
2484 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2486 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2487 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2489 $callbacks = array();
2490 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2491 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2492 $text = $this->replace_callback ($text, $callbacks);
2494 array_pop( $this->mArgStack
);
2496 wfProfileOut( $fname );
2501 * Replace magic variables
2504 function variableSubstitution( $matches ) {
2505 $fname = 'Parser::variableSubstitution';
2506 $varname = $matches[1];
2507 wfProfileIn( $fname );
2508 if ( !$this->mVariables
) {
2509 $this->initialiseVariables();
2512 if ( $this->mOutputType
== OT_WIKI
) {
2513 # Do only magic variables prefixed by SUBST
2514 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2515 if (!$mwSubst->matchStartAndRemove( $varname ))
2517 # Note that if we don't substitute the variable below,
2518 # we don't remove the {{subst:}} magic word, in case
2519 # it is a template rather than a magic variable.
2521 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2522 $id = $this->mVariables
[$varname];
2523 $text = $this->getVariableValue( $id );
2524 $this->mOutput
->mContainsOldMagic
= true;
2526 $text = $matches[0];
2528 wfProfileOut( $fname );
2532 # Split template arguments
2533 function getTemplateArgs( $argsString ) {
2534 if ( $argsString === '' ) {
2538 $args = explode( '|', substr( $argsString, 1 ) );
2540 # If any of the arguments contains a '[[' but no ']]', it needs to be
2541 # merged with the next arg because the '|' character between belongs
2542 # to the link syntax and not the template parameter syntax.
2543 $argc = count($args);
2545 for ( $i = 0; $i < $argc-1; $i++
) {
2546 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2547 $args[$i] .= '|'.$args[$i+
1];
2548 array_splice($args, $i+
1, 1);
2558 * Return the text of a template, after recursively
2559 * replacing any variables or templates within the template.
2561 * @param array $piece The parts of the template
2562 * $piece['text']: matched text
2563 * $piece['title']: the title, i.e. the part before the |
2564 * $piece['parts']: the parameter array
2565 * @return string the text of the template
2568 function braceSubstitution( $piece ) {
2569 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2570 $fname = 'Parser::braceSubstitution';
2571 wfProfileIn( $fname );
2574 $found = false; # $text has been filled
2575 $nowiki = false; # wiki markup in $text should be escaped
2576 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2577 $noargs = false; # Don't replace triple-brace arguments in $text
2578 $replaceHeadings = false; # Make the edit section links go to the template not the article
2579 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2580 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2582 # Title object, where $text came from
2587 # $part1 is the bit before the first |, and must contain only title characters
2588 # $args is a list of arguments, starting from index 0, not including $part1
2590 $part1 = $piece['title'];
2591 # If the third subpattern matched anything, it will start with |
2593 if (null == $piece['parts']) {
2594 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2595 if ($replaceWith != $piece['text']) {
2596 $text = $replaceWith;
2603 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2604 $argc = count( $args );
2608 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2609 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2610 # One of two possibilities is true:
2611 # 1) Found SUBST but not in the PST phase
2612 # 2) Didn't find SUBST and in the PST phase
2613 # In either case, return without further processing
2614 $text = $piece['text'];
2621 # MSG, MSGNW, INT and RAW
2624 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2625 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2628 # Remove obsolete MSG:
2629 $mwMsg =& MagicWord
::get( MAG_MSG
);
2630 $mwMsg->matchStartAndRemove( $part1 );
2634 $mwRaw =& MagicWord
::get( MAG_RAW
);
2635 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2636 $forceRawInterwiki = true;
2639 # Check if it is an internal message
2640 $mwInt =& MagicWord
::get( MAG_INT
);
2641 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2642 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2643 $text = $linestart . wfMsgReal( $part1, $args, true );
2651 # Check for NS: (namespace expansion)
2652 $mwNs = MagicWord
::get( MAG_NS
);
2653 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2654 if ( intval( $part1 ) ||
$part1 == "0" ) {
2655 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2658 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2659 if ( !is_null( $index ) ) {
2660 $text = $linestart . $wgContLang->getNsText( $index );
2669 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2670 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2671 $text = $linestart . urlencode( $part1 );
2676 # LCFIRST, UCFIRST, LC and UC
2678 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2679 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2680 $lc =& MagicWord
::get( MAG_LC
);
2681 $uc =& MagicWord
::get( MAG_UC
);
2682 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2683 $text = $linestart . $wgContLang->lcfirst( $part1 );
2685 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2686 $text = $linestart . $wgContLang->ucfirst( $part1 );
2688 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2689 $text = $linestart . $wgContLang->lc( $part1 );
2691 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2692 $text = $linestart . $wgContLang->uc( $part1 );
2697 # LOCALURL and FULLURL
2699 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2700 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2701 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2702 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2705 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2706 $func = 'getLocalURL';
2707 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2708 $func = 'escapeLocalURL';
2709 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2710 $func = 'getFullURL';
2711 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2712 $func = 'escapeFullURL';
2717 if ( $func !== false ) {
2718 $title = Title
::newFromText( $part1 );
2719 # Due to order of execution of a lot of bits, the values might be encoded
2720 # before arriving here; if that's true, then the title can't be created
2721 # and the variable will fail. If we can't get a decent title from the first
2722 # attempt, url-decode and try for a second.
2723 if( is_null( $title ) )
2724 $title = Title
::newFromUrl( urldecode( $part1 ) );
2725 if ( !is_null( $title ) ) {
2727 $text = $linestart . $title->$func( $args[0] );
2729 $text = $linestart . $title->$func();
2736 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2738 if ( !$found && $argc == 1 ) {
2739 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2740 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2741 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2747 if ( !$found && $argc >= 2 ) {
2748 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2749 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2750 while ( count($args) < 5 ) { $args[] = $args[count($args)-1]; }
2751 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1],
2752 $args[2], $args[3], $args[4]);
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 * Tag hook handler for 'pre'.
4037 function renderPreTag( $text, $attribs, $parser ) {
4038 // Backwards-compatibility hack
4039 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4041 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4042 return wfOpenElement( 'pre', $attribs ) .
4043 wfEscapeHTMLTagsOnly( $content ) .
4048 * Renders an image gallery from a text with one line per image.
4049 * text labels may be given by using |-style alternative text. E.g.
4050 * Image:one.jpg|The number "1"
4051 * Image:tree.jpg|A tree
4052 * given as text will return the HTML of a gallery with two images,
4053 * labeled 'The number "1"' and
4056 function renderImageGallery( $text ) {
4057 $ig = new ImageGallery();
4058 $ig->setShowBytes( false );
4059 $ig->setShowFilename( false );
4061 $lines = explode( "\n", $text );
4063 foreach ( $lines as $line ) {
4064 # match lines like these:
4065 # Image:someimage.jpg|This is some image
4066 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4068 if ( count( $matches ) == 0 ) {
4071 $nt =& Title
::newFromText( $matches[1] );
4072 if( is_null( $nt ) ) {
4073 # Bogus title. Ignore these so we don't bomb out later.
4076 if ( isset( $matches[3] ) ) {
4077 $label = $matches[3];
4082 $pout = $this->parse( $label,
4085 false, // Strip whitespace...?
4086 false // Don't clear state!
4088 $html = $pout->getText();
4090 $ig->add( new Image( $nt ), $html );
4092 # Only add real images (bug #5586)
4093 if ( $nt->getNamespace() == NS_IMAGE
) {
4094 $this->mOutput
->addImage( $nt->getDBkey() );
4097 return $ig->toHTML();
4101 * Parse image options text and use it to make an image
4103 function makeImage( &$nt, $options ) {
4104 global $wgUseImageResize;
4108 # Check if the options text is of the form "options|alt text"
4110 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4111 # * left no resizing, just left align. label is used for alt= only
4112 # * right same, but right aligned
4113 # * none same, but not aligned
4114 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4115 # * center center the image
4116 # * framed Keep original image size, no magnify-button.
4118 $part = explode( '|', $options);
4120 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4121 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4122 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4123 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4124 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4125 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4126 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4127 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4130 $width = $height = $framed = $thumb = false;
4131 $manual_thumb = '' ;
4133 foreach( $part as $key => $val ) {
4134 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4136 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4137 # use manually specified thumbnail
4139 $manual_thumb = $match;
4140 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4141 # remember to set an alignment, don't render immediately
4143 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4144 # remember to set an alignment, don't render immediately
4146 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4147 # remember to set an alignment, don't render immediately
4149 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4150 # remember to set an alignment, don't render immediately
4152 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4153 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4154 # $match is the image width in pixels
4155 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4156 $width = intval( $m[1] );
4157 $height = intval( $m[2] );
4159 $width = intval($match);
4161 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4167 # Strip bad stuff out of the alt text
4168 $alt = $this->replaceLinkHoldersText( $caption );
4170 # make sure there are no placeholders in thumbnail attributes
4171 # that are later expanded to html- so expand them now and
4173 $alt = $this->unstrip($alt, $this->mStripState
);
4174 $alt = Sanitizer
::stripAllTags( $alt );
4176 # Linker does the rest
4177 $sk =& $this->mOptions
->getSkin();
4178 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4182 * Set a flag in the output object indicating that the content is dynamic and
4183 * shouldn't be cached.
4185 function disableCache() {
4186 wfDebug( "Parser output marked as uncacheable.\n" );
4187 $this->mOutput
->mCacheTime
= -1;
4191 * Callback from the Sanitizer for expanding items found in HTML attribute
4192 * values, so they can be safely tested and escaped.
4193 * @param string $text
4194 * @param array $args
4198 function attributeStripCallback( &$text, $args ) {
4199 $text = $this->replaceVariables( $text, $args );
4200 $text = $this->unstripForHTML( $text );
4204 function unstripForHTML( $text ) {
4205 $text = $this->unstrip( $text, $this->mStripState
);
4206 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4214 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4215 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4216 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4222 function getTags() { return array_keys( $this->mTagHooks
); }
4227 * Break wikitext input into sections, and either pull or replace
4228 * some particular section's text.
4230 * External callers should use the getSection and replaceSection methods.
4232 * @param $text Page wikitext
4233 * @param $section Numbered section. 0 pulls the text before the first
4234 * heading; other numbers will pull the given section
4235 * along with its lower-level subsections.
4236 * @param $mode One of "get" or "replace"
4237 * @param $newtext Replacement text for section data.
4238 * @return string for "get", the extracted section text.
4239 * for "replace", the whole page with the section replaced.
4241 private function extractSections( $text, $section, $mode, $newtext='' ) {
4242 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4243 # comments to be stripped as well)
4244 $striparray = array();
4246 $oldOutputType = $this->mOutputType
;
4247 $oldOptions = $this->mOptions
;
4248 $this->mOptions
= new ParserOptions();
4249 $this->mOutputType
= OT_WIKI
;
4251 $striptext = $this->strip( $text, $striparray, true );
4253 $this->mOutputType
= $oldOutputType;
4254 $this->mOptions
= $oldOptions;
4256 # now that we can be sure that no pseudo-sections are in the source,
4257 # split it up by section
4258 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4259 $comment = "(?:$uniq-!--.*?QINU)";
4264 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4266 (=+) # Should this be limited to 6?
4267 .+? # Section title...
4268 \\2 # Ending = count must match start
4275 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4282 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4283 (=+) # Should this be limited to 6?
4284 .+? # Section title...
4285 \\2 # Ending = count must match start
4286 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4295 PREG_SPLIT_DELIM_CAPTURE
);
4297 if( $mode == "get" ) {
4298 if( $section == 0 ) {
4299 // "Section 0" returns the content before any other section.
4304 } elseif( $mode == "replace" ) {
4305 if( $section == 0 ) {
4306 $rv = $newtext . "\n\n";
4315 for( $index = 1; $index < count( $secs ); ) {
4316 $headerLine = $secs[$index++
];
4317 if( $secs[$index] ) {
4319 $headerLevel = strlen( $secs[$index++
] );
4323 $headerLevel = intval( $secs[$index++
] );
4325 $content = $secs[$index++
];
4328 if( $mode == "get" ) {
4329 if( $count == $section ) {
4330 $rv = $headerLine . $content;
4331 $sectionLevel = $headerLevel;
4332 } elseif( $count > $section ) {
4333 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4334 $rv .= $headerLine . $content;
4336 // Broke out to a higher-level section
4340 } elseif( $mode == "replace" ) {
4341 if( $count < $section ) {
4342 $rv .= $headerLine . $content;
4343 } elseif( $count == $section ) {
4344 $rv .= $newtext . "\n\n";
4345 $sectionLevel = $headerLevel;
4346 } elseif( $count > $section ) {
4347 if( $headerLevel <= $sectionLevel ) {
4348 // Passed the section's sub-parts.
4352 $rv .= $headerLine . $content;
4357 # reinsert stripped tags
4358 $rv = $this->unstrip( $rv, $striparray );
4359 $rv = $this->unstripNoWiki( $rv, $striparray );
4365 * This function returns the text of a section, specified by a number ($section).
4366 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4367 * the first section before any such heading (section 0).
4369 * If a section contains subsections, these are also returned.
4371 * @param $text String: text to look in
4372 * @param $section Integer: section number
4373 * @return string text of the requested section
4375 function getSection( $text, $section ) {
4376 return $this->extractSections( $text, $section, "get" );
4379 function replaceSection( $oldtext, $section, $text ) {
4380 return $this->extractSections( $oldtext, $section, "replace", $text );
4387 * @package MediaWiki
4391 var $mText, # The output text
4392 $mLanguageLinks, # List of the full text of language links, in the order they appear
4393 $mCategories, # Map of category names to sort keys
4394 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4395 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4396 $mVersion, # Compatibility check
4397 $mTitleText, # title text of the chosen language variant
4398 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4399 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4400 $mImages, # DB keys of the images used, in the array key only
4401 $mExternalLinks, # External link URLs, in the key only
4402 $mHTMLtitle, # Display HTML title
4403 $mSubtitle, # Additional subtitle
4404 $mNewSection; # Show a new section link?
4406 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4407 $containsOldMagic = false, $titletext = '' )
4409 $this->mText
= $text;
4410 $this->mLanguageLinks
= $languageLinks;
4411 $this->mCategories
= $categoryLinks;
4412 $this->mContainsOldMagic
= $containsOldMagic;
4413 $this->mCacheTime
= '';
4414 $this->mVersion
= MW_PARSER_VERSION
;
4415 $this->mTitleText
= $titletext;
4416 $this->mLinks
= array();
4417 $this->mTemplates
= array();
4418 $this->mImages
= array();
4419 $this->mExternalLinks
= array();
4420 $this->mHTMLtitle
= "" ;
4421 $this->mSubtitle
= "" ;
4422 $this->mNewSection
= false;
4425 function getText() { return $this->mText
; }
4426 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4427 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4428 function &getCategories() { return $this->mCategories
; }
4429 function getCacheTime() { return $this->mCacheTime
; }
4430 function getTitleText() { return $this->mTitleText
; }
4431 function &getLinks() { return $this->mLinks
; }
4432 function &getTemplates() { return $this->mTemplates
; }
4433 function &getImages() { return $this->mImages
; }
4434 function &getExternalLinks() { return $this->mExternalLinks
; }
4436 function containsOldMagic() { return $this->mContainsOldMagic
; }
4437 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4438 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4439 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4440 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4441 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4442 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4444 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4445 function addImage( $name ) { $this->mImages
[$name] = 1; }
4446 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4447 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4449 function setNewSection( $value ) {
4450 $this->mNewSection
= (bool)$value;
4452 function getNewSection() {
4453 return (bool)$this->mNewSection
;
4456 function addLink( $title, $id ) {
4457 $ns = $title->getNamespace();
4458 $dbk = $title->getDBkey();
4459 if ( !isset( $this->mLinks
[$ns] ) ) {
4460 $this->mLinks
[$ns] = array();
4462 $this->mLinks
[$ns][$dbk] = $id;
4465 function addTemplate( $title, $id ) {
4466 $ns = $title->getNamespace();
4467 $dbk = $title->getDBkey();
4468 if ( !isset( $this->mTemplates
[$ns] ) ) {
4469 $this->mTemplates
[$ns] = array();
4471 $this->mTemplates
[$ns][$dbk] = $id;
4475 * Return true if this cached output object predates the global or
4476 * per-article cache invalidation timestamps, or if it comes from
4477 * an incompatible older version.
4479 * @param string $touched the affected article's last touched timestamp
4483 function expired( $touched ) {
4484 global $wgCacheEpoch;
4485 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4486 $this->getCacheTime() < $touched ||
4487 $this->getCacheTime() <= $wgCacheEpoch ||
4488 !isset( $this->mVersion
) ||
4489 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4494 * Set options of the Parser
4496 * @package MediaWiki
4500 # All variables are private
4501 var $mUseTeX; # Use texvc to expand <math> tags
4502 var $mUseDynamicDates; # Use DateFormatter to format dates
4503 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4504 var $mAllowExternalImages; # Allow external images inline
4505 var $mAllowExternalImagesFrom; # If not, any exception?
4506 var $mSkin; # Reference to the preferred skin
4507 var $mDateFormat; # Date format index
4508 var $mEditSection; # Create "edit section" links
4509 var $mNumberHeadings; # Automatically number headings
4510 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4511 var $mTidy; # Ask for tidy cleanup
4512 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4514 function getUseTeX() { return $this->mUseTeX
; }
4515 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4516 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4517 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4518 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4519 function &getSkin() { return $this->mSkin
; }
4520 function getDateFormat() { return $this->mDateFormat
; }
4521 function getEditSection() { return $this->mEditSection
; }
4522 function getNumberHeadings() { return $this->mNumberHeadings
; }
4523 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4524 function getTidy() { return $this->mTidy
; }
4525 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4527 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4528 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4529 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4530 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4531 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4532 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4533 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4534 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4535 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4536 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4537 function setSkin( &$x ) { $this->mSkin
=& $x; }
4538 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4540 function ParserOptions() {
4542 $this->initialiseFromUser( $wgUser );
4546 * Get parser options
4549 function newFromUser( &$user ) {
4550 $popts = new ParserOptions
;
4551 $popts->initialiseFromUser( $user );
4555 /** Get user options */
4556 function initialiseFromUser( &$userInput ) {
4557 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4558 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4559 $fname = 'ParserOptions::initialiseFromUser';
4560 wfProfileIn( $fname );
4561 if ( !$userInput ) {
4563 $user->setLoaded( true );
4565 $user =& $userInput;
4568 $this->mUseTeX
= $wgUseTeX;
4569 $this->mUseDynamicDates
= $wgUseDynamicDates;
4570 $this->mInterwikiMagic
= $wgInterwikiMagic;
4571 $this->mAllowExternalImages
= $wgAllowExternalImages;
4572 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4573 wfProfileIn( $fname.'-skin' );
4574 $this->mSkin
=& $user->getSkin();
4575 wfProfileOut( $fname.'-skin' );
4576 $this->mDateFormat
= $user->getOption( 'date' );
4577 $this->mEditSection
= true;
4578 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4579 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4580 $this->mTidy
= false;
4581 $this->mInterfaceMessage
= false;
4582 wfProfileOut( $fname );
4587 * Callback function used by Parser::replaceLinkHolders()
4588 * to substitute link placeholders.
4590 function &wfOutputReplaceMatches( $matches ) {
4591 global $wgOutputReplace;
4592 return $wgOutputReplace[$matches[1]];
4596 * Return the total number of articles
4598 function wfNumberOfArticles() {
4599 global $wgNumberOfArticles;
4602 return $wgNumberOfArticles;
4606 * Return the number of files
4608 function wfNumberOfFiles() {
4609 $fname = 'wfNumberOfFiles';
4611 wfProfileIn( $fname );
4612 $dbr =& wfGetDB( DB_SLAVE
);
4613 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4614 wfProfileOut( $fname );
4620 * Return the number of user accounts
4623 function wfNumberOfUsers() {
4624 wfProfileIn( 'wfNumberOfUsers' );
4625 $dbr =& wfGetDB( DB_SLAVE
);
4626 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4627 wfProfileOut( 'wfNumberOfUsers' );
4632 * Return the total number of pages
4635 function wfNumberOfPages() {
4636 wfProfileIn( 'wfNumberOfPages' );
4637 $dbr =& wfGetDB( DB_SLAVE
);
4638 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4639 wfProfileOut( 'wfNumberOfPages' );
4644 * Get various statistics from the database
4647 function wfLoadSiteStats() {
4648 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4649 $fname = 'wfLoadSiteStats';
4651 if ( -1 != $wgNumberOfArticles ) return;
4652 $dbr =& wfGetDB( DB_SLAVE
);
4653 $s = $dbr->selectRow( 'site_stats',
4654 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4655 array( 'ss_row_id' => 1 ), $fname
4658 if ( $s === false ) {
4661 $wgTotalViews = $s->ss_total_views
;
4662 $wgTotalEdits = $s->ss_total_edits
;
4663 $wgNumberOfArticles = $s->ss_good_articles
;
4669 * Basically replacing " > and < with HTML entities ( ", >, <)
4671 * @param $in String: text that might contain HTML tags.
4672 * @return string Escaped string
4674 function wfEscapeHTMLTagsOnly( $in ) {
4676 array( '"', '>', '<' ),
4677 array( '"', '>', '<' ),