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 if ($argc==2) {$args[2]=$args[1];}
2751 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2757 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2758 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2759 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2761 # Set title in parser output object
2763 $parserOptions = new ParserOptions
;
2764 $local_parser = new Parser ();
2765 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2766 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2769 $t = $this->mTitle
->getPrefixedText();
2770 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2776 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2778 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2779 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2780 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2781 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2782 foreach( $mwWordsToCheck as $word => $func ) {
2783 $mwCurrentWord =& MagicWord
::get( $word );
2784 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2785 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2786 if( $mwRawSuffix->match( $args[0] ) ) {
2787 # Raw and unformatted
2788 $text = $linestart . call_user_func( $func );
2790 # Formatted according to the content default
2791 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2800 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2801 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2802 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2803 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2809 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2810 $colonPos = strpos( $part1, ':' );
2811 if ( $colonPos !== false ) {
2812 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2813 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2814 $funcArgs = array_map( 'trim', $args );
2815 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2816 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2819 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2823 if ( is_array( $result ) ) {
2824 $text = $linestart . $result[0];
2825 unset( $result[0] );
2827 // Extract flags into the local scope
2828 // This allows callers to set flags such as nowiki, noparse, found, etc.
2831 $text = $linestart . $result;
2837 # Template table test
2839 # Did we encounter this template already? If yes, it is in the cache
2840 # and we need to check for loops.
2841 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2844 # Infinite loop test
2845 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2849 $text = $linestart .
2850 '{{' . $part1 . '}}' .
2851 '<!-- WARNING: template loop detected -->';
2852 wfDebug( "$fname: template loop broken at '$part1'\n" );
2854 # set $text to cached message.
2855 $text = $linestart . $this->mTemplates
[$piece['title']];
2859 # Load from database
2860 $lastPathLevel = $this->mTemplatePath
;
2863 # declaring $subpage directly in the function call
2864 # does not work correctly with references and breaks
2865 # {{/subpage}}-style inclusions
2867 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2868 if ($subpage !== '') {
2869 $ns = $this->mTitle
->getNamespace();
2871 $title = Title
::newFromText( $part1, $ns );
2873 if ( !is_null( $title ) ) {
2874 if ( !$title->isExternal() ) {
2875 # Check for excessive inclusion
2876 $dbk = $title->getPrefixedDBkey();
2877 if ( $this->incrementIncludeCount( $dbk ) ) {
2878 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2879 $text = SpecialPage
::capturePath( $title );
2880 if ( is_string( $text ) ) {
2885 $this->disableCache();
2888 $articleContent = $this->fetchTemplate( $title );
2889 if ( $articleContent !== false ) {
2891 $text = $articleContent;
2892 $replaceHeadings = true;
2897 # If the title is valid but undisplayable, make a link to it
2898 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2899 $text = '[['.$title->getPrefixedText().']]';
2902 } elseif ( $title->isTrans() ) {
2903 // Interwiki transclusion
2904 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2905 $text = $this->interwikiTransclude( $title, 'render' );
2909 $text = $this->interwikiTransclude( $title, 'raw' );
2910 $replaceHeadings = true;
2915 # Template cache array insertion
2916 # Use the original $piece['title'] not the mangled $part1, so that
2917 # modifiers such as RAW: produce separate cache entries
2920 // A special page; don't store it in the template cache.
2922 $this->mTemplates
[$piece['title']] = $text;
2924 $text = $linestart . $text;
2929 # Recursive parsing, escaping and link table handling
2930 # Only for HTML output
2931 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2932 $text = wfEscapeWikiText( $text );
2933 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2935 $assocArgs = array();
2937 # Clean up argument array
2938 $assocArgs = array();
2940 foreach( $args as $arg ) {
2941 $eqpos = strpos( $arg, '=' );
2942 if ( $eqpos === false ) {
2943 $assocArgs[$index++
] = $arg;
2945 $name = trim( substr( $arg, 0, $eqpos ) );
2946 $value = trim( substr( $arg, $eqpos+
1 ) );
2947 if ( $value === false ) {
2950 if ( $name !== false ) {
2951 $assocArgs[$name] = $value;
2956 # Add a new element to the templace recursion path
2957 $this->mTemplatePath
[$part1] = 1;
2961 # If there are any <onlyinclude> tags, only include them
2962 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2963 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2965 foreach ($m[1] as $piece)
2968 # Remove <noinclude> sections and <includeonly> tags
2969 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2970 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2972 if( $this->mOutputType
== OT_HTML
) {
2973 # Strip <nowiki>, <pre>, etc.
2974 $text = $this->strip( $text, $this->mStripState
);
2975 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2977 $text = $this->replaceVariables( $text, $assocArgs );
2979 # If the template begins with a table or block-level
2980 # element, it should be treated as beginning a new line.
2981 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2982 $text = "\n" . $text;
2984 } elseif ( !$noargs ) {
2985 # $noparse and !$noargs
2986 # Just replace the arguments, not any double-brace items
2987 # This is used for rendered interwiki transclusion
2988 $text = $this->replaceVariables( $text, $assocArgs, true );
2991 # Prune lower levels off the recursion check path
2992 $this->mTemplatePath
= $lastPathLevel;
2995 wfProfileOut( $fname );
2996 return $piece['text'];
2999 # Replace raw HTML by a placeholder
3000 # Add a blank line preceding, to prevent it from mucking up
3001 # immediately preceding headings
3002 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3004 # replace ==section headers==
3005 # XXX this needs to go away once we have a better parser.
3006 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3007 if( !is_null( $title ) )
3008 $encodedname = base64_encode($title->getPrefixedDBkey());
3010 $encodedname = base64_encode("");
3011 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3012 PREG_SPLIT_DELIM_CAPTURE
);
3015 for( $i = 0; $i < count($m); $i +
= 2 ) {
3017 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3019 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3023 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3024 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3025 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3033 # Prune lower levels off the recursion check path
3034 $this->mTemplatePath
= $lastPathLevel;
3037 wfProfileOut( $fname );
3038 return $piece['text'];
3040 wfProfileOut( $fname );
3046 * Fetch the unparsed text of a template and register a reference to it.
3048 function fetchTemplate( $title ) {
3050 // Loop to fetch the article, with up to 1 redirect
3051 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3052 $rev = Revision
::newFromTitle( $title );
3053 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3057 $text = $rev->getText();
3058 if ( $text === false ) {
3062 $title = Title
::newFromRedirect( $text );
3068 * Transclude an interwiki link.
3070 function interwikiTransclude( $title, $action ) {
3071 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3073 if (!$wgEnableScaryTranscluding)
3074 return wfMsg('scarytranscludedisabled');
3076 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3077 // But we'll handle it generally anyway
3078 if ( $title->getNamespace() ) {
3079 // Use the canonical namespace, which should work anywhere
3080 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3082 $articleName = $title->getDBkey();
3085 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3086 $url .= "?action=$action";
3087 if (strlen($url) > 255)
3088 return wfMsg('scarytranscludetoolong');
3089 return $this->fetchScaryTemplateMaybeFromCache($url);
3092 function fetchScaryTemplateMaybeFromCache($url) {
3093 global $wgTranscludeCacheExpiry;
3094 $dbr =& wfGetDB(DB_SLAVE
);
3095 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3096 array('tc_url' => $url));
3098 $time = $obj->tc_time
;
3099 $text = $obj->tc_contents
;
3100 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3105 $text = wfGetHTTP($url);
3107 return wfMsg('scarytranscludefailed', $url);
3109 $dbw =& wfGetDB(DB_MASTER
);
3110 $dbw->replace('transcache', array('tc_url'), array(
3112 'tc_time' => time(),
3113 'tc_contents' => $text));
3119 * Triple brace replacement -- used for template arguments
3122 function argSubstitution( $matches ) {
3123 $arg = trim( $matches['title'] );
3124 $text = $matches['text'];
3125 $inputArgs = end( $this->mArgStack
);
3127 if ( array_key_exists( $arg, $inputArgs ) ) {
3128 $text = $inputArgs[$arg];
3129 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3130 $text = $matches['parts'][0];
3137 * Returns true if the function is allowed to include this entity
3140 function incrementIncludeCount( $dbk ) {
3141 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3142 $this->mIncludeCount
[$dbk] = 0;
3144 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3152 * Detect __TOC__ magic word and set a placeholder
3154 function stripToc( $text ) {
3155 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3157 $mw = MagicWord
::get( MAG_NOTOC
);
3158 if( $mw->matchAndRemove( $text ) ) {
3159 $this->mShowToc
= false;
3162 $mw = MagicWord
::get( MAG_TOC
);
3163 if( $mw->match( $text ) ) {
3164 $this->mShowToc
= true;
3165 $this->mForceTocPosition
= true;
3167 // Set a placeholder. At the end we'll fill it in with the TOC.
3168 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3170 // Only keep the first one.
3171 $text = $mw->replace( '', $text );
3177 * This function accomplishes several tasks:
3178 * 1) Auto-number headings if that option is enabled
3179 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3180 * 3) Add a Table of contents on the top for users who have enabled the option
3181 * 4) Auto-anchor headings
3183 * It loops through all headlines, collects the necessary data, then splits up the
3184 * string and re-inserts the newly formatted headlines.
3186 * @param string $text
3187 * @param boolean $isMain
3190 function formatHeadings( $text, $isMain=true ) {
3191 global $wgMaxTocLevel, $wgContLang;
3193 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3194 if( !$this->mTitle
->userCanEdit() ) {
3197 $showEditLink = $this->mOptions
->getEditSection();
3200 # Inhibit editsection links if requested in the page
3201 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3202 if( $esw->matchAndRemove( $text ) ) {
3206 # Get all headlines for numbering them and adding funky stuff like [edit]
3207 # links - this is for later, but we need the number of headlines right now
3208 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3210 # if there are fewer than 4 headlines in the article, do not show TOC
3211 # unless it's been explicitly enabled.
3212 $enoughToc = $this->mShowToc
&&
3213 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3215 # Allow user to stipulate that a page should have a "new section"
3216 # link added via __NEWSECTIONLINK__
3217 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3218 if( $mw->matchAndRemove( $text ) )
3219 $this->mOutput
->setNewSection( true );
3221 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3222 # override above conditions and always show TOC above first header
3223 $mw =& MagicWord
::get( MAG_FORCETOC
);
3224 if ($mw->matchAndRemove( $text ) ) {
3225 $this->mShowToc
= true;
3229 # Never ever show TOC if no headers
3230 if( $numMatches < 1 ) {
3234 # We need this to perform operations on the HTML
3235 $sk =& $this->mOptions
->getSkin();
3239 $sectionCount = 0; # headlineCount excluding template sections
3241 # Ugh .. the TOC should have neat indentation levels which can be
3242 # passed to the skin functions. These are determined here
3246 $sublevelCount = array();
3247 $levelCount = array();
3254 foreach( $matches[3] as $headline ) {
3256 $templatetitle = '';
3257 $templatesection = 0;
3260 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3262 $templatetitle = base64_decode($mat[1]);
3263 $templatesection = 1 +
(int)base64_decode($mat[2]);
3264 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3268 $prevlevel = $level;
3269 $prevtoclevel = $toclevel;
3271 $level = $matches[1][$headlineCount];
3273 if( $doNumberHeadings ||
$enoughToc ) {
3275 if ( $level > $prevlevel ) {
3276 # Increase TOC level
3278 $sublevelCount[$toclevel] = 0;
3279 if( $toclevel<$wgMaxTocLevel ) {
3280 $toc .= $sk->tocIndent();
3283 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3284 # Decrease TOC level, find level to jump to
3286 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3287 # Can only go down to level 1
3290 for ($i = $toclevel; $i > 0; $i--) {
3291 if ( $levelCount[$i] == $level ) {
3292 # Found last matching level
3296 elseif ( $levelCount[$i] < $level ) {
3297 # Found first matching level below current level
3303 if( $toclevel<$wgMaxTocLevel ) {
3304 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3308 # No change in level, end TOC line
3309 if( $toclevel<$wgMaxTocLevel ) {
3310 $toc .= $sk->tocLineEnd();
3314 $levelCount[$toclevel] = $level;
3316 # count number of headlines for each level
3317 @$sublevelCount[$toclevel]++
;
3319 for( $i = 1; $i <= $toclevel; $i++
) {
3320 if( !empty( $sublevelCount[$i] ) ) {
3324 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3330 # The canonized header is a version of the header text safe to use for links
3331 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3332 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3333 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3335 # Remove link placeholders by the link text.
3336 # <!--LINK number-->
3338 # link text with suffix
3339 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3340 "\$this->mLinkHolders['texts'][\$1]",
3341 $canonized_headline );
3342 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3343 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3344 $canonized_headline );
3347 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3348 $tocline = trim( $canonized_headline );
3349 # Save headline for section edit hint before it's escaped
3350 $headline_hint = trim( $canonized_headline );
3351 $canonized_headline = Sanitizer
::escapeId( $tocline );
3352 $refers[$headlineCount] = $canonized_headline;
3354 # count how many in assoc. array so we can track dupes in anchors
3355 @$refers[$canonized_headline]++
;
3356 $refcount[$headlineCount]=$refers[$canonized_headline];
3358 # Don't number the heading if it is the only one (looks silly)
3359 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3360 # the two are different if the line contains a link
3361 $headline=$numbering . ' ' . $headline;
3364 # Create the anchor for linking from the TOC to the section
3365 $anchor = $canonized_headline;
3366 if($refcount[$headlineCount] > 1 ) {
3367 $anchor .= '_' . $refcount[$headlineCount];
3369 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3370 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3372 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3373 if ( empty( $head[$headlineCount] ) ) {
3374 $head[$headlineCount] = '';
3377 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3379 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3382 # give headline the correct <h#> tag
3383 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3391 if( $toclevel<$wgMaxTocLevel ) {
3392 $toc .= $sk->tocUnindent( $toclevel - 1 );
3394 $toc = $sk->tocList( $toc );
3397 # split up and insert constructed headlines
3399 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3402 foreach( $blocks as $block ) {
3403 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3404 # This is the [edit] link that appears for the top block of text when
3405 # section editing is enabled
3407 # Disabled because it broke block formatting
3408 # For example, a bullet point in the top line
3409 # $full .= $sk->editSectionLink(0);
3412 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3413 # Top anchor now in skin
3417 if( !empty( $head[$i] ) ) {
3422 if( $this->mForceTocPosition
) {
3423 return str_replace( '<!--MWTOC-->', $toc, $full );
3430 * Return an HTML link for the "ISBN 123456" text
3433 function magicISBN( $text ) {
3434 $fname = 'Parser::magicISBN';
3435 wfProfileIn( $fname );
3437 $a = split( 'ISBN ', ' '.$text );
3438 if ( count ( $a ) < 2 ) {
3439 wfProfileOut( $fname );
3442 $text = substr( array_shift( $a ), 1);
3443 $valid = '0123456789-Xx';
3445 foreach ( $a as $x ) {
3446 # hack: don't replace inside thumbnail title/alt
3448 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3453 $isbn = $blank = '' ;
3454 while ( ' ' == $x{0} ) {
3456 $x = substr( $x, 1 );
3458 if ( $x == '' ) { # blank isbn
3459 $text .= "ISBN $blank";
3462 while ( strstr( $valid, $x{0} ) != false ) {
3464 $x = substr( $x, 1 );
3466 $num = str_replace( '-', '', $isbn );
3467 $num = str_replace( ' ', '', $num );
3468 $num = str_replace( 'x', 'X', $num );
3471 $text .= "ISBN $blank$x";
3473 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3474 $text .= '<a href="' .
3475 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3476 "\" class=\"internal\">ISBN $isbn</a>";
3480 wfProfileOut( $fname );
3485 * Return an HTML link for the "RFC 1234" text
3488 * @param string $text Text to be processed
3489 * @param string $keyword Magic keyword to use (default RFC)
3490 * @param string $urlmsg Interface message to use (default rfcurl)
3493 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3495 $valid = '0123456789';
3498 $a = split( $keyword, ' '.$text );
3499 if ( count ( $a ) < 2 ) {
3502 $text = substr( array_shift( $a ), 1);
3504 /* Check if keyword is preceed by [[.
3505 * This test is made here cause of the array_shift above
3506 * that prevent the test to be done in the foreach.
3508 if ( substr( $text, -2 ) == '[[' ) {
3512 foreach ( $a as $x ) {
3513 /* token might be empty if we have RFC RFC 1234 */
3519 # hack: don't replace inside thumbnail title/alt
3521 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3522 $text .= $keyword . $x;
3528 /** remove and save whitespaces in $blank */
3529 while ( $x{0} == ' ' ) {
3531 $x = substr( $x, 1 );
3534 /** remove and save the rfc number in $id */
3535 while ( strstr( $valid, $x{0} ) != false ) {
3537 $x = substr( $x, 1 );
3541 /* call back stripped spaces*/
3542 $text .= $keyword.$blank.$x;
3543 } elseif( $internal ) {
3545 $text .= $keyword.$id.$x;
3547 /* build the external link*/
3548 $url = wfMsg( $urlmsg, $id);
3549 $sk =& $this->mOptions
->getSkin();
3550 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3551 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3554 /* Check if the next RFC keyword is preceed by [[ */
3555 $internal = ( substr($x,-2) == '[[' );
3561 * Transform wiki markup when saving a page by doing \r\n -> \n
3562 * conversion, substitting signatures, {{subst:}} templates, etc.
3564 * @param string $text the text to transform
3565 * @param Title &$title the Title object for the current article
3566 * @param User &$user the User object describing the current user
3567 * @param ParserOptions $options parsing options
3568 * @param bool $clearState whether to clear the parser state first
3569 * @return string the altered wiki markup
3572 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3573 $this->mOptions
= $options;
3574 $this->mTitle
=& $title;
3575 $this->mOutputType
= OT_WIKI
;
3577 if ( $clearState ) {
3578 $this->clearState();
3581 $stripState = false;
3585 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3586 $text = $this->strip( $text, $stripState, true );
3587 $text = $this->pstPass2( $text, $stripState, $user );
3588 $text = $this->unstrip( $text, $stripState );
3589 $text = $this->unstripNoWiki( $text, $stripState );
3594 * Pre-save transform helper function
3597 function pstPass2( $text, &$stripState, &$user ) {
3598 global $wgContLang, $wgLocaltimezone;
3600 /* Note: This is the timestamp saved as hardcoded wikitext to
3601 * the database, we use $wgContLang here in order to give
3602 * everyone the same signature and use the default one rather
3603 * than the one selected in each user's preferences.
3605 if ( isset( $wgLocaltimezone ) ) {
3606 $oldtz = getenv( 'TZ' );
3607 putenv( 'TZ='.$wgLocaltimezone );
3609 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3610 ' (' . date( 'T' ) . ')';
3611 if ( isset( $wgLocaltimezone ) ) {
3612 putenv( 'TZ='.$oldtz );
3615 # Variable replacement
3616 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3617 $text = $this->replaceVariables( $text );
3619 # Strip out <nowiki> etc. added via replaceVariables
3620 $text = $this->strip( $text, $stripState );
3623 $sigText = $this->getUserSig( $user );
3624 $text = strtr( $text, array(
3626 '~~~~' => "$sigText $d",
3630 # Context links: [[|name]] and [[name (context)|]]
3632 global $wgLegalTitleChars;
3633 $tc = "[$wgLegalTitleChars]";
3634 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3636 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3637 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3639 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3640 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3641 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3642 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3644 $t = $this->mTitle
->getText();
3645 if ( preg_match( $conpat, $t, $m ) ) {
3648 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3649 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3650 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3652 if ( '' == $context ) {
3653 $text = preg_replace( $p2, '[[\\1]]', $text );
3655 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3658 # Trim trailing whitespace
3659 # MAG_END (__END__) tag allows for trailing
3660 # whitespace to be deliberately included
3661 $text = rtrim( $text );
3662 $mw =& MagicWord
::get( MAG_END
);
3663 $mw->matchAndRemove( $text );
3669 * Fetch the user's signature text, if any, and normalize to
3670 * validated, ready-to-insert wikitext.
3676 function getUserSig( &$user ) {
3677 $username = $user->getName();
3678 $nickname = $user->getOption( 'nickname' );
3679 $nickname = $nickname === '' ?
$username : $nickname;
3681 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3682 # Sig. might contain markup; validate this
3683 if( $this->validateSig( $nickname ) !== false ) {
3684 # Validated; clean up (if needed) and return it
3685 return $this->cleanSig( $nickname, true );
3687 # Failed to validate; fall back to the default
3688 $nickname = $username;
3689 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3693 # If we're still here, make it a link to the user page
3694 $userpage = $user->getUserPage();
3695 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3699 * Check that the user's signature contains no bad XML
3701 * @param string $text
3702 * @return mixed An expanded string, or false if invalid.
3704 function validateSig( $text ) {
3705 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3709 * Clean up signature text
3711 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3712 * 2) Substitute all transclusions
3714 * @param string $text
3715 * @param $parsing Whether we're cleaning (preferences save) or parsing
3716 * @return string Signature text
3718 function cleanSig( $text, $parsing = false ) {
3720 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3722 $substWord = MagicWord
::get( MAG_SUBST
);
3723 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3724 $substText = '{{' . $substWord->getSynonym( 0 );
3726 $text = preg_replace( $substRegex, $substText, $text );
3727 $text = preg_replace( '/~{3,5}/', '', $text );
3728 $text = $this->replaceVariables( $text );
3730 $this->clearState();
3735 * Set up some variables which are usually set up in parse()
3736 * so that an external function can call some class members with confidence
3739 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3740 $this->mTitle
=& $title;
3741 $this->mOptions
= $options;
3742 $this->mOutputType
= $outputType;
3743 if ( $clearState ) {
3744 $this->clearState();
3749 * Transform a MediaWiki message by replacing magic variables.
3751 * @param string $text the text to transform
3752 * @param ParserOptions $options options
3753 * @return string the text with variables substituted
3756 function transformMsg( $text, $options ) {
3758 static $executing = false;
3760 $fname = "Parser::transformMsg";
3762 # Guard against infinite recursion
3768 wfProfileIn($fname);
3770 $this->mTitle
= $wgTitle;
3771 $this->mOptions
= $options;
3772 $this->mOutputType
= OT_MSG
;
3773 $this->clearState();
3774 $text = $this->replaceVariables( $text );
3777 wfProfileOut($fname);
3782 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3783 * The callback should have the following form:
3784 * function myParserHook( $text, $params, &$parser ) { ... }
3786 * Transform and return $text. Use $parser for any required context, e.g. use
3787 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3791 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3792 * @param mixed $callback The callback function (and object) to use for the tag
3794 * @return The old value of the mTagHooks array associated with the hook
3796 function setHook( $tag, $callback ) {
3797 $tag = strtolower( $tag );
3798 $oldVal = @$this->mTagHooks
[$tag];
3799 $this->mTagHooks
[$tag] = $callback;
3805 * Create a function, e.g. {{sum:1|2|3}}
3806 * The callback function should have the form:
3807 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3809 * The callback may either return the text result of the function, or an array with the text
3810 * in element 0, and a number of flags in the other elements. The names of the flags are
3811 * specified in the keys. Valid flags are:
3812 * found The text returned is valid, stop processing the template. This
3814 * nowiki Wiki markup in the return value should be escaped
3815 * noparse Unsafe HTML tags should not be stripped, etc.
3816 * noargs Don't replace triple-brace arguments in the return value
3817 * isHTML The returned text is HTML, armour it against wikitext transformation
3821 * @param string $name The function name. Function names are case-insensitive.
3822 * @param mixed $callback The callback function (and object) to use
3824 * @return The old callback function for this name, if any
3826 function setFunctionHook( $name, $callback ) {
3827 $name = strtolower( $name );
3828 $oldVal = @$this->mFunctionHooks
[$name];
3829 $this->mFunctionHooks
[$name] = $callback;
3834 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3835 * Placeholders created in Skin::makeLinkObj()
3836 * Returns an array of links found, indexed by PDBK:
3840 * $options is a bit field, RLH_FOR_UPDATE to select for update
3842 function replaceLinkHolders( &$text, $options = 0 ) {
3844 global $wgOutputReplace;
3846 $fname = 'Parser::replaceLinkHolders';
3847 wfProfileIn( $fname );
3851 $sk =& $this->mOptions
->getSkin();
3852 $linkCache =& LinkCache
::singleton();
3854 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3855 wfProfileIn( $fname.'-check' );
3856 $dbr =& wfGetDB( DB_SLAVE
);
3857 $page = $dbr->tableName( 'page' );
3858 $threshold = $wgUser->getOption('stubthreshold');
3861 asort( $this->mLinkHolders
['namespaces'] );
3865 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3867 $title = $this->mLinkHolders
['titles'][$key];
3869 # Skip invalid entries.
3870 # Result will be ugly, but prevents crash.
3871 if ( is_null( $title ) ) {
3874 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3876 # Check if it's a static known link, e.g. interwiki
3877 if ( $title->isAlwaysKnown() ) {
3878 $colours[$pdbk] = 1;
3879 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3880 $colours[$pdbk] = 1;
3881 $this->mOutput
->addLink( $title, $id );
3882 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3883 $colours[$pdbk] = 0;
3885 # Not in the link cache, add it to the query
3886 if ( !isset( $current ) ) {
3888 $query = "SELECT page_id, page_namespace, page_title";
3889 if ( $threshold > 0 ) {
3890 $query .= ', page_len, page_is_redirect';
3892 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3893 } elseif ( $current != $ns ) {
3895 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3900 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3905 if ( $options & RLH_FOR_UPDATE
) {
3906 $query .= ' FOR UPDATE';
3909 $res = $dbr->query( $query, $fname );
3911 # Fetch data and form into an associative array
3912 # non-existent = broken
3915 while ( $s = $dbr->fetchObject($res) ) {
3916 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3917 $pdbk = $title->getPrefixedDBkey();
3918 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3919 $this->mOutput
->addLink( $title, $s->page_id
);
3921 if ( $threshold > 0 ) {
3922 $size = $s->page_len
;
3923 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3924 $colours[$pdbk] = 1;
3926 $colours[$pdbk] = 2;
3929 $colours[$pdbk] = 1;
3933 wfProfileOut( $fname.'-check' );
3935 # Construct search and replace arrays
3936 wfProfileIn( $fname.'-construct' );
3937 $wgOutputReplace = array();
3938 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3939 $pdbk = $pdbks[$key];
3940 $searchkey = "<!--LINK $key-->";
3941 $title = $this->mLinkHolders
['titles'][$key];
3942 if ( empty( $colours[$pdbk] ) ) {
3943 $linkCache->addBadLinkObj( $title );
3944 $colours[$pdbk] = 0;
3945 $this->mOutput
->addLink( $title, 0 );
3946 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3947 $this->mLinkHolders
['texts'][$key],
3948 $this->mLinkHolders
['queries'][$key] );
3949 } elseif ( $colours[$pdbk] == 1 ) {
3950 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3951 $this->mLinkHolders
['texts'][$key],
3952 $this->mLinkHolders
['queries'][$key] );
3953 } elseif ( $colours[$pdbk] == 2 ) {
3954 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3955 $this->mLinkHolders
['texts'][$key],
3956 $this->mLinkHolders
['queries'][$key] );
3959 wfProfileOut( $fname.'-construct' );
3962 wfProfileIn( $fname.'-replace' );
3964 $text = preg_replace_callback(
3965 '/(<!--LINK .*?-->)/',
3966 "wfOutputReplaceMatches",
3969 wfProfileOut( $fname.'-replace' );
3972 # Now process interwiki link holders
3973 # This is quite a bit simpler than internal links
3974 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3975 wfProfileIn( $fname.'-interwiki' );
3976 # Make interwiki link HTML
3977 $wgOutputReplace = array();
3978 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3979 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3980 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3983 $text = preg_replace_callback(
3984 '/<!--IWLINK (.*?)-->/',
3985 "wfOutputReplaceMatches",
3987 wfProfileOut( $fname.'-interwiki' );
3990 wfProfileOut( $fname );
3995 * Replace <!--LINK--> link placeholders with plain text of links
3996 * (not HTML-formatted).
3997 * @param string $text
4000 function replaceLinkHoldersText( $text ) {
4001 $fname = 'Parser::replaceLinkHoldersText';
4002 wfProfileIn( $fname );
4004 $text = preg_replace_callback(
4005 '/<!--(LINK|IWLINK) (.*?)-->/',
4006 array( &$this, 'replaceLinkHoldersTextCallback' ),
4009 wfProfileOut( $fname );
4014 * @param array $matches
4018 function replaceLinkHoldersTextCallback( $matches ) {
4019 $type = $matches[1];
4021 if( $type == 'LINK' ) {
4022 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4023 return $this->mLinkHolders
['texts'][$key];
4025 } elseif( $type == 'IWLINK' ) {
4026 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4027 return $this->mInterwikiLinkHolders
['texts'][$key];
4034 * Tag hook handler for 'pre'.
4036 function renderPreTag( $text, $attribs, $parser ) {
4037 // Backwards-compatibility hack
4038 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4040 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4041 return wfOpenElement( 'pre', $attribs ) .
4042 wfEscapeHTMLTagsOnly( $content ) .
4047 * Renders an image gallery from a text with one line per image.
4048 * text labels may be given by using |-style alternative text. E.g.
4049 * Image:one.jpg|The number "1"
4050 * Image:tree.jpg|A tree
4051 * given as text will return the HTML of a gallery with two images,
4052 * labeled 'The number "1"' and
4055 function renderImageGallery( $text ) {
4056 $ig = new ImageGallery();
4057 $ig->setShowBytes( false );
4058 $ig->setShowFilename( false );
4060 $lines = explode( "\n", $text );
4062 foreach ( $lines as $line ) {
4063 # match lines like these:
4064 # Image:someimage.jpg|This is some image
4065 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4067 if ( count( $matches ) == 0 ) {
4070 $nt =& Title
::newFromText( $matches[1] );
4071 if( is_null( $nt ) ) {
4072 # Bogus title. Ignore these so we don't bomb out later.
4075 if ( isset( $matches[3] ) ) {
4076 $label = $matches[3];
4081 $pout = $this->parse( $label,
4084 false, // Strip whitespace...?
4085 false // Don't clear state!
4087 $html = $pout->getText();
4089 $ig->add( new Image( $nt ), $html );
4091 # Only add real images (bug #5586)
4092 if ( $nt->getNamespace() == NS_IMAGE
) {
4093 $this->mOutput
->addImage( $nt->getDBkey() );
4096 return $ig->toHTML();
4100 * Parse image options text and use it to make an image
4102 function makeImage( &$nt, $options ) {
4103 global $wgUseImageResize;
4107 # Check if the options text is of the form "options|alt text"
4109 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4110 # * left no resizing, just left align. label is used for alt= only
4111 # * right same, but right aligned
4112 # * none same, but not aligned
4113 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4114 # * center center the image
4115 # * framed Keep original image size, no magnify-button.
4117 $part = explode( '|', $options);
4119 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4120 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4121 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4122 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4123 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4124 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4125 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4126 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4129 $width = $height = $framed = $thumb = false;
4130 $manual_thumb = '' ;
4132 foreach( $part as $key => $val ) {
4133 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4135 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4136 # use manually specified thumbnail
4138 $manual_thumb = $match;
4139 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4140 # remember to set an alignment, don't render immediately
4142 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4143 # remember to set an alignment, don't render immediately
4145 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4146 # remember to set an alignment, don't render immediately
4148 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4149 # remember to set an alignment, don't render immediately
4151 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4152 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4153 # $match is the image width in pixels
4154 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4155 $width = intval( $m[1] );
4156 $height = intval( $m[2] );
4158 $width = intval($match);
4160 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4166 # Strip bad stuff out of the alt text
4167 $alt = $this->replaceLinkHoldersText( $caption );
4169 # make sure there are no placeholders in thumbnail attributes
4170 # that are later expanded to html- so expand them now and
4172 $alt = $this->unstrip($alt, $this->mStripState
);
4173 $alt = Sanitizer
::stripAllTags( $alt );
4175 # Linker does the rest
4176 $sk =& $this->mOptions
->getSkin();
4177 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4181 * Set a flag in the output object indicating that the content is dynamic and
4182 * shouldn't be cached.
4184 function disableCache() {
4185 wfDebug( "Parser output marked as uncacheable.\n" );
4186 $this->mOutput
->mCacheTime
= -1;
4190 * Callback from the Sanitizer for expanding items found in HTML attribute
4191 * values, so they can be safely tested and escaped.
4192 * @param string $text
4193 * @param array $args
4197 function attributeStripCallback( &$text, $args ) {
4198 $text = $this->replaceVariables( $text, $args );
4199 $text = $this->unstripForHTML( $text );
4203 function unstripForHTML( $text ) {
4204 $text = $this->unstrip( $text, $this->mStripState
);
4205 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4213 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4214 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4215 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4221 function getTags() { return array_keys( $this->mTagHooks
); }
4226 * Break wikitext input into sections, and either pull or replace
4227 * some particular section's text.
4229 * External callers should use the getSection and replaceSection methods.
4231 * @param $text Page wikitext
4232 * @param $section Numbered section. 0 pulls the text before the first
4233 * heading; other numbers will pull the given section
4234 * along with its lower-level subsections.
4235 * @param $mode One of "get" or "replace"
4236 * @param $newtext Replacement text for section data.
4237 * @return string for "get", the extracted section text.
4238 * for "replace", the whole page with the section replaced.
4240 private function extractSections( $text, $section, $mode, $newtext='' ) {
4241 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4242 # comments to be stripped as well)
4243 $striparray = array();
4245 $oldOutputType = $this->mOutputType
;
4246 $oldOptions = $this->mOptions
;
4247 $this->mOptions
= new ParserOptions();
4248 $this->mOutputType
= OT_WIKI
;
4250 $striptext = $this->strip( $text, $striparray, true );
4252 $this->mOutputType
= $oldOutputType;
4253 $this->mOptions
= $oldOptions;
4255 # now that we can be sure that no pseudo-sections are in the source,
4256 # split it up by section
4257 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4258 $comment = "(?:$uniq-!--.*?QINU)";
4263 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4265 (=+) # Should this be limited to 6?
4266 .+? # Section title...
4267 \\2 # Ending = count must match start
4274 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4281 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4282 (=+) # Should this be limited to 6?
4283 .+? # Section title...
4284 \\2 # Ending = count must match start
4285 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4294 PREG_SPLIT_DELIM_CAPTURE
);
4296 if( $mode == "get" ) {
4297 if( $section == 0 ) {
4298 // "Section 0" returns the content before any other section.
4303 } elseif( $mode == "replace" ) {
4304 if( $section == 0 ) {
4305 $rv = $newtext . "\n\n";
4314 for( $index = 1; $index < count( $secs ); ) {
4315 $headerLine = $secs[$index++
];
4316 if( $secs[$index] ) {
4318 $headerLevel = strlen( $secs[$index++
] );
4322 $headerLevel = intval( $secs[$index++
] );
4324 $content = $secs[$index++
];
4327 if( $mode == "get" ) {
4328 if( $count == $section ) {
4329 $rv = $headerLine . $content;
4330 $sectionLevel = $headerLevel;
4331 } elseif( $count > $section ) {
4332 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4333 $rv .= $headerLine . $content;
4335 // Broke out to a higher-level section
4339 } elseif( $mode == "replace" ) {
4340 if( $count < $section ) {
4341 $rv .= $headerLine . $content;
4342 } elseif( $count == $section ) {
4343 $rv .= $newtext . "\n\n";
4344 $sectionLevel = $headerLevel;
4345 } elseif( $count > $section ) {
4346 if( $headerLevel <= $sectionLevel ) {
4347 // Passed the section's sub-parts.
4351 $rv .= $headerLine . $content;
4356 # reinsert stripped tags
4357 $rv = $this->unstrip( $rv, $striparray );
4358 $rv = $this->unstripNoWiki( $rv, $striparray );
4364 * This function returns the text of a section, specified by a number ($section).
4365 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4366 * the first section before any such heading (section 0).
4368 * If a section contains subsections, these are also returned.
4370 * @param $text String: text to look in
4371 * @param $section Integer: section number
4372 * @return string text of the requested section
4374 function getSection( $text, $section ) {
4375 return $this->extractSections( $text, $section, "get" );
4378 function replaceSection( $oldtext, $section, $text ) {
4379 return $this->extractSections( $oldtext, $section, "replace", $text );
4386 * @package MediaWiki
4390 var $mText, # The output text
4391 $mLanguageLinks, # List of the full text of language links, in the order they appear
4392 $mCategories, # Map of category names to sort keys
4393 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4394 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4395 $mVersion, # Compatibility check
4396 $mTitleText, # title text of the chosen language variant
4397 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4398 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4399 $mImages, # DB keys of the images used, in the array key only
4400 $mExternalLinks, # External link URLs, in the key only
4401 $mHTMLtitle, # Display HTML title
4402 $mSubtitle, # Additional subtitle
4403 $mNewSection; # Show a new section link?
4405 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4406 $containsOldMagic = false, $titletext = '' )
4408 $this->mText
= $text;
4409 $this->mLanguageLinks
= $languageLinks;
4410 $this->mCategories
= $categoryLinks;
4411 $this->mContainsOldMagic
= $containsOldMagic;
4412 $this->mCacheTime
= '';
4413 $this->mVersion
= MW_PARSER_VERSION
;
4414 $this->mTitleText
= $titletext;
4415 $this->mLinks
= array();
4416 $this->mTemplates
= array();
4417 $this->mImages
= array();
4418 $this->mExternalLinks
= array();
4419 $this->mHTMLtitle
= "" ;
4420 $this->mSubtitle
= "" ;
4421 $this->mNewSection
= false;
4424 function getText() { return $this->mText
; }
4425 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4426 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4427 function &getCategories() { return $this->mCategories
; }
4428 function getCacheTime() { return $this->mCacheTime
; }
4429 function getTitleText() { return $this->mTitleText
; }
4430 function &getLinks() { return $this->mLinks
; }
4431 function &getTemplates() { return $this->mTemplates
; }
4432 function &getImages() { return $this->mImages
; }
4433 function &getExternalLinks() { return $this->mExternalLinks
; }
4435 function containsOldMagic() { return $this->mContainsOldMagic
; }
4436 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4437 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4438 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4439 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4440 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4441 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4443 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4444 function addImage( $name ) { $this->mImages
[$name] = 1; }
4445 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4446 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4448 function setNewSection( $value ) {
4449 $this->mNewSection
= (bool)$value;
4451 function getNewSection() {
4452 return (bool)$this->mNewSection
;
4455 function addLink( $title, $id ) {
4456 $ns = $title->getNamespace();
4457 $dbk = $title->getDBkey();
4458 if ( !isset( $this->mLinks
[$ns] ) ) {
4459 $this->mLinks
[$ns] = array();
4461 $this->mLinks
[$ns][$dbk] = $id;
4464 function addTemplate( $title, $id ) {
4465 $ns = $title->getNamespace();
4466 $dbk = $title->getDBkey();
4467 if ( !isset( $this->mTemplates
[$ns] ) ) {
4468 $this->mTemplates
[$ns] = array();
4470 $this->mTemplates
[$ns][$dbk] = $id;
4474 * Return true if this cached output object predates the global or
4475 * per-article cache invalidation timestamps, or if it comes from
4476 * an incompatible older version.
4478 * @param string $touched the affected article's last touched timestamp
4482 function expired( $touched ) {
4483 global $wgCacheEpoch;
4484 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4485 $this->getCacheTime() < $touched ||
4486 $this->getCacheTime() <= $wgCacheEpoch ||
4487 !isset( $this->mVersion
) ||
4488 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4493 * Set options of the Parser
4495 * @package MediaWiki
4499 # All variables are private
4500 var $mUseTeX; # Use texvc to expand <math> tags
4501 var $mUseDynamicDates; # Use DateFormatter to format dates
4502 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4503 var $mAllowExternalImages; # Allow external images inline
4504 var $mAllowExternalImagesFrom; # If not, any exception?
4505 var $mSkin; # Reference to the preferred skin
4506 var $mDateFormat; # Date format index
4507 var $mEditSection; # Create "edit section" links
4508 var $mNumberHeadings; # Automatically number headings
4509 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4510 var $mTidy; # Ask for tidy cleanup
4511 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4513 function getUseTeX() { return $this->mUseTeX
; }
4514 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4515 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4516 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4517 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4518 function &getSkin() { return $this->mSkin
; }
4519 function getDateFormat() { return $this->mDateFormat
; }
4520 function getEditSection() { return $this->mEditSection
; }
4521 function getNumberHeadings() { return $this->mNumberHeadings
; }
4522 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4523 function getTidy() { return $this->mTidy
; }
4524 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4526 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4527 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4528 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4529 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4530 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4531 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4532 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4533 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4534 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4535 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4536 function setSkin( &$x ) { $this->mSkin
=& $x; }
4537 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4539 function ParserOptions() {
4541 $this->initialiseFromUser( $wgUser );
4545 * Get parser options
4548 function newFromUser( &$user ) {
4549 $popts = new ParserOptions
;
4550 $popts->initialiseFromUser( $user );
4554 /** Get user options */
4555 function initialiseFromUser( &$userInput ) {
4556 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4557 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4558 $fname = 'ParserOptions::initialiseFromUser';
4559 wfProfileIn( $fname );
4560 if ( !$userInput ) {
4562 $user->setLoaded( true );
4564 $user =& $userInput;
4567 $this->mUseTeX
= $wgUseTeX;
4568 $this->mUseDynamicDates
= $wgUseDynamicDates;
4569 $this->mInterwikiMagic
= $wgInterwikiMagic;
4570 $this->mAllowExternalImages
= $wgAllowExternalImages;
4571 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4572 wfProfileIn( $fname.'-skin' );
4573 $this->mSkin
=& $user->getSkin();
4574 wfProfileOut( $fname.'-skin' );
4575 $this->mDateFormat
= $user->getOption( 'date' );
4576 $this->mEditSection
= true;
4577 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4578 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4579 $this->mTidy
= false;
4580 $this->mInterfaceMessage
= false;
4581 wfProfileOut( $fname );
4586 * Callback function used by Parser::replaceLinkHolders()
4587 * to substitute link placeholders.
4589 function &wfOutputReplaceMatches( $matches ) {
4590 global $wgOutputReplace;
4591 return $wgOutputReplace[$matches[1]];
4595 * Return the total number of articles
4597 function wfNumberOfArticles() {
4598 global $wgNumberOfArticles;
4601 return $wgNumberOfArticles;
4605 * Return the number of files
4607 function wfNumberOfFiles() {
4608 $fname = 'wfNumberOfFiles';
4610 wfProfileIn( $fname );
4611 $dbr =& wfGetDB( DB_SLAVE
);
4612 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4613 wfProfileOut( $fname );
4619 * Return the number of user accounts
4622 function wfNumberOfUsers() {
4623 wfProfileIn( 'wfNumberOfUsers' );
4624 $dbr =& wfGetDB( DB_SLAVE
);
4625 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4626 wfProfileOut( 'wfNumberOfUsers' );
4631 * Return the total number of pages
4634 function wfNumberOfPages() {
4635 wfProfileIn( 'wfNumberOfPages' );
4636 $dbr =& wfGetDB( DB_SLAVE
);
4637 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4638 wfProfileOut( 'wfNumberOfPages' );
4643 * Get various statistics from the database
4646 function wfLoadSiteStats() {
4647 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4648 $fname = 'wfLoadSiteStats';
4650 if ( -1 != $wgNumberOfArticles ) return;
4651 $dbr =& wfGetDB( DB_SLAVE
);
4652 $s = $dbr->selectRow( 'site_stats',
4653 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4654 array( 'ss_row_id' => 1 ), $fname
4657 if ( $s === false ) {
4660 $wgTotalViews = $s->ss_total_views
;
4661 $wgTotalEdits = $s->ss_total_edits
;
4662 $wgNumberOfArticles = $s->ss_good_articles
;
4668 * Basically replacing " > and < with HTML entities ( ", >, <)
4670 * @param $in String: text that might contain HTML tags.
4671 * @return string Escaped string
4673 function wfEscapeHTMLTagsOnly( $in ) {
4675 array( '"', '>', '<' ),
4676 array( '"', '>', '<' ),