3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
17 * Variable substitution O(N^2) attack
19 * Without countermeasures, it would be possible to attack the parser by saving
20 * a page filled with a large number of inclusions of large pages. The size of
21 * the generated page would be proportional to the square of the input size.
22 * Hence, we limit the number of inclusions of any given page, thus bringing any
23 * attack back to O(N).
26 define( 'MAX_INCLUDE_REPEAT', 100 );
27 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
29 define( 'RLH_FOR_UPDATE', 1 );
31 # Allowed values for $mOutputType
32 define( 'OT_HTML', 1 );
33 define( 'OT_WIKI', 2 );
34 define( 'OT_MSG' , 3 );
36 # string parameter for extractTags which will cause it
37 # to strip HTML comments in addition to regular
38 # <XML>-style tags. This should not be anything we
39 # may want to use in wikisyntax
40 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
42 # Constants needed for external link processing
43 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
44 # Everything except bracket, space, or control characters
45 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
47 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
48 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
49 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
50 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
51 define( 'EXT_IMAGE_REGEX',
52 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
53 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
54 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
60 * Processes wiki markup
63 * There are three main entry points into the Parser class:
65 * produces HTML output
67 * produces altered wiki markup.
69 * performs brace substitution on MediaWiki messages
72 * objects: $wgLang, $wgContLang
74 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
77 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
78 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
79 * $wgLocaltimezone, $wgAllowSpecialInclusion*
81 * * only within ParserOptions
92 var $mTagHooks, $mFunctionHooks;
94 # Cleared with clearState():
95 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
96 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
97 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
98 var $mTemplates, // cache of already loaded templates, avoids
99 // multiple SQL queries for the same string
100 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
101 // in this path. Used for loop detection.
104 # These are variables reset at least once per parse regardless of $clearState
105 var $mOptions, // ParserOptions object
106 $mTitle, // Title context, used for self-link rendering and similar things
107 $mOutputType, // Output type, one of the OT_xxx constants
108 $mRevisionId; // ID to display in {{REVISIONID}} tags
118 $this->mTagHooks
= array();
119 $this->mFunctionHooks
= array();
128 function clearState() {
129 $this->mOutput
= new ParserOutput
;
130 $this->mAutonumber
= 0;
131 $this->mLastSection
= '';
132 $this->mDTopen
= false;
133 $this->mVariables
= false;
134 $this->mIncludeCount
= array();
135 $this->mStripState
= array();
136 $this->mArgStack
= array();
137 $this->mInPre
= false;
138 $this->mInterwikiLinkHolders
= array(
142 $this->mLinkHolders
= array(
143 'namespaces' => array(),
145 'queries' => array(),
149 $this->mRevisionId
= null;
152 * Prefix for temporary replacement strings for the multipass parser.
153 * \x07 should never appear in input as it's disallowed in XML.
154 * Using it at the front also gives us a little extra robustness
155 * since it shouldn't match when butted up against identifier-like
158 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
160 # Clear these on every parse, bug 4549
161 $this->mTemplates
= array();
162 $this->mTemplatePath
= array();
164 $this->mShowToc
= true;
165 $this->mForceTocPosition
= false;
167 wfRunHooks( 'ParserClearState', array( &$this ) );
171 * Accessor for mUniqPrefix.
175 function UniqPrefix() {
176 return $this->mUniqPrefix
;
180 * Convert wikitext to HTML
181 * Do not call this function recursively.
184 * @param string $text Text we want to parse
185 * @param Title &$title A title object
186 * @param array $options
187 * @param boolean $linestart
188 * @param boolean $clearState
189 * @param int $revid number to pass in {{REVISIONID}}
190 * @return ParserOutput a ParserOutput
192 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
194 * First pass--just handle <nowiki> sections, pass the rest off
195 * to internalParse() which does all the real work.
198 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
199 $fname = 'Parser::parse';
200 wfProfileIn( $fname );
206 $this->mOptions
= $options;
207 $this->mTitle
=& $title;
208 $this->mRevisionId
= $revid;
209 $this->mOutputType
= OT_HTML
;
211 //$text = $this->strip( $text, $this->mStripState );
212 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
213 $x =& $this->mStripState
;
215 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
216 $text = $this->strip( $text, $x );
217 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
219 # Hook to suspend the parser in this state
220 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
221 wfProfileOut( $fname );
225 $text = $this->internalParse( $text );
227 $text = $this->unstrip( $text, $this->mStripState
);
229 # Clean up special characters, only run once, next-to-last before doBlockLevels
231 # french spaces, last one Guillemet-left
232 # only if there is something before the space
233 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
234 # french spaces, Guillemet-right
235 '/(\\302\\253) /' => '\\1 ',
236 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
238 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
241 $text = $this->doBlockLevels( $text, $linestart );
243 $this->replaceLinkHolders( $text );
245 # the position of the parserConvert() call should not be changed. it
246 # assumes that the links are all replaced and the only thing left
247 # is the <nowiki> mark.
248 # Side-effects: this calls $this->mOutput->setTitleText()
249 $text = $wgContLang->parserConvert( $text, $this );
251 $text = $this->unstripNoWiki( $text, $this->mStripState
);
253 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
255 $text = Sanitizer
::normalizeCharReferences( $text );
257 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
258 $text = Parser
::tidy($text);
260 # attempt to sanitize at least some nesting problems
261 # (bug #2702 and quite a few others)
263 # ''Something [http://www.cool.com cool''] -->
264 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
265 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
266 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
267 # fix up an anchor inside another anchor, only
268 # at least for a single single nested link (bug 3695)
269 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
270 '\\1\\2</a>\\3</a>\\1\\4</a>',
271 # fix div inside inline elements- doBlockLevels won't wrap a line which
272 # contains a div, so fix it up here; replace
273 # div with escaped text
274 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
275 '\\1\\3<div\\5>\\6</div>\\8\\9',
276 # remove empty italic or bold tag pairs, some
277 # introduced by rules above
278 '/<([bi])><\/\\1>/' => ''
281 $text = preg_replace(
282 array_keys( $tidyregs ),
283 array_values( $tidyregs ),
287 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
289 $this->mOutput
->setText( $text );
290 wfProfileOut( $fname );
292 return $this->mOutput
;
296 * Get a random string
301 function getRandomString() {
302 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
305 function &getTitle() { return $this->mTitle
; }
306 function getOptions() { return $this->mOptions
; }
309 * Replaces all occurrences of <$tag>content</$tag> in the text
310 * with a random marker and returns the new text. the output parameter
311 * $content will be an associative array filled with data on the form
312 * $unique_marker => content.
314 * If $content is already set, the additional entries will be appended
315 * If $tag is set to STRIP_COMMENTS, the function will extract
316 * <!-- HTML comments -->
318 * $output: array( 'UNIQ-xxxxx' => array(
321 * array( 'param' => 'x' ),
322 * '<element param="x">' ) )
326 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
327 $rand = Parser
::getRandomString();
332 if( $elements == STRIP_COMMENTS
) {
333 $start = '/<!--()()/';
335 $taglist = implode( '|', $elements );
336 $start = "/<($taglist)(\\s+[^>]*|\\s*\/?)>/i";
339 while ( '' != $text ) {
340 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
342 if( count( $p ) < 4 ) {
349 // If $attributes ends with '/', we have an empty element tag, <tag />
350 if( $element != '' && substr( $attributes, -1 ) == '/' ) {
351 $attributes = substr( $attributes, 0, -1);
357 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
);
358 $stripped .= $marker;
360 if ( $empty === '/' ) {
361 // Empty element tag, <tag />
366 $end = "/<\\/$element\\s*>/i";
370 $q = preg_split( $end, $inside, 2 );
372 if( count( $q ) < 2 ) {
373 # No end tag -- let it run out to the end of the text.
380 $matches[$marker] = array( $element,
382 Sanitizer
::decodeTagAttributes( $attributes ),
383 "<$element$attributes$empty>" );
389 * Strips and renders nowiki, pre, math, hiero
390 * If $render is set, performs necessary rendering operations on plugins
391 * Returns the text, and fills an array with data needed in unstrip()
392 * If the $state is already a valid strip state, it adds to the state
394 * @param bool $stripcomments when set, HTML comments <!-- like this -->
395 * will be stripped in addition to other tags. This is important
396 * for section editing, where these comments cause confusion when
397 * counting the sections in the wikisource
401 function strip( $text, &$state, $stripcomments = false ) {
402 $render = ($this->mOutputType
== OT_HTML
);
404 # Replace any instances of the placeholders
405 $uniq_prefix = $this->mUniqPrefix
;
406 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
408 $elements = array_merge(
409 array( 'nowiki', 'pre', 'gallery' ),
410 array_keys( $this->mTagHooks
) );
413 $elements[] = 'html';
415 if( $this->mOptions
->getUseTeX() ) {
416 $elements[] = 'math';
420 // Strip comments in a first pass.
421 // This saves us from needlessly rendering extensions in comment text
422 $text = Parser
::extractTagsAndParams(STRIP_COMMENTS
, $text, $comment_matches, $uniq_prefix);
423 $commentState = array();
424 foreach( $comment_matches as $marker => $data ){
425 list( $element, $content, $params, $tag ) = $data;
426 $commentState[$marker] = '<!--' . $content . '-->';
430 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
432 foreach( $matches as $marker => $data ) {
433 list( $element, $content, $params, $tag ) = $data;
434 // Restore any comments; the extension can deal with them.
435 if( $content !== null) {
436 $content = strtr( $content, $commentState );
445 // Shouldn't happen otherwise. :)
447 $output = wfEscapeHTMLTagsOnly( $content );
450 $output = MathRenderer
::renderMath( $content );
453 // Backwards-compatibility hack
454 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $content );
455 $output = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
458 $output = $this->renderImageGallery( $content );
461 $tagName = strtolower( $element );
462 if( isset( $this->mTagHooks
[$tagName] ) ) {
463 $output = call_user_func_array( $this->mTagHooks
[$tagName],
464 array( $content, $params, $this ) );
466 wfDebugDieBacktrace( "Invalid call hook $element" );
470 // Just stripping tags; keep the source
471 if( $content === null ) {
474 $output = "$tag$content</$element>";
477 $state[$element][$marker] = $output;
480 # Unstrip comments unless explicitly told otherwise.
481 # (The comments are always stripped prior to this point, so as to
482 # not invoke any extension tags / parser hooks contained within
484 if ( $stripcomments ) {
485 // Add remaining comments to the state array
486 foreach( $commentState as $marker => $content ) {
487 $state['comment'][$marker] = $content;
490 // Put them all back and forget them
491 $text = strtr( $text, $commentState );
498 * Restores pre, math, and other extensions removed by strip()
500 * always call unstripNoWiki() after this one
503 function unstrip( $text, &$state ) {
504 if ( !is_array( $state ) ) {
508 $replacements = array();
509 foreach( $state as $tag => $contentDict ) {
510 if( $tag != 'nowiki' && $tag != 'html' ) {
511 foreach( $contentDict as $uniq => $content ) {
512 $replacements[$uniq] = $content;
516 $text = strtr( $text, $replacements );
522 * Always call this after unstrip() to preserve the order
526 function unstripNoWiki( $text, &$state ) {
527 if ( !is_array( $state ) ) {
531 $replacements = array();
532 foreach( $state as $tag => $contentDict ) {
533 if( $tag == 'nowiki' ||
$tag == 'html' ) {
534 foreach( $contentDict as $uniq => $content ) {
535 $replacements[$uniq] = $content;
539 $text = strtr( $text, $replacements );
545 * Add an item to the strip state
546 * Returns the unique tag which must be inserted into the stripped text
547 * The tag will be replaced with the original text in unstrip()
551 function insertStripItem( $text, &$state ) {
552 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
556 $state['item'][$rnd] = $text;
561 * Interface with html tidy, used if $wgUseTidy = true.
562 * If tidy isn't able to correct the markup, the original will be
563 * returned in all its glory with a warning comment appended.
565 * Either the external tidy program or the in-process tidy extension
566 * will be used depending on availability. Override the default
567 * $wgTidyInternal setting to disable the internal if it's not working.
569 * @param string $text Hideous HTML input
570 * @return string Corrected HTML output
574 function tidy( $text ) {
575 global $wgTidyInternal;
576 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
577 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
578 '<head><title>test</title></head><body>'.$text.'</body></html>';
579 if( $wgTidyInternal ) {
580 $correctedtext = Parser
::internalTidy( $wrappedtext );
582 $correctedtext = Parser
::externalTidy( $wrappedtext );
584 if( is_null( $correctedtext ) ) {
585 wfDebug( "Tidy error detected!\n" );
586 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
588 return $correctedtext;
592 * Spawn an external HTML tidy process and get corrected markup back from it.
597 function externalTidy( $text ) {
598 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
599 $fname = 'Parser::externalTidy';
600 wfProfileIn( $fname );
605 $descriptorspec = array(
606 0 => array('pipe', 'r'),
607 1 => array('pipe', 'w'),
608 2 => array('file', '/dev/null', 'a')
611 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
612 if (is_resource($process)) {
613 // Theoretically, this style of communication could cause a deadlock
614 // here. If the stdout buffer fills up, then writes to stdin could
615 // block. This doesn't appear to happen with tidy, because tidy only
616 // writes to stdout after it's finished reading from stdin. Search
617 // for tidyParseStdin and tidySaveStdout in console/tidy.c
618 fwrite($pipes[0], $text);
620 while (!feof($pipes[1])) {
621 $cleansource .= fgets($pipes[1], 1024);
624 proc_close($process);
627 wfProfileOut( $fname );
629 if( $cleansource == '' && $text != '') {
630 // Some kind of error happened, so we couldn't get the corrected text.
631 // Just give up; we'll use the source text and append a warning.
639 * Use the HTML tidy PECL extension to use the tidy library in-process,
640 * saving the overhead of spawning a new process. Currently written to
641 * the PHP 4.3.x version of the extension, may not work on PHP 5.
643 * 'pear install tidy' should be able to compile the extension module.
648 function internalTidy( $text ) {
650 $fname = 'Parser::internalTidy';
651 wfProfileIn( $fname );
653 tidy_load_config( $wgTidyConf );
654 tidy_set_encoding( 'utf8' );
655 tidy_parse_string( $text );
657 if( tidy_get_status() == 2 ) {
658 // 2 is magic number for fatal error
659 // http://www.php.net/manual/en/function.tidy-get-status.php
662 $cleansource = tidy_get_output();
664 wfProfileOut( $fname );
669 * parse the wiki syntax used to render tables
673 function doTableStuff ( $t ) {
674 $fname = 'Parser::doTableStuff';
675 wfProfileIn( $fname );
677 $t = explode ( "\n" , $t ) ;
678 $td = array () ; # Is currently a td tag open?
679 $ltd = array () ; # Was it TD or TH?
680 $tr = array () ; # Is currently a tr tag open?
681 $ltr = array () ; # tr attributes
682 $has_opened_tr = array(); # Did this table open a <tr> element?
683 $indent_level = 0; # indent level of the table
684 foreach ( $t AS $k => $x )
687 $fc = substr ( $x , 0 , 1 ) ;
688 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
689 $indent_level = strlen( $matches[1] );
691 $attributes = $this->unstripForHTML( $matches[2] );
693 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
694 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
695 array_push ( $td , false ) ;
696 array_push ( $ltd , '' ) ;
697 array_push ( $tr , false ) ;
698 array_push ( $ltr , '' ) ;
699 array_push ( $has_opened_tr, false );
701 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
702 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
703 $z = "</table>" . substr ( $x , 2);
704 $l = array_pop ( $ltd ) ;
705 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
706 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
707 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
709 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
711 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
712 $x = substr ( $x , 1 ) ;
713 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
715 $l = array_pop ( $ltd ) ;
716 array_pop ( $has_opened_tr );
717 array_push ( $has_opened_tr , true ) ;
718 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
719 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
722 array_push ( $tr , false ) ;
723 array_push ( $td , false ) ;
724 array_push ( $ltd , '' ) ;
725 $attributes = $this->unstripForHTML( $x );
726 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
728 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
730 if ( '|+' == substr ( $x , 0 , 2 ) ) {
732 $x = substr ( $x , 1 ) ;
734 $after = substr ( $x , 1 ) ;
735 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
737 // Split up multiple cells on the same line.
738 // FIXME: This can result in improper nesting of tags processed
739 // by earlier parser steps, but should avoid splitting up eg
740 // attribute values containing literal "||".
741 $after = wfExplodeMarkup( '||', $after );
745 # Loop through each table cell
746 foreach ( $after AS $theline )
751 $tra = array_pop ( $ltr ) ;
752 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
753 array_push ( $tr , true ) ;
754 array_push ( $ltr , '' ) ;
755 array_pop ( $has_opened_tr );
756 array_push ( $has_opened_tr , true ) ;
759 $l = array_pop ( $ltd ) ;
760 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
761 if ( $fc == '|' ) $l = 'td' ;
762 else if ( $fc == '!' ) $l = 'th' ;
763 else if ( $fc == '+' ) $l = 'caption' ;
765 array_push ( $ltd , $l ) ;
768 $y = explode ( '|' , $theline , 2 ) ;
769 # Note that a '|' inside an invalid link should not
770 # be mistaken as delimiting cell parameters
771 if ( strpos( $y[0], '[[' ) !== false ) {
772 $y = array ($theline);
774 if ( count ( $y ) == 1 )
775 $y = "{$z}<{$l}>{$y[0]}" ;
777 $attributes = $this->unstripForHTML( $y[0] );
778 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
781 array_push ( $td , true ) ;
786 # Closing open td, tr && table
787 while ( count ( $td ) > 0 )
789 $l = array_pop ( $ltd ) ;
790 if ( array_pop ( $td ) ) $t[] = '</td>' ;
791 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
792 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
796 $t = implode ( "\n" , $t ) ;
797 # special case: don't return empty table
798 if($t == "<table>\n<tr><td></td></tr>\n</table>")
800 wfProfileOut( $fname );
805 * Helper function for parse() that transforms wiki markup into
806 * HTML. Only called for $mOutputType == OT_HTML.
810 function internalParse( $text ) {
813 $fname = 'Parser::internalParse';
814 wfProfileIn( $fname );
816 # Remove <noinclude> tags and <includeonly> sections
817 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
818 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
819 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
821 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
823 $text = $this->replaceVariables( $text, $args );
825 // Tables need to come after variable replacement for things to work
826 // properly; putting them before other transformations should keep
827 // exciting things like link expansions from showing up in surprising
829 $text = $this->doTableStuff( $text );
831 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
833 $text = $this->stripToc( $text );
834 $text = $this->doHeadings( $text );
835 if($this->mOptions
->getUseDynamicDates()) {
836 $df =& DateFormatter
::getInstance();
837 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
839 $text = $this->doAllQuotes( $text );
840 $text = $this->replaceInternalLinks( $text );
841 $text = $this->replaceExternalLinks( $text );
843 # replaceInternalLinks may sometimes leave behind
844 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
845 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
847 $text = $this->doMagicLinks( $text );
848 $text = $this->formatHeadings( $text, $isMain );
850 wfProfileOut( $fname );
855 * Replace special strings like "ISBN xxx" and "RFC xxx" with
856 * magic external links.
860 function &doMagicLinks( &$text ) {
861 $text = $this->magicISBN( $text );
862 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
863 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
868 * Parse headers and return html
872 function doHeadings( $text ) {
873 $fname = 'Parser::doHeadings';
874 wfProfileIn( $fname );
875 for ( $i = 6; $i >= 1; --$i ) {
876 $h = str_repeat( '=', $i );
877 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
878 "<h{$i}>\\1</h{$i}>\\2", $text );
880 wfProfileOut( $fname );
885 * Replace single quotes with HTML markup
887 * @return string the altered text
889 function doAllQuotes( $text ) {
890 $fname = 'Parser::doAllQuotes';
891 wfProfileIn( $fname );
893 $lines = explode( "\n", $text );
894 foreach ( $lines as $line ) {
895 $outtext .= $this->doQuotes ( $line ) . "\n";
897 $outtext = substr($outtext, 0,-1);
898 wfProfileOut( $fname );
903 * Helper function for doAllQuotes()
906 function doQuotes( $text ) {
907 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
908 if ( count( $arr ) == 1 )
912 # First, do some preliminary work. This may shift some apostrophes from
913 # being mark-up to being text. It also counts the number of occurrences
914 # of bold and italics mark-ups.
918 foreach ( $arr as $r )
920 if ( ( $i %
2 ) == 1 )
922 # If there are ever four apostrophes, assume the first is supposed to
923 # be text, and the remaining three constitute mark-up for bold text.
924 if ( strlen( $arr[$i] ) == 4 )
929 # If there are more than 5 apostrophes in a row, assume they're all
930 # text except for the last 5.
931 else if ( strlen( $arr[$i] ) > 5 )
933 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
936 # Count the number of occurrences of bold and italics mark-ups.
937 # We are not counting sequences of five apostrophes.
938 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
939 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
940 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
945 # If there is an odd number of both bold and italics, it is likely
946 # that one of the bold ones was meant to be an apostrophe followed
947 # by italics. Which one we cannot know for certain, but it is more
948 # likely to be one that has a single-letter word before it.
949 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
952 $firstsingleletterword = -1;
953 $firstmultiletterword = -1;
955 foreach ( $arr as $r )
957 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
959 $x1 = substr ($arr[$i-1], -1);
960 $x2 = substr ($arr[$i-1], -2, 1);
962 if ($firstspace == -1) $firstspace = $i;
963 } else if ($x2 == ' ') {
964 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
966 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
972 # If there is a single-letter word, use it!
973 if ($firstsingleletterword > -1)
975 $arr [ $firstsingleletterword ] = "''";
976 $arr [ $firstsingleletterword-1 ] .= "'";
978 # If not, but there's a multi-letter word, use that one.
979 else if ($firstmultiletterword > -1)
981 $arr [ $firstmultiletterword ] = "''";
982 $arr [ $firstmultiletterword-1 ] .= "'";
984 # ... otherwise use the first one that has neither.
985 # (notice that it is possible for all three to be -1 if, for example,
986 # there is only one pentuple-apostrophe in the line)
987 else if ($firstspace > -1)
989 $arr [ $firstspace ] = "''";
990 $arr [ $firstspace-1 ] .= "'";
994 # Now let's actually convert our apostrophic mush to HTML!
1003 if ($state == 'both')
1010 if (strlen ($r) == 2)
1013 { $output .= '</i>'; $state = ''; }
1014 else if ($state == 'bi')
1015 { $output .= '</i>'; $state = 'b'; }
1016 else if ($state == 'ib')
1017 { $output .= '</b></i><b>'; $state = 'b'; }
1018 else if ($state == 'both')
1019 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1020 else # $state can be 'b' or ''
1021 { $output .= '<i>'; $state .= 'i'; }
1023 else if (strlen ($r) == 3)
1026 { $output .= '</b>'; $state = ''; }
1027 else if ($state == 'bi')
1028 { $output .= '</i></b><i>'; $state = 'i'; }
1029 else if ($state == 'ib')
1030 { $output .= '</b>'; $state = 'i'; }
1031 else if ($state == 'both')
1032 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1033 else # $state can be 'i' or ''
1034 { $output .= '<b>'; $state .= 'b'; }
1036 else if (strlen ($r) == 5)
1039 { $output .= '</b><i>'; $state = 'i'; }
1040 else if ($state == 'i')
1041 { $output .= '</i><b>'; $state = 'b'; }
1042 else if ($state == 'bi')
1043 { $output .= '</i></b>'; $state = ''; }
1044 else if ($state == 'ib')
1045 { $output .= '</b></i>'; $state = ''; }
1046 else if ($state == 'both')
1047 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1048 else # ($state == '')
1049 { $buffer = ''; $state = 'both'; }
1054 # Now close all remaining tags. Notice that the order is important.
1055 if ($state == 'b' ||
$state == 'ib')
1057 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1061 if ($state == 'both')
1062 $output .= '<b><i>'.$buffer.'</i></b>';
1068 * Replace external links
1070 * Note: this is all very hackish and the order of execution matters a lot.
1071 * Make sure to run maintenance/parserTests.php if you change this code.
1075 function replaceExternalLinks( $text ) {
1077 $fname = 'Parser::replaceExternalLinks';
1078 wfProfileIn( $fname );
1080 $sk =& $this->mOptions
->getSkin();
1082 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1084 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1087 while ( $i<count( $bits ) ) {
1089 $protocol = $bits[$i++
];
1090 $text = $bits[$i++
];
1091 $trail = $bits[$i++
];
1093 # The characters '<' and '>' (which were escaped by
1094 # removeHTMLtags()) should not be included in
1095 # URLs, per RFC 2396.
1096 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1097 $text = substr($url, $m2[0][1]) . ' ' . $text;
1098 $url = substr($url, 0, $m2[0][1]);
1101 # If the link text is an image URL, replace it with an <img> tag
1102 # This happened by accident in the original parser, but some people used it extensively
1103 $img = $this->maybeMakeExternalImage( $text );
1104 if ( $img !== false ) {
1110 # Set linktype for CSS - if URL==text, link is essentially free
1111 $linktype = ($text == $url) ?
'free' : 'text';
1113 # No link text, e.g. [http://domain.tld/some.link]
1114 if ( $text == '' ) {
1115 # Autonumber if allowed. See bug #5918
1116 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1117 $text = '[' . ++
$this->mAutonumber
. ']';
1118 $linktype = 'autonumber';
1120 # Otherwise just use the URL
1121 $text = htmlspecialchars( $url );
1125 # Have link text, e.g. [http://domain.tld/some.link text]s
1127 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1130 $text = $wgContLang->markNoConversion($text);
1132 # Normalize any HTML entities in input. They will be
1133 # re-escaped by makeExternalLink().
1134 $url = Sanitizer
::decodeCharReferences( $url );
1136 # Process the trail (i.e. everything after this link up until start of the next link),
1137 # replacing any non-bracketed links
1138 $trail = $this->replaceFreeExternalLinks( $trail );
1140 # Use the encoded URL
1141 # This means that users can paste URLs directly into the text
1142 # Funny characters like ö aren't valid in URLs anyway
1143 # This was changed in August 2004
1144 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1146 # Register link in the output object.
1147 # Replace unnecessary URL escape codes with the referenced character
1148 # This prevents spammers from hiding links from the filters
1149 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1150 $this->mOutput
->addExternalLink( $pasteurized );
1153 wfProfileOut( $fname );
1158 * Replace anything that looks like a URL with a link
1161 function replaceFreeExternalLinks( $text ) {
1163 $fname = 'Parser::replaceFreeExternalLinks';
1164 wfProfileIn( $fname );
1166 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1167 $s = array_shift( $bits );
1170 $sk =& $this->mOptions
->getSkin();
1172 while ( $i < count( $bits ) ){
1173 $protocol = $bits[$i++
];
1174 $remainder = $bits[$i++
];
1176 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1177 # Found some characters after the protocol that look promising
1178 $url = $protocol . $m[1];
1181 # special case: handle urls as url args:
1182 # http://www.example.com/foo?=http://www.example.com/bar
1183 if(strlen($trail) == 0 &&
1185 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1186 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1189 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1194 # The characters '<' and '>' (which were escaped by
1195 # removeHTMLtags()) should not be included in
1196 # URLs, per RFC 2396.
1197 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1198 $trail = substr($url, $m2[0][1]) . $trail;
1199 $url = substr($url, 0, $m2[0][1]);
1202 # Move trailing punctuation to $trail
1204 # If there is no left bracket, then consider right brackets fair game too
1205 if ( strpos( $url, '(' ) === false ) {
1209 $numSepChars = strspn( strrev( $url ), $sep );
1210 if ( $numSepChars ) {
1211 $trail = substr( $url, -$numSepChars ) . $trail;
1212 $url = substr( $url, 0, -$numSepChars );
1215 # Normalize any HTML entities in input. They will be
1216 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1217 $url = Sanitizer
::decodeCharReferences( $url );
1219 # Is this an external image?
1220 $text = $this->maybeMakeExternalImage( $url );
1221 if ( $text === false ) {
1222 # Not an image, make a link
1223 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1224 # Register it in the output object...
1225 # Replace unnecessary URL escape codes with their equivalent characters
1226 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1227 $this->mOutput
->addExternalLink( $pasteurized );
1229 $s .= $text . $trail;
1231 $s .= $protocol . $remainder;
1234 wfProfileOut( $fname );
1239 * Replace unusual URL escape codes with their equivalent characters
1243 * @fixme This can merge genuinely required bits in the path or query string,
1244 * breaking legit URLs. A proper fix would treat the various parts of
1245 * the URL differently; as a workaround, just use the output for
1246 * statistical records, not for actual linking/output.
1248 function replaceUnusualEscapes( $url ) {
1249 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1250 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1254 * Callback function used in replaceUnusualEscapes().
1255 * Replaces unusual URL escape codes with their equivalent character
1259 function replaceUnusualEscapesCallback( $matches ) {
1260 $char = urldecode( $matches[0] );
1261 $ord = ord( $char );
1262 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1263 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1264 // No, shouldn't be escaped
1267 // Yes, leave it escaped
1273 * make an image if it's allowed, either through the global
1274 * option or through the exception
1277 function maybeMakeExternalImage( $url ) {
1278 $sk =& $this->mOptions
->getSkin();
1279 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1280 $imagesexception = !empty($imagesfrom);
1282 if ( $this->mOptions
->getAllowExternalImages()
1283 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1284 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1286 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1293 * Process [[ ]] wikilinks
1297 function replaceInternalLinks( $s ) {
1299 static $fname = 'Parser::replaceInternalLinks' ;
1301 wfProfileIn( $fname );
1303 wfProfileIn( $fname.'-setup' );
1305 # the % is needed to support urlencoded titles as well
1306 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1308 $sk =& $this->mOptions
->getSkin();
1310 #split the entire text string on occurences of [[
1311 $a = explode( '[[', ' ' . $s );
1312 #get the first element (all text up to first [[), and remove the space we added
1313 $s = array_shift( $a );
1314 $s = substr( $s, 1 );
1316 # Match a link having the form [[namespace:link|alternate]]trail
1318 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1319 # Match cases where there is no "]]", which might still be images
1320 static $e1_img = FALSE;
1321 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1322 # Match the end of a line for a word that's not followed by whitespace,
1323 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1324 $e2 = wfMsgForContent( 'linkprefix' );
1326 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1328 if( is_null( $this->mTitle
) ) {
1329 wfDebugDieBacktrace( 'nooo' );
1331 $nottalk = !$this->mTitle
->isTalkPage();
1333 if ( $useLinkPrefixExtension ) {
1334 if ( preg_match( $e2, $s, $m ) ) {
1335 $first_prefix = $m[2];
1337 $first_prefix = false;
1343 $selflink = $this->mTitle
->getPrefixedText();
1344 wfProfileOut( $fname.'-setup' );
1346 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1347 $useSubpages = $this->areSubpagesAllowed();
1349 # Loop for each link
1350 for ($k = 0; isset( $a[$k] ); $k++
) {
1352 if ( $useLinkPrefixExtension ) {
1353 wfProfileIn( $fname.'-prefixhandling' );
1354 if ( preg_match( $e2, $s, $m ) ) {
1362 $prefix = $first_prefix;
1363 $first_prefix = false;
1365 wfProfileOut( $fname.'-prefixhandling' );
1368 $might_be_img = false;
1370 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1372 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1373 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1374 # the real problem is with the $e1 regex
1377 # Still some problems for cases where the ] is meant to be outside punctuation,
1378 # and no image is in sight. See bug 2095.
1381 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1382 strpos($text, '[') !== false
1385 $text .= ']'; # so that replaceExternalLinks($text) works later
1388 # fix up urlencoded title texts
1389 if(preg_match('/%/', $m[1] ))
1390 # Should anchors '#' also be rejected?
1391 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1393 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1394 $might_be_img = true;
1396 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1398 } else { # Invalid form; output directly
1399 $s .= $prefix . '[[' . $line ;
1403 # Don't allow internal links to pages containing
1404 # PROTO: where PROTO is a valid URL protocol; these
1405 # should be external links.
1406 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1407 $s .= $prefix . '[[' . $line ;
1411 # Make subpage if necessary
1412 if( $useSubpages ) {
1413 $link = $this->maybeDoSubpageLink( $m[1], $text );
1418 $noforce = (substr($m[1], 0, 1) != ':');
1420 # Strip off leading ':'
1421 $link = substr($link, 1);
1424 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1426 $s .= $prefix . '[[' . $line;
1430 #check other language variants of the link
1431 #if the article does not exist
1432 if( $checkVariantLink
1433 && $nt->getArticleID() == 0 ) {
1434 $wgContLang->findVariantLink($link, $nt);
1437 $ns = $nt->getNamespace();
1438 $iw = $nt->getInterWiki();
1440 if ($might_be_img) { # if this is actually an invalid link
1441 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1443 while (isset ($a[$k+
1]) ) {
1444 #look at the next 'line' to see if we can close it there
1445 $spliced = array_splice( $a, $k +
1, 1 );
1446 $next_line = array_shift( $spliced );
1447 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1448 # the first ]] closes the inner link, the second the image
1450 $text .= '[[' . $m[1];
1453 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1454 #if there's exactly one ]] that's fine, we'll keep looking
1455 $text .= '[[' . $m[0];
1457 #if $next_line is invalid too, we need look no further
1458 $text .= '[[' . $next_line;
1463 # we couldn't find the end of this imageLink, so output it raw
1464 #but don't ignore what might be perfectly normal links in the text we've examined
1465 $text = $this->replaceInternalLinks($text);
1466 $s .= $prefix . '[[' . $link . '|' . $text;
1467 # note: no $trail, because without an end, there *is* no trail
1470 } else { #it's not an image, so output it raw
1471 $s .= $prefix . '[[' . $link . '|' . $text;
1472 # note: no $trail, because without an end, there *is* no trail
1477 $wasblank = ( '' == $text );
1478 if( $wasblank ) $text = $link;
1481 # Link not escaped by : , create the various objects
1485 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1486 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1487 $s = rtrim($s . "\n");
1488 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1492 if ( $ns == NS_IMAGE
) {
1493 wfProfileIn( "$fname-image" );
1494 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1495 # recursively parse links inside the image caption
1496 # actually, this will parse them in any other parameters, too,
1497 # but it might be hard to fix that, and it doesn't matter ATM
1498 $text = $this->replaceExternalLinks($text);
1499 $text = $this->replaceInternalLinks($text);
1501 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1502 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1503 $this->mOutput
->addImage( $nt->getDBkey() );
1505 wfProfileOut( "$fname-image" );
1508 wfProfileOut( "$fname-image" );
1512 if ( $ns == NS_CATEGORY
) {
1513 wfProfileIn( "$fname-category" );
1514 $s = rtrim($s . "\n"); # bug 87
1517 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1518 $sortkey = $this->mTitle
->getText();
1520 $sortkey = $this->mTitle
->getPrefixedText();
1525 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1526 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1527 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1530 * Strip the whitespace Category links produce, see bug 87
1531 * @todo We might want to use trim($tmp, "\n") here.
1533 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1535 wfProfileOut( "$fname-category" );
1540 if( ( $nt->getPrefixedText() === $selflink ) &&
1541 ( $nt->getFragment() === '' ) ) {
1542 # Self-links are handled specially; generally de-link and change to bold.
1543 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1547 # Special and Media are pseudo-namespaces; no pages actually exist in them
1548 if( $ns == NS_MEDIA
) {
1549 $link = $sk->makeMediaLinkObj( $nt, $text );
1550 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1551 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1552 $this->mOutput
->addImage( $nt->getDBkey() );
1554 } elseif( $ns == NS_SPECIAL
) {
1555 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1557 } elseif( $ns == NS_IMAGE
) {
1558 $img = Image
::newFromTitle( $nt );
1559 if( $img->exists() ) {
1560 // Force a blue link if the file exists; may be a remote
1561 // upload on the shared repository, and we want to see its
1562 // auto-generated page.
1563 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1567 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1569 wfProfileOut( $fname );
1574 * Make a link placeholder. The text returned can be later resolved to a real link with
1575 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1576 * parsing of interwiki links, and secondly to allow all extistence checks and
1577 * article length checks (for stub links) to be bundled into a single query.
1580 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1581 if ( ! is_object($nt) ) {
1583 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1585 # Separate the link trail from the rest of the link
1586 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1588 if ( $nt->isExternal() ) {
1589 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1590 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1591 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1593 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1594 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1595 $this->mLinkHolders
['queries'][] = $query;
1596 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1597 $this->mLinkHolders
['titles'][] = $nt;
1599 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1606 * Render a forced-blue link inline; protect against double expansion of
1607 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1608 * Since this little disaster has to split off the trail text to avoid
1609 * breaking URLs in the following text without breaking trails on the
1610 * wiki links, it's been made into a horrible function.
1613 * @param string $text
1614 * @param string $query
1615 * @param string $trail
1616 * @param string $prefix
1617 * @return string HTML-wikitext mix oh yuck
1619 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1620 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1621 $sk =& $this->mOptions
->getSkin();
1622 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1623 return $this->armorLinks( $link ) . $trail;
1627 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1628 * going to go through further parsing steps before inline URL expansion.
1630 * In particular this is important when using action=render, which causes
1631 * full URLs to be included.
1633 * Oh man I hate our multi-layer parser!
1635 * @param string more-or-less HTML
1636 * @return string less-or-more HTML with NOPARSE bits
1638 function armorLinks( $text ) {
1639 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1640 "{$this->mUniqPrefix}NOPARSE$1", $text );
1644 * Return true if subpage links should be expanded on this page.
1647 function areSubpagesAllowed() {
1648 # Some namespaces don't allow subpages
1649 global $wgNamespacesWithSubpages;
1650 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1654 * Handle link to subpage if necessary
1655 * @param string $target the source of the link
1656 * @param string &$text the link text, modified as necessary
1657 * @return string the full name of the link
1660 function maybeDoSubpageLink($target, &$text) {
1663 # :Foobar -- override special treatment of prefix (images, language links)
1664 # /Foobar -- convert to CurrentPage/Foobar
1665 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1666 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1667 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1669 $fname = 'Parser::maybeDoSubpageLink';
1670 wfProfileIn( $fname );
1671 $ret = $target; # default return value is no change
1673 # Some namespaces don't allow subpages,
1674 # so only perform processing if subpages are allowed
1675 if( $this->areSubpagesAllowed() ) {
1676 # Look at the first character
1677 if( $target != '' && $target{0} == '/' ) {
1678 # / at end means we don't want the slash to be shown
1679 if( substr( $target, -1, 1 ) == '/' ) {
1680 $target = substr( $target, 1, -1 );
1683 $noslash = substr( $target, 1 );
1686 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1687 if( '' === $text ) {
1689 } # this might be changed for ugliness reasons
1691 # check for .. subpage backlinks
1693 $nodotdot = $target;
1694 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1696 $nodotdot = substr( $nodotdot, 3 );
1698 if($dotdotcount > 0) {
1699 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1700 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1701 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1702 # / at the end means don't show full path
1703 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1704 $nodotdot = substr( $nodotdot, 0, -1 );
1705 if( '' === $text ) {
1709 $nodotdot = trim( $nodotdot );
1710 if( $nodotdot != '' ) {
1711 $ret .= '/' . $nodotdot;
1718 wfProfileOut( $fname );
1723 * Used by doBlockLevels()
1726 /* private */ function closeParagraph() {
1728 if ( '' != $this->mLastSection
) {
1729 $result = '</' . $this->mLastSection
. ">\n";
1731 $this->mInPre
= false;
1732 $this->mLastSection
= '';
1735 # getCommon() returns the length of the longest common substring
1736 # of both arguments, starting at the beginning of both.
1738 /* private */ function getCommon( $st1, $st2 ) {
1739 $fl = strlen( $st1 );
1740 $shorter = strlen( $st2 );
1741 if ( $fl < $shorter ) { $shorter = $fl; }
1743 for ( $i = 0; $i < $shorter; ++
$i ) {
1744 if ( $st1{$i} != $st2{$i} ) { break; }
1748 # These next three functions open, continue, and close the list
1749 # element appropriate to the prefix character passed into them.
1751 /* private */ function openList( $char ) {
1752 $result = $this->closeParagraph();
1754 if ( '*' == $char ) { $result .= '<ul><li>'; }
1755 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1756 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1757 else if ( ';' == $char ) {
1758 $result .= '<dl><dt>';
1759 $this->mDTopen
= true;
1761 else { $result = '<!-- ERR 1 -->'; }
1766 /* private */ function nextItem( $char ) {
1767 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1768 else if ( ':' == $char ||
';' == $char ) {
1770 if ( $this->mDTopen
) { $close = '</dt>'; }
1771 if ( ';' == $char ) {
1772 $this->mDTopen
= true;
1773 return $close . '<dt>';
1775 $this->mDTopen
= false;
1776 return $close . '<dd>';
1779 return '<!-- ERR 2 -->';
1782 /* private */ function closeList( $char ) {
1783 if ( '*' == $char ) { $text = '</li></ul>'; }
1784 else if ( '#' == $char ) { $text = '</li></ol>'; }
1785 else if ( ':' == $char ) {
1786 if ( $this->mDTopen
) {
1787 $this->mDTopen
= false;
1788 $text = '</dt></dl>';
1790 $text = '</dd></dl>';
1793 else { return '<!-- ERR 3 -->'; }
1799 * Make lists from lines starting with ':', '*', '#', etc.
1802 * @return string the lists rendered as HTML
1804 function doBlockLevels( $text, $linestart ) {
1805 $fname = 'Parser::doBlockLevels';
1806 wfProfileIn( $fname );
1808 # Parsing through the text line by line. The main thing
1809 # happening here is handling of block-level elements p, pre,
1810 # and making lists from lines starting with * # : etc.
1812 $textLines = explode( "\n", $text );
1814 $lastPrefix = $output = '';
1815 $this->mDTopen
= $inBlockElem = false;
1817 $paragraphStack = false;
1819 if ( !$linestart ) {
1820 $output .= array_shift( $textLines );
1822 foreach ( $textLines as $oLine ) {
1823 $lastPrefixLength = strlen( $lastPrefix );
1824 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1825 $preOpenMatch = preg_match('/<pre/i', $oLine );
1826 if ( !$this->mInPre
) {
1827 # Multiple prefixes may abut each other for nested lists.
1828 $prefixLength = strspn( $oLine, '*#:;' );
1829 $pref = substr( $oLine, 0, $prefixLength );
1832 $pref2 = str_replace( ';', ':', $pref );
1833 $t = substr( $oLine, $prefixLength );
1834 $this->mInPre
= !empty($preOpenMatch);
1836 # Don't interpret any other prefixes in preformatted text
1838 $pref = $pref2 = '';
1843 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1844 # Same as the last item, so no need to deal with nesting or opening stuff
1845 $output .= $this->nextItem( substr( $pref, -1 ) );
1846 $paragraphStack = false;
1848 if ( substr( $pref, -1 ) == ';') {
1849 # The one nasty exception: definition lists work like this:
1850 # ; title : definition text
1851 # So we check for : in the remainder text to split up the
1852 # title and definition, without b0rking links.
1854 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1856 $output .= $term . $this->nextItem( ':' );
1859 } elseif( $prefixLength ||
$lastPrefixLength ) {
1860 # Either open or close a level...
1861 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1862 $paragraphStack = false;
1864 while( $commonPrefixLength < $lastPrefixLength ) {
1865 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1866 --$lastPrefixLength;
1868 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1869 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1871 while ( $prefixLength > $commonPrefixLength ) {
1872 $char = substr( $pref, $commonPrefixLength, 1 );
1873 $output .= $this->openList( $char );
1875 if ( ';' == $char ) {
1876 # FIXME: This is dupe of code above
1877 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1879 $output .= $term . $this->nextItem( ':' );
1882 ++
$commonPrefixLength;
1884 $lastPrefix = $pref2;
1886 if( 0 == $prefixLength ) {
1887 wfProfileIn( "$fname-paragraph" );
1888 # No prefix (not in list)--go to paragraph mode
1889 // XXX: use a stack for nestable elements like span, table and div
1890 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1891 $closematch = preg_match(
1892 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1893 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1894 if ( $openmatch or $closematch ) {
1895 $paragraphStack = false;
1896 #Â TODO bug 5718: paragraph closed
1897 $output .= $this->closeParagraph();
1898 if ( $preOpenMatch and !$preCloseMatch ) {
1899 $this->mInPre
= true;
1901 if ( $closematch ) {
1902 $inBlockElem = false;
1904 $inBlockElem = true;
1906 } else if ( !$inBlockElem && !$this->mInPre
) {
1907 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1909 if ($this->mLastSection
!= 'pre') {
1910 $paragraphStack = false;
1911 $output .= $this->closeParagraph().'<pre>';
1912 $this->mLastSection
= 'pre';
1914 $t = substr( $t, 1 );
1917 if ( '' == trim($t) ) {
1918 if ( $paragraphStack ) {
1919 $output .= $paragraphStack.'<br />';
1920 $paragraphStack = false;
1921 $this->mLastSection
= 'p';
1923 if ($this->mLastSection
!= 'p' ) {
1924 $output .= $this->closeParagraph();
1925 $this->mLastSection
= '';
1926 $paragraphStack = '<p>';
1928 $paragraphStack = '</p><p>';
1932 if ( $paragraphStack ) {
1933 $output .= $paragraphStack;
1934 $paragraphStack = false;
1935 $this->mLastSection
= 'p';
1936 } else if ($this->mLastSection
!= 'p') {
1937 $output .= $this->closeParagraph().'<p>';
1938 $this->mLastSection
= 'p';
1943 wfProfileOut( "$fname-paragraph" );
1945 // somewhere above we forget to get out of pre block (bug 785)
1946 if($preCloseMatch && $this->mInPre
) {
1947 $this->mInPre
= false;
1949 if ($paragraphStack === false) {
1953 while ( $prefixLength ) {
1954 $output .= $this->closeList( $pref2{$prefixLength-1} );
1957 if ( '' != $this->mLastSection
) {
1958 $output .= '</' . $this->mLastSection
. '>';
1959 $this->mLastSection
= '';
1962 wfProfileOut( $fname );
1967 * Split up a string on ':', ignoring any occurences inside
1968 * <a>..</a> or <span>...</span>
1969 * @param string $str the string to split
1970 * @param string &$before set to everything before the ':'
1971 * @param string &$after set to everything after the ':'
1972 * return string the position of the ':', or false if none found
1974 function findColonNoLinks($str, &$before, &$after) {
1975 # I wonder if we should make this count all tags, not just <a>
1976 # and <span>. That would prevent us from matching a ':' that
1977 # comes in the middle of italics other such formatting....
1979 $fname = 'Parser::findColonNoLinks';
1980 wfProfileIn( $fname );
1983 $colon = strpos($str, ':', $pos);
1985 if ($colon !== false) {
1986 $before = substr($str, 0, $colon);
1987 $after = substr($str, $colon +
1);
1989 # Skip any ':' within <a> or <span> pairs
1990 $a = substr_count($before, '<a');
1991 $s = substr_count($before, '<span');
1992 $ca = substr_count($before, '</a>');
1993 $cs = substr_count($before, '</span>');
1995 if ($a <= $ca and $s <= $cs) {
1996 # Tags are balanced before ':'; ok
2001 } while ($colon !== false);
2002 wfProfileOut( $fname );
2007 * Return value of a magic variable (like PAGENAME)
2011 function getVariableValue( $index ) {
2012 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2015 * Some of these require message or data lookups and can be
2016 * expensive to check many times.
2018 static $varCache = array();
2019 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2020 if ( isset( $varCache[$index] ) )
2021 return $varCache[$index];
2024 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2027 case MAG_CURRENTMONTH
:
2028 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2029 case MAG_CURRENTMONTHNAME
:
2030 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2031 case MAG_CURRENTMONTHNAMEGEN
:
2032 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2033 case MAG_CURRENTMONTHABBREV
:
2034 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2035 case MAG_CURRENTDAY
:
2036 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2037 case MAG_CURRENTDAY2
:
2038 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2040 return $this->mTitle
->getText();
2042 return $this->mTitle
->getPartialURL();
2043 case MAG_FULLPAGENAME
:
2044 return $this->mTitle
->getPrefixedText();
2045 case MAG_FULLPAGENAMEE
:
2046 return $this->mTitle
->getPrefixedURL();
2047 case MAG_SUBPAGENAME
:
2048 return $this->mTitle
->getSubpageText();
2049 case MAG_SUBPAGENAMEE
:
2050 return $this->mTitle
->getSubpageUrlForm();
2051 case MAG_BASEPAGENAME
:
2052 return $this->mTitle
->getBaseText();
2053 case MAG_BASEPAGENAMEE
:
2054 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2055 case MAG_TALKPAGENAME
:
2056 if( $this->mTitle
->canTalk() ) {
2057 $talkPage = $this->mTitle
->getTalkPage();
2058 return $talkPage->getPrefixedText();
2062 case MAG_TALKPAGENAMEE
:
2063 if( $this->mTitle
->canTalk() ) {
2064 $talkPage = $this->mTitle
->getTalkPage();
2065 return $talkPage->getPrefixedUrl();
2069 case MAG_SUBJECTPAGENAME
:
2070 $subjPage = $this->mTitle
->getSubjectPage();
2071 return $subjPage->getPrefixedText();
2072 case MAG_SUBJECTPAGENAMEE
:
2073 $subjPage = $this->mTitle
->getSubjectPage();
2074 return $subjPage->getPrefixedUrl();
2075 case MAG_REVISIONID
:
2076 return $this->mRevisionId
;
2078 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2079 case MAG_NAMESPACEE
:
2080 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2082 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2083 case MAG_TALKSPACEE
:
2084 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2085 case MAG_SUBJECTSPACE
:
2086 return $this->mTitle
->getSubjectNsText();
2087 case MAG_SUBJECTSPACEE
:
2088 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2089 case MAG_CURRENTDAYNAME
:
2090 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2091 case MAG_CURRENTYEAR
:
2092 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2093 case MAG_CURRENTTIME
:
2094 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2095 case MAG_CURRENTWEEK
:
2096 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2097 // int to remove the padding
2098 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2099 case MAG_CURRENTDOW
:
2100 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2101 case MAG_NUMBEROFARTICLES
:
2102 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2103 case MAG_NUMBEROFFILES
:
2104 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2105 case MAG_NUMBEROFUSERS
:
2106 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2107 case MAG_NUMBEROFPAGES
:
2108 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2109 case MAG_CURRENTTIMESTAMP
:
2110 return $varCache[$index] = wfTimestampNow();
2111 case MAG_CURRENTVERSION
:
2118 case MAG_SERVERNAME
:
2119 return $wgServerName;
2120 case MAG_SCRIPTPATH
:
2121 return $wgScriptPath;
2122 case MAG_DIRECTIONMARK
:
2123 return $wgContLang->getDirMark();
2126 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2134 * initialise the magic variables (like CURRENTMONTHNAME)
2138 function initialiseVariables() {
2139 $fname = 'Parser::initialiseVariables';
2140 wfProfileIn( $fname );
2141 global $wgVariableIDs;
2142 $this->mVariables
= array();
2143 foreach ( $wgVariableIDs as $id ) {
2144 $mw =& MagicWord
::get( $id );
2145 $mw->addToArray( $this->mVariables
, $id );
2147 wfProfileOut( $fname );
2151 * parse any parentheses in format ((title|part|part))
2152 * and call callbacks to get a replacement text for any found piece
2154 * @param string $text The text to parse
2155 * @param array $callbacks rules in form:
2156 * '{' => array( # opening parentheses
2157 * 'end' => '}', # closing parentheses
2158 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2159 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2164 function replace_callback ($text, $callbacks) {
2165 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2166 $lastOpeningBrace = -1; # last not closed parentheses
2168 for ($i = 0; $i < strlen($text); $i++
) {
2169 # check for any opening brace
2172 foreach ($callbacks as $key => $value) {
2173 $pos = strpos ($text, $key, $i);
2174 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2180 if ($lastOpeningBrace >= 0) {
2181 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2183 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2188 $pos = strpos ($text, '|', $i);
2190 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2201 # found openning brace, lets add it to parentheses stack
2202 if (null != $rule) {
2203 $piece = array('brace' => $text[$i],
2204 'braceEnd' => $rule['end'],
2209 # count openning brace characters
2210 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2215 $piece['startAt'] = $i+
1;
2216 $piece['partStart'] = $i+
1;
2218 # we need to add to stack only if openning brace count is enough for any given rule
2219 foreach ($rule['cb'] as $cnt => $fn) {
2220 if ($piece['count'] >= $cnt) {
2221 $lastOpeningBrace ++
;
2222 $openingBraceStack[$lastOpeningBrace] = $piece;
2229 else if ($lastOpeningBrace >= 0) {
2230 # first check if it is a closing brace
2231 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2232 # lets check if it is enough characters for closing brace
2234 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2237 # if there are more closing parentheses than opening ones, we parse less
2238 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2239 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2241 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2243 $matchingCallback = null;
2244 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2245 if ($count >= $cnt && $matchingCount < $cnt) {
2246 $matchingCount = $cnt;
2247 $matchingCallback = $fn;
2251 if ($matchingCount == 0) {
2256 # lets set a title or last part (if '|' was found)
2257 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2258 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2260 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2262 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2263 $pieceEnd = $i +
$matchingCount;
2265 if( is_callable( $matchingCallback ) ) {
2267 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2268 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2269 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2270 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2272 # finally we can call a user callback and replace piece of text
2273 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2274 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2275 $i = $pieceStart +
strlen($replaceWith) - 1;
2278 # null value for callback means that parentheses should be parsed, but not replaced
2279 $i +
= $matchingCount - 1;
2282 # reset last openning parentheses, but keep it in case there are unused characters
2283 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2284 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2285 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2288 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2289 $openingBraceStack[$lastOpeningBrace--] = null;
2291 if ($matchingCount < $piece['count']) {
2292 $piece['count'] -= $matchingCount;
2293 $piece['startAt'] -= $matchingCount;
2294 $piece['partStart'] = $piece['startAt'];
2295 # do we still qualify for any callback with remaining count?
2296 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2297 if ($piece['count'] >= $cnt) {
2298 $lastOpeningBrace ++
;
2299 $openingBraceStack[$lastOpeningBrace] = $piece;
2307 # lets set a title if it is a first separator, or next part otherwise
2308 if ($text[$i] == '|') {
2309 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2310 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2311 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2314 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2316 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2325 * Replace magic variables, templates, and template arguments
2326 * with the appropriate text. Templates are substituted recursively,
2327 * taking care to avoid infinite loops.
2329 * Note that the substitution depends on value of $mOutputType:
2330 * OT_WIKI: only {{subst:}} templates
2331 * OT_MSG: only magic variables
2332 * OT_HTML: all templates and magic variables
2334 * @param string $tex The text to transform
2335 * @param array $args Key-value pairs representing template parameters to substitute
2336 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2339 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2340 # Prevent too big inclusions
2341 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2345 $fname = 'Parser::replaceVariables';
2346 wfProfileIn( $fname );
2348 # This function is called recursively. To keep track of arguments we need a stack:
2349 array_push( $this->mArgStack
, $args );
2351 $braceCallbacks = array();
2353 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2355 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2356 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2358 $callbacks = array();
2359 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2360 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2361 $text = $this->replace_callback ($text, $callbacks);
2363 array_pop( $this->mArgStack
);
2365 wfProfileOut( $fname );
2370 * Replace magic variables
2373 function variableSubstitution( $matches ) {
2374 $fname = 'Parser::variableSubstitution';
2375 $varname = $matches[1];
2376 wfProfileIn( $fname );
2377 if ( !$this->mVariables
) {
2378 $this->initialiseVariables();
2381 if ( $this->mOutputType
== OT_WIKI
) {
2382 # Do only magic variables prefixed by SUBST
2383 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2384 if (!$mwSubst->matchStartAndRemove( $varname ))
2386 # Note that if we don't substitute the variable below,
2387 # we don't remove the {{subst:}} magic word, in case
2388 # it is a template rather than a magic variable.
2390 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2391 $id = $this->mVariables
[$varname];
2392 $text = $this->getVariableValue( $id );
2393 $this->mOutput
->mContainsOldMagic
= true;
2395 $text = $matches[0];
2397 wfProfileOut( $fname );
2401 # Split template arguments
2402 function getTemplateArgs( $argsString ) {
2403 if ( $argsString === '' ) {
2407 $args = explode( '|', substr( $argsString, 1 ) );
2409 # If any of the arguments contains a '[[' but no ']]', it needs to be
2410 # merged with the next arg because the '|' character between belongs
2411 # to the link syntax and not the template parameter syntax.
2412 $argc = count($args);
2414 for ( $i = 0; $i < $argc-1; $i++
) {
2415 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2416 $args[$i] .= '|'.$args[$i+
1];
2417 array_splice($args, $i+
1, 1);
2427 * Return the text of a template, after recursively
2428 * replacing any variables or templates within the template.
2430 * @param array $piece The parts of the template
2431 * $piece['text']: matched text
2432 * $piece['title']: the title, i.e. the part before the |
2433 * $piece['parts']: the parameter array
2434 * @return string the text of the template
2437 function braceSubstitution( $piece ) {
2438 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2439 $fname = 'Parser::braceSubstitution';
2440 wfProfileIn( $fname );
2443 $found = false; # $text has been filled
2444 $nowiki = false; # wiki markup in $text should be escaped
2445 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2446 $noargs = false; # Don't replace triple-brace arguments in $text
2447 $replaceHeadings = false; # Make the edit section links go to the template not the article
2448 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2449 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2451 # Title object, where $text came from
2456 # $part1 is the bit before the first |, and must contain only title characters
2457 # $args is a list of arguments, starting from index 0, not including $part1
2459 $part1 = $piece['title'];
2460 # If the third subpattern matched anything, it will start with |
2462 if (null == $piece['parts']) {
2463 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2464 if ($replaceWith != $piece['text']) {
2465 $text = $replaceWith;
2472 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2473 $argc = count( $args );
2477 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2478 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2479 # One of two possibilities is true:
2480 # 1) Found SUBST but not in the PST phase
2481 # 2) Didn't find SUBST and in the PST phase
2482 # In either case, return without further processing
2483 $text = $piece['text'];
2490 # MSG, MSGNW, INT and RAW
2493 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2494 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2497 # Remove obsolete MSG:
2498 $mwMsg =& MagicWord
::get( MAG_MSG
);
2499 $mwMsg->matchStartAndRemove( $part1 );
2503 $mwRaw =& MagicWord
::get( MAG_RAW
);
2504 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2505 $forceRawInterwiki = true;
2508 # Check if it is an internal message
2509 $mwInt =& MagicWord
::get( MAG_INT
);
2510 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2511 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2512 $text = $linestart . wfMsgReal( $part1, $args, true );
2520 # Check for NS: (namespace expansion)
2521 $mwNs = MagicWord
::get( MAG_NS
);
2522 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2523 if ( intval( $part1 ) ||
$part1 == "0" ) {
2524 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2527 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2528 if ( !is_null( $index ) ) {
2529 $text = $linestart . $wgContLang->getNsText( $index );
2538 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2539 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2540 $text = $linestart . urlencode( $part1 );
2545 # LCFIRST, UCFIRST, LC and UC
2547 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2548 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2549 $lc =& MagicWord
::get( MAG_LC
);
2550 $uc =& MagicWord
::get( MAG_UC
);
2551 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2552 $text = $linestart . $wgContLang->lcfirst( $part1 );
2554 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2555 $text = $linestart . $wgContLang->ucfirst( $part1 );
2557 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2558 $text = $linestart . $wgContLang->lc( $part1 );
2560 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2561 $text = $linestart . $wgContLang->uc( $part1 );
2566 # LOCALURL and FULLURL
2568 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2569 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2570 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2571 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2574 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2575 $func = 'getLocalURL';
2576 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2577 $func = 'escapeLocalURL';
2578 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2579 $func = 'getFullURL';
2580 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2581 $func = 'escapeFullURL';
2586 if ( $func !== false ) {
2587 $title = Title
::newFromText( $part1 );
2588 # Due to order of execution of a lot of bits, the values might be encoded
2589 # before arriving here; if that's true, then the title can't be created
2590 # and the variable will fail. If we can't get a decent title from the first
2591 # attempt, url-decode and try for a second.
2592 if( is_null( $title ) )
2593 $title = Title
::newFromUrl( urldecode( $part1 ) );
2594 if ( !is_null( $title ) ) {
2596 $text = $linestart . $title->$func( $args[0] );
2598 $text = $linestart . $title->$func();
2605 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2607 if ( !$found && $argc == 1 ) {
2608 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2609 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2610 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2616 if ( !$found && $argc >= 2 ) {
2617 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2618 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2619 if ($argc==2) {$args[2]=$args[1];}
2620 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2626 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2627 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2628 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2630 # Set title in parser output object
2632 $parserOptions = new ParserOptions
;
2633 $local_parser = new Parser ();
2634 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2635 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2638 $t = $this->mTitle
->getPrefixedText();
2639 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2645 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2647 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2648 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2649 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2650 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2651 foreach( $mwWordsToCheck as $word => $func ) {
2652 $mwCurrentWord =& MagicWord
::get( $word );
2653 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2654 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2655 if( $mwRawSuffix->match( $args[0] ) ) {
2656 # Raw and unformatted
2657 $text = $linestart . call_user_func( $func );
2659 # Formatted according to the content default
2660 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2669 $mwLanguage =& MagicWord
::get( MAG_LANGUAGE
);
2670 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2671 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2672 $text = $linestart . ( $lang != '' ?
$lang : $part1 );
2678 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2679 $colonPos = strpos( $part1, ':' );
2680 if ( $colonPos !== false ) {
2681 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2682 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2683 $funcArgs = array_map( 'trim', $args );
2684 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2685 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2688 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2692 if ( is_array( $result ) ) {
2693 $text = $linestart . $result[0];
2694 unset( $result[0] );
2696 // Extract flags into the local scope
2697 // This allows callers to set flags such as nowiki, noparse, found, etc.
2700 $text = $linestart . $result;
2706 # Template table test
2708 # Did we encounter this template already? If yes, it is in the cache
2709 # and we need to check for loops.
2710 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2713 # Infinite loop test
2714 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2718 $text = $linestart .
2719 '{{' . $part1 . '}}' .
2720 '<!-- WARNING: template loop detected -->';
2721 wfDebug( "$fname: template loop broken at '$part1'\n" );
2723 # set $text to cached message.
2724 $text = $linestart . $this->mTemplates
[$piece['title']];
2728 # Load from database
2729 $lastPathLevel = $this->mTemplatePath
;
2732 # declaring $subpage directly in the function call
2733 # does not work correctly with references and breaks
2734 # {{/subpage}}-style inclusions
2736 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2737 if ($subpage !== '') {
2738 $ns = $this->mTitle
->getNamespace();
2740 $title = Title
::newFromText( $part1, $ns );
2742 if ( !is_null( $title ) ) {
2743 if ( !$title->isExternal() ) {
2744 # Check for excessive inclusion
2745 $dbk = $title->getPrefixedDBkey();
2746 if ( $this->incrementIncludeCount( $dbk ) ) {
2747 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2748 $text = SpecialPage
::capturePath( $title );
2749 if ( is_string( $text ) ) {
2754 $this->disableCache();
2757 $articleContent = $this->fetchTemplate( $title );
2758 if ( $articleContent !== false ) {
2760 $text = $articleContent;
2761 $replaceHeadings = true;
2766 # If the title is valid but undisplayable, make a link to it
2767 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2768 $text = '[['.$title->getPrefixedText().']]';
2771 } elseif ( $title->isTrans() ) {
2772 // Interwiki transclusion
2773 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2774 $text = $this->interwikiTransclude( $title, 'render' );
2778 $text = $this->interwikiTransclude( $title, 'raw' );
2779 $replaceHeadings = true;
2784 # Template cache array insertion
2785 # Use the original $piece['title'] not the mangled $part1, so that
2786 # modifiers such as RAW: produce separate cache entries
2788 $this->mTemplates
[$piece['title']] = $text;
2789 $text = $linestart . $text;
2794 # Recursive parsing, escaping and link table handling
2795 # Only for HTML output
2796 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2797 $text = wfEscapeWikiText( $text );
2798 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2800 $assocArgs = array();
2802 # Clean up argument array
2803 $assocArgs = array();
2805 foreach( $args as $arg ) {
2806 $eqpos = strpos( $arg, '=' );
2807 if ( $eqpos === false ) {
2808 $assocArgs[$index++
] = $arg;
2810 $name = trim( substr( $arg, 0, $eqpos ) );
2811 $value = trim( substr( $arg, $eqpos+
1 ) );
2812 if ( $value === false ) {
2815 if ( $name !== false ) {
2816 $assocArgs[$name] = $value;
2821 # Add a new element to the templace recursion path
2822 $this->mTemplatePath
[$part1] = 1;
2826 # If there are any <onlyinclude> tags, only include them
2827 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2828 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2830 foreach ($m[1] as $piece)
2833 # Remove <noinclude> sections and <includeonly> tags
2834 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2835 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2837 if( $this->mOutputType
== OT_HTML
) {
2838 # Strip <nowiki>, <pre>, etc.
2839 $text = $this->strip( $text, $this->mStripState
);
2840 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2842 $text = $this->replaceVariables( $text, $assocArgs );
2844 # If the template begins with a table or block-level
2845 # element, it should be treated as beginning a new line.
2846 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2847 $text = "\n" . $text;
2849 } elseif ( !$noargs ) {
2850 # $noparse and !$noargs
2851 # Just replace the arguments, not any double-brace items
2852 # This is used for rendered interwiki transclusion
2853 $text = $this->replaceVariables( $text, $assocArgs, true );
2856 # Prune lower levels off the recursion check path
2857 $this->mTemplatePath
= $lastPathLevel;
2860 wfProfileOut( $fname );
2861 return $piece['text'];
2864 # Replace raw HTML by a placeholder
2865 # Add a blank line preceding, to prevent it from mucking up
2866 # immediately preceding headings
2867 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2869 # replace ==section headers==
2870 # XXX this needs to go away once we have a better parser.
2871 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2872 if( !is_null( $title ) )
2873 $encodedname = base64_encode($title->getPrefixedDBkey());
2875 $encodedname = base64_encode("");
2876 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2877 PREG_SPLIT_DELIM_CAPTURE
);
2880 for( $i = 0; $i < count($m); $i +
= 2 ) {
2882 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2884 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2888 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2889 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2890 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2898 # Prune lower levels off the recursion check path
2899 $this->mTemplatePath
= $lastPathLevel;
2902 wfProfileOut( $fname );
2903 return $piece['text'];
2905 wfProfileOut( $fname );
2911 * Fetch the unparsed text of a template and register a reference to it.
2913 function fetchTemplate( $title ) {
2915 // Loop to fetch the article, with up to 1 redirect
2916 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2917 $rev = Revision
::newFromTitle( $title );
2918 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2922 $text = $rev->getText();
2923 if ( $text === false ) {
2927 $title = Title
::newFromRedirect( $text );
2933 * Transclude an interwiki link.
2935 function interwikiTransclude( $title, $action ) {
2936 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2938 if (!$wgEnableScaryTranscluding)
2939 return wfMsg('scarytranscludedisabled');
2941 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2942 // But we'll handle it generally anyway
2943 if ( $title->getNamespace() ) {
2944 // Use the canonical namespace, which should work anywhere
2945 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2947 $articleName = $title->getDBkey();
2950 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2951 $url .= "?action=$action";
2952 if (strlen($url) > 255)
2953 return wfMsg('scarytranscludetoolong');
2954 return $this->fetchScaryTemplateMaybeFromCache($url);
2957 function fetchScaryTemplateMaybeFromCache($url) {
2958 global $wgTranscludeCacheExpiry;
2959 $dbr =& wfGetDB(DB_SLAVE
);
2960 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2961 array('tc_url' => $url));
2963 $time = $obj->tc_time
;
2964 $text = $obj->tc_contents
;
2965 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2970 $text = HttpFunctions
::getHTTP($url);
2972 return wfMsg('scarytranscludefailed', $url);
2974 $dbw =& wfGetDB(DB_MASTER
);
2975 $dbw->replace('transcache', array('tc_url'), array(
2977 'tc_time' => time(),
2978 'tc_contents' => $text));
2984 * Triple brace replacement -- used for template arguments
2987 function argSubstitution( $matches ) {
2988 $arg = trim( $matches['title'] );
2989 $text = $matches['text'];
2990 $inputArgs = end( $this->mArgStack
);
2992 if ( array_key_exists( $arg, $inputArgs ) ) {
2993 $text = $inputArgs[$arg];
2994 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2995 $text = $matches['parts'][0];
3002 * Returns true if the function is allowed to include this entity
3005 function incrementIncludeCount( $dbk ) {
3006 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3007 $this->mIncludeCount
[$dbk] = 0;
3009 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3017 * Detect __TOC__ magic word and set a placeholder
3019 function stripToc( $text ) {
3020 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3022 $mw = MagicWord
::get( MAG_NOTOC
);
3023 if( $mw->matchAndRemove( $text ) ) {
3024 $this->mShowToc
= false;
3027 $mw = MagicWord
::get( MAG_TOC
);
3028 if( $mw->match( $text ) ) {
3029 $this->mShowToc
= true;
3030 $this->mForceTocPosition
= true;
3032 // Set a placeholder. At the end we'll fill it in with the TOC.
3033 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3035 // Only keep the first one.
3036 $text = $mw->replace( '', $text );
3042 * This function accomplishes several tasks:
3043 * 1) Auto-number headings if that option is enabled
3044 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3045 * 3) Add a Table of contents on the top for users who have enabled the option
3046 * 4) Auto-anchor headings
3048 * It loops through all headlines, collects the necessary data, then splits up the
3049 * string and re-inserts the newly formatted headlines.
3051 * @param string $text
3052 * @param boolean $isMain
3055 function formatHeadings( $text, $isMain=true ) {
3056 global $wgMaxTocLevel, $wgContLang;
3058 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3059 if( !$this->mTitle
->userCanEdit() ) {
3062 $showEditLink = $this->mOptions
->getEditSection();
3065 # Inhibit editsection links if requested in the page
3066 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3067 if( $esw->matchAndRemove( $text ) ) {
3071 # Get all headlines for numbering them and adding funky stuff like [edit]
3072 # links - this is for later, but we need the number of headlines right now
3073 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3075 # if there are fewer than 4 headlines in the article, do not show TOC
3076 # unless it's been explicitly enabled.
3077 $enoughToc = $this->mShowToc
&&
3078 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3080 # Allow user to stipulate that a page should have a "new section"
3081 # link added via __NEWSECTIONLINK__
3082 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3083 if( $mw->matchAndRemove( $text ) )
3084 $this->mOutput
->setNewSection( true );
3086 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3087 # override above conditions and always show TOC above first header
3088 $mw =& MagicWord
::get( MAG_FORCETOC
);
3089 if ($mw->matchAndRemove( $text ) ) {
3090 $this->mShowToc
= true;
3094 # Never ever show TOC if no headers
3095 if( $numMatches < 1 ) {
3099 # We need this to perform operations on the HTML
3100 $sk =& $this->mOptions
->getSkin();
3104 $sectionCount = 0; # headlineCount excluding template sections
3106 # Ugh .. the TOC should have neat indentation levels which can be
3107 # passed to the skin functions. These are determined here
3111 $sublevelCount = array();
3112 $levelCount = array();
3119 foreach( $matches[3] as $headline ) {
3121 $templatetitle = '';
3122 $templatesection = 0;
3125 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3127 $templatetitle = base64_decode($mat[1]);
3128 $templatesection = 1 +
(int)base64_decode($mat[2]);
3129 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3133 $prevlevel = $level;
3134 $prevtoclevel = $toclevel;
3136 $level = $matches[1][$headlineCount];
3138 if( $doNumberHeadings ||
$enoughToc ) {
3140 if ( $level > $prevlevel ) {
3141 # Increase TOC level
3143 $sublevelCount[$toclevel] = 0;
3144 if( $toclevel<$wgMaxTocLevel ) {
3145 $toc .= $sk->tocIndent();
3148 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3149 # Decrease TOC level, find level to jump to
3151 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3152 # Can only go down to level 1
3155 for ($i = $toclevel; $i > 0; $i--) {
3156 if ( $levelCount[$i] == $level ) {
3157 # Found last matching level
3161 elseif ( $levelCount[$i] < $level ) {
3162 # Found first matching level below current level
3168 if( $toclevel<$wgMaxTocLevel ) {
3169 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3173 # No change in level, end TOC line
3174 if( $toclevel<$wgMaxTocLevel ) {
3175 $toc .= $sk->tocLineEnd();
3179 $levelCount[$toclevel] = $level;
3181 # count number of headlines for each level
3182 @$sublevelCount[$toclevel]++
;
3184 for( $i = 1; $i <= $toclevel; $i++
) {
3185 if( !empty( $sublevelCount[$i] ) ) {
3189 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3195 # The canonized header is a version of the header text safe to use for links
3196 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3197 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3198 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3200 # Remove link placeholders by the link text.
3201 # <!--LINK number-->
3203 # link text with suffix
3204 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3205 "\$this->mLinkHolders['texts'][\$1]",
3206 $canonized_headline );
3207 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3208 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3209 $canonized_headline );
3212 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3213 $tocline = trim( $canonized_headline );
3214 # Save headline for section edit hint before it's escaped
3215 $headline_hint = trim( $canonized_headline );
3216 $canonized_headline = Sanitizer
::escapeId( $tocline );
3217 $refers[$headlineCount] = $canonized_headline;
3219 # count how many in assoc. array so we can track dupes in anchors
3220 @$refers[$canonized_headline]++
;
3221 $refcount[$headlineCount]=$refers[$canonized_headline];
3223 # Don't number the heading if it is the only one (looks silly)
3224 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3225 # the two are different if the line contains a link
3226 $headline=$numbering . ' ' . $headline;
3229 # Create the anchor for linking from the TOC to the section
3230 $anchor = $canonized_headline;
3231 if($refcount[$headlineCount] > 1 ) {
3232 $anchor .= '_' . $refcount[$headlineCount];
3234 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3235 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3237 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3238 if ( empty( $head[$headlineCount] ) ) {
3239 $head[$headlineCount] = '';
3242 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3244 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3247 # give headline the correct <h#> tag
3248 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3256 if( $toclevel<$wgMaxTocLevel ) {
3257 $toc .= $sk->tocUnindent( $toclevel - 1 );
3259 $toc = $sk->tocList( $toc );
3262 # split up and insert constructed headlines
3264 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3267 foreach( $blocks as $block ) {
3268 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3269 # This is the [edit] link that appears for the top block of text when
3270 # section editing is enabled
3272 # Disabled because it broke block formatting
3273 # For example, a bullet point in the top line
3274 # $full .= $sk->editSectionLink(0);
3277 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3278 # Top anchor now in skin
3282 if( !empty( $head[$i] ) ) {
3287 if( $this->mForceTocPosition
) {
3288 return str_replace( '<!--MWTOC-->', $toc, $full );
3295 * Return an HTML link for the "ISBN 123456" text
3298 function magicISBN( $text ) {
3299 $fname = 'Parser::magicISBN';
3300 wfProfileIn( $fname );
3302 $a = split( 'ISBN ', ' '.$text );
3303 if ( count ( $a ) < 2 ) {
3304 wfProfileOut( $fname );
3307 $text = substr( array_shift( $a ), 1);
3308 $valid = '0123456789-Xx';
3310 foreach ( $a as $x ) {
3311 # hack: don't replace inside thumbnail title/alt
3313 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3318 $isbn = $blank = '' ;
3319 while ( ' ' == $x{0} ) {
3321 $x = substr( $x, 1 );
3323 if ( $x == '' ) { # blank isbn
3324 $text .= "ISBN $blank";
3327 while ( strstr( $valid, $x{0} ) != false ) {
3329 $x = substr( $x, 1 );
3331 $num = str_replace( '-', '', $isbn );
3332 $num = str_replace( ' ', '', $num );
3333 $num = str_replace( 'x', 'X', $num );
3336 $text .= "ISBN $blank$x";
3338 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3339 $text .= '<a href="' .
3340 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3341 "\" class=\"internal\">ISBN $isbn</a>";
3345 wfProfileOut( $fname );
3350 * Return an HTML link for the "RFC 1234" text
3353 * @param string $text Text to be processed
3354 * @param string $keyword Magic keyword to use (default RFC)
3355 * @param string $urlmsg Interface message to use (default rfcurl)
3358 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3360 $valid = '0123456789';
3363 $a = split( $keyword, ' '.$text );
3364 if ( count ( $a ) < 2 ) {
3367 $text = substr( array_shift( $a ), 1);
3369 /* Check if keyword is preceed by [[.
3370 * This test is made here cause of the array_shift above
3371 * that prevent the test to be done in the foreach.
3373 if ( substr( $text, -2 ) == '[[' ) {
3377 foreach ( $a as $x ) {
3378 /* token might be empty if we have RFC RFC 1234 */
3384 # hack: don't replace inside thumbnail title/alt
3386 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3387 $text .= $keyword . $x;
3393 /** remove and save whitespaces in $blank */
3394 while ( $x{0} == ' ' ) {
3396 $x = substr( $x, 1 );
3399 /** remove and save the rfc number in $id */
3400 while ( strstr( $valid, $x{0} ) != false ) {
3402 $x = substr( $x, 1 );
3406 /* call back stripped spaces*/
3407 $text .= $keyword.$blank.$x;
3408 } elseif( $internal ) {
3410 $text .= $keyword.$id.$x;
3412 /* build the external link*/
3413 $url = wfMsg( $urlmsg, $id);
3414 $sk =& $this->mOptions
->getSkin();
3415 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3416 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3419 /* Check if the next RFC keyword is preceed by [[ */
3420 $internal = ( substr($x,-2) == '[[' );
3426 * Transform wiki markup when saving a page by doing \r\n -> \n
3427 * conversion, substitting signatures, {{subst:}} templates, etc.
3429 * @param string $text the text to transform
3430 * @param Title &$title the Title object for the current article
3431 * @param User &$user the User object describing the current user
3432 * @param ParserOptions $options parsing options
3433 * @param bool $clearState whether to clear the parser state first
3434 * @return string the altered wiki markup
3437 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3438 $this->mOptions
= $options;
3439 $this->mTitle
=& $title;
3440 $this->mOutputType
= OT_WIKI
;
3442 if ( $clearState ) {
3443 $this->clearState();
3446 $stripState = false;
3450 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3451 $text = $this->strip( $text, $stripState, true );
3452 $text = $this->pstPass2( $text, $stripState, $user );
3453 $text = $this->unstrip( $text, $stripState );
3454 $text = $this->unstripNoWiki( $text, $stripState );
3459 * Pre-save transform helper function
3462 function pstPass2( $text, &$stripState, &$user ) {
3463 global $wgContLang, $wgLocaltimezone;
3465 /* Note: This is the timestamp saved as hardcoded wikitext to
3466 * the database, we use $wgContLang here in order to give
3467 * everyone the same signature and use the default one rather
3468 * than the one selected in each user's preferences.
3470 if ( isset( $wgLocaltimezone ) ) {
3471 $oldtz = getenv( 'TZ' );
3472 putenv( 'TZ='.$wgLocaltimezone );
3474 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3475 ' (' . date( 'T' ) . ')';
3476 if ( isset( $wgLocaltimezone ) ) {
3477 putenv( 'TZ='.$oldtz );
3480 # Variable replacement
3481 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3482 $text = $this->replaceVariables( $text );
3484 # Strip out <nowiki> etc. added via replaceVariables
3485 $text = $this->strip( $text, $stripState );
3488 $sigText = $this->getUserSig( $user );
3489 $text = strtr( $text, array(
3491 '~~~~' => "$sigText $d",
3495 # Context links: [[|name]] and [[name (context)|]]
3497 global $wgLegalTitleChars;
3498 $tc = "[$wgLegalTitleChars]";
3499 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3501 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3502 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3504 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3505 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3506 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3507 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3509 $t = $this->mTitle
->getText();
3510 if ( preg_match( $conpat, $t, $m ) ) {
3513 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3514 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3515 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3517 if ( '' == $context ) {
3518 $text = preg_replace( $p2, '[[\\1]]', $text );
3520 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3523 # Trim trailing whitespace
3524 # MAG_END (__END__) tag allows for trailing
3525 # whitespace to be deliberately included
3526 $text = rtrim( $text );
3527 $mw =& MagicWord
::get( MAG_END
);
3528 $mw->matchAndRemove( $text );
3534 * Fetch the user's signature text, if any, and normalize to
3535 * validated, ready-to-insert wikitext.
3541 function getUserSig( &$user ) {
3542 $username = $user->getName();
3543 $nickname = $user->getOption( 'nickname' );
3544 $nickname = $nickname === '' ?
$username : $nickname;
3546 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3547 # Sig. might contain markup; validate this
3548 if( $this->validateSig( $nickname ) !== false ) {
3549 # Validated; clean up (if needed) and return it
3550 return $this->cleanSig( $nickname, true );
3552 # Failed to validate; fall back to the default
3553 $nickname = $username;
3554 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3558 # If we're still here, make it a link to the user page
3559 $userpage = $user->getUserPage();
3560 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3564 * Check that the user's signature contains no bad XML
3566 * @param string $text
3567 * @return mixed An expanded string, or false if invalid.
3569 function validateSig( $text ) {
3570 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3574 * Clean up signature text
3576 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3577 * 2) Substitute all transclusions
3579 * @param string $text
3580 * @param $parsing Whether we're cleaning (preferences save) or parsing
3581 * @return string Signature text
3583 function cleanSig( $text, $parsing = false ) {
3585 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3587 $substWord = MagicWord
::get( MAG_SUBST
);
3588 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3589 $substText = '{{' . $substWord->getSynonym( 0 );
3591 $text = preg_replace( $substRegex, $substText, $text );
3592 $text = preg_replace( '/~{3,5}/', '', $text );
3593 $text = $this->replaceVariables( $text );
3595 $this->clearState();
3600 * Set up some variables which are usually set up in parse()
3601 * so that an external function can call some class members with confidence
3604 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3605 $this->mTitle
=& $title;
3606 $this->mOptions
= $options;
3607 $this->mOutputType
= $outputType;
3608 if ( $clearState ) {
3609 $this->clearState();
3614 * Transform a MediaWiki message by replacing magic variables.
3616 * @param string $text the text to transform
3617 * @param ParserOptions $options options
3618 * @return string the text with variables substituted
3621 function transformMsg( $text, $options ) {
3623 static $executing = false;
3625 $fname = "Parser::transformMsg";
3627 # Guard against infinite recursion
3633 wfProfileIn($fname);
3635 $this->mTitle
= $wgTitle;
3636 $this->mOptions
= $options;
3637 $this->mOutputType
= OT_MSG
;
3638 $this->clearState();
3639 $text = $this->replaceVariables( $text );
3642 wfProfileOut($fname);
3647 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3648 * The callback should have the following form:
3649 * function myParserHook( $text, $params, &$parser ) { ... }
3651 * Transform and return $text. Use $parser for any required context, e.g. use
3652 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3656 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3657 * @param mixed $callback The callback function (and object) to use for the tag
3659 * @return The old value of the mTagHooks array associated with the hook
3661 function setHook( $tag, $callback ) {
3662 $tag = strtolower( $tag );
3663 $oldVal = @$this->mTagHooks
[$tag];
3664 $this->mTagHooks
[$tag] = $callback;
3670 * Create a function, e.g. {{sum:1|2|3}}
3671 * The callback function should have the form:
3672 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3674 * The callback may either return the text result of the function, or an array with the text
3675 * in element 0, and a number of flags in the other elements. The names of the flags are
3676 * specified in the keys. Valid flags are:
3677 * found The text returned is valid, stop processing the template. This
3679 * nowiki Wiki markup in the return value should be escaped
3680 * noparse Unsafe HTML tags should not be stripped, etc.
3681 * noargs Don't replace triple-brace arguments in the return value
3682 * isHTML The returned text is HTML, armour it against wikitext transformation
3686 * @param string $name The function name. Function names are case-insensitive.
3687 * @param mixed $callback The callback function (and object) to use
3689 * @return The old callback function for this name, if any
3691 function setFunctionHook( $name, $callback ) {
3692 $name = strtolower( $name );
3693 $oldVal = @$this->mFunctionHooks
[$name];
3694 $this->mFunctionHooks
[$name] = $callback;
3699 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3700 * Placeholders created in Skin::makeLinkObj()
3701 * Returns an array of links found, indexed by PDBK:
3705 * $options is a bit field, RLH_FOR_UPDATE to select for update
3707 function replaceLinkHolders( &$text, $options = 0 ) {
3709 global $wgOutputReplace;
3711 $fname = 'Parser::replaceLinkHolders';
3712 wfProfileIn( $fname );
3716 $sk =& $this->mOptions
->getSkin();
3717 $linkCache =& LinkCache
::singleton();
3719 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3720 wfProfileIn( $fname.'-check' );
3721 $dbr =& wfGetDB( DB_SLAVE
);
3722 $page = $dbr->tableName( 'page' );
3723 $threshold = $wgUser->getOption('stubthreshold');
3726 asort( $this->mLinkHolders
['namespaces'] );
3730 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3732 $title = $this->mLinkHolders
['titles'][$key];
3734 # Skip invalid entries.
3735 # Result will be ugly, but prevents crash.
3736 if ( is_null( $title ) ) {
3739 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3741 # Check if it's a static known link, e.g. interwiki
3742 if ( $title->isAlwaysKnown() ) {
3743 $colours[$pdbk] = 1;
3744 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3745 $colours[$pdbk] = 1;
3746 $this->mOutput
->addLink( $title, $id );
3747 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3748 $colours[$pdbk] = 0;
3750 # Not in the link cache, add it to the query
3751 if ( !isset( $current ) ) {
3753 $query = "SELECT page_id, page_namespace, page_title";
3754 if ( $threshold > 0 ) {
3755 $query .= ', page_len, page_is_redirect';
3757 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3758 } elseif ( $current != $ns ) {
3760 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3765 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3770 if ( $options & RLH_FOR_UPDATE
) {
3771 $query .= ' FOR UPDATE';
3774 $res = $dbr->query( $query, $fname );
3776 # Fetch data and form into an associative array
3777 # non-existent = broken
3780 while ( $s = $dbr->fetchObject($res) ) {
3781 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3782 $pdbk = $title->getPrefixedDBkey();
3783 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3784 $this->mOutput
->addLink( $title, $s->page_id
);
3786 if ( $threshold > 0 ) {
3787 $size = $s->page_len
;
3788 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3789 $colours[$pdbk] = 1;
3791 $colours[$pdbk] = 2;
3794 $colours[$pdbk] = 1;
3798 wfProfileOut( $fname.'-check' );
3800 # Construct search and replace arrays
3801 wfProfileIn( $fname.'-construct' );
3802 $wgOutputReplace = array();
3803 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3804 $pdbk = $pdbks[$key];
3805 $searchkey = "<!--LINK $key-->";
3806 $title = $this->mLinkHolders
['titles'][$key];
3807 if ( empty( $colours[$pdbk] ) ) {
3808 $linkCache->addBadLinkObj( $title );
3809 $colours[$pdbk] = 0;
3810 $this->mOutput
->addLink( $title, 0 );
3811 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3812 $this->mLinkHolders
['texts'][$key],
3813 $this->mLinkHolders
['queries'][$key] );
3814 } elseif ( $colours[$pdbk] == 1 ) {
3815 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3816 $this->mLinkHolders
['texts'][$key],
3817 $this->mLinkHolders
['queries'][$key] );
3818 } elseif ( $colours[$pdbk] == 2 ) {
3819 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3820 $this->mLinkHolders
['texts'][$key],
3821 $this->mLinkHolders
['queries'][$key] );
3824 wfProfileOut( $fname.'-construct' );
3827 wfProfileIn( $fname.'-replace' );
3829 $text = preg_replace_callback(
3830 '/(<!--LINK .*?-->)/',
3831 "wfOutputReplaceMatches",
3834 wfProfileOut( $fname.'-replace' );
3837 # Now process interwiki link holders
3838 # This is quite a bit simpler than internal links
3839 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3840 wfProfileIn( $fname.'-interwiki' );
3841 # Make interwiki link HTML
3842 $wgOutputReplace = array();
3843 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3844 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3845 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3848 $text = preg_replace_callback(
3849 '/<!--IWLINK (.*?)-->/',
3850 "wfOutputReplaceMatches",
3852 wfProfileOut( $fname.'-interwiki' );
3855 wfProfileOut( $fname );
3860 * Replace <!--LINK--> link placeholders with plain text of links
3861 * (not HTML-formatted).
3862 * @param string $text
3865 function replaceLinkHoldersText( $text ) {
3866 $fname = 'Parser::replaceLinkHoldersText';
3867 wfProfileIn( $fname );
3869 $text = preg_replace_callback(
3870 '/<!--(LINK|IWLINK) (.*?)-->/',
3871 array( &$this, 'replaceLinkHoldersTextCallback' ),
3874 wfProfileOut( $fname );
3879 * @param array $matches
3883 function replaceLinkHoldersTextCallback( $matches ) {
3884 $type = $matches[1];
3886 if( $type == 'LINK' ) {
3887 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3888 return $this->mLinkHolders
['texts'][$key];
3890 } elseif( $type == 'IWLINK' ) {
3891 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3892 return $this->mInterwikiLinkHolders
['texts'][$key];
3899 * Renders an image gallery from a text with one line per image.
3900 * text labels may be given by using |-style alternative text. E.g.
3901 * Image:one.jpg|The number "1"
3902 * Image:tree.jpg|A tree
3903 * given as text will return the HTML of a gallery with two images,
3904 * labeled 'The number "1"' and
3907 function renderImageGallery( $text ) {
3909 $parserOptions = new ParserOptions
;
3910 $localParser = new Parser();
3912 $ig = new ImageGallery();
3913 $ig->setShowBytes( false );
3914 $ig->setShowFilename( false );
3916 $lines = explode( "\n", $text );
3918 foreach ( $lines as $line ) {
3919 # match lines like these:
3920 # Image:someimage.jpg|This is some image
3921 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3923 if ( count( $matches ) == 0 ) {
3926 $nt =& Title
::newFromText( $matches[1] );
3927 if( is_null( $nt ) ) {
3928 # Bogus title. Ignore these so we don't bomb out later.
3931 if ( isset( $matches[3] ) ) {
3932 $label = $matches[3];
3937 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3938 $html = $pout->getText();
3940 $ig->add( new Image( $nt ), $html );
3942 # Only add real images (bug #5586)
3943 if ( $nt->getNamespace() == NS_IMAGE
) {
3944 $this->mOutput
->addImage( $nt->getDBkey() );
3947 # Register links with the parent parser
3948 foreach( $pout->getLinks() as $ns => $keys ) {
3949 foreach( $keys as $dbk => $id )
3950 $this->mOutput
->addLink( Title
::makeTitle( $ns, $dbk ), $id );
3954 return $ig->toHTML();
3958 * Parse image options text and use it to make an image
3960 function makeImage( &$nt, $options ) {
3961 global $wgUseImageResize;
3965 # Check if the options text is of the form "options|alt text"
3967 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3968 # * left no resizing, just left align. label is used for alt= only
3969 # * right same, but right aligned
3970 # * none same, but not aligned
3971 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3972 # * center center the image
3973 # * framed Keep original image size, no magnify-button.
3975 $part = explode( '|', $options);
3977 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3978 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3979 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3980 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3981 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3982 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3983 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3984 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3987 $width = $height = $framed = $thumb = false;
3988 $manual_thumb = '' ;
3990 foreach( $part as $key => $val ) {
3991 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3993 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3994 # use manually specified thumbnail
3996 $manual_thumb = $match;
3997 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3998 # remember to set an alignment, don't render immediately
4000 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4001 # remember to set an alignment, don't render immediately
4003 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4004 # remember to set an alignment, don't render immediately
4006 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4007 # remember to set an alignment, don't render immediately
4009 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4010 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4011 # $match is the image width in pixels
4012 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4013 $width = intval( $m[1] );
4014 $height = intval( $m[2] );
4016 $width = intval($match);
4018 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4024 # Strip bad stuff out of the alt text
4025 $alt = $this->replaceLinkHoldersText( $caption );
4027 # make sure there are no placeholders in thumbnail attributes
4028 # that are later expanded to html- so expand them now and
4030 $alt = $this->unstrip($alt, $this->mStripState
);
4031 $alt = Sanitizer
::stripAllTags( $alt );
4033 # Linker does the rest
4034 $sk =& $this->mOptions
->getSkin();
4035 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4039 * Set a flag in the output object indicating that the content is dynamic and
4040 * shouldn't be cached.
4042 function disableCache() {
4043 wfDebug( "Parser output marked as uncacheable.\n" );
4044 $this->mOutput
->mCacheTime
= -1;
4048 * Callback from the Sanitizer for expanding items found in HTML attribute
4049 * values, so they can be safely tested and escaped.
4050 * @param string $text
4051 * @param array $args
4055 function attributeStripCallback( &$text, $args ) {
4056 $text = $this->replaceVariables( $text, $args );
4057 $text = $this->unstripForHTML( $text );
4061 function unstripForHTML( $text ) {
4062 $text = $this->unstrip( $text, $this->mStripState
);
4063 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4071 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4072 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4073 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4079 function getTags() { return array_keys( $this->mTagHooks
); }
4085 * @package MediaWiki
4089 var $mText, # The output text
4090 $mLanguageLinks, # List of the full text of language links, in the order they appear
4091 $mCategories, # Map of category names to sort keys
4092 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4093 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4094 $mVersion, # Compatibility check
4095 $mTitleText, # title text of the chosen language variant
4096 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4097 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4098 $mImages, # DB keys of the images used, in the array key only
4099 $mExternalLinks, # External link URLs, in the key only
4100 $mHTMLtitle, # Display HTML title
4101 $mSubtitle, # Additional subtitle
4102 $mNewSection; # Show a new section link?
4104 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4105 $containsOldMagic = false, $titletext = '' )
4107 $this->mText
= $text;
4108 $this->mLanguageLinks
= $languageLinks;
4109 $this->mCategories
= $categoryLinks;
4110 $this->mContainsOldMagic
= $containsOldMagic;
4111 $this->mCacheTime
= '';
4112 $this->mVersion
= MW_PARSER_VERSION
;
4113 $this->mTitleText
= $titletext;
4114 $this->mLinks
= array();
4115 $this->mTemplates
= array();
4116 $this->mImages
= array();
4117 $this->mExternalLinks
= array();
4118 $this->mHTMLtitle
= "" ;
4119 $this->mSubtitle
= "" ;
4120 $this->mNewSection
= false;
4123 function getText() { return $this->mText
; }
4124 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4125 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4126 function &getCategories() { return $this->mCategories
; }
4127 function getCacheTime() { return $this->mCacheTime
; }
4128 function getTitleText() { return $this->mTitleText
; }
4129 function &getLinks() { return $this->mLinks
; }
4130 function &getTemplates() { return $this->mTemplates
; }
4131 function &getImages() { return $this->mImages
; }
4132 function &getExternalLinks() { return $this->mExternalLinks
; }
4134 function containsOldMagic() { return $this->mContainsOldMagic
; }
4135 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4136 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4137 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4138 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4139 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4140 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4142 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4143 function addImage( $name ) { $this->mImages
[$name] = 1; }
4144 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4145 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4147 function setNewSection( $value ) {
4148 $this->mNewSection
= (bool)$value;
4150 function getNewSection() {
4151 return (bool)$this->mNewSection
;
4154 function addLink( $title, $id ) {
4155 $ns = $title->getNamespace();
4156 $dbk = $title->getDBkey();
4157 if ( !isset( $this->mLinks
[$ns] ) ) {
4158 $this->mLinks
[$ns] = array();
4160 $this->mLinks
[$ns][$dbk] = $id;
4163 function addTemplate( $title, $id ) {
4164 $ns = $title->getNamespace();
4165 $dbk = $title->getDBkey();
4166 if ( !isset( $this->mTemplates
[$ns] ) ) {
4167 $this->mTemplates
[$ns] = array();
4169 $this->mTemplates
[$ns][$dbk] = $id;
4173 * Return true if this cached output object predates the global or
4174 * per-article cache invalidation timestamps, or if it comes from
4175 * an incompatible older version.
4177 * @param string $touched the affected article's last touched timestamp
4181 function expired( $touched ) {
4182 global $wgCacheEpoch;
4183 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4184 $this->getCacheTime() < $touched ||
4185 $this->getCacheTime() <= $wgCacheEpoch ||
4186 !isset( $this->mVersion
) ||
4187 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4192 * Set options of the Parser
4194 * @package MediaWiki
4198 # All variables are private
4199 var $mUseTeX; # Use texvc to expand <math> tags
4200 var $mUseDynamicDates; # Use DateFormatter to format dates
4201 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4202 var $mAllowExternalImages; # Allow external images inline
4203 var $mAllowExternalImagesFrom; # If not, any exception?
4204 var $mSkin; # Reference to the preferred skin
4205 var $mDateFormat; # Date format index
4206 var $mEditSection; # Create "edit section" links
4207 var $mNumberHeadings; # Automatically number headings
4208 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4209 var $mTidy; # Ask for tidy cleanup
4210 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4212 function getUseTeX() { return $this->mUseTeX
; }
4213 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4214 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4215 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4216 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4217 function &getSkin() { return $this->mSkin
; }
4218 function getDateFormat() { return $this->mDateFormat
; }
4219 function getEditSection() { return $this->mEditSection
; }
4220 function getNumberHeadings() { return $this->mNumberHeadings
; }
4221 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4222 function getTidy() { return $this->mTidy
; }
4223 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4225 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4226 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4227 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4228 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4229 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4230 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4231 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4232 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4233 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4234 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4235 function setSkin( &$x ) { $this->mSkin
=& $x; }
4236 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4238 function ParserOptions() {
4240 $this->initialiseFromUser( $wgUser );
4244 * Get parser options
4247 function newFromUser( &$user ) {
4248 $popts = new ParserOptions
;
4249 $popts->initialiseFromUser( $user );
4253 /** Get user options */
4254 function initialiseFromUser( &$userInput ) {
4255 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4256 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4257 $fname = 'ParserOptions::initialiseFromUser';
4258 wfProfileIn( $fname );
4259 if ( !$userInput ) {
4261 $user->setLoaded( true );
4263 $user =& $userInput;
4266 $this->mUseTeX
= $wgUseTeX;
4267 $this->mUseDynamicDates
= $wgUseDynamicDates;
4268 $this->mInterwikiMagic
= $wgInterwikiMagic;
4269 $this->mAllowExternalImages
= $wgAllowExternalImages;
4270 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4271 wfProfileIn( $fname.'-skin' );
4272 $this->mSkin
=& $user->getSkin();
4273 wfProfileOut( $fname.'-skin' );
4274 $this->mDateFormat
= $user->getOption( 'date' );
4275 $this->mEditSection
= true;
4276 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4277 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4278 $this->mTidy
= false;
4279 $this->mInterfaceMessage
= false;
4280 wfProfileOut( $fname );
4285 * Callback function used by Parser::replaceLinkHolders()
4286 * to substitute link placeholders.
4288 function &wfOutputReplaceMatches( $matches ) {
4289 global $wgOutputReplace;
4290 return $wgOutputReplace[$matches[1]];
4294 * Return the total number of articles
4296 function wfNumberOfArticles() {
4297 global $wgNumberOfArticles;
4300 return $wgNumberOfArticles;
4304 * Return the number of files
4306 function wfNumberOfFiles() {
4307 $fname = 'wfNumberOfFiles';
4309 wfProfileIn( $fname );
4310 $dbr =& wfGetDB( DB_SLAVE
);
4311 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4312 wfProfileOut( $fname );
4318 * Return the number of user accounts
4321 function wfNumberOfUsers() {
4322 wfProfileIn( 'wfNumberOfUsers' );
4323 $dbr =& wfGetDB( DB_SLAVE
);
4324 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4325 wfProfileOut( 'wfNumberOfUsers' );
4330 * Return the total number of pages
4333 function wfNumberOfPages() {
4334 wfProfileIn( 'wfNumberOfPages' );
4335 $dbr =& wfGetDB( DB_SLAVE
);
4336 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4337 wfProfileOut( 'wfNumberOfPages' );
4342 * Get various statistics from the database
4345 function wfLoadSiteStats() {
4346 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4347 $fname = 'wfLoadSiteStats';
4349 if ( -1 != $wgNumberOfArticles ) return;
4350 $dbr =& wfGetDB( DB_SLAVE
);
4351 $s = $dbr->selectRow( 'site_stats',
4352 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4353 array( 'ss_row_id' => 1 ), $fname
4356 if ( $s === false ) {
4359 $wgTotalViews = $s->ss_total_views
;
4360 $wgTotalEdits = $s->ss_total_edits
;
4361 $wgNumberOfArticles = $s->ss_good_articles
;
4367 * Basically replacing " > and < with HTML entities ( ", >, <)
4369 * @param $in String: text that might contain HTML tags.
4370 * @return string Escaped string
4372 function wfEscapeHTMLTagsOnly( $in ) {
4374 array( '"', '>', '<' ),
4375 array( '"', '>', '<' ),