f969f7b9102c17b685eee4370f23bb60e6b9ba87
3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12 require_once( 'ImageGallery.php' );
15 * Update this version number when the ParserOutput format
16 * changes in an incompatible way, so the parser cache
17 * can automatically discard old data.
19 define( 'MW_PARSER_VERSION', '1.6.1' );
22 * Variable substitution O(N^2) attack
24 * Without countermeasures, it would be possible to attack the parser by saving
25 * a page filled with a large number of inclusions of large pages. The size of
26 * the generated page would be proportional to the square of the input size.
27 * Hence, we limit the number of inclusions of any given page, thus bringing any
28 * attack back to O(N).
31 define( 'MAX_INCLUDE_REPEAT', 100 );
32 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
34 define( 'RLH_FOR_UPDATE', 1 );
36 # Allowed values for $mOutputType
37 define( 'OT_HTML', 1 );
38 define( 'OT_WIKI', 2 );
39 define( 'OT_MSG' , 3 );
41 # string parameter for extractTags which will cause it
42 # to strip HTML comments in addition to regular
43 # <XML>-style tags. This should not be anything we
44 # may want to use in wikisyntax
45 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
47 # Constants needed for external link processing
48 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
49 # Everything except bracket, space, or control characters
50 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
52 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
53 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
54 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
55 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.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
65 * Processes wiki markup
68 * There are three main entry points into the Parser class:
70 * produces HTML output
72 * produces altered wiki markup.
74 * performs brace substitution on MediaWiki messages
77 * objects: $wgLang, $wgContLang
79 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
82 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
83 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
84 * $wgLocaltimezone, $wgAllowSpecialInclusion*
86 * * only within ParserOptions
97 var $mTagHooks, $mFunctionHooks;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
101 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
103 var $mTemplates, // cache of already loaded templates, avoids
104 // multiple SQL queries for the same string
105 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
106 // in this path. Used for loop detection.
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $mRevisionId; // ID to display in {{REVISIONID}} tags
123 $this->mTagHooks
= array();
124 $this->mFunctionHooks
= array();
133 function clearState() {
134 $this->mOutput
= new ParserOutput
;
135 $this->mAutonumber
= 0;
136 $this->mLastSection
= '';
137 $this->mDTopen
= false;
138 $this->mVariables
= false;
139 $this->mIncludeCount
= array();
140 $this->mStripState
= array();
141 $this->mArgStack
= array();
142 $this->mInPre
= false;
143 $this->mInterwikiLinkHolders
= array(
147 $this->mLinkHolders
= array(
148 'namespaces' => array(),
150 'queries' => array(),
154 $this->mRevisionId
= null;
157 * Prefix for temporary replacement strings for the multipass parser.
158 * \x07 should never appear in input as it's disallowed in XML.
159 * Using it at the front also gives us a little extra robustness
160 * since it shouldn't match when butted up against identifier-like
163 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
165 # Clear these on every parse, bug 4549
166 $this->mTemplates
= array();
167 $this->mTemplatePath
= array();
169 $this->mShowToc
= true;
170 $this->mForceTocPosition
= false;
172 wfRunHooks( 'ParserClearState', array( &$this ) );
176 * Accessor for mUniqPrefix.
180 function UniqPrefix() {
181 return $this->mUniqPrefix
;
185 * Convert wikitext to HTML
186 * Do not call this function recursively.
189 * @param string $text Text we want to parse
190 * @param Title &$title A title object
191 * @param array $options
192 * @param boolean $linestart
193 * @param boolean $clearState
194 * @param int $revid number to pass in {{REVISIONID}}
195 * @return ParserOutput a ParserOutput
197 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
199 * First pass--just handle <nowiki> sections, pass the rest off
200 * to internalParse() which does all the real work.
203 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
204 $fname = 'Parser::parse';
205 wfProfileIn( $fname );
211 $this->mOptions
= $options;
212 $this->mTitle
=& $title;
213 $this->mRevisionId
= $revid;
214 $this->mOutputType
= OT_HTML
;
216 //$text = $this->strip( $text, $this->mStripState );
217 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
218 $x =& $this->mStripState
;
220 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
221 $text = $this->strip( $text, $x );
222 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
224 # Hook to suspend the parser in this state
225 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
226 wfProfileOut( $fname );
230 $text = $this->internalParse( $text );
232 $text = $this->unstrip( $text, $this->mStripState
);
234 # Clean up special characters, only run once, next-to-last before doBlockLevels
236 # french spaces, last one Guillemet-left
237 # only if there is something before the space
238 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
239 # french spaces, Guillemet-right
240 '/(\\302\\253) /' => '\\1 ',
241 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
243 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
246 $text = $this->doBlockLevels( $text, $linestart );
248 $this->replaceLinkHolders( $text );
250 # the position of the parserConvert() call should not be changed. it
251 # assumes that the links are all replaced and the only thing left
252 # is the <nowiki> mark.
253 # Side-effects: this calls $this->mOutput->setTitleText()
254 $text = $wgContLang->parserConvert( $text, $this );
256 $text = $this->unstripNoWiki( $text, $this->mStripState
);
258 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
260 $text = Sanitizer
::normalizeCharReferences( $text );
262 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
263 $text = Parser
::tidy($text);
265 # attempt to sanitize at least some nesting problems
266 # (bug #2702 and quite a few others)
268 # ''Something [http://www.cool.com cool''] -->
269 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
270 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
271 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
272 # fix up an anchor inside another anchor, only
273 # at least for a single single nested link (bug 3695)
274 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
275 '\\1\\2</a>\\3</a>\\1\\4</a>',
276 # fix div inside inline elements- doBlockLevels won't wrap a line which
277 # contains a div, so fix it up here; replace
278 # div with escaped text
279 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
280 '\\1\\3<div\\5>\\6</div>\\8\\9',
281 # remove empty italic or bold tag pairs, some
282 # introduced by rules above
283 '/<([bi])><\/\\1>/' => ''
286 $text = preg_replace(
287 array_keys( $tidyregs ),
288 array_values( $tidyregs ),
292 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
294 $this->mOutput
->setText( $text );
295 wfProfileOut( $fname );
297 return $this->mOutput
;
301 * Get a random string
306 function getRandomString() {
307 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
310 function &getTitle() { return $this->mTitle
; }
311 function getOptions() { return $this->mOptions
; }
314 * Replaces all occurrences of HTML-style comments and the given tags
315 * in the text with a random marker and returns teh next text. The output
316 * parameter $matches will be an associative array filled with data in
318 * 'UNIQ-xxxxx' => array(
321 * array( 'param' => 'x' ),
322 * '<element param="x">tag content</element>' ) )
324 * @param $elements list of element names. Comments are always extracted.
325 * @param $text Source text string.
326 * @param $uniq_prefix
331 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
332 $rand = Parser
::getRandomString();
337 $taglist = implode( '|', $elements );
338 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
340 while ( '' != $text ) {
341 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
343 if( count( $p ) < 5 ) {
346 if( count( $p ) > 5 ) {
360 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
);
361 $stripped .= $marker;
363 if ( $close === '/>' ) {
364 // Empty element tag, <tag />
369 if( $element == '!--' ) {
372 $end = "/(<\\/$element\\s*>)/i";
374 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
376 if( count( $q ) < 3 ) {
377 # No end tag -- let it run out to the end of the text.
386 $matches[$marker] = array( $element,
388 Sanitizer
::decodeTagAttributes( $attributes ),
389 "<$element$attributes$close$content$tail" );
395 * Strips and renders nowiki, pre, math, hiero
396 * If $render is set, performs necessary rendering operations on plugins
397 * Returns the text, and fills an array with data needed in unstrip()
398 * If the $state is already a valid strip state, it adds to the state
400 * @param bool $stripcomments when set, HTML comments <!-- like this -->
401 * will be stripped in addition to other tags. This is important
402 * for section editing, where these comments cause confusion when
403 * counting the sections in the wikisource
407 function strip( $text, &$state, $stripcomments = false ) {
408 $render = ($this->mOutputType
== OT_HTML
);
410 # Replace any instances of the placeholders
411 $uniq_prefix = $this->mUniqPrefix
;
412 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
413 $commentState = array();
415 $elements = array_merge(
416 array( 'nowiki', 'pre', 'gallery' ),
417 array_keys( $this->mTagHooks
) );
420 $elements[] = 'html';
422 if( $this->mOptions
->getUseTeX() ) {
423 $elements[] = 'math';
428 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
430 foreach( $matches as $marker => $data ) {
431 list( $element, $content, $params, $tag ) = $data;
433 $tagName = strtolower( $element );
437 if( substr( $tag, -3 ) == '-->' ) {
440 // Unclosed comment in input.
441 // Close it so later stripping can remove it
450 // Shouldn't happen otherwise. :)
452 $output = wfEscapeHTMLTagsOnly( $content );
455 $output = renderMath( $content );
458 // Backwards-compatibility hack
459 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $content );
460 $output = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
463 $output = $this->renderImageGallery( $content );
466 if( isset( $this->mTagHooks
[$tagName] ) ) {
467 $output = call_user_func_array( $this->mTagHooks
[$tagName],
468 array( $content, $params, $this ) );
470 wfDebugDieBacktrace( "Invalid call hook $element" );
474 // Just stripping tags; keep the source
477 if( !$stripcomments && $element == '!--' ) {
478 $commentState[$marker] = $output;
480 $state[$element][$marker] = $output;
484 # Unstrip comments unless explicitly told otherwise.
485 # (The comments are always stripped prior to this point, so as to
486 # not invoke any extension tags / parser hooks contained within
488 if ( !$stripcomments ) {
489 // Put them all back and forget them
490 $text = strtr( $text, $commentState );
497 * Restores pre, math, and other extensions removed by strip()
499 * always call unstripNoWiki() after this one
502 function unstrip( $text, &$state ) {
503 if ( !is_array( $state ) ) {
507 $replacements = array();
508 foreach( $state as $tag => $contentDict ) {
509 if( $tag != 'nowiki' && $tag != 'html' ) {
510 foreach( $contentDict as $uniq => $content ) {
511 $replacements[$uniq] = $content;
515 $text = strtr( $text, $replacements );
521 * Always call this after unstrip() to preserve the order
525 function unstripNoWiki( $text, &$state ) {
526 if ( !is_array( $state ) ) {
530 $replacements = array();
531 foreach( $state as $tag => $contentDict ) {
532 if( $tag == 'nowiki' ||
$tag == 'html' ) {
533 foreach( $contentDict as $uniq => $content ) {
534 $replacements[$uniq] = $content;
538 $text = strtr( $text, $replacements );
544 * Add an item to the strip state
545 * Returns the unique tag which must be inserted into the stripped text
546 * The tag will be replaced with the original text in unstrip()
550 function insertStripItem( $text, &$state ) {
551 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
555 $state['item'][$rnd] = $text;
560 * Interface with html tidy, used if $wgUseTidy = true.
561 * If tidy isn't able to correct the markup, the original will be
562 * returned in all its glory with a warning comment appended.
564 * Either the external tidy program or the in-process tidy extension
565 * will be used depending on availability. Override the default
566 * $wgTidyInternal setting to disable the internal if it's not working.
568 * @param string $text Hideous HTML input
569 * @return string Corrected HTML output
573 function tidy( $text ) {
574 global $wgTidyInternal;
575 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
576 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
577 '<head><title>test</title></head><body>'.$text.'</body></html>';
578 if( $wgTidyInternal ) {
579 $correctedtext = Parser
::internalTidy( $wrappedtext );
581 $correctedtext = Parser
::externalTidy( $wrappedtext );
583 if( is_null( $correctedtext ) ) {
584 wfDebug( "Tidy error detected!\n" );
585 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
587 return $correctedtext;
591 * Spawn an external HTML tidy process and get corrected markup back from it.
596 function externalTidy( $text ) {
597 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
598 $fname = 'Parser::externalTidy';
599 wfProfileIn( $fname );
604 $descriptorspec = array(
605 0 => array('pipe', 'r'),
606 1 => array('pipe', 'w'),
607 2 => array('file', '/dev/null', 'a')
610 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
611 if (is_resource($process)) {
612 // Theoretically, this style of communication could cause a deadlock
613 // here. If the stdout buffer fills up, then writes to stdin could
614 // block. This doesn't appear to happen with tidy, because tidy only
615 // writes to stdout after it's finished reading from stdin. Search
616 // for tidyParseStdin and tidySaveStdout in console/tidy.c
617 fwrite($pipes[0], $text);
619 while (!feof($pipes[1])) {
620 $cleansource .= fgets($pipes[1], 1024);
623 proc_close($process);
626 wfProfileOut( $fname );
628 if( $cleansource == '' && $text != '') {
629 // Some kind of error happened, so we couldn't get the corrected text.
630 // Just give up; we'll use the source text and append a warning.
638 * Use the HTML tidy PECL extension to use the tidy library in-process,
639 * saving the overhead of spawning a new process. Currently written to
640 * the PHP 4.3.x version of the extension, may not work on PHP 5.
642 * 'pear install tidy' should be able to compile the extension module.
647 function internalTidy( $text ) {
649 $fname = 'Parser::internalTidy';
650 wfProfileIn( $fname );
652 tidy_load_config( $wgTidyConf );
653 tidy_set_encoding( 'utf8' );
654 tidy_parse_string( $text );
656 if( tidy_get_status() == 2 ) {
657 // 2 is magic number for fatal error
658 // http://www.php.net/manual/en/function.tidy-get-status.php
661 $cleansource = tidy_get_output();
663 wfProfileOut( $fname );
668 * parse the wiki syntax used to render tables
672 function doTableStuff ( $t ) {
673 $fname = 'Parser::doTableStuff';
674 wfProfileIn( $fname );
676 $t = explode ( "\n" , $t ) ;
677 $td = array () ; # Is currently a td tag open?
678 $ltd = array () ; # Was it TD or TH?
679 $tr = array () ; # Is currently a tr tag open?
680 $ltr = array () ; # tr attributes
681 $has_opened_tr = array(); # Did this table open a <tr> element?
682 $indent_level = 0; # indent level of the table
683 foreach ( $t AS $k => $x )
686 $fc = substr ( $x , 0 , 1 ) ;
687 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
688 $indent_level = strlen( $matches[1] );
690 $attributes = $this->unstripForHTML( $matches[2] );
692 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
693 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
694 array_push ( $td , false ) ;
695 array_push ( $ltd , '' ) ;
696 array_push ( $tr , false ) ;
697 array_push ( $ltr , '' ) ;
698 array_push ( $has_opened_tr, false );
700 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
701 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
702 $z = "</table>" . substr ( $x , 2);
703 $l = array_pop ( $ltd ) ;
704 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
705 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
706 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
708 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
710 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
711 $x = substr ( $x , 1 ) ;
712 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
714 $l = array_pop ( $ltd ) ;
715 array_pop ( $has_opened_tr );
716 array_push ( $has_opened_tr , true ) ;
717 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
718 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
721 array_push ( $tr , false ) ;
722 array_push ( $td , false ) ;
723 array_push ( $ltd , '' ) ;
724 $attributes = $this->unstripForHTML( $x );
725 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
727 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
729 if ( '|+' == substr ( $x , 0 , 2 ) ) {
731 $x = substr ( $x , 1 ) ;
733 $after = substr ( $x , 1 ) ;
734 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
736 // Split up multiple cells on the same line.
737 // FIXME: This can result in improper nesting of tags processed
738 // by earlier parser steps, but should avoid splitting up eg
739 // attribute values containing literal "||".
740 $after = wfExplodeMarkup( '||', $after );
744 # Loop through each table cell
745 foreach ( $after AS $theline )
750 $tra = array_pop ( $ltr ) ;
751 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
752 array_push ( $tr , true ) ;
753 array_push ( $ltr , '' ) ;
754 array_pop ( $has_opened_tr );
755 array_push ( $has_opened_tr , true ) ;
758 $l = array_pop ( $ltd ) ;
759 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
760 if ( $fc == '|' ) $l = 'td' ;
761 else if ( $fc == '!' ) $l = 'th' ;
762 else if ( $fc == '+' ) $l = 'caption' ;
764 array_push ( $ltd , $l ) ;
767 $y = explode ( '|' , $theline , 2 ) ;
768 # Note that a '|' inside an invalid link should not
769 # be mistaken as delimiting cell parameters
770 if ( strpos( $y[0], '[[' ) !== false ) {
771 $y = array ($theline);
773 if ( count ( $y ) == 1 )
774 $y = "{$z}<{$l}>{$y[0]}" ;
776 $attributes = $this->unstripForHTML( $y[0] );
777 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
780 array_push ( $td , true ) ;
785 # Closing open td, tr && table
786 while ( count ( $td ) > 0 )
788 $l = array_pop ( $ltd ) ;
789 if ( array_pop ( $td ) ) $t[] = '</td>' ;
790 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
791 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
795 $t = implode ( "\n" , $t ) ;
796 # special case: don't return empty table
797 if($t == "<table>\n<tr><td></td></tr>\n</table>")
799 wfProfileOut( $fname );
804 * Helper function for parse() that transforms wiki markup into
805 * HTML. Only called for $mOutputType == OT_HTML.
809 function internalParse( $text ) {
812 $fname = 'Parser::internalParse';
813 wfProfileIn( $fname );
815 # Remove <noinclude> tags and <includeonly> sections
816 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
817 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
818 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
820 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
822 $text = $this->replaceVariables( $text, $args );
824 // Tables need to come after variable replacement for things to work
825 // properly; putting them before other transformations should keep
826 // exciting things like link expansions from showing up in surprising
828 $text = $this->doTableStuff( $text );
830 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
832 $text = $this->stripToc( $text );
833 $text = $this->doHeadings( $text );
834 if($this->mOptions
->getUseDynamicDates()) {
835 $df =& DateFormatter
::getInstance();
836 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
838 $text = $this->doAllQuotes( $text );
839 $text = $this->replaceInternalLinks( $text );
840 $text = $this->replaceExternalLinks( $text );
842 # replaceInternalLinks may sometimes leave behind
843 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
844 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
846 $text = $this->doMagicLinks( $text );
847 $text = $this->formatHeadings( $text, $isMain );
849 wfProfileOut( $fname );
854 * Replace special strings like "ISBN xxx" and "RFC xxx" with
855 * magic external links.
859 function &doMagicLinks( &$text ) {
860 $text = $this->magicISBN( $text );
861 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
862 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
867 * Parse headers and return html
871 function doHeadings( $text ) {
872 $fname = 'Parser::doHeadings';
873 wfProfileIn( $fname );
874 for ( $i = 6; $i >= 1; --$i ) {
875 $h = str_repeat( '=', $i );
876 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
877 "<h{$i}>\\1</h{$i}>\\2", $text );
879 wfProfileOut( $fname );
884 * Replace single quotes with HTML markup
886 * @return string the altered text
888 function doAllQuotes( $text ) {
889 $fname = 'Parser::doAllQuotes';
890 wfProfileIn( $fname );
892 $lines = explode( "\n", $text );
893 foreach ( $lines as $line ) {
894 $outtext .= $this->doQuotes ( $line ) . "\n";
896 $outtext = substr($outtext, 0,-1);
897 wfProfileOut( $fname );
902 * Helper function for doAllQuotes()
905 function doQuotes( $text ) {
906 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
907 if ( count( $arr ) == 1 )
911 # First, do some preliminary work. This may shift some apostrophes from
912 # being mark-up to being text. It also counts the number of occurrences
913 # of bold and italics mark-ups.
917 foreach ( $arr as $r )
919 if ( ( $i %
2 ) == 1 )
921 # If there are ever four apostrophes, assume the first is supposed to
922 # be text, and the remaining three constitute mark-up for bold text.
923 if ( strlen( $arr[$i] ) == 4 )
928 # If there are more than 5 apostrophes in a row, assume they're all
929 # text except for the last 5.
930 else if ( strlen( $arr[$i] ) > 5 )
932 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
935 # Count the number of occurrences of bold and italics mark-ups.
936 # We are not counting sequences of five apostrophes.
937 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
938 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
939 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
944 # If there is an odd number of both bold and italics, it is likely
945 # that one of the bold ones was meant to be an apostrophe followed
946 # by italics. Which one we cannot know for certain, but it is more
947 # likely to be one that has a single-letter word before it.
948 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
951 $firstsingleletterword = -1;
952 $firstmultiletterword = -1;
954 foreach ( $arr as $r )
956 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
958 $x1 = substr ($arr[$i-1], -1);
959 $x2 = substr ($arr[$i-1], -2, 1);
961 if ($firstspace == -1) $firstspace = $i;
962 } else if ($x2 == ' ') {
963 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
965 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
971 # If there is a single-letter word, use it!
972 if ($firstsingleletterword > -1)
974 $arr [ $firstsingleletterword ] = "''";
975 $arr [ $firstsingleletterword-1 ] .= "'";
977 # If not, but there's a multi-letter word, use that one.
978 else if ($firstmultiletterword > -1)
980 $arr [ $firstmultiletterword ] = "''";
981 $arr [ $firstmultiletterword-1 ] .= "'";
983 # ... otherwise use the first one that has neither.
984 # (notice that it is possible for all three to be -1 if, for example,
985 # there is only one pentuple-apostrophe in the line)
986 else if ($firstspace > -1)
988 $arr [ $firstspace ] = "''";
989 $arr [ $firstspace-1 ] .= "'";
993 # Now let's actually convert our apostrophic mush to HTML!
1002 if ($state == 'both')
1009 if (strlen ($r) == 2)
1012 { $output .= '</i>'; $state = ''; }
1013 else if ($state == 'bi')
1014 { $output .= '</i>'; $state = 'b'; }
1015 else if ($state == 'ib')
1016 { $output .= '</b></i><b>'; $state = 'b'; }
1017 else if ($state == 'both')
1018 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1019 else # $state can be 'b' or ''
1020 { $output .= '<i>'; $state .= 'i'; }
1022 else if (strlen ($r) == 3)
1025 { $output .= '</b>'; $state = ''; }
1026 else if ($state == 'bi')
1027 { $output .= '</i></b><i>'; $state = 'i'; }
1028 else if ($state == 'ib')
1029 { $output .= '</b>'; $state = 'i'; }
1030 else if ($state == 'both')
1031 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1032 else # $state can be 'i' or ''
1033 { $output .= '<b>'; $state .= 'b'; }
1035 else if (strlen ($r) == 5)
1038 { $output .= '</b><i>'; $state = 'i'; }
1039 else if ($state == 'i')
1040 { $output .= '</i><b>'; $state = 'b'; }
1041 else if ($state == 'bi')
1042 { $output .= '</i></b>'; $state = ''; }
1043 else if ($state == 'ib')
1044 { $output .= '</b></i>'; $state = ''; }
1045 else if ($state == 'both')
1046 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1047 else # ($state == '')
1048 { $buffer = ''; $state = 'both'; }
1053 # Now close all remaining tags. Notice that the order is important.
1054 if ($state == 'b' ||
$state == 'ib')
1056 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1060 if ($state == 'both')
1061 $output .= '<b><i>'.$buffer.'</i></b>';
1067 * Replace external links
1069 * Note: this is all very hackish and the order of execution matters a lot.
1070 * Make sure to run maintenance/parserTests.php if you change this code.
1074 function replaceExternalLinks( $text ) {
1076 $fname = 'Parser::replaceExternalLinks';
1077 wfProfileIn( $fname );
1079 $sk =& $this->mOptions
->getSkin();
1081 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1083 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1086 while ( $i<count( $bits ) ) {
1088 $protocol = $bits[$i++
];
1089 $text = $bits[$i++
];
1090 $trail = $bits[$i++
];
1092 # The characters '<' and '>' (which were escaped by
1093 # removeHTMLtags()) should not be included in
1094 # URLs, per RFC 2396.
1095 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1096 $text = substr($url, $m2[0][1]) . ' ' . $text;
1097 $url = substr($url, 0, $m2[0][1]);
1100 # If the link text is an image URL, replace it with an <img> tag
1101 # This happened by accident in the original parser, but some people used it extensively
1102 $img = $this->maybeMakeExternalImage( $text );
1103 if ( $img !== false ) {
1109 # Set linktype for CSS - if URL==text, link is essentially free
1110 $linktype = ($text == $url) ?
'free' : 'text';
1112 # No link text, e.g. [http://domain.tld/some.link]
1113 if ( $text == '' ) {
1114 # Autonumber if allowed. See bug #5918
1115 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1116 $text = '[' . ++
$this->mAutonumber
. ']';
1117 $linktype = 'autonumber';
1119 # Otherwise just use the URL
1120 $text = htmlspecialchars( $url );
1124 # Have link text, e.g. [http://domain.tld/some.link text]s
1126 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1129 $text = $wgContLang->markNoConversion($text);
1131 # Normalize any HTML entities in input. They will be
1132 # re-escaped by makeExternalLink().
1133 $url = Sanitizer
::decodeCharReferences( $url );
1135 # Process the trail (i.e. everything after this link up until start of the next link),
1136 # replacing any non-bracketed links
1137 $trail = $this->replaceFreeExternalLinks( $trail );
1139 # Use the encoded URL
1140 # This means that users can paste URLs directly into the text
1141 # Funny characters like ö aren't valid in URLs anyway
1142 # This was changed in August 2004
1143 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1145 # Register link in the output object.
1146 # Replace unnecessary URL escape codes with the referenced character
1147 # This prevents spammers from hiding links from the filters
1148 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1149 $this->mOutput
->addExternalLink( $pasteurized );
1152 wfProfileOut( $fname );
1157 * Replace anything that looks like a URL with a link
1160 function replaceFreeExternalLinks( $text ) {
1162 $fname = 'Parser::replaceFreeExternalLinks';
1163 wfProfileIn( $fname );
1165 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1166 $s = array_shift( $bits );
1169 $sk =& $this->mOptions
->getSkin();
1171 while ( $i < count( $bits ) ){
1172 $protocol = $bits[$i++
];
1173 $remainder = $bits[$i++
];
1175 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1176 # Found some characters after the protocol that look promising
1177 $url = $protocol . $m[1];
1180 # special case: handle urls as url args:
1181 # http://www.example.com/foo?=http://www.example.com/bar
1182 if(strlen($trail) == 0 &&
1184 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1185 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1188 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1193 # The characters '<' and '>' (which were escaped by
1194 # removeHTMLtags()) should not be included in
1195 # URLs, per RFC 2396.
1196 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1197 $trail = substr($url, $m2[0][1]) . $trail;
1198 $url = substr($url, 0, $m2[0][1]);
1201 # Move trailing punctuation to $trail
1203 # If there is no left bracket, then consider right brackets fair game too
1204 if ( strpos( $url, '(' ) === false ) {
1208 $numSepChars = strspn( strrev( $url ), $sep );
1209 if ( $numSepChars ) {
1210 $trail = substr( $url, -$numSepChars ) . $trail;
1211 $url = substr( $url, 0, -$numSepChars );
1214 # Normalize any HTML entities in input. They will be
1215 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1216 $url = Sanitizer
::decodeCharReferences( $url );
1218 # Is this an external image?
1219 $text = $this->maybeMakeExternalImage( $url );
1220 if ( $text === false ) {
1221 # Not an image, make a link
1222 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1223 # Register it in the output object...
1224 # Replace unnecessary URL escape codes with their equivalent characters
1225 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1226 $this->mOutput
->addExternalLink( $pasteurized );
1228 $s .= $text . $trail;
1230 $s .= $protocol . $remainder;
1233 wfProfileOut( $fname );
1238 * Replace unusual URL escape codes with their equivalent characters
1242 * @fixme This can merge genuinely required bits in the path or query string,
1243 * breaking legit URLs. A proper fix would treat the various parts of
1244 * the URL differently; as a workaround, just use the output for
1245 * statistical records, not for actual linking/output.
1247 function replaceUnusualEscapes( $url ) {
1248 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1249 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1253 * Callback function used in replaceUnusualEscapes().
1254 * Replaces unusual URL escape codes with their equivalent character
1258 function replaceUnusualEscapesCallback( $matches ) {
1259 $char = urldecode( $matches[0] );
1260 $ord = ord( $char );
1261 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1262 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1263 // No, shouldn't be escaped
1266 // Yes, leave it escaped
1272 * make an image if it's allowed, either through the global
1273 * option or through the exception
1276 function maybeMakeExternalImage( $url ) {
1277 $sk =& $this->mOptions
->getSkin();
1278 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1279 $imagesexception = !empty($imagesfrom);
1281 if ( $this->mOptions
->getAllowExternalImages()
1282 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1283 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1285 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1292 * Process [[ ]] wikilinks
1296 function replaceInternalLinks( $s ) {
1298 static $fname = 'Parser::replaceInternalLinks' ;
1300 wfProfileIn( $fname );
1302 wfProfileIn( $fname.'-setup' );
1304 # the % is needed to support urlencoded titles as well
1305 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1307 $sk =& $this->mOptions
->getSkin();
1309 #split the entire text string on occurences of [[
1310 $a = explode( '[[', ' ' . $s );
1311 #get the first element (all text up to first [[), and remove the space we added
1312 $s = array_shift( $a );
1313 $s = substr( $s, 1 );
1315 # Match a link having the form [[namespace:link|alternate]]trail
1317 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1318 # Match cases where there is no "]]", which might still be images
1319 static $e1_img = FALSE;
1320 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1321 # Match the end of a line for a word that's not followed by whitespace,
1322 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1323 $e2 = wfMsgForContent( 'linkprefix' );
1325 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1327 if( is_null( $this->mTitle
) ) {
1328 wfDebugDieBacktrace( 'nooo' );
1330 $nottalk = !$this->mTitle
->isTalkPage();
1332 if ( $useLinkPrefixExtension ) {
1333 if ( preg_match( $e2, $s, $m ) ) {
1334 $first_prefix = $m[2];
1336 $first_prefix = false;
1342 $selflink = $this->mTitle
->getPrefixedText();
1343 wfProfileOut( $fname.'-setup' );
1345 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1346 $useSubpages = $this->areSubpagesAllowed();
1348 # Loop for each link
1349 for ($k = 0; isset( $a[$k] ); $k++
) {
1351 if ( $useLinkPrefixExtension ) {
1352 wfProfileIn( $fname.'-prefixhandling' );
1353 if ( preg_match( $e2, $s, $m ) ) {
1361 $prefix = $first_prefix;
1362 $first_prefix = false;
1364 wfProfileOut( $fname.'-prefixhandling' );
1367 $might_be_img = false;
1369 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1371 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1372 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1373 # the real problem is with the $e1 regex
1376 # Still some problems for cases where the ] is meant to be outside punctuation,
1377 # and no image is in sight. See bug 2095.
1380 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1381 strpos($text, '[') !== false
1384 $text .= ']'; # so that replaceExternalLinks($text) works later
1387 # fix up urlencoded title texts
1388 if(preg_match('/%/', $m[1] ))
1389 # Should anchors '#' also be rejected?
1390 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1392 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1393 $might_be_img = true;
1395 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1397 } else { # Invalid form; output directly
1398 $s .= $prefix . '[[' . $line ;
1402 # Don't allow internal links to pages containing
1403 # PROTO: where PROTO is a valid URL protocol; these
1404 # should be external links.
1405 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1406 $s .= $prefix . '[[' . $line ;
1410 # Make subpage if necessary
1411 if( $useSubpages ) {
1412 $link = $this->maybeDoSubpageLink( $m[1], $text );
1417 $noforce = (substr($m[1], 0, 1) != ':');
1419 # Strip off leading ':'
1420 $link = substr($link, 1);
1423 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1425 $s .= $prefix . '[[' . $line;
1429 #check other language variants of the link
1430 #if the article does not exist
1431 if( $checkVariantLink
1432 && $nt->getArticleID() == 0 ) {
1433 $wgContLang->findVariantLink($link, $nt);
1436 $ns = $nt->getNamespace();
1437 $iw = $nt->getInterWiki();
1439 if ($might_be_img) { # if this is actually an invalid link
1440 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1442 while (isset ($a[$k+
1]) ) {
1443 #look at the next 'line' to see if we can close it there
1444 $spliced = array_splice( $a, $k +
1, 1 );
1445 $next_line = array_shift( $spliced );
1446 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1447 # the first ]] closes the inner link, the second the image
1449 $text .= '[[' . $m[1];
1452 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1453 #if there's exactly one ]] that's fine, we'll keep looking
1454 $text .= '[[' . $m[0];
1456 #if $next_line is invalid too, we need look no further
1457 $text .= '[[' . $next_line;
1462 # we couldn't find the end of this imageLink, so output it raw
1463 #but don't ignore what might be perfectly normal links in the text we've examined
1464 $text = $this->replaceInternalLinks($text);
1465 $s .= $prefix . '[[' . $link . '|' . $text;
1466 # note: no $trail, because without an end, there *is* no trail
1469 } else { #it's not an image, so output it raw
1470 $s .= $prefix . '[[' . $link . '|' . $text;
1471 # note: no $trail, because without an end, there *is* no trail
1476 $wasblank = ( '' == $text );
1477 if( $wasblank ) $text = $link;
1480 # Link not escaped by : , create the various objects
1484 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1485 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1486 $s = rtrim($s . "\n");
1487 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1491 if ( $ns == NS_IMAGE
) {
1492 wfProfileIn( "$fname-image" );
1493 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1494 # recursively parse links inside the image caption
1495 # actually, this will parse them in any other parameters, too,
1496 # but it might be hard to fix that, and it doesn't matter ATM
1497 $text = $this->replaceExternalLinks($text);
1498 $text = $this->replaceInternalLinks($text);
1500 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1501 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1502 $this->mOutput
->addImage( $nt->getDBkey() );
1504 wfProfileOut( "$fname-image" );
1507 wfProfileOut( "$fname-image" );
1511 if ( $ns == NS_CATEGORY
) {
1512 wfProfileIn( "$fname-category" );
1513 $s = rtrim($s . "\n"); # bug 87
1516 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1517 $sortkey = $this->mTitle
->getText();
1519 $sortkey = $this->mTitle
->getPrefixedText();
1524 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1525 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1526 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1529 * Strip the whitespace Category links produce, see bug 87
1530 * @todo We might want to use trim($tmp, "\n") here.
1532 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1534 wfProfileOut( "$fname-category" );
1539 if( ( $nt->getPrefixedText() === $selflink ) &&
1540 ( $nt->getFragment() === '' ) ) {
1541 # Self-links are handled specially; generally de-link and change to bold.
1542 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1546 # Special and Media are pseudo-namespaces; no pages actually exist in them
1547 if( $ns == NS_MEDIA
) {
1548 $link = $sk->makeMediaLinkObj( $nt, $text );
1549 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1550 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1551 $this->mOutput
->addImage( $nt->getDBkey() );
1553 } elseif( $ns == NS_SPECIAL
) {
1554 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1556 } elseif( $ns == NS_IMAGE
) {
1557 $img = Image
::newFromTitle( $nt );
1558 if( $img->exists() ) {
1559 // Force a blue link if the file exists; may be a remote
1560 // upload on the shared repository, and we want to see its
1561 // auto-generated page.
1562 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1566 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1568 wfProfileOut( $fname );
1573 * Make a link placeholder. The text returned can be later resolved to a real link with
1574 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1575 * parsing of interwiki links, and secondly to allow all extistence checks and
1576 * article length checks (for stub links) to be bundled into a single query.
1579 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1580 if ( ! is_object($nt) ) {
1582 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1584 # Separate the link trail from the rest of the link
1585 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1587 if ( $nt->isExternal() ) {
1588 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1589 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1590 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1592 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1593 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1594 $this->mLinkHolders
['queries'][] = $query;
1595 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1596 $this->mLinkHolders
['titles'][] = $nt;
1598 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1605 * Render a forced-blue link inline; protect against double expansion of
1606 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1607 * Since this little disaster has to split off the trail text to avoid
1608 * breaking URLs in the following text without breaking trails on the
1609 * wiki links, it's been made into a horrible function.
1612 * @param string $text
1613 * @param string $query
1614 * @param string $trail
1615 * @param string $prefix
1616 * @return string HTML-wikitext mix oh yuck
1618 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1619 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1620 $sk =& $this->mOptions
->getSkin();
1621 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1622 return $this->armorLinks( $link ) . $trail;
1626 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1627 * going to go through further parsing steps before inline URL expansion.
1629 * In particular this is important when using action=render, which causes
1630 * full URLs to be included.
1632 * Oh man I hate our multi-layer parser!
1634 * @param string more-or-less HTML
1635 * @return string less-or-more HTML with NOPARSE bits
1637 function armorLinks( $text ) {
1638 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1639 "{$this->mUniqPrefix}NOPARSE$1", $text );
1643 * Return true if subpage links should be expanded on this page.
1646 function areSubpagesAllowed() {
1647 # Some namespaces don't allow subpages
1648 global $wgNamespacesWithSubpages;
1649 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1653 * Handle link to subpage if necessary
1654 * @param string $target the source of the link
1655 * @param string &$text the link text, modified as necessary
1656 * @return string the full name of the link
1659 function maybeDoSubpageLink($target, &$text) {
1662 # :Foobar -- override special treatment of prefix (images, language links)
1663 # /Foobar -- convert to CurrentPage/Foobar
1664 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1665 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1666 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1668 $fname = 'Parser::maybeDoSubpageLink';
1669 wfProfileIn( $fname );
1670 $ret = $target; # default return value is no change
1672 # Some namespaces don't allow subpages,
1673 # so only perform processing if subpages are allowed
1674 if( $this->areSubpagesAllowed() ) {
1675 # Look at the first character
1676 if( $target != '' && $target{0} == '/' ) {
1677 # / at end means we don't want the slash to be shown
1678 if( substr( $target, -1, 1 ) == '/' ) {
1679 $target = substr( $target, 1, -1 );
1682 $noslash = substr( $target, 1 );
1685 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1686 if( '' === $text ) {
1688 } # this might be changed for ugliness reasons
1690 # check for .. subpage backlinks
1692 $nodotdot = $target;
1693 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1695 $nodotdot = substr( $nodotdot, 3 );
1697 if($dotdotcount > 0) {
1698 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1699 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1700 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1701 # / at the end means don't show full path
1702 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1703 $nodotdot = substr( $nodotdot, 0, -1 );
1704 if( '' === $text ) {
1708 $nodotdot = trim( $nodotdot );
1709 if( $nodotdot != '' ) {
1710 $ret .= '/' . $nodotdot;
1717 wfProfileOut( $fname );
1722 * Used by doBlockLevels()
1725 /* private */ function closeParagraph() {
1727 if ( '' != $this->mLastSection
) {
1728 $result = '</' . $this->mLastSection
. ">\n";
1730 $this->mInPre
= false;
1731 $this->mLastSection
= '';
1734 # getCommon() returns the length of the longest common substring
1735 # of both arguments, starting at the beginning of both.
1737 /* private */ function getCommon( $st1, $st2 ) {
1738 $fl = strlen( $st1 );
1739 $shorter = strlen( $st2 );
1740 if ( $fl < $shorter ) { $shorter = $fl; }
1742 for ( $i = 0; $i < $shorter; ++
$i ) {
1743 if ( $st1{$i} != $st2{$i} ) { break; }
1747 # These next three functions open, continue, and close the list
1748 # element appropriate to the prefix character passed into them.
1750 /* private */ function openList( $char ) {
1751 $result = $this->closeParagraph();
1753 if ( '*' == $char ) { $result .= '<ul><li>'; }
1754 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1755 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1756 else if ( ';' == $char ) {
1757 $result .= '<dl><dt>';
1758 $this->mDTopen
= true;
1760 else { $result = '<!-- ERR 1 -->'; }
1765 /* private */ function nextItem( $char ) {
1766 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1767 else if ( ':' == $char ||
';' == $char ) {
1769 if ( $this->mDTopen
) { $close = '</dt>'; }
1770 if ( ';' == $char ) {
1771 $this->mDTopen
= true;
1772 return $close . '<dt>';
1774 $this->mDTopen
= false;
1775 return $close . '<dd>';
1778 return '<!-- ERR 2 -->';
1781 /* private */ function closeList( $char ) {
1782 if ( '*' == $char ) { $text = '</li></ul>'; }
1783 else if ( '#' == $char ) { $text = '</li></ol>'; }
1784 else if ( ':' == $char ) {
1785 if ( $this->mDTopen
) {
1786 $this->mDTopen
= false;
1787 $text = '</dt></dl>';
1789 $text = '</dd></dl>';
1792 else { return '<!-- ERR 3 -->'; }
1798 * Make lists from lines starting with ':', '*', '#', etc.
1801 * @return string the lists rendered as HTML
1803 function doBlockLevels( $text, $linestart ) {
1804 $fname = 'Parser::doBlockLevels';
1805 wfProfileIn( $fname );
1807 # Parsing through the text line by line. The main thing
1808 # happening here is handling of block-level elements p, pre,
1809 # and making lists from lines starting with * # : etc.
1811 $textLines = explode( "\n", $text );
1813 $lastPrefix = $output = '';
1814 $this->mDTopen
= $inBlockElem = false;
1816 $paragraphStack = false;
1818 if ( !$linestart ) {
1819 $output .= array_shift( $textLines );
1821 foreach ( $textLines as $oLine ) {
1822 $lastPrefixLength = strlen( $lastPrefix );
1823 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1824 $preOpenMatch = preg_match('/<pre/i', $oLine );
1825 if ( !$this->mInPre
) {
1826 # Multiple prefixes may abut each other for nested lists.
1827 $prefixLength = strspn( $oLine, '*#:;' );
1828 $pref = substr( $oLine, 0, $prefixLength );
1831 $pref2 = str_replace( ';', ':', $pref );
1832 $t = substr( $oLine, $prefixLength );
1833 $this->mInPre
= !empty($preOpenMatch);
1835 # Don't interpret any other prefixes in preformatted text
1837 $pref = $pref2 = '';
1842 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1843 # Same as the last item, so no need to deal with nesting or opening stuff
1844 $output .= $this->nextItem( substr( $pref, -1 ) );
1845 $paragraphStack = false;
1847 if ( substr( $pref, -1 ) == ';') {
1848 # The one nasty exception: definition lists work like this:
1849 # ; title : definition text
1850 # So we check for : in the remainder text to split up the
1851 # title and definition, without b0rking links.
1853 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1855 $output .= $term . $this->nextItem( ':' );
1858 } elseif( $prefixLength ||
$lastPrefixLength ) {
1859 # Either open or close a level...
1860 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1861 $paragraphStack = false;
1863 while( $commonPrefixLength < $lastPrefixLength ) {
1864 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1865 --$lastPrefixLength;
1867 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1868 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1870 while ( $prefixLength > $commonPrefixLength ) {
1871 $char = substr( $pref, $commonPrefixLength, 1 );
1872 $output .= $this->openList( $char );
1874 if ( ';' == $char ) {
1875 # FIXME: This is dupe of code above
1876 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1878 $output .= $term . $this->nextItem( ':' );
1881 ++
$commonPrefixLength;
1883 $lastPrefix = $pref2;
1885 if( 0 == $prefixLength ) {
1886 wfProfileIn( "$fname-paragraph" );
1887 # No prefix (not in list)--go to paragraph mode
1888 // XXX: use a stack for nestable elements like span, table and div
1889 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1890 $closematch = preg_match(
1891 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1892 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1893 if ( $openmatch or $closematch ) {
1894 $paragraphStack = false;
1895 #Â TODO bug 5718: paragraph closed
1896 $output .= $this->closeParagraph();
1897 if ( $preOpenMatch and !$preCloseMatch ) {
1898 $this->mInPre
= true;
1900 if ( $closematch ) {
1901 $inBlockElem = false;
1903 $inBlockElem = true;
1905 } else if ( !$inBlockElem && !$this->mInPre
) {
1906 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1908 if ($this->mLastSection
!= 'pre') {
1909 $paragraphStack = false;
1910 $output .= $this->closeParagraph().'<pre>';
1911 $this->mLastSection
= 'pre';
1913 $t = substr( $t, 1 );
1916 if ( '' == trim($t) ) {
1917 if ( $paragraphStack ) {
1918 $output .= $paragraphStack.'<br />';
1919 $paragraphStack = false;
1920 $this->mLastSection
= 'p';
1922 if ($this->mLastSection
!= 'p' ) {
1923 $output .= $this->closeParagraph();
1924 $this->mLastSection
= '';
1925 $paragraphStack = '<p>';
1927 $paragraphStack = '</p><p>';
1931 if ( $paragraphStack ) {
1932 $output .= $paragraphStack;
1933 $paragraphStack = false;
1934 $this->mLastSection
= 'p';
1935 } else if ($this->mLastSection
!= 'p') {
1936 $output .= $this->closeParagraph().'<p>';
1937 $this->mLastSection
= 'p';
1942 wfProfileOut( "$fname-paragraph" );
1944 // somewhere above we forget to get out of pre block (bug 785)
1945 if($preCloseMatch && $this->mInPre
) {
1946 $this->mInPre
= false;
1948 if ($paragraphStack === false) {
1952 while ( $prefixLength ) {
1953 $output .= $this->closeList( $pref2{$prefixLength-1} );
1956 if ( '' != $this->mLastSection
) {
1957 $output .= '</' . $this->mLastSection
. '>';
1958 $this->mLastSection
= '';
1961 wfProfileOut( $fname );
1966 * Split up a string on ':', ignoring any occurences inside
1967 * <a>..</a> or <span>...</span>
1968 * @param string $str the string to split
1969 * @param string &$before set to everything before the ':'
1970 * @param string &$after set to everything after the ':'
1971 * return string the position of the ':', or false if none found
1973 function findColonNoLinks($str, &$before, &$after) {
1974 # I wonder if we should make this count all tags, not just <a>
1975 # and <span>. That would prevent us from matching a ':' that
1976 # comes in the middle of italics other such formatting....
1978 $fname = 'Parser::findColonNoLinks';
1979 wfProfileIn( $fname );
1982 $colon = strpos($str, ':', $pos);
1984 if ($colon !== false) {
1985 $before = substr($str, 0, $colon);
1986 $after = substr($str, $colon +
1);
1988 # Skip any ':' within <a> or <span> pairs
1989 $a = substr_count($before, '<a');
1990 $s = substr_count($before, '<span');
1991 $ca = substr_count($before, '</a>');
1992 $cs = substr_count($before, '</span>');
1994 if ($a <= $ca and $s <= $cs) {
1995 # Tags are balanced before ':'; ok
2000 } while ($colon !== false);
2001 wfProfileOut( $fname );
2006 * Return value of a magic variable (like PAGENAME)
2010 function getVariableValue( $index ) {
2011 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2014 * Some of these require message or data lookups and can be
2015 * expensive to check many times.
2017 static $varCache = array();
2018 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2019 if ( isset( $varCache[$index] ) )
2020 return $varCache[$index];
2023 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2026 case MAG_CURRENTMONTH
:
2027 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2028 case MAG_CURRENTMONTHNAME
:
2029 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2030 case MAG_CURRENTMONTHNAMEGEN
:
2031 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2032 case MAG_CURRENTMONTHABBREV
:
2033 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2034 case MAG_CURRENTDAY
:
2035 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2036 case MAG_CURRENTDAY2
:
2037 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2039 return $this->mTitle
->getText();
2041 return $this->mTitle
->getPartialURL();
2042 case MAG_FULLPAGENAME
:
2043 return $this->mTitle
->getPrefixedText();
2044 case MAG_FULLPAGENAMEE
:
2045 return $this->mTitle
->getPrefixedURL();
2046 case MAG_SUBPAGENAME
:
2047 return $this->mTitle
->getSubpageText();
2048 case MAG_SUBPAGENAMEE
:
2049 return $this->mTitle
->getSubpageUrlForm();
2050 case MAG_BASEPAGENAME
:
2051 return $this->mTitle
->getBaseText();
2052 case MAG_BASEPAGENAMEE
:
2053 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2054 case MAG_TALKPAGENAME
:
2055 if( $this->mTitle
->canTalk() ) {
2056 $talkPage = $this->mTitle
->getTalkPage();
2057 return $talkPage->getPrefixedText();
2061 case MAG_TALKPAGENAMEE
:
2062 if( $this->mTitle
->canTalk() ) {
2063 $talkPage = $this->mTitle
->getTalkPage();
2064 return $talkPage->getPrefixedUrl();
2068 case MAG_SUBJECTPAGENAME
:
2069 $subjPage = $this->mTitle
->getSubjectPage();
2070 return $subjPage->getPrefixedText();
2071 case MAG_SUBJECTPAGENAMEE
:
2072 $subjPage = $this->mTitle
->getSubjectPage();
2073 return $subjPage->getPrefixedUrl();
2074 case MAG_REVISIONID
:
2075 return $this->mRevisionId
;
2077 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2078 case MAG_NAMESPACEE
:
2079 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2081 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2082 case MAG_TALKSPACEE
:
2083 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2084 case MAG_SUBJECTSPACE
:
2085 return $this->mTitle
->getSubjectNsText();
2086 case MAG_SUBJECTSPACEE
:
2087 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2088 case MAG_CURRENTDAYNAME
:
2089 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2090 case MAG_CURRENTYEAR
:
2091 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2092 case MAG_CURRENTTIME
:
2093 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2094 case MAG_CURRENTWEEK
:
2095 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2096 // int to remove the padding
2097 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2098 case MAG_CURRENTDOW
:
2099 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2100 case MAG_NUMBEROFARTICLES
:
2101 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2102 case MAG_NUMBEROFFILES
:
2103 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2104 case MAG_NUMBEROFUSERS
:
2105 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2106 case MAG_NUMBEROFPAGES
:
2107 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2108 case MAG_CURRENTTIMESTAMP
:
2109 return $varCache[$index] = wfTimestampNow();
2110 case MAG_CURRENTVERSION
:
2117 case MAG_SERVERNAME
:
2118 return $wgServerName;
2119 case MAG_SCRIPTPATH
:
2120 return $wgScriptPath;
2121 case MAG_DIRECTIONMARK
:
2122 return $wgContLang->getDirMark();
2125 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2133 * initialise the magic variables (like CURRENTMONTHNAME)
2137 function initialiseVariables() {
2138 $fname = 'Parser::initialiseVariables';
2139 wfProfileIn( $fname );
2140 global $wgVariableIDs;
2141 $this->mVariables
= array();
2142 foreach ( $wgVariableIDs as $id ) {
2143 $mw =& MagicWord
::get( $id );
2144 $mw->addToArray( $this->mVariables
, $id );
2146 wfProfileOut( $fname );
2150 * parse any parentheses in format ((title|part|part))
2151 * and call callbacks to get a replacement text for any found piece
2153 * @param string $text The text to parse
2154 * @param array $callbacks rules in form:
2155 * '{' => array( # opening parentheses
2156 * 'end' => '}', # closing parentheses
2157 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2158 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2163 function replace_callback ($text, $callbacks) {
2164 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2165 $lastOpeningBrace = -1; # last not closed parentheses
2167 for ($i = 0; $i < strlen($text); $i++
) {
2168 # check for any opening brace
2171 foreach ($callbacks as $key => $value) {
2172 $pos = strpos ($text, $key, $i);
2173 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2179 if ($lastOpeningBrace >= 0) {
2180 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2182 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2187 $pos = strpos ($text, '|', $i);
2189 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2200 # found openning brace, lets add it to parentheses stack
2201 if (null != $rule) {
2202 $piece = array('brace' => $text[$i],
2203 'braceEnd' => $rule['end'],
2208 # count openning brace characters
2209 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2214 $piece['startAt'] = $i+
1;
2215 $piece['partStart'] = $i+
1;
2217 # we need to add to stack only if openning brace count is enough for any given rule
2218 foreach ($rule['cb'] as $cnt => $fn) {
2219 if ($piece['count'] >= $cnt) {
2220 $lastOpeningBrace ++
;
2221 $openingBraceStack[$lastOpeningBrace] = $piece;
2228 else if ($lastOpeningBrace >= 0) {
2229 # first check if it is a closing brace
2230 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2231 # lets check if it is enough characters for closing brace
2233 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2236 # if there are more closing parentheses than opening ones, we parse less
2237 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2238 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2240 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2242 $matchingCallback = null;
2243 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2244 if ($count >= $cnt && $matchingCount < $cnt) {
2245 $matchingCount = $cnt;
2246 $matchingCallback = $fn;
2250 if ($matchingCount == 0) {
2255 # lets set a title or last part (if '|' was found)
2256 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2257 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2259 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2261 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2262 $pieceEnd = $i +
$matchingCount;
2264 if( is_callable( $matchingCallback ) ) {
2266 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2267 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2268 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2269 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2271 # finally we can call a user callback and replace piece of text
2272 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2273 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2274 $i = $pieceStart +
strlen($replaceWith) - 1;
2277 # null value for callback means that parentheses should be parsed, but not replaced
2278 $i +
= $matchingCount - 1;
2281 # reset last openning parentheses, but keep it in case there are unused characters
2282 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2283 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2284 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2287 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2288 $openingBraceStack[$lastOpeningBrace--] = null;
2290 if ($matchingCount < $piece['count']) {
2291 $piece['count'] -= $matchingCount;
2292 $piece['startAt'] -= $matchingCount;
2293 $piece['partStart'] = $piece['startAt'];
2294 # do we still qualify for any callback with remaining count?
2295 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2296 if ($piece['count'] >= $cnt) {
2297 $lastOpeningBrace ++
;
2298 $openingBraceStack[$lastOpeningBrace] = $piece;
2306 # lets set a title if it is a first separator, or next part otherwise
2307 if ($text[$i] == '|') {
2308 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2309 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2310 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2313 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2315 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2324 * Replace magic variables, templates, and template arguments
2325 * with the appropriate text. Templates are substituted recursively,
2326 * taking care to avoid infinite loops.
2328 * Note that the substitution depends on value of $mOutputType:
2329 * OT_WIKI: only {{subst:}} templates
2330 * OT_MSG: only magic variables
2331 * OT_HTML: all templates and magic variables
2333 * @param string $tex The text to transform
2334 * @param array $args Key-value pairs representing template parameters to substitute
2335 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2338 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2339 # Prevent too big inclusions
2340 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2344 $fname = 'Parser::replaceVariables';
2345 wfProfileIn( $fname );
2347 # This function is called recursively. To keep track of arguments we need a stack:
2348 array_push( $this->mArgStack
, $args );
2350 $braceCallbacks = array();
2352 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2354 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2355 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2357 $callbacks = array();
2358 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2359 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2360 $text = $this->replace_callback ($text, $callbacks);
2362 array_pop( $this->mArgStack
);
2364 wfProfileOut( $fname );
2369 * Replace magic variables
2372 function variableSubstitution( $matches ) {
2373 $fname = 'Parser::variableSubstitution';
2374 $varname = $matches[1];
2375 wfProfileIn( $fname );
2376 if ( !$this->mVariables
) {
2377 $this->initialiseVariables();
2380 if ( $this->mOutputType
== OT_WIKI
) {
2381 # Do only magic variables prefixed by SUBST
2382 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2383 if (!$mwSubst->matchStartAndRemove( $varname ))
2385 # Note that if we don't substitute the variable below,
2386 # we don't remove the {{subst:}} magic word, in case
2387 # it is a template rather than a magic variable.
2389 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2390 $id = $this->mVariables
[$varname];
2391 $text = $this->getVariableValue( $id );
2392 $this->mOutput
->mContainsOldMagic
= true;
2394 $text = $matches[0];
2396 wfProfileOut( $fname );
2400 # Split template arguments
2401 function getTemplateArgs( $argsString ) {
2402 if ( $argsString === '' ) {
2406 $args = explode( '|', substr( $argsString, 1 ) );
2408 # If any of the arguments contains a '[[' but no ']]', it needs to be
2409 # merged with the next arg because the '|' character between belongs
2410 # to the link syntax and not the template parameter syntax.
2411 $argc = count($args);
2413 for ( $i = 0; $i < $argc-1; $i++
) {
2414 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2415 $args[$i] .= '|'.$args[$i+
1];
2416 array_splice($args, $i+
1, 1);
2426 * Return the text of a template, after recursively
2427 * replacing any variables or templates within the template.
2429 * @param array $piece The parts of the template
2430 * $piece['text']: matched text
2431 * $piece['title']: the title, i.e. the part before the |
2432 * $piece['parts']: the parameter array
2433 * @return string the text of the template
2436 function braceSubstitution( $piece ) {
2437 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2438 $fname = 'Parser::braceSubstitution';
2439 wfProfileIn( $fname );
2442 $found = false; # $text has been filled
2443 $nowiki = false; # wiki markup in $text should be escaped
2444 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2445 $noargs = false; # Don't replace triple-brace arguments in $text
2446 $replaceHeadings = false; # Make the edit section links go to the template not the article
2447 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2448 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2450 # Title object, where $text came from
2455 # $part1 is the bit before the first |, and must contain only title characters
2456 # $args is a list of arguments, starting from index 0, not including $part1
2458 $part1 = $piece['title'];
2459 # If the third subpattern matched anything, it will start with |
2461 if (null == $piece['parts']) {
2462 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2463 if ($replaceWith != $piece['text']) {
2464 $text = $replaceWith;
2471 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2472 $argc = count( $args );
2476 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2477 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2478 # One of two possibilities is true:
2479 # 1) Found SUBST but not in the PST phase
2480 # 2) Didn't find SUBST and in the PST phase
2481 # In either case, return without further processing
2482 $text = $piece['text'];
2489 # MSG, MSGNW, INT and RAW
2492 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2493 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2496 # Remove obsolete MSG:
2497 $mwMsg =& MagicWord
::get( MAG_MSG
);
2498 $mwMsg->matchStartAndRemove( $part1 );
2502 $mwRaw =& MagicWord
::get( MAG_RAW
);
2503 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2504 $forceRawInterwiki = true;
2507 # Check if it is an internal message
2508 $mwInt =& MagicWord
::get( MAG_INT
);
2509 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2510 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2511 $text = $linestart . wfMsgReal( $part1, $args, true );
2519 # Check for NS: (namespace expansion)
2520 $mwNs = MagicWord
::get( MAG_NS
);
2521 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2522 if ( intval( $part1 ) ||
$part1 == "0" ) {
2523 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2526 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2527 if ( !is_null( $index ) ) {
2528 $text = $linestart . $wgContLang->getNsText( $index );
2537 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2538 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2539 $text = $linestart . urlencode( $part1 );
2544 # LCFIRST, UCFIRST, LC and UC
2546 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2547 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2548 $lc =& MagicWord
::get( MAG_LC
);
2549 $uc =& MagicWord
::get( MAG_UC
);
2550 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2551 $text = $linestart . $wgContLang->lcfirst( $part1 );
2553 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2554 $text = $linestart . $wgContLang->ucfirst( $part1 );
2556 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2557 $text = $linestart . $wgContLang->lc( $part1 );
2559 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2560 $text = $linestart . $wgContLang->uc( $part1 );
2565 # LOCALURL and FULLURL
2567 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2568 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2569 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2570 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2573 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2574 $func = 'getLocalURL';
2575 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2576 $func = 'escapeLocalURL';
2577 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2578 $func = 'getFullURL';
2579 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2580 $func = 'escapeFullURL';
2585 if ( $func !== false ) {
2586 $title = Title
::newFromText( $part1 );
2587 # Due to order of execution of a lot of bits, the values might be encoded
2588 # before arriving here; if that's true, then the title can't be created
2589 # and the variable will fail. If we can't get a decent title from the first
2590 # attempt, url-decode and try for a second.
2591 if( is_null( $title ) )
2592 $title = Title
::newFromUrl( urldecode( $part1 ) );
2593 if ( !is_null( $title ) ) {
2595 $text = $linestart . $title->$func( $args[0] );
2597 $text = $linestart . $title->$func();
2604 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2606 if ( !$found && $argc == 1 ) {
2607 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2608 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2609 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2615 if ( !$found && $argc >= 2 ) {
2616 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2617 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2618 if ($argc==2) {$args[2]=$args[1];}
2619 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2625 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2626 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2627 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2629 # Set title in parser output object
2631 $parserOptions = new ParserOptions
;
2632 $local_parser = new Parser ();
2633 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2634 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2637 $t = $this->mTitle
->getPrefixedText();
2638 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2644 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2646 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2647 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2648 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2649 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2650 foreach( $mwWordsToCheck as $word => $func ) {
2651 $mwCurrentWord =& MagicWord
::get( $word );
2652 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2653 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2654 if( $mwRawSuffix->match( $args[0] ) ) {
2655 # Raw and unformatted
2656 $text = $linestart . call_user_func( $func );
2658 # Formatted according to the content default
2659 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2668 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2669 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2670 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2671 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2677 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2678 $colonPos = strpos( $part1, ':' );
2679 if ( $colonPos !== false ) {
2680 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2681 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2682 $funcArgs = array_map( 'trim', $args );
2683 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2684 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2687 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2691 if ( is_array( $result ) ) {
2692 $text = $linestart . $result[0];
2693 unset( $result[0] );
2695 // Extract flags into the local scope
2696 // This allows callers to set flags such as nowiki, noparse, found, etc.
2699 $text = $linestart . $result;
2705 # Template table test
2707 # Did we encounter this template already? If yes, it is in the cache
2708 # and we need to check for loops.
2709 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2712 # Infinite loop test
2713 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2717 $text = $linestart .
2718 '{{' . $part1 . '}}' .
2719 '<!-- WARNING: template loop detected -->';
2720 wfDebug( "$fname: template loop broken at '$part1'\n" );
2722 # set $text to cached message.
2723 $text = $linestart . $this->mTemplates
[$piece['title']];
2727 # Load from database
2728 $lastPathLevel = $this->mTemplatePath
;
2731 # declaring $subpage directly in the function call
2732 # does not work correctly with references and breaks
2733 # {{/subpage}}-style inclusions
2735 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2736 if ($subpage !== '') {
2737 $ns = $this->mTitle
->getNamespace();
2739 $title = Title
::newFromText( $part1, $ns );
2741 if ( !is_null( $title ) ) {
2742 if ( !$title->isExternal() ) {
2743 # Check for excessive inclusion
2744 $dbk = $title->getPrefixedDBkey();
2745 if ( $this->incrementIncludeCount( $dbk ) ) {
2746 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2747 $text = SpecialPage
::capturePath( $title );
2748 if ( is_string( $text ) ) {
2753 $this->disableCache();
2756 $articleContent = $this->fetchTemplate( $title );
2757 if ( $articleContent !== false ) {
2759 $text = $articleContent;
2760 $replaceHeadings = true;
2765 # If the title is valid but undisplayable, make a link to it
2766 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2767 $text = '[['.$title->getPrefixedText().']]';
2770 } elseif ( $title->isTrans() ) {
2771 // Interwiki transclusion
2772 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2773 $text = $this->interwikiTransclude( $title, 'render' );
2777 $text = $this->interwikiTransclude( $title, 'raw' );
2778 $replaceHeadings = true;
2783 # Template cache array insertion
2784 # Use the original $piece['title'] not the mangled $part1, so that
2785 # modifiers such as RAW: produce separate cache entries
2787 $this->mTemplates
[$piece['title']] = $text;
2788 $text = $linestart . $text;
2793 # Recursive parsing, escaping and link table handling
2794 # Only for HTML output
2795 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2796 $text = wfEscapeWikiText( $text );
2797 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2799 $assocArgs = array();
2801 # Clean up argument array
2802 $assocArgs = array();
2804 foreach( $args as $arg ) {
2805 $eqpos = strpos( $arg, '=' );
2806 if ( $eqpos === false ) {
2807 $assocArgs[$index++
] = $arg;
2809 $name = trim( substr( $arg, 0, $eqpos ) );
2810 $value = trim( substr( $arg, $eqpos+
1 ) );
2811 if ( $value === false ) {
2814 if ( $name !== false ) {
2815 $assocArgs[$name] = $value;
2820 # Add a new element to the templace recursion path
2821 $this->mTemplatePath
[$part1] = 1;
2825 # If there are any <onlyinclude> tags, only include them
2826 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2827 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2829 foreach ($m[1] as $piece)
2832 # Remove <noinclude> sections and <includeonly> tags
2833 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2834 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2836 if( $this->mOutputType
== OT_HTML
) {
2837 # Strip <nowiki>, <pre>, etc.
2838 $text = $this->strip( $text, $this->mStripState
);
2839 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2841 $text = $this->replaceVariables( $text, $assocArgs );
2843 # If the template begins with a table or block-level
2844 # element, it should be treated as beginning a new line.
2845 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2846 $text = "\n" . $text;
2848 } elseif ( !$noargs ) {
2849 # $noparse and !$noargs
2850 # Just replace the arguments, not any double-brace items
2851 # This is used for rendered interwiki transclusion
2852 $text = $this->replaceVariables( $text, $assocArgs, true );
2855 # Prune lower levels off the recursion check path
2856 $this->mTemplatePath
= $lastPathLevel;
2859 wfProfileOut( $fname );
2860 return $piece['text'];
2863 # Replace raw HTML by a placeholder
2864 # Add a blank line preceding, to prevent it from mucking up
2865 # immediately preceding headings
2866 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2868 # replace ==section headers==
2869 # XXX this needs to go away once we have a better parser.
2870 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2871 if( !is_null( $title ) )
2872 $encodedname = base64_encode($title->getPrefixedDBkey());
2874 $encodedname = base64_encode("");
2875 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2876 PREG_SPLIT_DELIM_CAPTURE
);
2879 for( $i = 0; $i < count($m); $i +
= 2 ) {
2881 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2883 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2887 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2888 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2889 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2897 # Prune lower levels off the recursion check path
2898 $this->mTemplatePath
= $lastPathLevel;
2901 wfProfileOut( $fname );
2902 return $piece['text'];
2904 wfProfileOut( $fname );
2910 * Fetch the unparsed text of a template and register a reference to it.
2912 function fetchTemplate( $title ) {
2914 // Loop to fetch the article, with up to 1 redirect
2915 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2916 $rev = Revision
::newFromTitle( $title );
2917 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2921 $text = $rev->getText();
2922 if ( $text === false ) {
2926 $title = Title
::newFromRedirect( $text );
2932 * Transclude an interwiki link.
2934 function interwikiTransclude( $title, $action ) {
2935 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2937 if (!$wgEnableScaryTranscluding)
2938 return wfMsg('scarytranscludedisabled');
2940 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2941 // But we'll handle it generally anyway
2942 if ( $title->getNamespace() ) {
2943 // Use the canonical namespace, which should work anywhere
2944 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2946 $articleName = $title->getDBkey();
2949 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2950 $url .= "?action=$action";
2951 if (strlen($url) > 255)
2952 return wfMsg('scarytranscludetoolong');
2953 return $this->fetchScaryTemplateMaybeFromCache($url);
2956 function fetchScaryTemplateMaybeFromCache($url) {
2957 global $wgTranscludeCacheExpiry;
2958 $dbr =& wfGetDB(DB_SLAVE
);
2959 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2960 array('tc_url' => $url));
2962 $time = $obj->tc_time
;
2963 $text = $obj->tc_contents
;
2964 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2969 $text = wfGetHTTP($url);
2971 return wfMsg('scarytranscludefailed', $url);
2973 $dbw =& wfGetDB(DB_MASTER
);
2974 $dbw->replace('transcache', array('tc_url'), array(
2976 'tc_time' => time(),
2977 'tc_contents' => $text));
2983 * Triple brace replacement -- used for template arguments
2986 function argSubstitution( $matches ) {
2987 $arg = trim( $matches['title'] );
2988 $text = $matches['text'];
2989 $inputArgs = end( $this->mArgStack
);
2991 if ( array_key_exists( $arg, $inputArgs ) ) {
2992 $text = $inputArgs[$arg];
2993 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2994 $text = $matches['parts'][0];
3001 * Returns true if the function is allowed to include this entity
3004 function incrementIncludeCount( $dbk ) {
3005 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3006 $this->mIncludeCount
[$dbk] = 0;
3008 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3016 * Detect __TOC__ magic word and set a placeholder
3018 function stripToc( $text ) {
3019 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3021 $mw = MagicWord
::get( MAG_NOTOC
);
3022 if( $mw->matchAndRemove( $text ) ) {
3023 $this->mShowToc
= false;
3026 $mw = MagicWord
::get( MAG_TOC
);
3027 if( $mw->match( $text ) ) {
3028 $this->mShowToc
= true;
3029 $this->mForceTocPosition
= true;
3031 // Set a placeholder. At the end we'll fill it in with the TOC.
3032 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3034 // Only keep the first one.
3035 $text = $mw->replace( '', $text );
3041 * This function accomplishes several tasks:
3042 * 1) Auto-number headings if that option is enabled
3043 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3044 * 3) Add a Table of contents on the top for users who have enabled the option
3045 * 4) Auto-anchor headings
3047 * It loops through all headlines, collects the necessary data, then splits up the
3048 * string and re-inserts the newly formatted headlines.
3050 * @param string $text
3051 * @param boolean $isMain
3054 function formatHeadings( $text, $isMain=true ) {
3055 global $wgMaxTocLevel, $wgContLang;
3057 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3058 if( !$this->mTitle
->userCanEdit() ) {
3061 $showEditLink = $this->mOptions
->getEditSection();
3064 # Inhibit editsection links if requested in the page
3065 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3066 if( $esw->matchAndRemove( $text ) ) {
3070 # Get all headlines for numbering them and adding funky stuff like [edit]
3071 # links - this is for later, but we need the number of headlines right now
3072 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3074 # if there are fewer than 4 headlines in the article, do not show TOC
3075 # unless it's been explicitly enabled.
3076 $enoughToc = $this->mShowToc
&&
3077 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3079 # Allow user to stipulate that a page should have a "new section"
3080 # link added via __NEWSECTIONLINK__
3081 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3082 if( $mw->matchAndRemove( $text ) )
3083 $this->mOutput
->setNewSection( true );
3085 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3086 # override above conditions and always show TOC above first header
3087 $mw =& MagicWord
::get( MAG_FORCETOC
);
3088 if ($mw->matchAndRemove( $text ) ) {
3089 $this->mShowToc
= true;
3093 # Never ever show TOC if no headers
3094 if( $numMatches < 1 ) {
3098 # We need this to perform operations on the HTML
3099 $sk =& $this->mOptions
->getSkin();
3103 $sectionCount = 0; # headlineCount excluding template sections
3105 # Ugh .. the TOC should have neat indentation levels which can be
3106 # passed to the skin functions. These are determined here
3110 $sublevelCount = array();
3111 $levelCount = array();
3118 foreach( $matches[3] as $headline ) {
3120 $templatetitle = '';
3121 $templatesection = 0;
3124 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3126 $templatetitle = base64_decode($mat[1]);
3127 $templatesection = 1 +
(int)base64_decode($mat[2]);
3128 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3132 $prevlevel = $level;
3133 $prevtoclevel = $toclevel;
3135 $level = $matches[1][$headlineCount];
3137 if( $doNumberHeadings ||
$enoughToc ) {
3139 if ( $level > $prevlevel ) {
3140 # Increase TOC level
3142 $sublevelCount[$toclevel] = 0;
3143 if( $toclevel<$wgMaxTocLevel ) {
3144 $toc .= $sk->tocIndent();
3147 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3148 # Decrease TOC level, find level to jump to
3150 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3151 # Can only go down to level 1
3154 for ($i = $toclevel; $i > 0; $i--) {
3155 if ( $levelCount[$i] == $level ) {
3156 # Found last matching level
3160 elseif ( $levelCount[$i] < $level ) {
3161 # Found first matching level below current level
3167 if( $toclevel<$wgMaxTocLevel ) {
3168 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3172 # No change in level, end TOC line
3173 if( $toclevel<$wgMaxTocLevel ) {
3174 $toc .= $sk->tocLineEnd();
3178 $levelCount[$toclevel] = $level;
3180 # count number of headlines for each level
3181 @$sublevelCount[$toclevel]++
;
3183 for( $i = 1; $i <= $toclevel; $i++
) {
3184 if( !empty( $sublevelCount[$i] ) ) {
3188 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3194 # The canonized header is a version of the header text safe to use for links
3195 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3196 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3197 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3199 # Remove link placeholders by the link text.
3200 # <!--LINK number-->
3202 # link text with suffix
3203 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3204 "\$this->mLinkHolders['texts'][\$1]",
3205 $canonized_headline );
3206 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3207 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3208 $canonized_headline );
3211 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3212 $tocline = trim( $canonized_headline );
3213 # Save headline for section edit hint before it's escaped
3214 $headline_hint = trim( $canonized_headline );
3215 $canonized_headline = Sanitizer
::escapeId( $tocline );
3216 $refers[$headlineCount] = $canonized_headline;
3218 # count how many in assoc. array so we can track dupes in anchors
3219 @$refers[$canonized_headline]++
;
3220 $refcount[$headlineCount]=$refers[$canonized_headline];
3222 # Don't number the heading if it is the only one (looks silly)
3223 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3224 # the two are different if the line contains a link
3225 $headline=$numbering . ' ' . $headline;
3228 # Create the anchor for linking from the TOC to the section
3229 $anchor = $canonized_headline;
3230 if($refcount[$headlineCount] > 1 ) {
3231 $anchor .= '_' . $refcount[$headlineCount];
3233 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3234 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3236 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3237 if ( empty( $head[$headlineCount] ) ) {
3238 $head[$headlineCount] = '';
3241 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3243 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3246 # give headline the correct <h#> tag
3247 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3255 if( $toclevel<$wgMaxTocLevel ) {
3256 $toc .= $sk->tocUnindent( $toclevel - 1 );
3258 $toc = $sk->tocList( $toc );
3261 # split up and insert constructed headlines
3263 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3266 foreach( $blocks as $block ) {
3267 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3268 # This is the [edit] link that appears for the top block of text when
3269 # section editing is enabled
3271 # Disabled because it broke block formatting
3272 # For example, a bullet point in the top line
3273 # $full .= $sk->editSectionLink(0);
3276 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3277 # Top anchor now in skin
3281 if( !empty( $head[$i] ) ) {
3286 if( $this->mForceTocPosition
) {
3287 return str_replace( '<!--MWTOC-->', $toc, $full );
3294 * Return an HTML link for the "ISBN 123456" text
3297 function magicISBN( $text ) {
3298 $fname = 'Parser::magicISBN';
3299 wfProfileIn( $fname );
3301 $a = split( 'ISBN ', ' '.$text );
3302 if ( count ( $a ) < 2 ) {
3303 wfProfileOut( $fname );
3306 $text = substr( array_shift( $a ), 1);
3307 $valid = '0123456789-Xx';
3309 foreach ( $a as $x ) {
3310 # hack: don't replace inside thumbnail title/alt
3312 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3317 $isbn = $blank = '' ;
3318 while ( ' ' == $x{0} ) {
3320 $x = substr( $x, 1 );
3322 if ( $x == '' ) { # blank isbn
3323 $text .= "ISBN $blank";
3326 while ( strstr( $valid, $x{0} ) != false ) {
3328 $x = substr( $x, 1 );
3330 $num = str_replace( '-', '', $isbn );
3331 $num = str_replace( ' ', '', $num );
3332 $num = str_replace( 'x', 'X', $num );
3335 $text .= "ISBN $blank$x";
3337 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3338 $text .= '<a href="' .
3339 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3340 "\" class=\"internal\">ISBN $isbn</a>";
3344 wfProfileOut( $fname );
3349 * Return an HTML link for the "RFC 1234" text
3352 * @param string $text Text to be processed
3353 * @param string $keyword Magic keyword to use (default RFC)
3354 * @param string $urlmsg Interface message to use (default rfcurl)
3357 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3359 $valid = '0123456789';
3362 $a = split( $keyword, ' '.$text );
3363 if ( count ( $a ) < 2 ) {
3366 $text = substr( array_shift( $a ), 1);
3368 /* Check if keyword is preceed by [[.
3369 * This test is made here cause of the array_shift above
3370 * that prevent the test to be done in the foreach.
3372 if ( substr( $text, -2 ) == '[[' ) {
3376 foreach ( $a as $x ) {
3377 /* token might be empty if we have RFC RFC 1234 */
3383 # hack: don't replace inside thumbnail title/alt
3385 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3386 $text .= $keyword . $x;
3392 /** remove and save whitespaces in $blank */
3393 while ( $x{0} == ' ' ) {
3395 $x = substr( $x, 1 );
3398 /** remove and save the rfc number in $id */
3399 while ( strstr( $valid, $x{0} ) != false ) {
3401 $x = substr( $x, 1 );
3405 /* call back stripped spaces*/
3406 $text .= $keyword.$blank.$x;
3407 } elseif( $internal ) {
3409 $text .= $keyword.$id.$x;
3411 /* build the external link*/
3412 $url = wfMsg( $urlmsg, $id);
3413 $sk =& $this->mOptions
->getSkin();
3414 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3415 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3418 /* Check if the next RFC keyword is preceed by [[ */
3419 $internal = ( substr($x,-2) == '[[' );
3425 * Transform wiki markup when saving a page by doing \r\n -> \n
3426 * conversion, substitting signatures, {{subst:}} templates, etc.
3428 * @param string $text the text to transform
3429 * @param Title &$title the Title object for the current article
3430 * @param User &$user the User object describing the current user
3431 * @param ParserOptions $options parsing options
3432 * @param bool $clearState whether to clear the parser state first
3433 * @return string the altered wiki markup
3436 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3437 $this->mOptions
= $options;
3438 $this->mTitle
=& $title;
3439 $this->mOutputType
= OT_WIKI
;
3441 if ( $clearState ) {
3442 $this->clearState();
3445 $stripState = false;
3449 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3450 $text = $this->strip( $text, $stripState, true );
3451 $text = $this->pstPass2( $text, $stripState, $user );
3452 $text = $this->unstrip( $text, $stripState );
3453 $text = $this->unstripNoWiki( $text, $stripState );
3458 * Pre-save transform helper function
3461 function pstPass2( $text, &$stripState, &$user ) {
3462 global $wgContLang, $wgLocaltimezone;
3464 /* Note: This is the timestamp saved as hardcoded wikitext to
3465 * the database, we use $wgContLang here in order to give
3466 * everyone the same signature and use the default one rather
3467 * than the one selected in each user's preferences.
3469 if ( isset( $wgLocaltimezone ) ) {
3470 $oldtz = getenv( 'TZ' );
3471 putenv( 'TZ='.$wgLocaltimezone );
3473 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3474 ' (' . date( 'T' ) . ')';
3475 if ( isset( $wgLocaltimezone ) ) {
3476 putenv( 'TZ='.$oldtz );
3479 # Variable replacement
3480 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3481 $text = $this->replaceVariables( $text );
3483 # Strip out <nowiki> etc. added via replaceVariables
3484 $text = $this->strip( $text, $stripState );
3487 $sigText = $this->getUserSig( $user );
3488 $text = strtr( $text, array(
3490 '~~~~' => "$sigText $d",
3494 # Context links: [[|name]] and [[name (context)|]]
3496 global $wgLegalTitleChars;
3497 $tc = "[$wgLegalTitleChars]";
3498 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3500 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3501 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3503 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3504 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3505 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3506 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3508 $t = $this->mTitle
->getText();
3509 if ( preg_match( $conpat, $t, $m ) ) {
3512 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3513 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3514 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3516 if ( '' == $context ) {
3517 $text = preg_replace( $p2, '[[\\1]]', $text );
3519 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3522 # Trim trailing whitespace
3523 # MAG_END (__END__) tag allows for trailing
3524 # whitespace to be deliberately included
3525 $text = rtrim( $text );
3526 $mw =& MagicWord
::get( MAG_END
);
3527 $mw->matchAndRemove( $text );
3533 * Fetch the user's signature text, if any, and normalize to
3534 * validated, ready-to-insert wikitext.
3540 function getUserSig( &$user ) {
3541 $username = $user->getName();
3542 $nickname = $user->getOption( 'nickname' );
3543 $nickname = $nickname === '' ?
$username : $nickname;
3545 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3546 # Sig. might contain markup; validate this
3547 if( $this->validateSig( $nickname ) !== false ) {
3548 # Validated; clean up (if needed) and return it
3549 return $this->cleanSig( $nickname, true );
3551 # Failed to validate; fall back to the default
3552 $nickname = $username;
3553 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3557 # If we're still here, make it a link to the user page
3558 $userpage = $user->getUserPage();
3559 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3563 * Check that the user's signature contains no bad XML
3565 * @param string $text
3566 * @return mixed An expanded string, or false if invalid.
3568 function validateSig( $text ) {
3569 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3573 * Clean up signature text
3575 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3576 * 2) Substitute all transclusions
3578 * @param string $text
3579 * @param $parsing Whether we're cleaning (preferences save) or parsing
3580 * @return string Signature text
3582 function cleanSig( $text, $parsing = false ) {
3584 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3586 $substWord = MagicWord
::get( MAG_SUBST
);
3587 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3588 $substText = '{{' . $substWord->getSynonym( 0 );
3590 $text = preg_replace( $substRegex, $substText, $text );
3591 $text = preg_replace( '/~{3,5}/', '', $text );
3592 $text = $this->replaceVariables( $text );
3594 $this->clearState();
3599 * Set up some variables which are usually set up in parse()
3600 * so that an external function can call some class members with confidence
3603 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3604 $this->mTitle
=& $title;
3605 $this->mOptions
= $options;
3606 $this->mOutputType
= $outputType;
3607 if ( $clearState ) {
3608 $this->clearState();
3613 * Transform a MediaWiki message by replacing magic variables.
3615 * @param string $text the text to transform
3616 * @param ParserOptions $options options
3617 * @return string the text with variables substituted
3620 function transformMsg( $text, $options ) {
3622 static $executing = false;
3624 $fname = "Parser::transformMsg";
3626 # Guard against infinite recursion
3632 wfProfileIn($fname);
3634 $this->mTitle
= $wgTitle;
3635 $this->mOptions
= $options;
3636 $this->mOutputType
= OT_MSG
;
3637 $this->clearState();
3638 $text = $this->replaceVariables( $text );
3641 wfProfileOut($fname);
3646 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3647 * The callback should have the following form:
3648 * function myParserHook( $text, $params, &$parser ) { ... }
3650 * Transform and return $text. Use $parser for any required context, e.g. use
3651 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3655 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3656 * @param mixed $callback The callback function (and object) to use for the tag
3658 * @return The old value of the mTagHooks array associated with the hook
3660 function setHook( $tag, $callback ) {
3661 $tag = strtolower( $tag );
3662 $oldVal = @$this->mTagHooks
[$tag];
3663 $this->mTagHooks
[$tag] = $callback;
3669 * Create a function, e.g. {{sum:1|2|3}}
3670 * The callback function should have the form:
3671 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3673 * The callback may either return the text result of the function, or an array with the text
3674 * in element 0, and a number of flags in the other elements. The names of the flags are
3675 * specified in the keys. Valid flags are:
3676 * found The text returned is valid, stop processing the template. This
3678 * nowiki Wiki markup in the return value should be escaped
3679 * noparse Unsafe HTML tags should not be stripped, etc.
3680 * noargs Don't replace triple-brace arguments in the return value
3681 * isHTML The returned text is HTML, armour it against wikitext transformation
3685 * @param string $name The function name. Function names are case-insensitive.
3686 * @param mixed $callback The callback function (and object) to use
3688 * @return The old callback function for this name, if any
3690 function setFunctionHook( $name, $callback ) {
3691 $name = strtolower( $name );
3692 $oldVal = @$this->mFunctionHooks
[$name];
3693 $this->mFunctionHooks
[$name] = $callback;
3698 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3699 * Placeholders created in Skin::makeLinkObj()
3700 * Returns an array of links found, indexed by PDBK:
3704 * $options is a bit field, RLH_FOR_UPDATE to select for update
3706 function replaceLinkHolders( &$text, $options = 0 ) {
3708 global $wgOutputReplace;
3710 $fname = 'Parser::replaceLinkHolders';
3711 wfProfileIn( $fname );
3715 $sk =& $this->mOptions
->getSkin();
3716 $linkCache =& LinkCache
::singleton();
3718 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3719 wfProfileIn( $fname.'-check' );
3720 $dbr =& wfGetDB( DB_SLAVE
);
3721 $page = $dbr->tableName( 'page' );
3722 $threshold = $wgUser->getOption('stubthreshold');
3725 asort( $this->mLinkHolders
['namespaces'] );
3729 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3731 $title = $this->mLinkHolders
['titles'][$key];
3733 # Skip invalid entries.
3734 # Result will be ugly, but prevents crash.
3735 if ( is_null( $title ) ) {
3738 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3740 # Check if it's a static known link, e.g. interwiki
3741 if ( $title->isAlwaysKnown() ) {
3742 $colours[$pdbk] = 1;
3743 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3744 $colours[$pdbk] = 1;
3745 $this->mOutput
->addLink( $title, $id );
3746 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3747 $colours[$pdbk] = 0;
3749 # Not in the link cache, add it to the query
3750 if ( !isset( $current ) ) {
3752 $query = "SELECT page_id, page_namespace, page_title";
3753 if ( $threshold > 0 ) {
3754 $query .= ', page_len, page_is_redirect';
3756 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3757 } elseif ( $current != $ns ) {
3759 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3764 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3769 if ( $options & RLH_FOR_UPDATE
) {
3770 $query .= ' FOR UPDATE';
3773 $res = $dbr->query( $query, $fname );
3775 # Fetch data and form into an associative array
3776 # non-existent = broken
3779 while ( $s = $dbr->fetchObject($res) ) {
3780 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3781 $pdbk = $title->getPrefixedDBkey();
3782 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3783 $this->mOutput
->addLink( $title, $s->page_id
);
3785 if ( $threshold > 0 ) {
3786 $size = $s->page_len
;
3787 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3788 $colours[$pdbk] = 1;
3790 $colours[$pdbk] = 2;
3793 $colours[$pdbk] = 1;
3797 wfProfileOut( $fname.'-check' );
3799 # Construct search and replace arrays
3800 wfProfileIn( $fname.'-construct' );
3801 $wgOutputReplace = array();
3802 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3803 $pdbk = $pdbks[$key];
3804 $searchkey = "<!--LINK $key-->";
3805 $title = $this->mLinkHolders
['titles'][$key];
3806 if ( empty( $colours[$pdbk] ) ) {
3807 $linkCache->addBadLinkObj( $title );
3808 $colours[$pdbk] = 0;
3809 $this->mOutput
->addLink( $title, 0 );
3810 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3811 $this->mLinkHolders
['texts'][$key],
3812 $this->mLinkHolders
['queries'][$key] );
3813 } elseif ( $colours[$pdbk] == 1 ) {
3814 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3815 $this->mLinkHolders
['texts'][$key],
3816 $this->mLinkHolders
['queries'][$key] );
3817 } elseif ( $colours[$pdbk] == 2 ) {
3818 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3819 $this->mLinkHolders
['texts'][$key],
3820 $this->mLinkHolders
['queries'][$key] );
3823 wfProfileOut( $fname.'-construct' );
3826 wfProfileIn( $fname.'-replace' );
3828 $text = preg_replace_callback(
3829 '/(<!--LINK .*?-->)/',
3830 "wfOutputReplaceMatches",
3833 wfProfileOut( $fname.'-replace' );
3836 # Now process interwiki link holders
3837 # This is quite a bit simpler than internal links
3838 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3839 wfProfileIn( $fname.'-interwiki' );
3840 # Make interwiki link HTML
3841 $wgOutputReplace = array();
3842 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3843 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3844 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3847 $text = preg_replace_callback(
3848 '/<!--IWLINK (.*?)-->/',
3849 "wfOutputReplaceMatches",
3851 wfProfileOut( $fname.'-interwiki' );
3854 wfProfileOut( $fname );
3859 * Replace <!--LINK--> link placeholders with plain text of links
3860 * (not HTML-formatted).
3861 * @param string $text
3864 function replaceLinkHoldersText( $text ) {
3865 $fname = 'Parser::replaceLinkHoldersText';
3866 wfProfileIn( $fname );
3868 $text = preg_replace_callback(
3869 '/<!--(LINK|IWLINK) (.*?)-->/',
3870 array( &$this, 'replaceLinkHoldersTextCallback' ),
3873 wfProfileOut( $fname );
3878 * @param array $matches
3882 function replaceLinkHoldersTextCallback( $matches ) {
3883 $type = $matches[1];
3885 if( $type == 'LINK' ) {
3886 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3887 return $this->mLinkHolders
['texts'][$key];
3889 } elseif( $type == 'IWLINK' ) {
3890 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3891 return $this->mInterwikiLinkHolders
['texts'][$key];
3898 * Renders an image gallery from a text with one line per image.
3899 * text labels may be given by using |-style alternative text. E.g.
3900 * Image:one.jpg|The number "1"
3901 * Image:tree.jpg|A tree
3902 * given as text will return the HTML of a gallery with two images,
3903 * labeled 'The number "1"' and
3906 function renderImageGallery( $text ) {
3908 $parserOptions = new ParserOptions
;
3909 $localParser = new Parser();
3911 $ig = new ImageGallery();
3912 $ig->setShowBytes( false );
3913 $ig->setShowFilename( false );
3915 $lines = explode( "\n", $text );
3917 foreach ( $lines as $line ) {
3918 # match lines like these:
3919 # Image:someimage.jpg|This is some image
3920 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3922 if ( count( $matches ) == 0 ) {
3925 $nt =& Title
::newFromText( $matches[1] );
3926 if( is_null( $nt ) ) {
3927 # Bogus title. Ignore these so we don't bomb out later.
3930 if ( isset( $matches[3] ) ) {
3931 $label = $matches[3];
3936 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3937 $html = $pout->getText();
3939 $ig->add( new Image( $nt ), $html );
3941 # Only add real images (bug #5586)
3942 if ( $nt->getNamespace() == NS_IMAGE
) {
3943 $this->mOutput
->addImage( $nt->getDBkey() );
3946 # Register links with the parent parser
3947 foreach( $pout->getLinks() as $ns => $keys ) {
3948 foreach( $keys as $dbk => $id )
3949 $this->mOutput
->addLink( Title
::makeTitle( $ns, $dbk ), $id );
3953 return $ig->toHTML();
3957 * Parse image options text and use it to make an image
3959 function makeImage( &$nt, $options ) {
3960 global $wgUseImageResize;
3964 # Check if the options text is of the form "options|alt text"
3966 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3967 # * left no resizing, just left align. label is used for alt= only
3968 # * right same, but right aligned
3969 # * none same, but not aligned
3970 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3971 # * center center the image
3972 # * framed Keep original image size, no magnify-button.
3974 $part = explode( '|', $options);
3976 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3977 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3978 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3979 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3980 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3981 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3982 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3983 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3986 $width = $height = $framed = $thumb = false;
3987 $manual_thumb = '' ;
3989 foreach( $part as $key => $val ) {
3990 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3992 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3993 # use manually specified thumbnail
3995 $manual_thumb = $match;
3996 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3997 # remember to set an alignment, don't render immediately
3999 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4000 # remember to set an alignment, don't render immediately
4002 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4003 # remember to set an alignment, don't render immediately
4005 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4006 # remember to set an alignment, don't render immediately
4008 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4009 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4010 # $match is the image width in pixels
4011 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4012 $width = intval( $m[1] );
4013 $height = intval( $m[2] );
4015 $width = intval($match);
4017 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4023 # Strip bad stuff out of the alt text
4024 $alt = $this->replaceLinkHoldersText( $caption );
4026 # make sure there are no placeholders in thumbnail attributes
4027 # that are later expanded to html- so expand them now and
4029 $alt = $this->unstrip($alt, $this->mStripState
);
4030 $alt = Sanitizer
::stripAllTags( $alt );
4032 # Linker does the rest
4033 $sk =& $this->mOptions
->getSkin();
4034 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4038 * Set a flag in the output object indicating that the content is dynamic and
4039 * shouldn't be cached.
4041 function disableCache() {
4042 wfDebug( "Parser output marked as uncacheable.\n" );
4043 $this->mOutput
->mCacheTime
= -1;
4047 * Callback from the Sanitizer for expanding items found in HTML attribute
4048 * values, so they can be safely tested and escaped.
4049 * @param string $text
4050 * @param array $args
4054 function attributeStripCallback( &$text, $args ) {
4055 $text = $this->replaceVariables( $text, $args );
4056 $text = $this->unstripForHTML( $text );
4060 function unstripForHTML( $text ) {
4061 $text = $this->unstrip( $text, $this->mStripState
);
4062 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4070 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4071 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4072 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4078 function getTags() { return array_keys( $this->mTagHooks
); }
4084 * @package MediaWiki
4088 var $mText, # The output text
4089 $mLanguageLinks, # List of the full text of language links, in the order they appear
4090 $mCategories, # Map of category names to sort keys
4091 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4092 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4093 $mVersion, # Compatibility check
4094 $mTitleText, # title text of the chosen language variant
4095 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4096 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4097 $mImages, # DB keys of the images used, in the array key only
4098 $mExternalLinks, # External link URLs, in the key only
4099 $mHTMLtitle, # Display HTML title
4100 $mSubtitle, # Additional subtitle
4101 $mNewSection; # Show a new section link?
4103 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4104 $containsOldMagic = false, $titletext = '' )
4106 $this->mText
= $text;
4107 $this->mLanguageLinks
= $languageLinks;
4108 $this->mCategories
= $categoryLinks;
4109 $this->mContainsOldMagic
= $containsOldMagic;
4110 $this->mCacheTime
= '';
4111 $this->mVersion
= MW_PARSER_VERSION
;
4112 $this->mTitleText
= $titletext;
4113 $this->mLinks
= array();
4114 $this->mTemplates
= array();
4115 $this->mImages
= array();
4116 $this->mExternalLinks
= array();
4117 $this->mHTMLtitle
= "" ;
4118 $this->mSubtitle
= "" ;
4119 $this->mNewSection
= false;
4122 function getText() { return $this->mText
; }
4123 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4124 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4125 function &getCategories() { return $this->mCategories
; }
4126 function getCacheTime() { return $this->mCacheTime
; }
4127 function getTitleText() { return $this->mTitleText
; }
4128 function &getLinks() { return $this->mLinks
; }
4129 function &getTemplates() { return $this->mTemplates
; }
4130 function &getImages() { return $this->mImages
; }
4131 function &getExternalLinks() { return $this->mExternalLinks
; }
4133 function containsOldMagic() { return $this->mContainsOldMagic
; }
4134 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4135 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4136 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4137 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4138 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4139 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4141 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4142 function addImage( $name ) { $this->mImages
[$name] = 1; }
4143 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4144 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4146 function setNewSection( $value ) {
4147 $this->mNewSection
= (bool)$value;
4149 function getNewSection() {
4150 return (bool)$this->mNewSection
;
4153 function addLink( $title, $id ) {
4154 $ns = $title->getNamespace();
4155 $dbk = $title->getDBkey();
4156 if ( !isset( $this->mLinks
[$ns] ) ) {
4157 $this->mLinks
[$ns] = array();
4159 $this->mLinks
[$ns][$dbk] = $id;
4162 function addTemplate( $title, $id ) {
4163 $ns = $title->getNamespace();
4164 $dbk = $title->getDBkey();
4165 if ( !isset( $this->mTemplates
[$ns] ) ) {
4166 $this->mTemplates
[$ns] = array();
4168 $this->mTemplates
[$ns][$dbk] = $id;
4172 * Return true if this cached output object predates the global or
4173 * per-article cache invalidation timestamps, or if it comes from
4174 * an incompatible older version.
4176 * @param string $touched the affected article's last touched timestamp
4180 function expired( $touched ) {
4181 global $wgCacheEpoch;
4182 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4183 $this->getCacheTime() < $touched ||
4184 $this->getCacheTime() <= $wgCacheEpoch ||
4185 !isset( $this->mVersion
) ||
4186 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4191 * Set options of the Parser
4193 * @package MediaWiki
4197 # All variables are private
4198 var $mUseTeX; # Use texvc to expand <math> tags
4199 var $mUseDynamicDates; # Use DateFormatter to format dates
4200 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4201 var $mAllowExternalImages; # Allow external images inline
4202 var $mAllowExternalImagesFrom; # If not, any exception?
4203 var $mSkin; # Reference to the preferred skin
4204 var $mDateFormat; # Date format index
4205 var $mEditSection; # Create "edit section" links
4206 var $mNumberHeadings; # Automatically number headings
4207 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4208 var $mTidy; # Ask for tidy cleanup
4209 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4211 function getUseTeX() { return $this->mUseTeX
; }
4212 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4213 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4214 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4215 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4216 function &getSkin() { return $this->mSkin
; }
4217 function getDateFormat() { return $this->mDateFormat
; }
4218 function getEditSection() { return $this->mEditSection
; }
4219 function getNumberHeadings() { return $this->mNumberHeadings
; }
4220 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4221 function getTidy() { return $this->mTidy
; }
4222 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4224 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4225 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4226 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4227 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4228 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4229 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4230 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4231 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4232 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4233 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4234 function setSkin( &$x ) { $this->mSkin
=& $x; }
4235 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4237 function ParserOptions() {
4239 $this->initialiseFromUser( $wgUser );
4243 * Get parser options
4246 function newFromUser( &$user ) {
4247 $popts = new ParserOptions
;
4248 $popts->initialiseFromUser( $user );
4252 /** Get user options */
4253 function initialiseFromUser( &$userInput ) {
4254 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4255 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4256 $fname = 'ParserOptions::initialiseFromUser';
4257 wfProfileIn( $fname );
4258 if ( !$userInput ) {
4260 $user->setLoaded( true );
4262 $user =& $userInput;
4265 $this->mUseTeX
= $wgUseTeX;
4266 $this->mUseDynamicDates
= $wgUseDynamicDates;
4267 $this->mInterwikiMagic
= $wgInterwikiMagic;
4268 $this->mAllowExternalImages
= $wgAllowExternalImages;
4269 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4270 wfProfileIn( $fname.'-skin' );
4271 $this->mSkin
=& $user->getSkin();
4272 wfProfileOut( $fname.'-skin' );
4273 $this->mDateFormat
= $user->getOption( 'date' );
4274 $this->mEditSection
= true;
4275 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4276 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4277 $this->mTidy
= false;
4278 $this->mInterfaceMessage
= false;
4279 wfProfileOut( $fname );
4284 * Callback function used by Parser::replaceLinkHolders()
4285 * to substitute link placeholders.
4287 function &wfOutputReplaceMatches( $matches ) {
4288 global $wgOutputReplace;
4289 return $wgOutputReplace[$matches[1]];
4293 * Return the total number of articles
4295 function wfNumberOfArticles() {
4296 global $wgNumberOfArticles;
4299 return $wgNumberOfArticles;
4303 * Return the number of files
4305 function wfNumberOfFiles() {
4306 $fname = 'wfNumberOfFiles';
4308 wfProfileIn( $fname );
4309 $dbr =& wfGetDB( DB_SLAVE
);
4310 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4311 wfProfileOut( $fname );
4317 * Return the number of user accounts
4320 function wfNumberOfUsers() {
4321 wfProfileIn( 'wfNumberOfUsers' );
4322 $dbr =& wfGetDB( DB_SLAVE
);
4323 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4324 wfProfileOut( 'wfNumberOfUsers' );
4329 * Return the total number of pages
4332 function wfNumberOfPages() {
4333 wfProfileIn( 'wfNumberOfPages' );
4334 $dbr =& wfGetDB( DB_SLAVE
);
4335 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4336 wfProfileOut( 'wfNumberOfPages' );
4341 * Get various statistics from the database
4344 function wfLoadSiteStats() {
4345 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4346 $fname = 'wfLoadSiteStats';
4348 if ( -1 != $wgNumberOfArticles ) return;
4349 $dbr =& wfGetDB( DB_SLAVE
);
4350 $s = $dbr->selectRow( 'site_stats',
4351 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4352 array( 'ss_row_id' => 1 ), $fname
4355 if ( $s === false ) {
4358 $wgTotalViews = $s->ss_total_views
;
4359 $wgTotalEdits = $s->ss_total_edits
;
4360 $wgNumberOfArticles = $s->ss_good_articles
;
4366 * Basically replacing " > and < with HTML entities ( ", >, <)
4368 * @param $in String: text that might contain HTML tags.
4369 * @return string Escaped string
4371 function wfEscapeHTMLTagsOnly( $in ) {
4373 array( '"', '>', '<' ),
4374 array( '"', '>', '<' ),