3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.1' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
96 var $mTagHooks, $mFunctionHooks;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
123 $this->mFunctionHooks
= array();
132 function clearState() {
133 $this->mOutput
= new ParserOutput
;
134 $this->mAutonumber
= 0;
135 $this->mLastSection
= '';
136 $this->mDTopen
= false;
137 $this->mVariables
= false;
138 $this->mIncludeCount
= array();
139 $this->mStripState
= array();
140 $this->mArgStack
= array();
141 $this->mInPre
= false;
142 $this->mInterwikiLinkHolders
= array(
146 $this->mLinkHolders
= array(
147 'namespaces' => array(),
149 'queries' => array(),
153 $this->mRevisionId
= null;
156 * Prefix for temporary replacement strings for the multipass parser.
157 * \x07 should never appear in input as it's disallowed in XML.
158 * Using it at the front also gives us a little extra robustness
159 * since it shouldn't match when butted up against identifier-like
162 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
164 # Clear these on every parse, bug 4549
165 $this->mTemplates
= array();
166 $this->mTemplatePath
= array();
168 $this->mShowToc
= true;
169 $this->mForceTocPosition
= false;
171 wfRunHooks( 'ParserClearState', array( &$this ) );
175 * Accessor for mUniqPrefix.
179 function UniqPrefix() {
180 return $this->mUniqPrefix
;
184 * Convert wikitext to HTML
185 * Do not call this function recursively.
188 * @param string $text Text we want to parse
189 * @param Title &$title A title object
190 * @param array $options
191 * @param boolean $linestart
192 * @param boolean $clearState
193 * @param int $revid number to pass in {{REVISIONID}}
194 * @return ParserOutput a ParserOutput
196 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
198 * First pass--just handle <nowiki> sections, pass the rest off
199 * to internalParse() which does all the real work.
202 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
203 $fname = 'Parser::parse';
204 wfProfileIn( $fname );
210 $this->mOptions
= $options;
211 $this->mTitle
=& $title;
212 $this->mRevisionId
= $revid;
213 $this->mOutputType
= OT_HTML
;
215 //$text = $this->strip( $text, $this->mStripState );
216 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
217 $x =& $this->mStripState
;
219 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
220 $text = $this->strip( $text, $x );
221 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
223 # Hook to suspend the parser in this state
224 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
225 wfProfileOut( $fname );
229 $text = $this->internalParse( $text );
231 $text = $this->unstrip( $text, $this->mStripState
);
233 # Clean up special characters, only run once, next-to-last before doBlockLevels
235 # french spaces, last one Guillemet-left
236 # only if there is something before the space
237 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
238 # french spaces, Guillemet-right
239 '/(\\302\\253) /' => '\\1 ',
240 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
242 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
245 $text = $this->doBlockLevels( $text, $linestart );
247 $this->replaceLinkHolders( $text );
249 # the position of the parserConvert() call should not be changed. it
250 # assumes that the links are all replaced and the only thing left
251 # is the <nowiki> mark.
252 # Side-effects: this calls $this->mOutput->setTitleText()
253 $text = $wgContLang->parserConvert( $text, $this );
255 $text = $this->unstripNoWiki( $text, $this->mStripState
);
257 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
259 $text = Sanitizer
::normalizeCharReferences( $text );
261 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
262 $text = Parser
::tidy($text);
264 # attempt to sanitize at least some nesting problems
265 # (bug #2702 and quite a few others)
267 # ''Something [http://www.cool.com cool''] -->
268 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
269 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
270 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
271 # fix up an anchor inside another anchor, only
272 # at least for a single single nested link (bug 3695)
273 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
274 '\\1\\2</a>\\3</a>\\1\\4</a>',
275 # fix div inside inline elements- doBlockLevels won't wrap a line which
276 # contains a div, so fix it up here; replace
277 # div with escaped text
278 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
279 '\\1\\3<div\\5>\\6</div>\\8\\9',
280 # remove empty italic or bold tag pairs, some
281 # introduced by rules above
282 '/<([bi])><\/\\1>/' => ''
285 $text = preg_replace(
286 array_keys( $tidyregs ),
287 array_values( $tidyregs ),
291 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
293 $this->mOutput
->setText( $text );
294 wfProfileOut( $fname );
296 return $this->mOutput
;
300 * Get a random string
305 function getRandomString() {
306 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
309 function &getTitle() { return $this->mTitle
; }
310 function getOptions() { return $this->mOptions
; }
313 * Replaces all occurrences of <$tag>content</$tag> in the text
314 * with a random marker and returns the new text. the output parameter
315 * $content will be an associative array filled with data on the form
316 * $unique_marker => content.
318 * If $content is already set, the additional entries will be appended
319 * If $tag is set to STRIP_COMMENTS, the function will extract
320 * <!-- HTML comments -->
325 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
326 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
341 if( $tag == STRIP_COMMENTS
) {
345 $start = "/<$tag(\\s+[^>]*|\\s*\/?)>/i";
346 $end = "/<\\/$tag\\s*>/i";
349 while ( '' != $text ) {
350 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
352 if( count( $p ) < 3 ) {
358 // If $attributes ends with '/', we have an empty element tag, <tag />
359 if( $tag != STRIP_COMMENTS
&& substr( $attributes, -1 ) == '/' ) {
360 $attributes = substr( $attributes, 0, -1);
366 $marker = $rnd . sprintf('%08X', $n++
);
367 $stripped .= $marker;
369 $tags[$marker] = "<$tag$attributes$empty>";
370 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
372 if ( $empty === '/' ) {
373 // Empty element tag, <tag />
374 $content[$marker] = null;
377 $q = preg_split( $end, $inside, 2 );
378 $content[$marker] = $q[0];
379 if( count( $q ) < 2 ) {
380 # No end tag -- let it run out to the end of the text.
391 * Wrapper function for extractTagsAndParams
392 * for cases where $tags and $params isn't needed
393 * i.e. where tags will never have params, like <nowiki>
398 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
399 $dummy_tags = array();
400 $dummy_params = array();
402 return Parser
::extractTagsAndParams( $tag, $text, $content,
403 $dummy_tags, $dummy_params, $uniq_prefix );
407 * Strips and renders nowiki, pre, math, hiero
408 * If $render is set, performs necessary rendering operations on plugins
409 * Returns the text, and fills an array with data needed in unstrip()
410 * If the $state is already a valid strip state, it adds to the state
412 * @param bool $stripcomments when set, HTML comments <!-- like this -->
413 * will be stripped in addition to other tags. This is important
414 * for section editing, where these comments cause confusion when
415 * counting the sections in the wikisource
419 function strip( $text, &$state, $stripcomments = false ) {
420 $render = ($this->mOutputType
== OT_HTML
);
421 $html_content = array();
422 $nowiki_content = array();
423 $math_content = array();
424 $pre_content = array();
425 $comment_content = array();
426 $ext_content = array();
428 $ext_params = array();
429 $gallery_content = array();
431 # Replace any instances of the placeholders
432 $uniq_prefix = $this->mUniqPrefix
;
433 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
438 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
439 foreach( $html_content as $marker => $content ) {
441 # Raw and unchecked for validity.
442 $state['html'][$marker] = $content;
444 $state['html'][$marker] = '<html>'.$content.'</html>';
450 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
451 foreach( $nowiki_content as $marker => $content ) {
453 $state['nowiki'][$marker] = wfEscapeHTMLTagsOnly( $content );
455 $state['nowiki'][$marker] = '<nowiki>'.$content.'</nowiki>';
460 if( $this->mOptions
->getUseTeX() ) {
461 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
462 foreach( $math_content as $marker => $content ){
464 $state['math'][$marker] = renderMath( $content );
466 $state['math'][$marker] = '<math>'.$content.'</math>';
472 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
473 foreach( $pre_content as $marker => $content ){
475 $state['pre'][$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
477 $state['pre'][$marker] = '<pre>'.$content.'</pre>';
482 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
483 foreach( $gallery_content as $marker => $content ) {
484 require_once( 'ImageGallery.php' );
486 $state['gallery'][$marker] = $this->renderImageGallery( $content );
488 $state['gallery'][$marker] = '<gallery>'.$content.'</gallery>';
493 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
494 foreach( $comment_content as $marker => $content ){
495 $comment_content[$marker] = '<!--'.$content.'-->';
499 foreach ( $this->mTagHooks
as $tag => $callback ) {
500 $ext_content[$tag] = array();
501 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
502 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
503 foreach( $ext_content[$tag] as $marker => $content ) {
504 $full_tag = $ext_tags[$tag][$marker];
505 $params = $ext_params[$tag][$marker];
507 $state[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, $this ) );
509 if ( is_null( $content ) ) {
511 $state[$tag][$marker] = $full_tag;
513 $state[$tag][$marker] = "$full_tag$content</$tag>";
519 # Unstrip comments unless explicitly told otherwise.
520 # (The comments are always stripped prior to this point, so as to
521 # not invoke any extension tags / parser hooks contained within
523 if ( !$stripcomments ) {
524 $tempstate = array( 'comment' => $comment_content );
525 $text = $this->unstrip( $text, $tempstate );
526 $comment_content = array();
528 if( !isset( $state['comment'] ) ) {
529 $state['comment'] = array();
531 $state['comment'] +
= $comment_content;
538 * restores pre, math, and hiero removed by strip()
540 * always call unstripNoWiki() after this one
543 function unstrip( $text, &$state ) {
544 if ( !is_array( $state ) ) {
548 # Must expand in reverse order, otherwise nested tags will be corrupted
549 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
550 if( $tag != 'nowiki' && $tag != 'html' ) {
551 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
552 $text = str_replace( $uniq, $content, $text );
561 * always call this after unstrip() to preserve the order
565 function unstripNoWiki( $text, &$state ) {
566 if ( !is_array( $state ) ) {
570 # Must expand in reverse order, otherwise nested tags will be corrupted
571 if( isset( $state['nowiki'] ) )
572 foreach( array_reverse( $state['nowiki'], true ) as $uniq => $content ) {
573 $text = str_replace( $uniq, $content, $text );
577 if ($wgRawHtml && isset( $state['html'] ) ) {
578 foreach( array_reverse( $state['html'], true ) as $uniq => $content ) {
579 $text = str_replace( $uniq, $content, $text );
587 * Add an item to the strip state
588 * Returns the unique tag which must be inserted into the stripped text
589 * The tag will be replaced with the original text in unstrip()
593 function insertStripItem( $text, &$state ) {
594 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
601 'comment' => array(),
602 'gallery' => array(),
605 $state['item'][$rnd] = $text;
610 * Interface with html tidy, used if $wgUseTidy = true.
611 * If tidy isn't able to correct the markup, the original will be
612 * returned in all its glory with a warning comment appended.
614 * Either the external tidy program or the in-process tidy extension
615 * will be used depending on availability. Override the default
616 * $wgTidyInternal setting to disable the internal if it's not working.
618 * @param string $text Hideous HTML input
619 * @return string Corrected HTML output
623 function tidy( $text ) {
624 global $wgTidyInternal;
625 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
626 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
627 '<head><title>test</title></head><body>'.$text.'</body></html>';
628 if( $wgTidyInternal ) {
629 $correctedtext = Parser
::internalTidy( $wrappedtext );
631 $correctedtext = Parser
::externalTidy( $wrappedtext );
633 if( is_null( $correctedtext ) ) {
634 wfDebug( "Tidy error detected!\n" );
635 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
637 return $correctedtext;
641 * Spawn an external HTML tidy process and get corrected markup back from it.
646 function externalTidy( $text ) {
647 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
648 $fname = 'Parser::externalTidy';
649 wfProfileIn( $fname );
654 $descriptorspec = array(
655 0 => array('pipe', 'r'),
656 1 => array('pipe', 'w'),
657 2 => array('file', '/dev/null', 'a')
660 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
661 if (is_resource($process)) {
662 // Theoretically, this style of communication could cause a deadlock
663 // here. If the stdout buffer fills up, then writes to stdin could
664 // block. This doesn't appear to happen with tidy, because tidy only
665 // writes to stdout after it's finished reading from stdin. Search
666 // for tidyParseStdin and tidySaveStdout in console/tidy.c
667 fwrite($pipes[0], $text);
669 while (!feof($pipes[1])) {
670 $cleansource .= fgets($pipes[1], 1024);
673 proc_close($process);
676 wfProfileOut( $fname );
678 if( $cleansource == '' && $text != '') {
679 // Some kind of error happened, so we couldn't get the corrected text.
680 // Just give up; we'll use the source text and append a warning.
688 * Use the HTML tidy PECL extension to use the tidy library in-process,
689 * saving the overhead of spawning a new process. Currently written to
690 * the PHP 4.3.x version of the extension, may not work on PHP 5.
692 * 'pear install tidy' should be able to compile the extension module.
697 function internalTidy( $text ) {
699 $fname = 'Parser::internalTidy';
700 wfProfileIn( $fname );
702 tidy_load_config( $wgTidyConf );
703 tidy_set_encoding( 'utf8' );
704 tidy_parse_string( $text );
706 if( tidy_get_status() == 2 ) {
707 // 2 is magic number for fatal error
708 // http://www.php.net/manual/en/function.tidy-get-status.php
711 $cleansource = tidy_get_output();
713 wfProfileOut( $fname );
718 * parse the wiki syntax used to render tables
722 function doTableStuff ( $t ) {
723 $fname = 'Parser::doTableStuff';
724 wfProfileIn( $fname );
726 $t = explode ( "\n" , $t ) ;
727 $td = array () ; # Is currently a td tag open?
728 $ltd = array () ; # Was it TD or TH?
729 $tr = array () ; # Is currently a tr tag open?
730 $ltr = array () ; # tr attributes
731 $has_opened_tr = array(); # Did this table open a <tr> element?
732 $indent_level = 0; # indent level of the table
733 foreach ( $t AS $k => $x )
736 $fc = substr ( $x , 0 , 1 ) ;
737 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
738 $indent_level = strlen( $matches[1] );
740 $attributes = $this->unstripForHTML( $matches[2] );
742 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
743 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
744 array_push ( $td , false ) ;
745 array_push ( $ltd , '' ) ;
746 array_push ( $tr , false ) ;
747 array_push ( $ltr , '' ) ;
748 array_push ( $has_opened_tr, false );
750 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
751 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
752 $z = "</table>" . substr ( $x , 2);
753 $l = array_pop ( $ltd ) ;
754 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
755 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
756 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
758 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
760 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
761 $x = substr ( $x , 1 ) ;
762 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
764 $l = array_pop ( $ltd ) ;
765 array_pop ( $has_opened_tr );
766 array_push ( $has_opened_tr , true ) ;
767 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
768 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
771 array_push ( $tr , false ) ;
772 array_push ( $td , false ) ;
773 array_push ( $ltd , '' ) ;
774 $attributes = $this->unstripForHTML( $x );
775 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
777 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
779 if ( '|+' == substr ( $x , 0 , 2 ) ) {
781 $x = substr ( $x , 1 ) ;
783 $after = substr ( $x , 1 ) ;
784 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
786 // Split up multiple cells on the same line.
787 // FIXME: This can result in improper nesting of tags processed
788 // by earlier parser steps, but should avoid splitting up eg
789 // attribute values containing literal "||".
790 $after = wfExplodeMarkup( '||', $after );
794 # Loop through each table cell
795 foreach ( $after AS $theline )
800 $tra = array_pop ( $ltr ) ;
801 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
802 array_push ( $tr , true ) ;
803 array_push ( $ltr , '' ) ;
804 array_pop ( $has_opened_tr );
805 array_push ( $has_opened_tr , true ) ;
808 $l = array_pop ( $ltd ) ;
809 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
810 if ( $fc == '|' ) $l = 'td' ;
811 else if ( $fc == '!' ) $l = 'th' ;
812 else if ( $fc == '+' ) $l = 'caption' ;
814 array_push ( $ltd , $l ) ;
817 $y = explode ( '|' , $theline , 2 ) ;
818 # Note that a '|' inside an invalid link should not
819 # be mistaken as delimiting cell parameters
820 if ( strpos( $y[0], '[[' ) !== false ) {
821 $y = array ($theline);
823 if ( count ( $y ) == 1 )
824 $y = "{$z}<{$l}>{$y[0]}" ;
826 $attributes = $this->unstripForHTML( $y[0] );
827 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
830 array_push ( $td , true ) ;
835 # Closing open td, tr && table
836 while ( count ( $td ) > 0 )
838 $l = array_pop ( $ltd ) ;
839 if ( array_pop ( $td ) ) $t[] = '</td>' ;
840 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
841 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
845 $t = implode ( "\n" , $t ) ;
846 # special case: don't return empty table
847 if($t == "<table>\n<tr><td></td></tr>\n</table>")
849 wfProfileOut( $fname );
854 * Helper function for parse() that transforms wiki markup into
855 * HTML. Only called for $mOutputType == OT_HTML.
859 function internalParse( $text ) {
862 $fname = 'Parser::internalParse';
863 wfProfileIn( $fname );
865 # Remove <noinclude> tags and <includeonly> sections
866 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
867 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
868 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
870 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
872 $text = $this->replaceVariables( $text, $args );
874 // Tables need to come after variable replacement for things to work
875 // properly; putting them before other transformations should keep
876 // exciting things like link expansions from showing up in surprising
878 $text = $this->doTableStuff( $text );
880 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
882 $text = $this->stripToc( $text );
883 $text = $this->doHeadings( $text );
884 if($this->mOptions
->getUseDynamicDates()) {
885 $df =& DateFormatter
::getInstance();
886 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
888 $text = $this->doAllQuotes( $text );
889 $text = $this->replaceInternalLinks( $text );
890 $text = $this->replaceExternalLinks( $text );
892 # replaceInternalLinks may sometimes leave behind
893 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
894 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
896 $text = $this->doMagicLinks( $text );
897 $text = $this->formatHeadings( $text, $isMain );
899 wfProfileOut( $fname );
904 * Replace special strings like "ISBN xxx" and "RFC xxx" with
905 * magic external links.
909 function &doMagicLinks( &$text ) {
910 $text = $this->magicISBN( $text );
911 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
912 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
917 * Parse headers and return html
921 function doHeadings( $text ) {
922 $fname = 'Parser::doHeadings';
923 wfProfileIn( $fname );
924 for ( $i = 6; $i >= 1; --$i ) {
925 $h = str_repeat( '=', $i );
926 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
927 "<h{$i}>\\1</h{$i}>\\2", $text );
929 wfProfileOut( $fname );
934 * Replace single quotes with HTML markup
936 * @return string the altered text
938 function doAllQuotes( $text ) {
939 $fname = 'Parser::doAllQuotes';
940 wfProfileIn( $fname );
942 $lines = explode( "\n", $text );
943 foreach ( $lines as $line ) {
944 $outtext .= $this->doQuotes ( $line ) . "\n";
946 $outtext = substr($outtext, 0,-1);
947 wfProfileOut( $fname );
952 * Helper function for doAllQuotes()
955 function doQuotes( $text ) {
956 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
957 if ( count( $arr ) == 1 )
961 # First, do some preliminary work. This may shift some apostrophes from
962 # being mark-up to being text. It also counts the number of occurrences
963 # of bold and italics mark-ups.
967 foreach ( $arr as $r )
969 if ( ( $i %
2 ) == 1 )
971 # If there are ever four apostrophes, assume the first is supposed to
972 # be text, and the remaining three constitute mark-up for bold text.
973 if ( strlen( $arr[$i] ) == 4 )
978 # If there are more than 5 apostrophes in a row, assume they're all
979 # text except for the last 5.
980 else if ( strlen( $arr[$i] ) > 5 )
982 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
985 # Count the number of occurrences of bold and italics mark-ups.
986 # We are not counting sequences of five apostrophes.
987 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
988 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
989 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
994 # If there is an odd number of both bold and italics, it is likely
995 # that one of the bold ones was meant to be an apostrophe followed
996 # by italics. Which one we cannot know for certain, but it is more
997 # likely to be one that has a single-letter word before it.
998 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1001 $firstsingleletterword = -1;
1002 $firstmultiletterword = -1;
1004 foreach ( $arr as $r )
1006 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1008 $x1 = substr ($arr[$i-1], -1);
1009 $x2 = substr ($arr[$i-1], -2, 1);
1011 if ($firstspace == -1) $firstspace = $i;
1012 } else if ($x2 == ' ') {
1013 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1015 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1021 # If there is a single-letter word, use it!
1022 if ($firstsingleletterword > -1)
1024 $arr [ $firstsingleletterword ] = "''";
1025 $arr [ $firstsingleletterword-1 ] .= "'";
1027 # If not, but there's a multi-letter word, use that one.
1028 else if ($firstmultiletterword > -1)
1030 $arr [ $firstmultiletterword ] = "''";
1031 $arr [ $firstmultiletterword-1 ] .= "'";
1033 # ... otherwise use the first one that has neither.
1034 # (notice that it is possible for all three to be -1 if, for example,
1035 # there is only one pentuple-apostrophe in the line)
1036 else if ($firstspace > -1)
1038 $arr [ $firstspace ] = "''";
1039 $arr [ $firstspace-1 ] .= "'";
1043 # Now let's actually convert our apostrophic mush to HTML!
1048 foreach ($arr as $r)
1052 if ($state == 'both')
1059 if (strlen ($r) == 2)
1062 { $output .= '</i>'; $state = ''; }
1063 else if ($state == 'bi')
1064 { $output .= '</i>'; $state = 'b'; }
1065 else if ($state == 'ib')
1066 { $output .= '</b></i><b>'; $state = 'b'; }
1067 else if ($state == 'both')
1068 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1069 else # $state can be 'b' or ''
1070 { $output .= '<i>'; $state .= 'i'; }
1072 else if (strlen ($r) == 3)
1075 { $output .= '</b>'; $state = ''; }
1076 else if ($state == 'bi')
1077 { $output .= '</i></b><i>'; $state = 'i'; }
1078 else if ($state == 'ib')
1079 { $output .= '</b>'; $state = 'i'; }
1080 else if ($state == 'both')
1081 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1082 else # $state can be 'i' or ''
1083 { $output .= '<b>'; $state .= 'b'; }
1085 else if (strlen ($r) == 5)
1088 { $output .= '</b><i>'; $state = 'i'; }
1089 else if ($state == 'i')
1090 { $output .= '</i><b>'; $state = 'b'; }
1091 else if ($state == 'bi')
1092 { $output .= '</i></b>'; $state = ''; }
1093 else if ($state == 'ib')
1094 { $output .= '</b></i>'; $state = ''; }
1095 else if ($state == 'both')
1096 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1097 else # ($state == '')
1098 { $buffer = ''; $state = 'both'; }
1103 # Now close all remaining tags. Notice that the order is important.
1104 if ($state == 'b' ||
$state == 'ib')
1106 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1110 if ($state == 'both')
1111 $output .= '<b><i>'.$buffer.'</i></b>';
1117 * Replace external links
1119 * Note: this is all very hackish and the order of execution matters a lot.
1120 * Make sure to run maintenance/parserTests.php if you change this code.
1124 function replaceExternalLinks( $text ) {
1126 $fname = 'Parser::replaceExternalLinks';
1127 wfProfileIn( $fname );
1129 $sk =& $this->mOptions
->getSkin();
1131 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1133 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1136 while ( $i<count( $bits ) ) {
1138 $protocol = $bits[$i++
];
1139 $text = $bits[$i++
];
1140 $trail = $bits[$i++
];
1142 # The characters '<' and '>' (which were escaped by
1143 # removeHTMLtags()) should not be included in
1144 # URLs, per RFC 2396.
1145 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1146 $text = substr($url, $m2[0][1]) . ' ' . $text;
1147 $url = substr($url, 0, $m2[0][1]);
1150 # If the link text is an image URL, replace it with an <img> tag
1151 # This happened by accident in the original parser, but some people used it extensively
1152 $img = $this->maybeMakeExternalImage( $text );
1153 if ( $img !== false ) {
1159 # Set linktype for CSS - if URL==text, link is essentially free
1160 $linktype = ($text == $url) ?
'free' : 'text';
1162 # No link text, e.g. [http://domain.tld/some.link]
1163 if ( $text == '' ) {
1164 # Autonumber if allowed. See bug #5918
1165 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1166 $text = '[' . ++
$this->mAutonumber
. ']';
1167 $linktype = 'autonumber';
1169 # Otherwise just use the URL
1170 $text = htmlspecialchars( $url );
1174 # Have link text, e.g. [http://domain.tld/some.link text]s
1176 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1179 $text = $wgContLang->markNoConversion($text);
1181 # Normalize any HTML entities in input. They will be
1182 # re-escaped by makeExternalLink().
1183 $url = Sanitizer
::decodeCharReferences( $url );
1185 # Process the trail (i.e. everything after this link up until start of the next link),
1186 # replacing any non-bracketed links
1187 $trail = $this->replaceFreeExternalLinks( $trail );
1189 # Use the encoded URL
1190 # This means that users can paste URLs directly into the text
1191 # Funny characters like ö aren't valid in URLs anyway
1192 # This was changed in August 2004
1193 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1195 # Register link in the output object.
1196 # Replace unnecessary URL escape codes with the referenced character
1197 # This prevents spammers from hiding links from the filters
1198 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1199 $this->mOutput
->addExternalLink( $pasteurized );
1202 wfProfileOut( $fname );
1207 * Replace anything that looks like a URL with a link
1210 function replaceFreeExternalLinks( $text ) {
1212 $fname = 'Parser::replaceFreeExternalLinks';
1213 wfProfileIn( $fname );
1215 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1216 $s = array_shift( $bits );
1219 $sk =& $this->mOptions
->getSkin();
1221 while ( $i < count( $bits ) ){
1222 $protocol = $bits[$i++
];
1223 $remainder = $bits[$i++
];
1225 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1226 # Found some characters after the protocol that look promising
1227 $url = $protocol . $m[1];
1230 # special case: handle urls as url args:
1231 # http://www.example.com/foo?=http://www.example.com/bar
1232 if(strlen($trail) == 0 &&
1234 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1235 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1238 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1243 # The characters '<' and '>' (which were escaped by
1244 # removeHTMLtags()) should not be included in
1245 # URLs, per RFC 2396.
1246 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1247 $trail = substr($url, $m2[0][1]) . $trail;
1248 $url = substr($url, 0, $m2[0][1]);
1251 # Move trailing punctuation to $trail
1253 # If there is no left bracket, then consider right brackets fair game too
1254 if ( strpos( $url, '(' ) === false ) {
1258 $numSepChars = strspn( strrev( $url ), $sep );
1259 if ( $numSepChars ) {
1260 $trail = substr( $url, -$numSepChars ) . $trail;
1261 $url = substr( $url, 0, -$numSepChars );
1264 # Normalize any HTML entities in input. They will be
1265 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1266 $url = Sanitizer
::decodeCharReferences( $url );
1268 # Is this an external image?
1269 $text = $this->maybeMakeExternalImage( $url );
1270 if ( $text === false ) {
1271 # Not an image, make a link
1272 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1273 # Register it in the output object...
1274 # Replace unnecessary URL escape codes with their equivalent characters
1275 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1276 $this->mOutput
->addExternalLink( $pasteurized );
1278 $s .= $text . $trail;
1280 $s .= $protocol . $remainder;
1283 wfProfileOut( $fname );
1288 * Replace unusual URL escape codes with their equivalent characters
1292 * @fixme This can merge genuinely required bits in the path or query string,
1293 * breaking legit URLs. A proper fix would treat the various parts of
1294 * the URL differently; as a workaround, just use the output for
1295 * statistical records, not for actual linking/output.
1297 function replaceUnusualEscapes( $url ) {
1298 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1299 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1303 * Callback function used in replaceUnusualEscapes().
1304 * Replaces unusual URL escape codes with their equivalent character
1308 function replaceUnusualEscapesCallback( $matches ) {
1309 $char = urldecode( $matches[0] );
1310 $ord = ord( $char );
1311 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1312 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1313 // No, shouldn't be escaped
1316 // Yes, leave it escaped
1322 * make an image if it's allowed, either through the global
1323 * option or through the exception
1326 function maybeMakeExternalImage( $url ) {
1327 $sk =& $this->mOptions
->getSkin();
1328 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1329 $imagesexception = !empty($imagesfrom);
1331 if ( $this->mOptions
->getAllowExternalImages()
1332 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1333 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1335 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1342 * Process [[ ]] wikilinks
1346 function replaceInternalLinks( $s ) {
1348 static $fname = 'Parser::replaceInternalLinks' ;
1350 wfProfileIn( $fname );
1352 wfProfileIn( $fname.'-setup' );
1354 # the % is needed to support urlencoded titles as well
1355 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1357 $sk =& $this->mOptions
->getSkin();
1359 #split the entire text string on occurences of [[
1360 $a = explode( '[[', ' ' . $s );
1361 #get the first element (all text up to first [[), and remove the space we added
1362 $s = array_shift( $a );
1363 $s = substr( $s, 1 );
1365 # Match a link having the form [[namespace:link|alternate]]trail
1367 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1368 # Match cases where there is no "]]", which might still be images
1369 static $e1_img = FALSE;
1370 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1371 # Match the end of a line for a word that's not followed by whitespace,
1372 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1373 $e2 = wfMsgForContent( 'linkprefix' );
1375 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1377 if( is_null( $this->mTitle
) ) {
1378 wfDebugDieBacktrace( 'nooo' );
1380 $nottalk = !$this->mTitle
->isTalkPage();
1382 if ( $useLinkPrefixExtension ) {
1383 if ( preg_match( $e2, $s, $m ) ) {
1384 $first_prefix = $m[2];
1386 $first_prefix = false;
1392 $selflink = $this->mTitle
->getPrefixedText();
1393 wfProfileOut( $fname.'-setup' );
1395 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1396 $useSubpages = $this->areSubpagesAllowed();
1398 # Loop for each link
1399 for ($k = 0; isset( $a[$k] ); $k++
) {
1401 if ( $useLinkPrefixExtension ) {
1402 wfProfileIn( $fname.'-prefixhandling' );
1403 if ( preg_match( $e2, $s, $m ) ) {
1411 $prefix = $first_prefix;
1412 $first_prefix = false;
1414 wfProfileOut( $fname.'-prefixhandling' );
1417 $might_be_img = false;
1419 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1421 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1422 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1423 # the real problem is with the $e1 regex
1426 # Still some problems for cases where the ] is meant to be outside punctuation,
1427 # and no image is in sight. See bug 2095.
1430 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1431 strpos($text, '[') !== false
1434 $text .= ']'; # so that replaceExternalLinks($text) works later
1437 # fix up urlencoded title texts
1438 if(preg_match('/%/', $m[1] ))
1439 # Should anchors '#' also be rejected?
1440 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1442 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1443 $might_be_img = true;
1445 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1447 } else { # Invalid form; output directly
1448 $s .= $prefix . '[[' . $line ;
1452 # Don't allow internal links to pages containing
1453 # PROTO: where PROTO is a valid URL protocol; these
1454 # should be external links.
1455 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1456 $s .= $prefix . '[[' . $line ;
1460 # Make subpage if necessary
1461 if( $useSubpages ) {
1462 $link = $this->maybeDoSubpageLink( $m[1], $text );
1467 $noforce = (substr($m[1], 0, 1) != ':');
1469 # Strip off leading ':'
1470 $link = substr($link, 1);
1473 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1475 $s .= $prefix . '[[' . $line;
1479 #check other language variants of the link
1480 #if the article does not exist
1481 if( $checkVariantLink
1482 && $nt->getArticleID() == 0 ) {
1483 $wgContLang->findVariantLink($link, $nt);
1486 $ns = $nt->getNamespace();
1487 $iw = $nt->getInterWiki();
1489 if ($might_be_img) { # if this is actually an invalid link
1490 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1492 while (isset ($a[$k+
1]) ) {
1493 #look at the next 'line' to see if we can close it there
1494 $spliced = array_splice( $a, $k +
1, 1 );
1495 $next_line = array_shift( $spliced );
1496 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1497 # the first ]] closes the inner link, the second the image
1499 $text .= '[[' . $m[1];
1502 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1503 #if there's exactly one ]] that's fine, we'll keep looking
1504 $text .= '[[' . $m[0];
1506 #if $next_line is invalid too, we need look no further
1507 $text .= '[[' . $next_line;
1512 # we couldn't find the end of this imageLink, so output it raw
1513 #but don't ignore what might be perfectly normal links in the text we've examined
1514 $text = $this->replaceInternalLinks($text);
1515 $s .= $prefix . '[[' . $link . '|' . $text;
1516 # note: no $trail, because without an end, there *is* no trail
1519 } else { #it's not an image, so output it raw
1520 $s .= $prefix . '[[' . $link . '|' . $text;
1521 # note: no $trail, because without an end, there *is* no trail
1526 $wasblank = ( '' == $text );
1527 if( $wasblank ) $text = $link;
1530 # Link not escaped by : , create the various objects
1534 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1535 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1536 $s = rtrim($s . "\n");
1537 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1541 if ( $ns == NS_IMAGE
) {
1542 wfProfileIn( "$fname-image" );
1543 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1544 # recursively parse links inside the image caption
1545 # actually, this will parse them in any other parameters, too,
1546 # but it might be hard to fix that, and it doesn't matter ATM
1547 $text = $this->replaceExternalLinks($text);
1548 $text = $this->replaceInternalLinks($text);
1550 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1551 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1552 $this->mOutput
->addImage( $nt->getDBkey() );
1554 wfProfileOut( "$fname-image" );
1557 wfProfileOut( "$fname-image" );
1561 if ( $ns == NS_CATEGORY
) {
1562 wfProfileIn( "$fname-category" );
1563 $s = rtrim($s . "\n"); # bug 87
1566 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1567 $sortkey = $this->mTitle
->getText();
1569 $sortkey = $this->mTitle
->getPrefixedText();
1574 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1575 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1576 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1579 * Strip the whitespace Category links produce, see bug 87
1580 * @todo We might want to use trim($tmp, "\n") here.
1582 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1584 wfProfileOut( "$fname-category" );
1589 if( ( $nt->getPrefixedText() === $selflink ) &&
1590 ( $nt->getFragment() === '' ) ) {
1591 # Self-links are handled specially; generally de-link and change to bold.
1592 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1596 # Special and Media are pseudo-namespaces; no pages actually exist in them
1597 if( $ns == NS_MEDIA
) {
1598 $link = $sk->makeMediaLinkObj( $nt, $text );
1599 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1600 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1601 $this->mOutput
->addImage( $nt->getDBkey() );
1603 } elseif( $ns == NS_SPECIAL
) {
1604 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1606 } elseif( $ns == NS_IMAGE
) {
1607 $img = Image
::newFromTitle( $nt );
1608 if( $img->exists() ) {
1609 // Force a blue link if the file exists; may be a remote
1610 // upload on the shared repository, and we want to see its
1611 // auto-generated page.
1612 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1616 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1618 wfProfileOut( $fname );
1623 * Make a link placeholder. The text returned can be later resolved to a real link with
1624 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1625 * parsing of interwiki links, and secondly to allow all extistence checks and
1626 * article length checks (for stub links) to be bundled into a single query.
1629 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1630 if ( ! is_object($nt) ) {
1632 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1634 # Separate the link trail from the rest of the link
1635 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1637 if ( $nt->isExternal() ) {
1638 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1639 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1640 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1642 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1643 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1644 $this->mLinkHolders
['queries'][] = $query;
1645 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1646 $this->mLinkHolders
['titles'][] = $nt;
1648 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1655 * Render a forced-blue link inline; protect against double expansion of
1656 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1657 * Since this little disaster has to split off the trail text to avoid
1658 * breaking URLs in the following text without breaking trails on the
1659 * wiki links, it's been made into a horrible function.
1662 * @param string $text
1663 * @param string $query
1664 * @param string $trail
1665 * @param string $prefix
1666 * @return string HTML-wikitext mix oh yuck
1668 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1669 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1670 $sk =& $this->mOptions
->getSkin();
1671 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1672 return $this->armorLinks( $link ) . $trail;
1676 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1677 * going to go through further parsing steps before inline URL expansion.
1679 * In particular this is important when using action=render, which causes
1680 * full URLs to be included.
1682 * Oh man I hate our multi-layer parser!
1684 * @param string more-or-less HTML
1685 * @return string less-or-more HTML with NOPARSE bits
1687 function armorLinks( $text ) {
1688 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1689 "{$this->mUniqPrefix}NOPARSE$1", $text );
1693 * Return true if subpage links should be expanded on this page.
1696 function areSubpagesAllowed() {
1697 # Some namespaces don't allow subpages
1698 global $wgNamespacesWithSubpages;
1699 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1703 * Handle link to subpage if necessary
1704 * @param string $target the source of the link
1705 * @param string &$text the link text, modified as necessary
1706 * @return string the full name of the link
1709 function maybeDoSubpageLink($target, &$text) {
1712 # :Foobar -- override special treatment of prefix (images, language links)
1713 # /Foobar -- convert to CurrentPage/Foobar
1714 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1715 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1716 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1718 $fname = 'Parser::maybeDoSubpageLink';
1719 wfProfileIn( $fname );
1720 $ret = $target; # default return value is no change
1722 # Some namespaces don't allow subpages,
1723 # so only perform processing if subpages are allowed
1724 if( $this->areSubpagesAllowed() ) {
1725 # Look at the first character
1726 if( $target != '' && $target{0} == '/' ) {
1727 # / at end means we don't want the slash to be shown
1728 if( substr( $target, -1, 1 ) == '/' ) {
1729 $target = substr( $target, 1, -1 );
1732 $noslash = substr( $target, 1 );
1735 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1736 if( '' === $text ) {
1738 } # this might be changed for ugliness reasons
1740 # check for .. subpage backlinks
1742 $nodotdot = $target;
1743 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1745 $nodotdot = substr( $nodotdot, 3 );
1747 if($dotdotcount > 0) {
1748 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1749 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1750 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1751 # / at the end means don't show full path
1752 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1753 $nodotdot = substr( $nodotdot, 0, -1 );
1754 if( '' === $text ) {
1758 $nodotdot = trim( $nodotdot );
1759 if( $nodotdot != '' ) {
1760 $ret .= '/' . $nodotdot;
1767 wfProfileOut( $fname );
1772 * Used by doBlockLevels()
1775 /* private */ function closeParagraph() {
1777 if ( '' != $this->mLastSection
) {
1778 $result = '</' . $this->mLastSection
. ">\n";
1780 $this->mInPre
= false;
1781 $this->mLastSection
= '';
1784 # getCommon() returns the length of the longest common substring
1785 # of both arguments, starting at the beginning of both.
1787 /* private */ function getCommon( $st1, $st2 ) {
1788 $fl = strlen( $st1 );
1789 $shorter = strlen( $st2 );
1790 if ( $fl < $shorter ) { $shorter = $fl; }
1792 for ( $i = 0; $i < $shorter; ++
$i ) {
1793 if ( $st1{$i} != $st2{$i} ) { break; }
1797 # These next three functions open, continue, and close the list
1798 # element appropriate to the prefix character passed into them.
1800 /* private */ function openList( $char ) {
1801 $result = $this->closeParagraph();
1803 if ( '*' == $char ) { $result .= '<ul><li>'; }
1804 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1805 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1806 else if ( ';' == $char ) {
1807 $result .= '<dl><dt>';
1808 $this->mDTopen
= true;
1810 else { $result = '<!-- ERR 1 -->'; }
1815 /* private */ function nextItem( $char ) {
1816 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1817 else if ( ':' == $char ||
';' == $char ) {
1819 if ( $this->mDTopen
) { $close = '</dt>'; }
1820 if ( ';' == $char ) {
1821 $this->mDTopen
= true;
1822 return $close . '<dt>';
1824 $this->mDTopen
= false;
1825 return $close . '<dd>';
1828 return '<!-- ERR 2 -->';
1831 /* private */ function closeList( $char ) {
1832 if ( '*' == $char ) { $text = '</li></ul>'; }
1833 else if ( '#' == $char ) { $text = '</li></ol>'; }
1834 else if ( ':' == $char ) {
1835 if ( $this->mDTopen
) {
1836 $this->mDTopen
= false;
1837 $text = '</dt></dl>';
1839 $text = '</dd></dl>';
1842 else { return '<!-- ERR 3 -->'; }
1848 * Make lists from lines starting with ':', '*', '#', etc.
1851 * @return string the lists rendered as HTML
1853 function doBlockLevels( $text, $linestart ) {
1854 $fname = 'Parser::doBlockLevels';
1855 wfProfileIn( $fname );
1857 # Parsing through the text line by line. The main thing
1858 # happening here is handling of block-level elements p, pre,
1859 # and making lists from lines starting with * # : etc.
1861 $textLines = explode( "\n", $text );
1863 $lastPrefix = $output = '';
1864 $this->mDTopen
= $inBlockElem = false;
1866 $paragraphStack = false;
1868 if ( !$linestart ) {
1869 $output .= array_shift( $textLines );
1871 foreach ( $textLines as $oLine ) {
1872 $lastPrefixLength = strlen( $lastPrefix );
1873 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1874 $preOpenMatch = preg_match('/<pre/i', $oLine );
1875 if ( !$this->mInPre
) {
1876 # Multiple prefixes may abut each other for nested lists.
1877 $prefixLength = strspn( $oLine, '*#:;' );
1878 $pref = substr( $oLine, 0, $prefixLength );
1881 $pref2 = str_replace( ';', ':', $pref );
1882 $t = substr( $oLine, $prefixLength );
1883 $this->mInPre
= !empty($preOpenMatch);
1885 # Don't interpret any other prefixes in preformatted text
1887 $pref = $pref2 = '';
1892 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1893 # Same as the last item, so no need to deal with nesting or opening stuff
1894 $output .= $this->nextItem( substr( $pref, -1 ) );
1895 $paragraphStack = false;
1897 if ( substr( $pref, -1 ) == ';') {
1898 # The one nasty exception: definition lists work like this:
1899 # ; title : definition text
1900 # So we check for : in the remainder text to split up the
1901 # title and definition, without b0rking links.
1903 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1905 $output .= $term . $this->nextItem( ':' );
1908 } elseif( $prefixLength ||
$lastPrefixLength ) {
1909 # Either open or close a level...
1910 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1911 $paragraphStack = false;
1913 while( $commonPrefixLength < $lastPrefixLength ) {
1914 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1915 --$lastPrefixLength;
1917 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1918 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1920 while ( $prefixLength > $commonPrefixLength ) {
1921 $char = substr( $pref, $commonPrefixLength, 1 );
1922 $output .= $this->openList( $char );
1924 if ( ';' == $char ) {
1925 # FIXME: This is dupe of code above
1926 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1928 $output .= $term . $this->nextItem( ':' );
1931 ++
$commonPrefixLength;
1933 $lastPrefix = $pref2;
1935 if( 0 == $prefixLength ) {
1936 wfProfileIn( "$fname-paragraph" );
1937 # No prefix (not in list)--go to paragraph mode
1938 // XXX: use a stack for nestable elements like span, table and div
1939 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1940 $closematch = preg_match(
1941 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1942 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1943 if ( $openmatch or $closematch ) {
1944 $paragraphStack = false;
1945 #Â TODO bug 5718: paragraph closed
1946 $output .= $this->closeParagraph();
1947 if ( $preOpenMatch and !$preCloseMatch ) {
1948 $this->mInPre
= true;
1950 if ( $closematch ) {
1951 $inBlockElem = false;
1953 $inBlockElem = true;
1955 } else if ( !$inBlockElem && !$this->mInPre
) {
1956 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1958 if ($this->mLastSection
!= 'pre') {
1959 $paragraphStack = false;
1960 $output .= $this->closeParagraph().'<pre>';
1961 $this->mLastSection
= 'pre';
1963 $t = substr( $t, 1 );
1966 if ( '' == trim($t) ) {
1967 if ( $paragraphStack ) {
1968 $output .= $paragraphStack.'<br />';
1969 $paragraphStack = false;
1970 $this->mLastSection
= 'p';
1972 if ($this->mLastSection
!= 'p' ) {
1973 $output .= $this->closeParagraph();
1974 $this->mLastSection
= '';
1975 $paragraphStack = '<p>';
1977 $paragraphStack = '</p><p>';
1981 if ( $paragraphStack ) {
1982 $output .= $paragraphStack;
1983 $paragraphStack = false;
1984 $this->mLastSection
= 'p';
1985 } else if ($this->mLastSection
!= 'p') {
1986 $output .= $this->closeParagraph().'<p>';
1987 $this->mLastSection
= 'p';
1992 wfProfileOut( "$fname-paragraph" );
1994 // somewhere above we forget to get out of pre block (bug 785)
1995 if($preCloseMatch && $this->mInPre
) {
1996 $this->mInPre
= false;
1998 if ($paragraphStack === false) {
2002 while ( $prefixLength ) {
2003 $output .= $this->closeList( $pref2{$prefixLength-1} );
2006 if ( '' != $this->mLastSection
) {
2007 $output .= '</' . $this->mLastSection
. '>';
2008 $this->mLastSection
= '';
2011 wfProfileOut( $fname );
2016 * Split up a string on ':', ignoring any occurences inside
2017 * <a>..</a> or <span>...</span>
2018 * @param string $str the string to split
2019 * @param string &$before set to everything before the ':'
2020 * @param string &$after set to everything after the ':'
2021 * return string the position of the ':', or false if none found
2023 function findColonNoLinks($str, &$before, &$after) {
2024 # I wonder if we should make this count all tags, not just <a>
2025 # and <span>. That would prevent us from matching a ':' that
2026 # comes in the middle of italics other such formatting....
2028 $fname = 'Parser::findColonNoLinks';
2029 wfProfileIn( $fname );
2032 $colon = strpos($str, ':', $pos);
2034 if ($colon !== false) {
2035 $before = substr($str, 0, $colon);
2036 $after = substr($str, $colon +
1);
2038 # Skip any ':' within <a> or <span> pairs
2039 $a = substr_count($before, '<a');
2040 $s = substr_count($before, '<span');
2041 $ca = substr_count($before, '</a>');
2042 $cs = substr_count($before, '</span>');
2044 if ($a <= $ca and $s <= $cs) {
2045 # Tags are balanced before ':'; ok
2050 } while ($colon !== false);
2051 wfProfileOut( $fname );
2056 * Return value of a magic variable (like PAGENAME)
2060 function getVariableValue( $index ) {
2061 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2064 * Some of these require message or data lookups and can be
2065 * expensive to check many times.
2067 static $varCache = array();
2068 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2069 if ( isset( $varCache[$index] ) )
2070 return $varCache[$index];
2073 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2076 case MAG_CURRENTMONTH
:
2077 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2078 case MAG_CURRENTMONTHNAME
:
2079 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2080 case MAG_CURRENTMONTHNAMEGEN
:
2081 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2082 case MAG_CURRENTMONTHABBREV
:
2083 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2084 case MAG_CURRENTDAY
:
2085 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2086 case MAG_CURRENTDAY2
:
2087 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2089 return $this->mTitle
->getText();
2091 return $this->mTitle
->getPartialURL();
2092 case MAG_FULLPAGENAME
:
2093 return $this->mTitle
->getPrefixedText();
2094 case MAG_FULLPAGENAMEE
:
2095 return $this->mTitle
->getPrefixedURL();
2096 case MAG_SUBPAGENAME
:
2097 return $this->mTitle
->getSubpageText();
2098 case MAG_SUBPAGENAMEE
:
2099 return $this->mTitle
->getSubpageUrlForm();
2100 case MAG_BASEPAGENAME
:
2101 return $this->mTitle
->getBaseText();
2102 case MAG_BASEPAGENAMEE
:
2103 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2104 case MAG_TALKPAGENAME
:
2105 if( $this->mTitle
->canTalk() ) {
2106 $talkPage = $this->mTitle
->getTalkPage();
2107 return $talkPage->getPrefixedText();
2111 case MAG_TALKPAGENAMEE
:
2112 if( $this->mTitle
->canTalk() ) {
2113 $talkPage = $this->mTitle
->getTalkPage();
2114 return $talkPage->getPrefixedUrl();
2118 case MAG_SUBJECTPAGENAME
:
2119 $subjPage = $this->mTitle
->getSubjectPage();
2120 return $subjPage->getPrefixedText();
2121 case MAG_SUBJECTPAGENAMEE
:
2122 $subjPage = $this->mTitle
->getSubjectPage();
2123 return $subjPage->getPrefixedUrl();
2124 case MAG_REVISIONID
:
2125 return $this->mRevisionId
;
2127 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2128 case MAG_NAMESPACEE
:
2129 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2131 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2132 case MAG_TALKSPACEE
:
2133 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2134 case MAG_SUBJECTSPACE
:
2135 return $this->mTitle
->getSubjectNsText();
2136 case MAG_SUBJECTSPACEE
:
2137 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2138 case MAG_CURRENTDAYNAME
:
2139 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2140 case MAG_CURRENTYEAR
:
2141 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2142 case MAG_CURRENTTIME
:
2143 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2144 case MAG_CURRENTWEEK
:
2145 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2146 // int to remove the padding
2147 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2148 case MAG_CURRENTDOW
:
2149 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2150 case MAG_NUMBEROFARTICLES
:
2151 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2152 case MAG_NUMBEROFFILES
:
2153 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2154 case MAG_NUMBEROFUSERS
:
2155 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2156 case MAG_NUMBEROFPAGES
:
2157 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2158 case MAG_CURRENTTIMESTAMP
:
2159 return $varCache[$index] = wfTimestampNow();
2160 case MAG_CURRENTVERSION
:
2167 case MAG_SERVERNAME
:
2168 return $wgServerName;
2169 case MAG_SCRIPTPATH
:
2170 return $wgScriptPath;
2171 case MAG_DIRECTIONMARK
:
2172 return $wgContLang->getDirMark();
2175 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2183 * initialise the magic variables (like CURRENTMONTHNAME)
2187 function initialiseVariables() {
2188 $fname = 'Parser::initialiseVariables';
2189 wfProfileIn( $fname );
2190 global $wgVariableIDs;
2191 $this->mVariables
= array();
2192 foreach ( $wgVariableIDs as $id ) {
2193 $mw =& MagicWord
::get( $id );
2194 $mw->addToArray( $this->mVariables
, $id );
2196 wfProfileOut( $fname );
2200 * parse any parentheses in format ((title|part|part))
2201 * and call callbacks to get a replacement text for any found piece
2203 * @param string $text The text to parse
2204 * @param array $callbacks rules in form:
2205 * '{' => array( # opening parentheses
2206 * 'end' => '}', # closing parentheses
2207 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2208 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2213 function replace_callback ($text, $callbacks) {
2214 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2215 $lastOpeningBrace = -1; # last not closed parentheses
2217 for ($i = 0; $i < strlen($text); $i++
) {
2218 # check for any opening brace
2221 foreach ($callbacks as $key => $value) {
2222 $pos = strpos ($text, $key, $i);
2223 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2229 if ($lastOpeningBrace >= 0) {
2230 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2232 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2237 $pos = strpos ($text, '|', $i);
2239 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2250 # found openning brace, lets add it to parentheses stack
2251 if (null != $rule) {
2252 $piece = array('brace' => $text[$i],
2253 'braceEnd' => $rule['end'],
2258 # count openning brace characters
2259 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2264 $piece['startAt'] = $i+
1;
2265 $piece['partStart'] = $i+
1;
2267 # we need to add to stack only if openning brace count is enough for any given rule
2268 foreach ($rule['cb'] as $cnt => $fn) {
2269 if ($piece['count'] >= $cnt) {
2270 $lastOpeningBrace ++
;
2271 $openingBraceStack[$lastOpeningBrace] = $piece;
2278 else if ($lastOpeningBrace >= 0) {
2279 # first check if it is a closing brace
2280 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2281 # lets check if it is enough characters for closing brace
2283 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2286 # if there are more closing parentheses than opening ones, we parse less
2287 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2288 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2290 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2292 $matchingCallback = null;
2293 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2294 if ($count >= $cnt && $matchingCount < $cnt) {
2295 $matchingCount = $cnt;
2296 $matchingCallback = $fn;
2300 if ($matchingCount == 0) {
2305 # lets set a title or last part (if '|' was found)
2306 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2307 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2309 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2311 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2312 $pieceEnd = $i +
$matchingCount;
2314 if( is_callable( $matchingCallback ) ) {
2316 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2317 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2318 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2319 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2321 # finally we can call a user callback and replace piece of text
2322 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2323 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2324 $i = $pieceStart +
strlen($replaceWith) - 1;
2327 # null value for callback means that parentheses should be parsed, but not replaced
2328 $i +
= $matchingCount - 1;
2331 # reset last openning parentheses, but keep it in case there are unused characters
2332 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2333 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2334 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2337 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2338 $openingBraceStack[$lastOpeningBrace--] = null;
2340 if ($matchingCount < $piece['count']) {
2341 $piece['count'] -= $matchingCount;
2342 $piece['startAt'] -= $matchingCount;
2343 $piece['partStart'] = $piece['startAt'];
2344 # do we still qualify for any callback with remaining count?
2345 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2346 if ($piece['count'] >= $cnt) {
2347 $lastOpeningBrace ++
;
2348 $openingBraceStack[$lastOpeningBrace] = $piece;
2356 # lets set a title if it is a first separator, or next part otherwise
2357 if ($text[$i] == '|') {
2358 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2359 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2360 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2363 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2365 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2374 * Replace magic variables, templates, and template arguments
2375 * with the appropriate text. Templates are substituted recursively,
2376 * taking care to avoid infinite loops.
2378 * Note that the substitution depends on value of $mOutputType:
2379 * OT_WIKI: only {{subst:}} templates
2380 * OT_MSG: only magic variables
2381 * OT_HTML: all templates and magic variables
2383 * @param string $tex The text to transform
2384 * @param array $args Key-value pairs representing template parameters to substitute
2385 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2388 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2389 # Prevent too big inclusions
2390 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2394 $fname = 'Parser::replaceVariables';
2395 wfProfileIn( $fname );
2397 # This function is called recursively. To keep track of arguments we need a stack:
2398 array_push( $this->mArgStack
, $args );
2400 $braceCallbacks = array();
2402 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2404 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2405 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2407 $callbacks = array();
2408 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2409 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2410 $text = $this->replace_callback ($text, $callbacks);
2412 array_pop( $this->mArgStack
);
2414 wfProfileOut( $fname );
2419 * Replace magic variables
2422 function variableSubstitution( $matches ) {
2423 $fname = 'Parser::variableSubstitution';
2424 $varname = $matches[1];
2425 wfProfileIn( $fname );
2426 if ( !$this->mVariables
) {
2427 $this->initialiseVariables();
2430 if ( $this->mOutputType
== OT_WIKI
) {
2431 # Do only magic variables prefixed by SUBST
2432 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2433 if (!$mwSubst->matchStartAndRemove( $varname ))
2435 # Note that if we don't substitute the variable below,
2436 # we don't remove the {{subst:}} magic word, in case
2437 # it is a template rather than a magic variable.
2439 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2440 $id = $this->mVariables
[$varname];
2441 $text = $this->getVariableValue( $id );
2442 $this->mOutput
->mContainsOldMagic
= true;
2444 $text = $matches[0];
2446 wfProfileOut( $fname );
2450 # Split template arguments
2451 function getTemplateArgs( $argsString ) {
2452 if ( $argsString === '' ) {
2456 $args = explode( '|', substr( $argsString, 1 ) );
2458 # If any of the arguments contains a '[[' but no ']]', it needs to be
2459 # merged with the next arg because the '|' character between belongs
2460 # to the link syntax and not the template parameter syntax.
2461 $argc = count($args);
2463 for ( $i = 0; $i < $argc-1; $i++
) {
2464 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2465 $args[$i] .= '|'.$args[$i+
1];
2466 array_splice($args, $i+
1, 1);
2476 * Return the text of a template, after recursively
2477 * replacing any variables or templates within the template.
2479 * @param array $piece The parts of the template
2480 * $piece['text']: matched text
2481 * $piece['title']: the title, i.e. the part before the |
2482 * $piece['parts']: the parameter array
2483 * @return string the text of the template
2486 function braceSubstitution( $piece ) {
2487 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2488 $fname = 'Parser::braceSubstitution';
2489 wfProfileIn( $fname );
2492 $found = false; # $text has been filled
2493 $nowiki = false; # wiki markup in $text should be escaped
2494 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2495 $noargs = false; # Don't replace triple-brace arguments in $text
2496 $replaceHeadings = false; # Make the edit section links go to the template not the article
2497 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2498 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2500 # Title object, where $text came from
2505 # $part1 is the bit before the first |, and must contain only title characters
2506 # $args is a list of arguments, starting from index 0, not including $part1
2508 $part1 = $piece['title'];
2509 # If the third subpattern matched anything, it will start with |
2511 if (null == $piece['parts']) {
2512 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2513 if ($replaceWith != $piece['text']) {
2514 $text = $replaceWith;
2521 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2522 $argc = count( $args );
2526 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2527 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2528 # One of two possibilities is true:
2529 # 1) Found SUBST but not in the PST phase
2530 # 2) Didn't find SUBST and in the PST phase
2531 # In either case, return without further processing
2532 $text = $piece['text'];
2539 # MSG, MSGNW, INT and RAW
2542 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2543 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2546 # Remove obsolete MSG:
2547 $mwMsg =& MagicWord
::get( MAG_MSG
);
2548 $mwMsg->matchStartAndRemove( $part1 );
2552 $mwRaw =& MagicWord
::get( MAG_RAW
);
2553 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2554 $forceRawInterwiki = true;
2557 # Check if it is an internal message
2558 $mwInt =& MagicWord
::get( MAG_INT
);
2559 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2560 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2561 $text = $linestart . wfMsgReal( $part1, $args, true );
2569 # Check for NS: (namespace expansion)
2570 $mwNs = MagicWord
::get( MAG_NS
);
2571 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2572 if ( intval( $part1 ) ||
$part1 == "0" ) {
2573 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2576 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2577 if ( !is_null( $index ) ) {
2578 $text = $linestart . $wgContLang->getNsText( $index );
2587 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2588 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2589 $text = $linestart . urlencode( $part1 );
2594 # LCFIRST, UCFIRST, LC and UC
2596 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2597 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2598 $lc =& MagicWord
::get( MAG_LC
);
2599 $uc =& MagicWord
::get( MAG_UC
);
2600 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2601 $text = $linestart . $wgContLang->lcfirst( $part1 );
2603 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2604 $text = $linestart . $wgContLang->ucfirst( $part1 );
2606 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2607 $text = $linestart . $wgContLang->lc( $part1 );
2609 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2610 $text = $linestart . $wgContLang->uc( $part1 );
2615 # LOCALURL and FULLURL
2617 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2618 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2619 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2620 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2623 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2624 $func = 'getLocalURL';
2625 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2626 $func = 'escapeLocalURL';
2627 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2628 $func = 'getFullURL';
2629 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2630 $func = 'escapeFullURL';
2635 if ( $func !== false ) {
2636 $title = Title
::newFromText( $part1 );
2637 # Due to order of execution of a lot of bits, the values might be encoded
2638 # before arriving here; if that's true, then the title can't be created
2639 # and the variable will fail. If we can't get a decent title from the first
2640 # attempt, url-decode and try for a second.
2641 if( is_null( $title ) )
2642 $title = Title
::newFromUrl( urldecode( $part1 ) );
2643 if ( !is_null( $title ) ) {
2645 $text = $linestart . $title->$func( $args[0] );
2647 $text = $linestart . $title->$func();
2654 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2656 if ( !$found && $argc == 1 ) {
2657 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2658 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2659 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2665 if ( !$found && $argc >= 2 ) {
2666 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2667 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2668 if ($argc==2) {$args[2]=$args[1];}
2669 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2675 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2676 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2677 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2679 # Set title in parser output object
2681 $parserOptions = new ParserOptions
;
2682 $local_parser = new Parser ();
2683 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2684 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2687 $t = $this->mTitle
->getPrefixedText();
2688 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2694 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2696 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2697 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2698 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2699 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2700 foreach( $mwWordsToCheck as $word => $func ) {
2701 $mwCurrentWord =& MagicWord
::get( $word );
2702 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2703 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2704 if( $mwRawSuffix->match( $args[0] ) ) {
2705 # Raw and unformatted
2706 $text = $linestart . call_user_func( $func );
2708 # Formatted according to the content default
2709 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2717 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2718 $colonPos = strpos( $part1, ':' );
2719 if ( $colonPos !== false ) {
2720 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2721 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2722 $funcArgs = array_map( 'trim', $args );
2723 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2724 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2727 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2731 if ( is_array( $result ) ) {
2732 $text = $linestart . $result[0];
2733 unset( $result[0] );
2735 // Extract flags into the local scope
2736 // This allows callers to set flags such as nowiki, noparse, found, etc.
2739 $text = $linestart . $result;
2745 # Template table test
2747 # Did we encounter this template already? If yes, it is in the cache
2748 # and we need to check for loops.
2749 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2752 # Infinite loop test
2753 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2757 $text = $linestart .
2758 '{{' . $part1 . '}}' .
2759 '<!-- WARNING: template loop detected -->';
2760 wfDebug( "$fname: template loop broken at '$part1'\n" );
2762 # set $text to cached message.
2763 $text = $linestart . $this->mTemplates
[$piece['title']];
2767 # Load from database
2768 $lastPathLevel = $this->mTemplatePath
;
2771 # declaring $subpage directly in the function call
2772 # does not work correctly with references and breaks
2773 # {{/subpage}}-style inclusions
2775 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2776 if ($subpage !== '') {
2777 $ns = $this->mTitle
->getNamespace();
2779 $title = Title
::newFromText( $part1, $ns );
2781 if ( !is_null( $title ) ) {
2782 if ( !$title->isExternal() ) {
2783 # Check for excessive inclusion
2784 $dbk = $title->getPrefixedDBkey();
2785 if ( $this->incrementIncludeCount( $dbk ) ) {
2786 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2787 $text = SpecialPage
::capturePath( $title );
2788 if ( is_string( $text ) ) {
2793 $this->disableCache();
2796 $articleContent = $this->fetchTemplate( $title );
2797 if ( $articleContent !== false ) {
2799 $text = $articleContent;
2800 $replaceHeadings = true;
2805 # If the title is valid but undisplayable, make a link to it
2806 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2807 $text = '[['.$title->getPrefixedText().']]';
2810 } elseif ( $title->isTrans() ) {
2811 // Interwiki transclusion
2812 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2813 $text = $this->interwikiTransclude( $title, 'render' );
2817 $text = $this->interwikiTransclude( $title, 'raw' );
2818 $replaceHeadings = true;
2823 # Template cache array insertion
2824 # Use the original $piece['title'] not the mangled $part1, so that
2825 # modifiers such as RAW: produce separate cache entries
2827 $this->mTemplates
[$piece['title']] = $text;
2828 $text = $linestart . $text;
2833 # Recursive parsing, escaping and link table handling
2834 # Only for HTML output
2835 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2836 $text = wfEscapeWikiText( $text );
2837 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2839 $assocArgs = array();
2841 # Clean up argument array
2842 $assocArgs = array();
2844 foreach( $args as $arg ) {
2845 $eqpos = strpos( $arg, '=' );
2846 if ( $eqpos === false ) {
2847 $assocArgs[$index++
] = $arg;
2849 $name = trim( substr( $arg, 0, $eqpos ) );
2850 $value = trim( substr( $arg, $eqpos+
1 ) );
2851 if ( $value === false ) {
2854 if ( $name !== false ) {
2855 $assocArgs[$name] = $value;
2860 # Add a new element to the templace recursion path
2861 $this->mTemplatePath
[$part1] = 1;
2865 # If there are any <onlyinclude> tags, only include them
2866 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2867 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2869 foreach ($m[1] as $piece)
2872 # Remove <noinclude> sections and <includeonly> tags
2873 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2874 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2876 if( $this->mOutputType
== OT_HTML
) {
2877 # Strip <nowiki>, <pre>, etc.
2878 $text = $this->strip( $text, $this->mStripState
);
2879 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2881 $text = $this->replaceVariables( $text, $assocArgs );
2883 # If the template begins with a table or block-level
2884 # element, it should be treated as beginning a new line.
2885 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2886 $text = "\n" . $text;
2888 } elseif ( !$noargs ) {
2889 # $noparse and !$noargs
2890 # Just replace the arguments, not any double-brace items
2891 # This is used for rendered interwiki transclusion
2892 $text = $this->replaceVariables( $text, $assocArgs, true );
2895 # Prune lower levels off the recursion check path
2896 $this->mTemplatePath
= $lastPathLevel;
2899 wfProfileOut( $fname );
2900 return $piece['text'];
2903 # Replace raw HTML by a placeholder
2904 # Add a blank line preceding, to prevent it from mucking up
2905 # immediately preceding headings
2906 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2908 # replace ==section headers==
2909 # XXX this needs to go away once we have a better parser.
2910 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2911 if( !is_null( $title ) )
2912 $encodedname = base64_encode($title->getPrefixedDBkey());
2914 $encodedname = base64_encode("");
2915 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2916 PREG_SPLIT_DELIM_CAPTURE
);
2919 for( $i = 0; $i < count($m); $i +
= 2 ) {
2921 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2923 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2927 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2928 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2929 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2937 # Prune lower levels off the recursion check path
2938 $this->mTemplatePath
= $lastPathLevel;
2941 wfProfileOut( $fname );
2942 return $piece['text'];
2944 wfProfileOut( $fname );
2950 * Fetch the unparsed text of a template and register a reference to it.
2952 function fetchTemplate( $title ) {
2954 // Loop to fetch the article, with up to 1 redirect
2955 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2956 $rev = Revision
::newFromTitle( $title );
2957 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2961 $text = $rev->getText();
2962 if ( $text === false ) {
2966 $title = Title
::newFromRedirect( $text );
2972 * Transclude an interwiki link.
2974 function interwikiTransclude( $title, $action ) {
2975 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2977 if (!$wgEnableScaryTranscluding)
2978 return wfMsg('scarytranscludedisabled');
2980 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2981 // But we'll handle it generally anyway
2982 if ( $title->getNamespace() ) {
2983 // Use the canonical namespace, which should work anywhere
2984 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2986 $articleName = $title->getDBkey();
2989 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2990 $url .= "?action=$action";
2991 if (strlen($url) > 255)
2992 return wfMsg('scarytranscludetoolong');
2993 return $this->fetchScaryTemplateMaybeFromCache($url);
2996 function fetchScaryTemplateMaybeFromCache($url) {
2997 global $wgTranscludeCacheExpiry;
2998 $dbr =& wfGetDB(DB_SLAVE
);
2999 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3000 array('tc_url' => $url));
3002 $time = $obj->tc_time
;
3003 $text = $obj->tc_contents
;
3004 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3009 $text = wfGetHTTP($url);
3011 return wfMsg('scarytranscludefailed', $url);
3013 $dbw =& wfGetDB(DB_MASTER
);
3014 $dbw->replace('transcache', array('tc_url'), array(
3016 'tc_time' => time(),
3017 'tc_contents' => $text));
3023 * Triple brace replacement -- used for template arguments
3026 function argSubstitution( $matches ) {
3027 $arg = trim( $matches['title'] );
3028 $text = $matches['text'];
3029 $inputArgs = end( $this->mArgStack
);
3031 if ( array_key_exists( $arg, $inputArgs ) ) {
3032 $text = $inputArgs[$arg];
3033 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3034 $text = $matches['parts'][0];
3041 * Returns true if the function is allowed to include this entity
3044 function incrementIncludeCount( $dbk ) {
3045 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3046 $this->mIncludeCount
[$dbk] = 0;
3048 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3056 * Detect __TOC__ magic word and set a placeholder
3058 function stripToc( $text ) {
3059 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3061 $mw = MagicWord
::get( MAG_NOTOC
);
3062 if( $mw->matchAndRemove( $text ) ) {
3063 $this->mShowToc
= false;
3066 $mw = MagicWord
::get( MAG_TOC
);
3067 if( $mw->match( $text ) ) {
3068 $this->mShowToc
= true;
3069 $this->mForceTocPosition
= true;
3071 // Set a placeholder. At the end we'll fill it in with the TOC.
3072 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3074 // Only keep the first one.
3075 $text = $mw->replace( '', $text );
3081 * This function accomplishes several tasks:
3082 * 1) Auto-number headings if that option is enabled
3083 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3084 * 3) Add a Table of contents on the top for users who have enabled the option
3085 * 4) Auto-anchor headings
3087 * It loops through all headlines, collects the necessary data, then splits up the
3088 * string and re-inserts the newly formatted headlines.
3090 * @param string $text
3091 * @param boolean $isMain
3094 function formatHeadings( $text, $isMain=true ) {
3095 global $wgMaxTocLevel, $wgContLang;
3097 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3098 if( !$this->mTitle
->userCanEdit() ) {
3101 $showEditLink = $this->mOptions
->getEditSection();
3104 # Inhibit editsection links if requested in the page
3105 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3106 if( $esw->matchAndRemove( $text ) ) {
3110 # Get all headlines for numbering them and adding funky stuff like [edit]
3111 # links - this is for later, but we need the number of headlines right now
3112 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3114 # if there are fewer than 4 headlines in the article, do not show TOC
3115 # unless it's been explicitly enabled.
3116 $enoughToc = $this->mShowToc
&&
3117 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3119 # Allow user to stipulate that a page should have a "new section"
3120 # link added via __NEWSECTIONLINK__
3121 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3122 if( $mw->matchAndRemove( $text ) )
3123 $this->mOutput
->setNewSection( true );
3125 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3126 # override above conditions and always show TOC above first header
3127 $mw =& MagicWord
::get( MAG_FORCETOC
);
3128 if ($mw->matchAndRemove( $text ) ) {
3129 $this->mShowToc
= true;
3133 # Never ever show TOC if no headers
3134 if( $numMatches < 1 ) {
3138 # We need this to perform operations on the HTML
3139 $sk =& $this->mOptions
->getSkin();
3143 $sectionCount = 0; # headlineCount excluding template sections
3145 # Ugh .. the TOC should have neat indentation levels which can be
3146 # passed to the skin functions. These are determined here
3150 $sublevelCount = array();
3151 $levelCount = array();
3158 foreach( $matches[3] as $headline ) {
3160 $templatetitle = '';
3161 $templatesection = 0;
3164 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3166 $templatetitle = base64_decode($mat[1]);
3167 $templatesection = 1 +
(int)base64_decode($mat[2]);
3168 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3172 $prevlevel = $level;
3173 $prevtoclevel = $toclevel;
3175 $level = $matches[1][$headlineCount];
3177 if( $doNumberHeadings ||
$enoughToc ) {
3179 if ( $level > $prevlevel ) {
3180 # Increase TOC level
3182 $sublevelCount[$toclevel] = 0;
3183 if( $toclevel<$wgMaxTocLevel ) {
3184 $toc .= $sk->tocIndent();
3187 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3188 # Decrease TOC level, find level to jump to
3190 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3191 # Can only go down to level 1
3194 for ($i = $toclevel; $i > 0; $i--) {
3195 if ( $levelCount[$i] == $level ) {
3196 # Found last matching level
3200 elseif ( $levelCount[$i] < $level ) {
3201 # Found first matching level below current level
3207 if( $toclevel<$wgMaxTocLevel ) {
3208 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3212 # No change in level, end TOC line
3213 if( $toclevel<$wgMaxTocLevel ) {
3214 $toc .= $sk->tocLineEnd();
3218 $levelCount[$toclevel] = $level;
3220 # count number of headlines for each level
3221 @$sublevelCount[$toclevel]++
;
3223 for( $i = 1; $i <= $toclevel; $i++
) {
3224 if( !empty( $sublevelCount[$i] ) ) {
3228 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3234 # The canonized header is a version of the header text safe to use for links
3235 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3236 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3237 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3239 # Remove link placeholders by the link text.
3240 # <!--LINK number-->
3242 # link text with suffix
3243 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3244 "\$this->mLinkHolders['texts'][\$1]",
3245 $canonized_headline );
3246 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3247 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3248 $canonized_headline );
3251 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3252 $tocline = trim( $canonized_headline );
3253 # Save headline for section edit hint before it's escaped
3254 $headline_hint = trim( $canonized_headline );
3255 $canonized_headline = Sanitizer
::escapeId( $tocline );
3256 $refers[$headlineCount] = $canonized_headline;
3258 # count how many in assoc. array so we can track dupes in anchors
3259 @$refers[$canonized_headline]++
;
3260 $refcount[$headlineCount]=$refers[$canonized_headline];
3262 # Don't number the heading if it is the only one (looks silly)
3263 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3264 # the two are different if the line contains a link
3265 $headline=$numbering . ' ' . $headline;
3268 # Create the anchor for linking from the TOC to the section
3269 $anchor = $canonized_headline;
3270 if($refcount[$headlineCount] > 1 ) {
3271 $anchor .= '_' . $refcount[$headlineCount];
3273 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3274 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3276 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3277 if ( empty( $head[$headlineCount] ) ) {
3278 $head[$headlineCount] = '';
3281 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3283 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3286 # give headline the correct <h#> tag
3287 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3295 if( $toclevel<$wgMaxTocLevel ) {
3296 $toc .= $sk->tocUnindent( $toclevel - 1 );
3298 $toc = $sk->tocList( $toc );
3301 # split up and insert constructed headlines
3303 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3306 foreach( $blocks as $block ) {
3307 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3308 # This is the [edit] link that appears for the top block of text when
3309 # section editing is enabled
3311 # Disabled because it broke block formatting
3312 # For example, a bullet point in the top line
3313 # $full .= $sk->editSectionLink(0);
3316 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3317 # Top anchor now in skin
3321 if( !empty( $head[$i] ) ) {
3326 if( $this->mForceTocPosition
) {
3327 return str_replace( '<!--MWTOC-->', $toc, $full );
3334 * Return an HTML link for the "ISBN 123456" text
3337 function magicISBN( $text ) {
3338 $fname = 'Parser::magicISBN';
3339 wfProfileIn( $fname );
3341 $a = split( 'ISBN ', ' '.$text );
3342 if ( count ( $a ) < 2 ) {
3343 wfProfileOut( $fname );
3346 $text = substr( array_shift( $a ), 1);
3347 $valid = '0123456789-Xx';
3349 foreach ( $a as $x ) {
3350 # hack: don't replace inside thumbnail title/alt
3352 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3357 $isbn = $blank = '' ;
3358 while ( ' ' == $x{0} ) {
3360 $x = substr( $x, 1 );
3362 if ( $x == '' ) { # blank isbn
3363 $text .= "ISBN $blank";
3366 while ( strstr( $valid, $x{0} ) != false ) {
3368 $x = substr( $x, 1 );
3370 $num = str_replace( '-', '', $isbn );
3371 $num = str_replace( ' ', '', $num );
3372 $num = str_replace( 'x', 'X', $num );
3375 $text .= "ISBN $blank$x";
3377 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3378 $text .= '<a href="' .
3379 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3380 "\" class=\"internal\">ISBN $isbn</a>";
3384 wfProfileOut( $fname );
3389 * Return an HTML link for the "RFC 1234" text
3392 * @param string $text Text to be processed
3393 * @param string $keyword Magic keyword to use (default RFC)
3394 * @param string $urlmsg Interface message to use (default rfcurl)
3397 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3399 $valid = '0123456789';
3402 $a = split( $keyword, ' '.$text );
3403 if ( count ( $a ) < 2 ) {
3406 $text = substr( array_shift( $a ), 1);
3408 /* Check if keyword is preceed by [[.
3409 * This test is made here cause of the array_shift above
3410 * that prevent the test to be done in the foreach.
3412 if ( substr( $text, -2 ) == '[[' ) {
3416 foreach ( $a as $x ) {
3417 /* token might be empty if we have RFC RFC 1234 */
3423 # hack: don't replace inside thumbnail title/alt
3425 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3426 $text .= $keyword . $x;
3432 /** remove and save whitespaces in $blank */
3433 while ( $x{0} == ' ' ) {
3435 $x = substr( $x, 1 );
3438 /** remove and save the rfc number in $id */
3439 while ( strstr( $valid, $x{0} ) != false ) {
3441 $x = substr( $x, 1 );
3445 /* call back stripped spaces*/
3446 $text .= $keyword.$blank.$x;
3447 } elseif( $internal ) {
3449 $text .= $keyword.$id.$x;
3451 /* build the external link*/
3452 $url = wfMsg( $urlmsg, $id);
3453 $sk =& $this->mOptions
->getSkin();
3454 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3455 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3458 /* Check if the next RFC keyword is preceed by [[ */
3459 $internal = ( substr($x,-2) == '[[' );
3465 * Transform wiki markup when saving a page by doing \r\n -> \n
3466 * conversion, substitting signatures, {{subst:}} templates, etc.
3468 * @param string $text the text to transform
3469 * @param Title &$title the Title object for the current article
3470 * @param User &$user the User object describing the current user
3471 * @param ParserOptions $options parsing options
3472 * @param bool $clearState whether to clear the parser state first
3473 * @return string the altered wiki markup
3476 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3477 $this->mOptions
= $options;
3478 $this->mTitle
=& $title;
3479 $this->mOutputType
= OT_WIKI
;
3481 if ( $clearState ) {
3482 $this->clearState();
3485 $stripState = false;
3489 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3490 $text = $this->strip( $text, $stripState, true );
3491 $text = $this->pstPass2( $text, $stripState, $user );
3492 $text = $this->unstrip( $text, $stripState );
3493 $text = $this->unstripNoWiki( $text, $stripState );
3498 * Pre-save transform helper function
3501 function pstPass2( $text, &$stripState, &$user ) {
3502 global $wgContLang, $wgLocaltimezone;
3504 /* Note: This is the timestamp saved as hardcoded wikitext to
3505 * the database, we use $wgContLang here in order to give
3506 * everyone the same signature and use the default one rather
3507 * than the one selected in each user's preferences.
3509 if ( isset( $wgLocaltimezone ) ) {
3510 $oldtz = getenv( 'TZ' );
3511 putenv( 'TZ='.$wgLocaltimezone );
3513 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3514 ' (' . date( 'T' ) . ')';
3515 if ( isset( $wgLocaltimezone ) ) {
3516 putenv( 'TZ='.$oldtz );
3519 # Variable replacement
3520 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3521 $text = $this->replaceVariables( $text );
3523 # Strip out <nowiki> etc. added via replaceVariables
3524 $text = $this->strip( $text, $stripState );
3527 $sigText = $this->getUserSig( $user );
3528 $text = strtr( $text, array(
3530 '~~~~' => "$sigText $d",
3534 # Context links: [[|name]] and [[name (context)|]]
3536 global $wgLegalTitleChars;
3537 $tc = "[$wgLegalTitleChars]";
3538 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3540 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3541 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3543 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3544 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3545 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3546 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3548 $t = $this->mTitle
->getText();
3549 if ( preg_match( $conpat, $t, $m ) ) {
3552 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3553 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3554 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3556 if ( '' == $context ) {
3557 $text = preg_replace( $p2, '[[\\1]]', $text );
3559 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3562 # Trim trailing whitespace
3563 # MAG_END (__END__) tag allows for trailing
3564 # whitespace to be deliberately included
3565 $text = rtrim( $text );
3566 $mw =& MagicWord
::get( MAG_END
);
3567 $mw->matchAndRemove( $text );
3573 * Fetch the user's signature text, if any, and normalize to
3574 * validated, ready-to-insert wikitext.
3580 function getUserSig( &$user ) {
3581 $username = $user->getName();
3582 $nickname = $user->getOption( 'nickname' );
3583 $nickname = $nickname === '' ?
$username : $nickname;
3585 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3586 # Sig. might contain markup; validate this
3587 if( $this->validateSig( $nickname ) !== false ) {
3588 # Validated; clean up (if needed) and return it
3589 return $this->cleanSig( $nickname, true );
3591 # Failed to validate; fall back to the default
3592 $nickname = $username;
3593 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3597 # If we're still here, make it a link to the user page
3598 $userpage = $user->getUserPage();
3599 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3603 * Check that the user's signature contains no bad XML
3605 * @param string $text
3606 * @return mixed An expanded string, or false if invalid.
3608 function validateSig( $text ) {
3609 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3613 * Clean up signature text
3615 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3616 * 2) Substitute all transclusions
3618 * @param string $text
3619 * @param $parsing Whether we're cleaning (preferences save) or parsing
3620 * @return string Signature text
3622 function cleanSig( $text, $parsing = false ) {
3624 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3626 $substWord = MagicWord
::get( MAG_SUBST
);
3627 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3628 $substText = '{{' . $substWord->getSynonym( 0 );
3630 $text = preg_replace( $substRegex, $substText, $text );
3631 $text = preg_replace( '/~{3,5}/', '', $text );
3632 $text = $this->replaceVariables( $text );
3634 $this->clearState();
3639 * Set up some variables which are usually set up in parse()
3640 * so that an external function can call some class members with confidence
3643 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3644 $this->mTitle
=& $title;
3645 $this->mOptions
= $options;
3646 $this->mOutputType
= $outputType;
3647 if ( $clearState ) {
3648 $this->clearState();
3653 * Transform a MediaWiki message by replacing magic variables.
3655 * @param string $text the text to transform
3656 * @param ParserOptions $options options
3657 * @return string the text with variables substituted
3660 function transformMsg( $text, $options ) {
3662 static $executing = false;
3664 $fname = "Parser::transformMsg";
3666 # Guard against infinite recursion
3672 wfProfileIn($fname);
3674 $this->mTitle
= $wgTitle;
3675 $this->mOptions
= $options;
3676 $this->mOutputType
= OT_MSG
;
3677 $this->clearState();
3678 $text = $this->replaceVariables( $text );
3681 wfProfileOut($fname);
3686 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3687 * The callback should have the following form:
3688 * function myParserHook( $text, $params, &$parser ) { ... }
3690 * Transform and return $text. Use $parser for any required context, e.g. use
3691 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3695 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3696 * @param mixed $callback The callback function (and object) to use for the tag
3698 * @return The old value of the mTagHooks array associated with the hook
3700 function setHook( $tag, $callback ) {
3701 $oldVal = @$this->mTagHooks
[$tag];
3702 $this->mTagHooks
[$tag] = $callback;
3708 * Create a function, e.g. {{sum:1|2|3}}
3709 * The callback function should have the form:
3710 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3712 * The callback may either return the text result of the function, or an array with the text
3713 * in element 0, and a number of flags in the other elements. The names of the flags are
3714 * specified in the keys. Valid flags are:
3715 * found The text returned is valid, stop processing the template. This
3717 * nowiki Wiki markup in the return value should be escaped
3718 * noparse Unsafe HTML tags should not be stripped, etc.
3719 * noargs Don't replace triple-brace arguments in the return value
3720 * isHTML The returned text is HTML, armour it against wikitext transformation
3724 * @param string $name The function name. Function names are case-insensitive.
3725 * @param mixed $callback The callback function (and object) to use
3727 * @return The old callback function for this name, if any
3729 function setFunctionHook( $name, $callback ) {
3730 $name = strtolower( $name );
3731 $oldVal = @$this->mFunctionHooks
[$name];
3732 $this->mFunctionHooks
[$name] = $callback;
3737 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3738 * Placeholders created in Skin::makeLinkObj()
3739 * Returns an array of links found, indexed by PDBK:
3743 * $options is a bit field, RLH_FOR_UPDATE to select for update
3745 function replaceLinkHolders( &$text, $options = 0 ) {
3747 global $wgOutputReplace;
3749 $fname = 'Parser::replaceLinkHolders';
3750 wfProfileIn( $fname );
3754 $sk =& $this->mOptions
->getSkin();
3755 $linkCache =& LinkCache
::singleton();
3757 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3758 wfProfileIn( $fname.'-check' );
3759 $dbr =& wfGetDB( DB_SLAVE
);
3760 $page = $dbr->tableName( 'page' );
3761 $threshold = $wgUser->getOption('stubthreshold');
3764 asort( $this->mLinkHolders
['namespaces'] );
3768 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3770 $title = $this->mLinkHolders
['titles'][$key];
3772 # Skip invalid entries.
3773 # Result will be ugly, but prevents crash.
3774 if ( is_null( $title ) ) {
3777 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3779 # Check if it's a static known link, e.g. interwiki
3780 if ( $title->isAlwaysKnown() ) {
3781 $colours[$pdbk] = 1;
3782 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3783 $colours[$pdbk] = 1;
3784 $this->mOutput
->addLink( $title, $id );
3785 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3786 $colours[$pdbk] = 0;
3788 # Not in the link cache, add it to the query
3789 if ( !isset( $current ) ) {
3791 $query = "SELECT page_id, page_namespace, page_title";
3792 if ( $threshold > 0 ) {
3793 $query .= ', page_len, page_is_redirect';
3795 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3796 } elseif ( $current != $ns ) {
3798 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3803 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3808 if ( $options & RLH_FOR_UPDATE
) {
3809 $query .= ' FOR UPDATE';
3812 $res = $dbr->query( $query, $fname );
3814 # Fetch data and form into an associative array
3815 # non-existent = broken
3818 while ( $s = $dbr->fetchObject($res) ) {
3819 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3820 $pdbk = $title->getPrefixedDBkey();
3821 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3822 $this->mOutput
->addLink( $title, $s->page_id
);
3824 if ( $threshold > 0 ) {
3825 $size = $s->page_len
;
3826 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3827 $colours[$pdbk] = 1;
3829 $colours[$pdbk] = 2;
3832 $colours[$pdbk] = 1;
3836 wfProfileOut( $fname.'-check' );
3838 # Construct search and replace arrays
3839 wfProfileIn( $fname.'-construct' );
3840 $wgOutputReplace = array();
3841 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3842 $pdbk = $pdbks[$key];
3843 $searchkey = "<!--LINK $key-->";
3844 $title = $this->mLinkHolders
['titles'][$key];
3845 if ( empty( $colours[$pdbk] ) ) {
3846 $linkCache->addBadLinkObj( $title );
3847 $colours[$pdbk] = 0;
3848 $this->mOutput
->addLink( $title, 0 );
3849 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3850 $this->mLinkHolders
['texts'][$key],
3851 $this->mLinkHolders
['queries'][$key] );
3852 } elseif ( $colours[$pdbk] == 1 ) {
3853 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3854 $this->mLinkHolders
['texts'][$key],
3855 $this->mLinkHolders
['queries'][$key] );
3856 } elseif ( $colours[$pdbk] == 2 ) {
3857 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3858 $this->mLinkHolders
['texts'][$key],
3859 $this->mLinkHolders
['queries'][$key] );
3862 wfProfileOut( $fname.'-construct' );
3865 wfProfileIn( $fname.'-replace' );
3867 $text = preg_replace_callback(
3868 '/(<!--LINK .*?-->)/',
3869 "wfOutputReplaceMatches",
3872 wfProfileOut( $fname.'-replace' );
3875 # Now process interwiki link holders
3876 # This is quite a bit simpler than internal links
3877 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3878 wfProfileIn( $fname.'-interwiki' );
3879 # Make interwiki link HTML
3880 $wgOutputReplace = array();
3881 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3882 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3883 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3886 $text = preg_replace_callback(
3887 '/<!--IWLINK (.*?)-->/',
3888 "wfOutputReplaceMatches",
3890 wfProfileOut( $fname.'-interwiki' );
3893 wfProfileOut( $fname );
3898 * Replace <!--LINK--> link placeholders with plain text of links
3899 * (not HTML-formatted).
3900 * @param string $text
3903 function replaceLinkHoldersText( $text ) {
3904 $fname = 'Parser::replaceLinkHoldersText';
3905 wfProfileIn( $fname );
3907 $text = preg_replace_callback(
3908 '/<!--(LINK|IWLINK) (.*?)-->/',
3909 array( &$this, 'replaceLinkHoldersTextCallback' ),
3912 wfProfileOut( $fname );
3917 * @param array $matches
3921 function replaceLinkHoldersTextCallback( $matches ) {
3922 $type = $matches[1];
3924 if( $type == 'LINK' ) {
3925 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3926 return $this->mLinkHolders
['texts'][$key];
3928 } elseif( $type == 'IWLINK' ) {
3929 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3930 return $this->mInterwikiLinkHolders
['texts'][$key];
3937 * Renders an image gallery from a text with one line per image.
3938 * text labels may be given by using |-style alternative text. E.g.
3939 * Image:one.jpg|The number "1"
3940 * Image:tree.jpg|A tree
3941 * given as text will return the HTML of a gallery with two images,
3942 * labeled 'The number "1"' and
3945 function renderImageGallery( $text ) {
3947 $parserOptions = new ParserOptions
;
3948 $localParser = new Parser();
3950 $ig = new ImageGallery();
3951 $ig->setShowBytes( false );
3952 $ig->setShowFilename( false );
3954 $lines = explode( "\n", $text );
3956 foreach ( $lines as $line ) {
3957 # match lines like these:
3958 # Image:someimage.jpg|This is some image
3959 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3961 if ( count( $matches ) == 0 ) {
3964 $nt =& Title
::newFromText( $matches[1] );
3965 if( is_null( $nt ) ) {
3966 # Bogus title. Ignore these so we don't bomb out later.
3969 if ( isset( $matches[3] ) ) {
3970 $label = $matches[3];
3975 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3976 $html = $pout->getText();
3978 $ig->add( new Image( $nt ), $html );
3980 # Only add real images (bug #5586)
3981 if ( $nt->getNamespace() == NS_IMAGE
) {
3982 $this->mOutput
->addImage( $nt->getDBkey() );
3985 # Register links with the parent parser
3986 foreach( $pout->getLinks() as $ns => $keys ) {
3987 foreach( $keys as $dbk => $id )
3988 $this->mOutput
->addLink( Title
::makeTitle( $ns, $dbk ), $id );
3992 return $ig->toHTML();
3996 * Parse image options text and use it to make an image
3998 function makeImage( &$nt, $options ) {
3999 global $wgUseImageResize;
4003 # Check if the options text is of the form "options|alt text"
4005 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4006 # * left no resizing, just left align. label is used for alt= only
4007 # * right same, but right aligned
4008 # * none same, but not aligned
4009 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4010 # * center center the image
4011 # * framed Keep original image size, no magnify-button.
4013 $part = explode( '|', $options);
4015 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4016 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4017 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4018 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4019 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4020 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4021 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4022 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4025 $width = $height = $framed = $thumb = false;
4026 $manual_thumb = '' ;
4028 foreach( $part as $key => $val ) {
4029 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4031 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4032 # use manually specified thumbnail
4034 $manual_thumb = $match;
4035 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4036 # remember to set an alignment, don't render immediately
4038 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4039 # remember to set an alignment, don't render immediately
4041 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4042 # remember to set an alignment, don't render immediately
4044 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4045 # remember to set an alignment, don't render immediately
4047 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4048 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4049 # $match is the image width in pixels
4050 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4051 $width = intval( $m[1] );
4052 $height = intval( $m[2] );
4054 $width = intval($match);
4056 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4062 # Strip bad stuff out of the alt text
4063 $alt = $this->replaceLinkHoldersText( $caption );
4065 # make sure there are no placeholders in thumbnail attributes
4066 # that are later expanded to html- so expand them now and
4068 $alt = $this->unstrip($alt, $this->mStripState
);
4069 $alt = Sanitizer
::stripAllTags( $alt );
4071 # Linker does the rest
4072 $sk =& $this->mOptions
->getSkin();
4073 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4077 * Set a flag in the output object indicating that the content is dynamic and
4078 * shouldn't be cached.
4080 function disableCache() {
4081 wfDebug( "Parser output marked as uncacheable.\n" );
4082 $this->mOutput
->mCacheTime
= -1;
4086 * Callback from the Sanitizer for expanding items found in HTML attribute
4087 * values, so they can be safely tested and escaped.
4088 * @param string $text
4089 * @param array $args
4093 function attributeStripCallback( &$text, $args ) {
4094 $text = $this->replaceVariables( $text, $args );
4095 $text = $this->unstripForHTML( $text );
4099 function unstripForHTML( $text ) {
4100 $text = $this->unstrip( $text, $this->mStripState
);
4101 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4109 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4110 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4111 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4117 function getTags() { return array_keys( $this->mTagHooks
); }
4123 * @package MediaWiki
4127 var $mText, # The output text
4128 $mLanguageLinks, # List of the full text of language links, in the order they appear
4129 $mCategories, # Map of category names to sort keys
4130 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4131 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4132 $mVersion, # Compatibility check
4133 $mTitleText, # title text of the chosen language variant
4134 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4135 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4136 $mImages, # DB keys of the images used, in the array key only
4137 $mExternalLinks, # External link URLs, in the key only
4138 $mHTMLtitle, # Display HTML title
4139 $mSubtitle, # Additional subtitle
4140 $mNewSection; # Show a new section link?
4142 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4143 $containsOldMagic = false, $titletext = '' )
4145 $this->mText
= $text;
4146 $this->mLanguageLinks
= $languageLinks;
4147 $this->mCategories
= $categoryLinks;
4148 $this->mContainsOldMagic
= $containsOldMagic;
4149 $this->mCacheTime
= '';
4150 $this->mVersion
= MW_PARSER_VERSION
;
4151 $this->mTitleText
= $titletext;
4152 $this->mLinks
= array();
4153 $this->mTemplates
= array();
4154 $this->mImages
= array();
4155 $this->mExternalLinks
= array();
4156 $this->mHTMLtitle
= "" ;
4157 $this->mSubtitle
= "" ;
4158 $this->mNewSection
= false;
4161 function getText() { return $this->mText
; }
4162 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4163 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4164 function &getCategories() { return $this->mCategories
; }
4165 function getCacheTime() { return $this->mCacheTime
; }
4166 function getTitleText() { return $this->mTitleText
; }
4167 function &getLinks() { return $this->mLinks
; }
4168 function &getTemplates() { return $this->mTemplates
; }
4169 function &getImages() { return $this->mImages
; }
4170 function &getExternalLinks() { return $this->mExternalLinks
; }
4172 function containsOldMagic() { return $this->mContainsOldMagic
; }
4173 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4174 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4175 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4176 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4177 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4178 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4180 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4181 function addImage( $name ) { $this->mImages
[$name] = 1; }
4182 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4183 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4185 function setNewSection( $value ) {
4186 $this->mNewSection
= (bool)$value;
4188 function getNewSection() {
4189 return (bool)$this->mNewSection
;
4192 function addLink( $title, $id ) {
4193 $ns = $title->getNamespace();
4194 $dbk = $title->getDBkey();
4195 if ( !isset( $this->mLinks
[$ns] ) ) {
4196 $this->mLinks
[$ns] = array();
4198 $this->mLinks
[$ns][$dbk] = $id;
4201 function addTemplate( $title, $id ) {
4202 $ns = $title->getNamespace();
4203 $dbk = $title->getDBkey();
4204 if ( !isset( $this->mTemplates
[$ns] ) ) {
4205 $this->mTemplates
[$ns] = array();
4207 $this->mTemplates
[$ns][$dbk] = $id;
4211 * Return true if this cached output object predates the global or
4212 * per-article cache invalidation timestamps, or if it comes from
4213 * an incompatible older version.
4215 * @param string $touched the affected article's last touched timestamp
4219 function expired( $touched ) {
4220 global $wgCacheEpoch;
4221 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4222 $this->getCacheTime() < $touched ||
4223 $this->getCacheTime() <= $wgCacheEpoch ||
4224 !isset( $this->mVersion
) ||
4225 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4230 * Set options of the Parser
4232 * @package MediaWiki
4236 # All variables are private
4237 var $mUseTeX; # Use texvc to expand <math> tags
4238 var $mUseDynamicDates; # Use DateFormatter to format dates
4239 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4240 var $mAllowExternalImages; # Allow external images inline
4241 var $mAllowExternalImagesFrom; # If not, any exception?
4242 var $mSkin; # Reference to the preferred skin
4243 var $mDateFormat; # Date format index
4244 var $mEditSection; # Create "edit section" links
4245 var $mNumberHeadings; # Automatically number headings
4246 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4247 var $mTidy; # Ask for tidy cleanup
4248 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4250 function getUseTeX() { return $this->mUseTeX
; }
4251 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4252 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4253 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4254 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4255 function &getSkin() { return $this->mSkin
; }
4256 function getDateFormat() { return $this->mDateFormat
; }
4257 function getEditSection() { return $this->mEditSection
; }
4258 function getNumberHeadings() { return $this->mNumberHeadings
; }
4259 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4260 function getTidy() { return $this->mTidy
; }
4261 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4263 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4264 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4265 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4266 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4267 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4268 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4269 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4270 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4271 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4272 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4273 function setSkin( &$x ) { $this->mSkin
=& $x; }
4274 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4276 function ParserOptions() {
4278 $this->initialiseFromUser( $wgUser );
4282 * Get parser options
4285 function newFromUser( &$user ) {
4286 $popts = new ParserOptions
;
4287 $popts->initialiseFromUser( $user );
4291 /** Get user options */
4292 function initialiseFromUser( &$userInput ) {
4293 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4294 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4295 $fname = 'ParserOptions::initialiseFromUser';
4296 wfProfileIn( $fname );
4297 if ( !$userInput ) {
4299 $user->setLoaded( true );
4301 $user =& $userInput;
4304 $this->mUseTeX
= $wgUseTeX;
4305 $this->mUseDynamicDates
= $wgUseDynamicDates;
4306 $this->mInterwikiMagic
= $wgInterwikiMagic;
4307 $this->mAllowExternalImages
= $wgAllowExternalImages;
4308 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4309 wfProfileIn( $fname.'-skin' );
4310 $this->mSkin
=& $user->getSkin();
4311 wfProfileOut( $fname.'-skin' );
4312 $this->mDateFormat
= $user->getOption( 'date' );
4313 $this->mEditSection
= true;
4314 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4315 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4316 $this->mTidy
= false;
4317 $this->mInterfaceMessage
= false;
4318 wfProfileOut( $fname );
4323 * Callback function used by Parser::replaceLinkHolders()
4324 * to substitute link placeholders.
4326 function &wfOutputReplaceMatches( $matches ) {
4327 global $wgOutputReplace;
4328 return $wgOutputReplace[$matches[1]];
4332 * Return the total number of articles
4334 function wfNumberOfArticles() {
4335 global $wgNumberOfArticles;
4338 return $wgNumberOfArticles;
4342 * Return the number of files
4344 function wfNumberOfFiles() {
4345 $fname = 'wfNumberOfFiles';
4347 wfProfileIn( $fname );
4348 $dbr =& wfGetDB( DB_SLAVE
);
4349 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4350 wfProfileOut( $fname );
4356 * Return the number of user accounts
4359 function wfNumberOfUsers() {
4360 wfProfileIn( 'wfNumberOfUsers' );
4361 $dbr =& wfGetDB( DB_SLAVE
);
4362 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4363 wfProfileOut( 'wfNumberOfUsers' );
4368 * Return the total number of pages
4371 function wfNumberOfPages() {
4372 wfProfileIn( 'wfNumberOfPages' );
4373 $dbr =& wfGetDB( DB_SLAVE
);
4374 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4375 wfProfileOut( 'wfNumberOfPages' );
4380 * Get various statistics from the database
4383 function wfLoadSiteStats() {
4384 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4385 $fname = 'wfLoadSiteStats';
4387 if ( -1 != $wgNumberOfArticles ) return;
4388 $dbr =& wfGetDB( DB_SLAVE
);
4389 $s = $dbr->selectRow( 'site_stats',
4390 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4391 array( 'ss_row_id' => 1 ), $fname
4394 if ( $s === false ) {
4397 $wgTotalViews = $s->ss_total_views
;
4398 $wgTotalEdits = $s->ss_total_edits
;
4399 $wgNumberOfArticles = $s->ss_good_articles
;
4405 * Basically replacing " > and < with HTML entities ( ", >, <)
4407 * @param $in String: text that might contain HTML tags.
4408 * @return string Escaped string
4410 function wfEscapeHTMLTagsOnly( $in ) {
4412 array( '"', '>', '<' ),
4413 array( '"', '>', '<' ),