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;
154 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
156 # Clear these on every parse, bug 4549
157 $this->mTemplates
= array();
158 $this->mTemplatePath
= array();
160 $this->mShowToc
= true;
161 $this->mForceTocPosition
= false;
163 wfRunHooks( 'ParserClearState', array( &$this ) );
167 * Accessor for mUniqPrefix.
171 function UniqPrefix() {
172 return $this->mUniqPrefix
;
176 * Convert wikitext to HTML
177 * Do not call this function recursively.
180 * @param string $text Text we want to parse
181 * @param Title &$title A title object
182 * @param array $options
183 * @param boolean $linestart
184 * @param boolean $clearState
185 * @param int $revid number to pass in {{REVISIONID}}
186 * @return ParserOutput a ParserOutput
188 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
190 * First pass--just handle <nowiki> sections, pass the rest off
191 * to internalParse() which does all the real work.
194 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
195 $fname = 'Parser::parse';
196 wfProfileIn( $fname );
202 $this->mOptions
= $options;
203 $this->mTitle
=& $title;
204 $this->mRevisionId
= $revid;
205 $this->mOutputType
= OT_HTML
;
207 //$text = $this->strip( $text, $this->mStripState );
208 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
209 $x =& $this->mStripState
;
211 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
212 $text = $this->strip( $text, $x );
213 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
215 # Hook to suspend the parser in this state
216 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
217 wfProfileOut( $fname );
221 $text = $this->internalParse( $text );
223 $text = $this->unstrip( $text, $this->mStripState
);
225 # Clean up special characters, only run once, next-to-last before doBlockLevels
227 # french spaces, last one Guillemet-left
228 # only if there is something before the space
229 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
230 # french spaces, Guillemet-right
231 '/(\\302\\253) /' => '\\1 ',
232 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
234 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
237 $text = $this->doBlockLevels( $text, $linestart );
239 $this->replaceLinkHolders( $text );
241 # the position of the parserConvert() call should not be changed. it
242 # assumes that the links are all replaced and the only thing left
243 # is the <nowiki> mark.
244 # Side-effects: this calls $this->mOutput->setTitleText()
245 $text = $wgContLang->parserConvert( $text, $this );
247 $text = $this->unstripNoWiki( $text, $this->mStripState
);
249 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
251 $text = Sanitizer
::normalizeCharReferences( $text );
253 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
254 $text = Parser
::tidy($text);
256 # attempt to sanitize at least some nesting problems
257 # (bug #2702 and quite a few others)
259 # ''Something [http://www.cool.com cool''] -->
260 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
261 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
262 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
263 # fix up an anchor inside another anchor, only
264 # at least for a single single nested link (bug 3695)
265 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
266 '\\1\\2</a>\\3</a>\\1\\4</a>',
267 # fix div inside inline elements- doBlockLevels won't wrap a line which
268 # contains a div, so fix it up here; replace
269 # div with escaped text
270 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
271 '\\1\\3<div\\5>\\6</div>\\8\\9',
272 # remove empty italic or bold tag pairs, some
273 # introduced by rules above
274 '/<([bi])><\/\\1>/' => ''
277 $text = preg_replace(
278 array_keys( $tidyregs ),
279 array_values( $tidyregs ),
283 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
285 $this->mOutput
->setText( $text );
286 wfProfileOut( $fname );
288 return $this->mOutput
;
292 * Get a random string
297 function getRandomString() {
298 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
301 function &getTitle() { return $this->mTitle
; }
302 function getOptions() { return $this->mOptions
; }
305 * Replaces all occurrences of <$tag>content</$tag> in the text
306 * with a random marker and returns the new text. the output parameter
307 * $content will be an associative array filled with data on the form
308 * $unique_marker => content.
310 * If $content is already set, the additional entries will be appended
311 * If $tag is set to STRIP_COMMENTS, the function will extract
312 * <!-- HTML comments -->
317 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
318 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
333 if( $tag == STRIP_COMMENTS
) {
337 $start = "/<$tag(\\s+[^>]*|\\s*\/?)>/i";
338 $end = "/<\\/$tag\\s*>/i";
341 while ( '' != $text ) {
342 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
344 if( count( $p ) < 3 ) {
350 // If $attributes ends with '/', we have an empty element tag, <tag />
351 if( $tag != STRIP_COMMENTS
&& substr( $attributes, -1 ) == '/' ) {
352 $attributes = substr( $attributes, 0, -1);
358 $marker = $rnd . sprintf('%08X', $n++
);
359 $stripped .= $marker;
361 $tags[$marker] = "<$tag$attributes$empty>";
362 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
364 if ( $empty === '/' ) {
365 // Empty element tag, <tag />
366 $content[$marker] = null;
369 $q = preg_split( $end, $inside, 2 );
370 $content[$marker] = $q[0];
371 if( count( $q ) < 2 ) {
372 # No end tag -- let it run out to the end of the text.
383 * Wrapper function for extractTagsAndParams
384 * for cases where $tags and $params isn't needed
385 * i.e. where tags will never have params, like <nowiki>
390 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
391 $dummy_tags = array();
392 $dummy_params = array();
394 return Parser
::extractTagsAndParams( $tag, $text, $content,
395 $dummy_tags, $dummy_params, $uniq_prefix );
399 * Strips and renders nowiki, pre, math, hiero
400 * If $render is set, performs necessary rendering operations on plugins
401 * Returns the text, and fills an array with data needed in unstrip()
402 * If the $state is already a valid strip state, it adds to the state
404 * @param bool $stripcomments when set, HTML comments <!-- like this -->
405 * will be stripped in addition to other tags. This is important
406 * for section editing, where these comments cause confusion when
407 * counting the sections in the wikisource
411 function strip( $text, &$state, $stripcomments = false ) {
412 $render = ($this->mOutputType
== OT_HTML
);
413 $html_content = array();
414 $nowiki_content = array();
415 $math_content = array();
416 $pre_content = array();
417 $comment_content = array();
418 $ext_content = array();
420 $ext_params = array();
421 $gallery_content = array();
423 # Replace any instances of the placeholders
424 $uniq_prefix = $this->mUniqPrefix
;
425 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
430 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
431 foreach( $html_content as $marker => $content ) {
433 # Raw and unchecked for validity.
434 $html_content[$marker] = $content;
436 $html_content[$marker] = '<html>'.$content.'</html>';
442 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
443 foreach( $nowiki_content as $marker => $content ) {
445 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
447 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
452 if( $this->mOptions
->getUseTeX() ) {
453 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
454 foreach( $math_content as $marker => $content ){
456 $math_content[$marker] = renderMath( $content );
458 $math_content[$marker] = '<math>'.$content.'</math>';
464 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
465 foreach( $pre_content as $marker => $content ){
467 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
469 $pre_content[$marker] = '<pre>'.$content.'</pre>';
474 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
475 foreach( $gallery_content as $marker => $content ) {
476 require_once( 'ImageGallery.php' );
478 $gallery_content[$marker] = $this->renderImageGallery( $content );
480 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
485 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
486 foreach( $comment_content as $marker => $content ){
487 $comment_content[$marker] = '<!--'.$content.'-->';
491 foreach ( $this->mTagHooks
as $tag => $callback ) {
492 $ext_content[$tag] = array();
493 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
494 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
495 foreach( $ext_content[$tag] as $marker => $content ) {
496 $full_tag = $ext_tags[$tag][$marker];
497 $params = $ext_params[$tag][$marker];
499 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
501 if ( is_null( $content ) ) {
503 $ext_content[$tag][$marker] = $full_tag;
505 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
511 # Unstrip comments unless explicitly told otherwise.
512 # (The comments are always stripped prior to this point, so as to
513 # not invoke any extension tags / parser hooks contained within
515 if ( !$stripcomments ) {
516 $tempstate = array( 'comment' => $comment_content );
517 $text = $this->unstrip( $text, $tempstate );
518 $comment_content = array();
521 # Merge state with the pre-existing state, if there is one
523 $state['html'] = $state['html'] +
$html_content;
524 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
525 $state['math'] = $state['math'] +
$math_content;
526 $state['pre'] = $state['pre'] +
$pre_content;
527 $state['gallery'] = $state['gallery'] +
$gallery_content;
528 $state['comment'] = $state['comment'] +
$comment_content;
530 foreach( $ext_content as $tag => $array ) {
531 if ( array_key_exists( $tag, $state ) ) {
532 $state[$tag] = $state[$tag] +
$array;
537 'html' => $html_content,
538 'nowiki' => $nowiki_content,
539 'math' => $math_content,
540 'pre' => $pre_content,
541 'gallery' => $gallery_content,
542 'comment' => $comment_content,
549 * restores pre, math, and hiero removed by strip()
551 * always call unstripNoWiki() after this one
554 function unstrip( $text, &$state ) {
555 if ( !is_array( $state ) ) {
559 # Must expand in reverse order, otherwise nested tags will be corrupted
560 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
561 if( $tag != 'nowiki' && $tag != 'html' ) {
562 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
563 $text = str_replace( $uniq, $content, $text );
572 * always call this after unstrip() to preserve the order
576 function unstripNoWiki( $text, &$state ) {
577 if ( !is_array( $state ) ) {
581 # Must expand in reverse order, otherwise nested tags will be corrupted
582 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
583 $text = str_replace( key( $state['nowiki'] ), $content, $text );
588 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
589 $text = str_replace( key( $state['html'] ), $content, $text );
597 * Add an item to the strip state
598 * Returns the unique tag which must be inserted into the stripped text
599 * The tag will be replaced with the original text in unstrip()
603 function insertStripItem( $text, &$state ) {
604 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
611 'comment' => array(),
612 'gallery' => array(),
615 $state['item'][$rnd] = $text;
620 * Interface with html tidy, used if $wgUseTidy = true.
621 * If tidy isn't able to correct the markup, the original will be
622 * returned in all its glory with a warning comment appended.
624 * Either the external tidy program or the in-process tidy extension
625 * will be used depending on availability. Override the default
626 * $wgTidyInternal setting to disable the internal if it's not working.
628 * @param string $text Hideous HTML input
629 * @return string Corrected HTML output
633 function tidy( $text ) {
634 global $wgTidyInternal;
635 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
636 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
637 '<head><title>test</title></head><body>'.$text.'</body></html>';
638 if( $wgTidyInternal ) {
639 $correctedtext = Parser
::internalTidy( $wrappedtext );
641 $correctedtext = Parser
::externalTidy( $wrappedtext );
643 if( is_null( $correctedtext ) ) {
644 wfDebug( "Tidy error detected!\n" );
645 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
647 return $correctedtext;
651 * Spawn an external HTML tidy process and get corrected markup back from it.
656 function externalTidy( $text ) {
657 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
658 $fname = 'Parser::externalTidy';
659 wfProfileIn( $fname );
664 $descriptorspec = array(
665 0 => array('pipe', 'r'),
666 1 => array('pipe', 'w'),
667 2 => array('file', '/dev/null', 'a')
670 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
671 if (is_resource($process)) {
672 // Theoretically, this style of communication could cause a deadlock
673 // here. If the stdout buffer fills up, then writes to stdin could
674 // block. This doesn't appear to happen with tidy, because tidy only
675 // writes to stdout after it's finished reading from stdin. Search
676 // for tidyParseStdin and tidySaveStdout in console/tidy.c
677 fwrite($pipes[0], $text);
679 while (!feof($pipes[1])) {
680 $cleansource .= fgets($pipes[1], 1024);
683 proc_close($process);
686 wfProfileOut( $fname );
688 if( $cleansource == '' && $text != '') {
689 // Some kind of error happened, so we couldn't get the corrected text.
690 // Just give up; we'll use the source text and append a warning.
698 * Use the HTML tidy PECL extension to use the tidy library in-process,
699 * saving the overhead of spawning a new process. Currently written to
700 * the PHP 4.3.x version of the extension, may not work on PHP 5.
702 * 'pear install tidy' should be able to compile the extension module.
707 function internalTidy( $text ) {
709 $fname = 'Parser::internalTidy';
710 wfProfileIn( $fname );
712 tidy_load_config( $wgTidyConf );
713 tidy_set_encoding( 'utf8' );
714 tidy_parse_string( $text );
716 if( tidy_get_status() == 2 ) {
717 // 2 is magic number for fatal error
718 // http://www.php.net/manual/en/function.tidy-get-status.php
721 $cleansource = tidy_get_output();
723 wfProfileOut( $fname );
728 * parse the wiki syntax used to render tables
732 function doTableStuff ( $t ) {
733 $fname = 'Parser::doTableStuff';
734 wfProfileIn( $fname );
736 $t = explode ( "\n" , $t ) ;
737 $td = array () ; # Is currently a td tag open?
738 $ltd = array () ; # Was it TD or TH?
739 $tr = array () ; # Is currently a tr tag open?
740 $ltr = array () ; # tr attributes
741 $has_opened_tr = array(); # Did this table open a <tr> element?
742 $indent_level = 0; # indent level of the table
743 foreach ( $t AS $k => $x )
746 $fc = substr ( $x , 0 , 1 ) ;
747 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
748 $indent_level = strlen( $matches[1] );
750 $attributes = $this->unstripForHTML( $matches[2] );
752 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
753 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
754 array_push ( $td , false ) ;
755 array_push ( $ltd , '' ) ;
756 array_push ( $tr , false ) ;
757 array_push ( $ltr , '' ) ;
758 array_push ( $has_opened_tr, false );
760 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
761 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
762 $z = "</table>" . substr ( $x , 2);
763 $l = array_pop ( $ltd ) ;
764 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
765 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
766 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
768 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
770 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
771 $x = substr ( $x , 1 ) ;
772 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
774 $l = array_pop ( $ltd ) ;
775 array_pop ( $has_opened_tr );
776 array_push ( $has_opened_tr , true ) ;
777 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
778 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
781 array_push ( $tr , false ) ;
782 array_push ( $td , false ) ;
783 array_push ( $ltd , '' ) ;
784 $attributes = $this->unstripForHTML( $x );
785 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
787 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
789 if ( '|+' == substr ( $x , 0 , 2 ) ) {
791 $x = substr ( $x , 1 ) ;
793 $after = substr ( $x , 1 ) ;
794 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
796 // Split up multiple cells on the same line.
797 // FIXME: This can result in improper nesting of tags processed
798 // by earlier parser steps, but should avoid splitting up eg
799 // attribute values containing literal "||".
800 $after = wfExplodeMarkup( '||', $after );
804 # Loop through each table cell
805 foreach ( $after AS $theline )
810 $tra = array_pop ( $ltr ) ;
811 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
812 array_push ( $tr , true ) ;
813 array_push ( $ltr , '' ) ;
814 array_pop ( $has_opened_tr );
815 array_push ( $has_opened_tr , true ) ;
818 $l = array_pop ( $ltd ) ;
819 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
820 if ( $fc == '|' ) $l = 'td' ;
821 else if ( $fc == '!' ) $l = 'th' ;
822 else if ( $fc == '+' ) $l = 'caption' ;
824 array_push ( $ltd , $l ) ;
827 $y = explode ( '|' , $theline , 2 ) ;
828 # Note that a '|' inside an invalid link should not
829 # be mistaken as delimiting cell parameters
830 if ( strpos( $y[0], '[[' ) !== false ) {
831 $y = array ($theline);
833 if ( count ( $y ) == 1 )
834 $y = "{$z}<{$l}>{$y[0]}" ;
836 $attributes = $this->unstripForHTML( $y[0] );
837 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
840 array_push ( $td , true ) ;
845 # Closing open td, tr && table
846 while ( count ( $td ) > 0 )
848 $l = array_pop ( $ltd ) ;
849 if ( array_pop ( $td ) ) $t[] = '</td>' ;
850 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
851 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
855 $t = implode ( "\n" , $t ) ;
856 # special case: don't return empty table
857 if($t == "<table>\n<tr><td></td></tr>\n</table>")
859 wfProfileOut( $fname );
864 * Helper function for parse() that transforms wiki markup into
865 * HTML. Only called for $mOutputType == OT_HTML.
869 function internalParse( $text ) {
872 $fname = 'Parser::internalParse';
873 wfProfileIn( $fname );
875 # Remove <noinclude> tags and <includeonly> sections
876 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
877 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
878 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
880 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
882 $text = $this->replaceVariables( $text, $args );
884 // Tables need to come after variable replacement for things to work
885 // properly; putting them before other transformations should keep
886 // exciting things like link expansions from showing up in surprising
888 $text = $this->doTableStuff( $text );
890 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
892 $text = $this->stripToc( $text );
893 $text = $this->doHeadings( $text );
894 if($this->mOptions
->getUseDynamicDates()) {
895 $df =& DateFormatter
::getInstance();
896 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
898 $text = $this->doAllQuotes( $text );
899 $text = $this->replaceInternalLinks( $text );
900 $text = $this->replaceExternalLinks( $text );
902 # replaceInternalLinks may sometimes leave behind
903 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
904 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
906 $text = $this->doMagicLinks( $text );
907 $text = $this->formatHeadings( $text, $isMain );
909 wfProfileOut( $fname );
914 * Replace special strings like "ISBN xxx" and "RFC xxx" with
915 * magic external links.
919 function &doMagicLinks( &$text ) {
920 $text = $this->magicISBN( $text );
921 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
922 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
927 * Parse headers and return html
931 function doHeadings( $text ) {
932 $fname = 'Parser::doHeadings';
933 wfProfileIn( $fname );
934 for ( $i = 6; $i >= 1; --$i ) {
935 $h = str_repeat( '=', $i );
936 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
937 "<h{$i}>\\1</h{$i}>\\2", $text );
939 wfProfileOut( $fname );
944 * Replace single quotes with HTML markup
946 * @return string the altered text
948 function doAllQuotes( $text ) {
949 $fname = 'Parser::doAllQuotes';
950 wfProfileIn( $fname );
952 $lines = explode( "\n", $text );
953 foreach ( $lines as $line ) {
954 $outtext .= $this->doQuotes ( $line ) . "\n";
956 $outtext = substr($outtext, 0,-1);
957 wfProfileOut( $fname );
962 * Helper function for doAllQuotes()
965 function doQuotes( $text ) {
966 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
967 if ( count( $arr ) == 1 )
971 # First, do some preliminary work. This may shift some apostrophes from
972 # being mark-up to being text. It also counts the number of occurrences
973 # of bold and italics mark-ups.
977 foreach ( $arr as $r )
979 if ( ( $i %
2 ) == 1 )
981 # If there are ever four apostrophes, assume the first is supposed to
982 # be text, and the remaining three constitute mark-up for bold text.
983 if ( strlen( $arr[$i] ) == 4 )
988 # If there are more than 5 apostrophes in a row, assume they're all
989 # text except for the last 5.
990 else if ( strlen( $arr[$i] ) > 5 )
992 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
995 # Count the number of occurrences of bold and italics mark-ups.
996 # We are not counting sequences of five apostrophes.
997 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
998 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
999 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1004 # If there is an odd number of both bold and italics, it is likely
1005 # that one of the bold ones was meant to be an apostrophe followed
1006 # by italics. Which one we cannot know for certain, but it is more
1007 # likely to be one that has a single-letter word before it.
1008 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1011 $firstsingleletterword = -1;
1012 $firstmultiletterword = -1;
1014 foreach ( $arr as $r )
1016 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1018 $x1 = substr ($arr[$i-1], -1);
1019 $x2 = substr ($arr[$i-1], -2, 1);
1021 if ($firstspace == -1) $firstspace = $i;
1022 } else if ($x2 == ' ') {
1023 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1025 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1031 # If there is a single-letter word, use it!
1032 if ($firstsingleletterword > -1)
1034 $arr [ $firstsingleletterword ] = "''";
1035 $arr [ $firstsingleletterword-1 ] .= "'";
1037 # If not, but there's a multi-letter word, use that one.
1038 else if ($firstmultiletterword > -1)
1040 $arr [ $firstmultiletterword ] = "''";
1041 $arr [ $firstmultiletterword-1 ] .= "'";
1043 # ... otherwise use the first one that has neither.
1044 # (notice that it is possible for all three to be -1 if, for example,
1045 # there is only one pentuple-apostrophe in the line)
1046 else if ($firstspace > -1)
1048 $arr [ $firstspace ] = "''";
1049 $arr [ $firstspace-1 ] .= "'";
1053 # Now let's actually convert our apostrophic mush to HTML!
1058 foreach ($arr as $r)
1062 if ($state == 'both')
1069 if (strlen ($r) == 2)
1072 { $output .= '</i>'; $state = ''; }
1073 else if ($state == 'bi')
1074 { $output .= '</i>'; $state = 'b'; }
1075 else if ($state == 'ib')
1076 { $output .= '</b></i><b>'; $state = 'b'; }
1077 else if ($state == 'both')
1078 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1079 else # $state can be 'b' or ''
1080 { $output .= '<i>'; $state .= 'i'; }
1082 else if (strlen ($r) == 3)
1085 { $output .= '</b>'; $state = ''; }
1086 else if ($state == 'bi')
1087 { $output .= '</i></b><i>'; $state = 'i'; }
1088 else if ($state == 'ib')
1089 { $output .= '</b>'; $state = 'i'; }
1090 else if ($state == 'both')
1091 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1092 else # $state can be 'i' or ''
1093 { $output .= '<b>'; $state .= 'b'; }
1095 else if (strlen ($r) == 5)
1098 { $output .= '</b><i>'; $state = 'i'; }
1099 else if ($state == 'i')
1100 { $output .= '</i><b>'; $state = 'b'; }
1101 else if ($state == 'bi')
1102 { $output .= '</i></b>'; $state = ''; }
1103 else if ($state == 'ib')
1104 { $output .= '</b></i>'; $state = ''; }
1105 else if ($state == 'both')
1106 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1107 else # ($state == '')
1108 { $buffer = ''; $state = 'both'; }
1113 # Now close all remaining tags. Notice that the order is important.
1114 if ($state == 'b' ||
$state == 'ib')
1116 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1120 if ($state == 'both')
1121 $output .= '<b><i>'.$buffer.'</i></b>';
1127 * Replace external links
1129 * Note: this is all very hackish and the order of execution matters a lot.
1130 * Make sure to run maintenance/parserTests.php if you change this code.
1134 function replaceExternalLinks( $text ) {
1136 $fname = 'Parser::replaceExternalLinks';
1137 wfProfileIn( $fname );
1139 $sk =& $this->mOptions
->getSkin();
1141 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1143 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1146 while ( $i<count( $bits ) ) {
1148 $protocol = $bits[$i++
];
1149 $text = $bits[$i++
];
1150 $trail = $bits[$i++
];
1152 # The characters '<' and '>' (which were escaped by
1153 # removeHTMLtags()) should not be included in
1154 # URLs, per RFC 2396.
1155 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1156 $text = substr($url, $m2[0][1]) . ' ' . $text;
1157 $url = substr($url, 0, $m2[0][1]);
1160 # If the link text is an image URL, replace it with an <img> tag
1161 # This happened by accident in the original parser, but some people used it extensively
1162 $img = $this->maybeMakeExternalImage( $text );
1163 if ( $img !== false ) {
1169 # Set linktype for CSS - if URL==text, link is essentially free
1170 $linktype = ($text == $url) ?
'free' : 'text';
1172 # No link text, e.g. [http://domain.tld/some.link]
1173 if ( $text == '' ) {
1174 # Autonumber if allowed. See bug #5918
1175 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1176 $text = '[' . ++
$this->mAutonumber
. ']';
1177 $linktype = 'autonumber';
1179 # Otherwise just use the URL
1180 $text = htmlspecialchars( $url );
1184 # Have link text, e.g. [http://domain.tld/some.link text]s
1186 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1189 $text = $wgContLang->markNoConversion($text);
1191 # Replace & from obsolete syntax with &.
1192 # All HTML entities will be escaped by makeExternalLink()
1193 $url = str_replace( '&', '&', $url );
1195 # Process the trail (i.e. everything after this link up until start of the next link),
1196 # replacing any non-bracketed links
1197 $trail = $this->replaceFreeExternalLinks( $trail );
1199 # Use the encoded URL
1200 # This means that users can paste URLs directly into the text
1201 # Funny characters like ö aren't valid in URLs anyway
1202 # This was changed in August 2004
1203 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1205 # Register link in the output object.
1206 # Replace unnecessary URL escape codes with the referenced character
1207 # This prevents spammers from hiding links from the filters
1208 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1209 $this->mOutput
->addExternalLink( $pasteurized );
1212 wfProfileOut( $fname );
1217 * Replace anything that looks like a URL with a link
1220 function replaceFreeExternalLinks( $text ) {
1222 $fname = 'Parser::replaceFreeExternalLinks';
1223 wfProfileIn( $fname );
1225 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1226 $s = array_shift( $bits );
1229 $sk =& $this->mOptions
->getSkin();
1231 while ( $i < count( $bits ) ){
1232 $protocol = $bits[$i++
];
1233 $remainder = $bits[$i++
];
1235 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1236 # Found some characters after the protocol that look promising
1237 $url = $protocol . $m[1];
1240 # special case: handle urls as url args:
1241 # http://www.example.com/foo?=http://www.example.com/bar
1242 if(strlen($trail) == 0 &&
1244 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1245 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1248 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1253 # The characters '<' and '>' (which were escaped by
1254 # removeHTMLtags()) should not be included in
1255 # URLs, per RFC 2396.
1256 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1257 $trail = substr($url, $m2[0][1]) . $trail;
1258 $url = substr($url, 0, $m2[0][1]);
1261 # Move trailing punctuation to $trail
1263 # If there is no left bracket, then consider right brackets fair game too
1264 if ( strpos( $url, '(' ) === false ) {
1268 $numSepChars = strspn( strrev( $url ), $sep );
1269 if ( $numSepChars ) {
1270 $trail = substr( $url, -$numSepChars ) . $trail;
1271 $url = substr( $url, 0, -$numSepChars );
1274 # Replace & from obsolete syntax with &.
1275 # All HTML entities will be escaped by makeExternalLink()
1276 # or maybeMakeExternalImage()
1277 $url = str_replace( '&', '&', $url );
1279 # Is this an external image?
1280 $text = $this->maybeMakeExternalImage( $url );
1281 if ( $text === false ) {
1282 # Not an image, make a link
1283 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1284 # Register it in the output object...
1285 # Replace unnecessary URL escape codes with their equivalent characters
1286 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1287 $this->mOutput
->addExternalLink( $pasteurized );
1289 $s .= $text . $trail;
1291 $s .= $protocol . $remainder;
1294 wfProfileOut( $fname );
1299 * Replace unusual URL escape codes with their equivalent characters
1303 * @fixme This can merge genuinely required bits in the path or query string,
1304 * breaking legit URLs. A proper fix would treat the various parts of
1305 * the URL differently; as a workaround, just use the output for
1306 * statistical records, not for actual linking/output.
1308 function replaceUnusualEscapes( $url ) {
1309 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1310 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1314 * Callback function used in replaceUnusualEscapes().
1315 * Replaces unusual URL escape codes with their equivalent character
1319 function replaceUnusualEscapesCallback( $matches ) {
1320 $char = urldecode( $matches[0] );
1321 $ord = ord( $char );
1322 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1323 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1324 // No, shouldn't be escaped
1327 // Yes, leave it escaped
1333 * make an image if it's allowed, either through the global
1334 * option or through the exception
1337 function maybeMakeExternalImage( $url ) {
1338 $sk =& $this->mOptions
->getSkin();
1339 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1340 $imagesexception = !empty($imagesfrom);
1342 if ( $this->mOptions
->getAllowExternalImages()
1343 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1344 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1346 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1353 * Process [[ ]] wikilinks
1357 function replaceInternalLinks( $s ) {
1359 static $fname = 'Parser::replaceInternalLinks' ;
1361 wfProfileIn( $fname );
1363 wfProfileIn( $fname.'-setup' );
1365 # the % is needed to support urlencoded titles as well
1366 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1368 $sk =& $this->mOptions
->getSkin();
1370 #split the entire text string on occurences of [[
1371 $a = explode( '[[', ' ' . $s );
1372 #get the first element (all text up to first [[), and remove the space we added
1373 $s = array_shift( $a );
1374 $s = substr( $s, 1 );
1376 # Match a link having the form [[namespace:link|alternate]]trail
1378 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1379 # Match cases where there is no "]]", which might still be images
1380 static $e1_img = FALSE;
1381 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1382 # Match the end of a line for a word that's not followed by whitespace,
1383 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1384 $e2 = wfMsgForContent( 'linkprefix' );
1386 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1388 if( is_null( $this->mTitle
) ) {
1389 wfDebugDieBacktrace( 'nooo' );
1391 $nottalk = !$this->mTitle
->isTalkPage();
1393 if ( $useLinkPrefixExtension ) {
1394 if ( preg_match( $e2, $s, $m ) ) {
1395 $first_prefix = $m[2];
1397 $first_prefix = false;
1403 $selflink = $this->mTitle
->getPrefixedText();
1404 wfProfileOut( $fname.'-setup' );
1406 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1407 $useSubpages = $this->areSubpagesAllowed();
1409 # Loop for each link
1410 for ($k = 0; isset( $a[$k] ); $k++
) {
1412 if ( $useLinkPrefixExtension ) {
1413 wfProfileIn( $fname.'-prefixhandling' );
1414 if ( preg_match( $e2, $s, $m ) ) {
1422 $prefix = $first_prefix;
1423 $first_prefix = false;
1425 wfProfileOut( $fname.'-prefixhandling' );
1428 $might_be_img = false;
1430 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1432 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1433 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1434 # the real problem is with the $e1 regex
1437 # Still some problems for cases where the ] is meant to be outside punctuation,
1438 # and no image is in sight. See bug 2095.
1441 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1442 strpos($text, '[') !== false
1445 $text .= ']'; # so that replaceExternalLinks($text) works later
1448 # fix up urlencoded title texts
1449 if(preg_match('/%/', $m[1] ))
1450 # Should anchors '#' also be rejected?
1451 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1453 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1454 $might_be_img = true;
1456 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1458 } else { # Invalid form; output directly
1459 $s .= $prefix . '[[' . $line ;
1463 # Don't allow internal links to pages containing
1464 # PROTO: where PROTO is a valid URL protocol; these
1465 # should be external links.
1466 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1467 $s .= $prefix . '[[' . $line ;
1471 # Make subpage if necessary
1472 if( $useSubpages ) {
1473 $link = $this->maybeDoSubpageLink( $m[1], $text );
1478 $noforce = (substr($m[1], 0, 1) != ':');
1480 # Strip off leading ':'
1481 $link = substr($link, 1);
1484 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1486 $s .= $prefix . '[[' . $line;
1490 #check other language variants of the link
1491 #if the article does not exist
1492 if( $checkVariantLink
1493 && $nt->getArticleID() == 0 ) {
1494 $wgContLang->findVariantLink($link, $nt);
1497 $ns = $nt->getNamespace();
1498 $iw = $nt->getInterWiki();
1500 if ($might_be_img) { # if this is actually an invalid link
1501 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1503 while (isset ($a[$k+
1]) ) {
1504 #look at the next 'line' to see if we can close it there
1505 $spliced = array_splice( $a, $k +
1, 1 );
1506 $next_line = array_shift( $spliced );
1507 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1508 # the first ]] closes the inner link, the second the image
1510 $text .= '[[' . $m[1];
1513 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1514 #if there's exactly one ]] that's fine, we'll keep looking
1515 $text .= '[[' . $m[0];
1517 #if $next_line is invalid too, we need look no further
1518 $text .= '[[' . $next_line;
1523 # we couldn't find the end of this imageLink, so output it raw
1524 #but don't ignore what might be perfectly normal links in the text we've examined
1525 $text = $this->replaceInternalLinks($text);
1526 $s .= $prefix . '[[' . $link . '|' . $text;
1527 # note: no $trail, because without an end, there *is* no trail
1530 } else { #it's not an image, so output it raw
1531 $s .= $prefix . '[[' . $link . '|' . $text;
1532 # note: no $trail, because without an end, there *is* no trail
1537 $wasblank = ( '' == $text );
1538 if( $wasblank ) $text = $link;
1541 # Link not escaped by : , create the various objects
1545 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1546 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1547 $s = rtrim($s . "\n");
1548 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1552 if ( $ns == NS_IMAGE
) {
1553 wfProfileIn( "$fname-image" );
1554 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1555 # recursively parse links inside the image caption
1556 # actually, this will parse them in any other parameters, too,
1557 # but it might be hard to fix that, and it doesn't matter ATM
1558 $text = $this->replaceExternalLinks($text);
1559 $text = $this->replaceInternalLinks($text);
1561 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1562 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1563 $this->mOutput
->addImage( $nt->getDBkey() );
1565 wfProfileOut( "$fname-image" );
1568 wfProfileOut( "$fname-image" );
1572 if ( $ns == NS_CATEGORY
) {
1573 wfProfileIn( "$fname-category" );
1574 $s = rtrim($s . "\n"); # bug 87
1577 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1578 $sortkey = $this->mTitle
->getText();
1580 $sortkey = $this->mTitle
->getPrefixedText();
1585 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1586 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1587 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1590 * Strip the whitespace Category links produce, see bug 87
1591 * @todo We might want to use trim($tmp, "\n") here.
1593 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1595 wfProfileOut( "$fname-category" );
1600 if( ( $nt->getPrefixedText() === $selflink ) &&
1601 ( $nt->getFragment() === '' ) ) {
1602 # Self-links are handled specially; generally de-link and change to bold.
1603 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1607 # Special and Media are pseudo-namespaces; no pages actually exist in them
1608 if( $ns == NS_MEDIA
) {
1609 $link = $sk->makeMediaLinkObj( $nt, $text );
1610 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1611 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1612 $this->mOutput
->addImage( $nt->getDBkey() );
1614 } elseif( $ns == NS_SPECIAL
) {
1615 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1617 } elseif( $ns == NS_IMAGE
) {
1618 $img = Image
::newFromTitle( $nt );
1619 if( $img->exists() ) {
1620 // Force a blue link if the file exists; may be a remote
1621 // upload on the shared repository, and we want to see its
1622 // auto-generated page.
1623 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1627 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1629 wfProfileOut( $fname );
1634 * Make a link placeholder. The text returned can be later resolved to a real link with
1635 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1636 * parsing of interwiki links, and secondly to allow all extistence checks and
1637 * article length checks (for stub links) to be bundled into a single query.
1640 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1641 if ( ! is_object($nt) ) {
1643 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1645 # Separate the link trail from the rest of the link
1646 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1648 if ( $nt->isExternal() ) {
1649 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1650 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1651 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1653 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1654 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1655 $this->mLinkHolders
['queries'][] = $query;
1656 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1657 $this->mLinkHolders
['titles'][] = $nt;
1659 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1666 * Render a forced-blue link inline; protect against double expansion of
1667 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1668 * Since this little disaster has to split off the trail text to avoid
1669 * breaking URLs in the following text without breaking trails on the
1670 * wiki links, it's been made into a horrible function.
1673 * @param string $text
1674 * @param string $query
1675 * @param string $trail
1676 * @param string $prefix
1677 * @return string HTML-wikitext mix oh yuck
1679 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1680 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1681 $sk =& $this->mOptions
->getSkin();
1682 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1683 return $this->armorLinks( $link ) . $trail;
1687 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1688 * going to go through further parsing steps before inline URL expansion.
1690 * In particular this is important when using action=render, which causes
1691 * full URLs to be included.
1693 * Oh man I hate our multi-layer parser!
1695 * @param string more-or-less HTML
1696 * @return string less-or-more HTML with NOPARSE bits
1698 function armorLinks( $text ) {
1699 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1700 "{$this->mUniqPrefix}NOPARSE$1", $text );
1704 * Return true if subpage links should be expanded on this page.
1707 function areSubpagesAllowed() {
1708 # Some namespaces don't allow subpages
1709 global $wgNamespacesWithSubpages;
1710 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1714 * Handle link to subpage if necessary
1715 * @param string $target the source of the link
1716 * @param string &$text the link text, modified as necessary
1717 * @return string the full name of the link
1720 function maybeDoSubpageLink($target, &$text) {
1723 # :Foobar -- override special treatment of prefix (images, language links)
1724 # /Foobar -- convert to CurrentPage/Foobar
1725 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1726 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1727 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1729 $fname = 'Parser::maybeDoSubpageLink';
1730 wfProfileIn( $fname );
1731 $ret = $target; # default return value is no change
1733 # Some namespaces don't allow subpages,
1734 # so only perform processing if subpages are allowed
1735 if( $this->areSubpagesAllowed() ) {
1736 # Look at the first character
1737 if( $target != '' && $target{0} == '/' ) {
1738 # / at end means we don't want the slash to be shown
1739 if( substr( $target, -1, 1 ) == '/' ) {
1740 $target = substr( $target, 1, -1 );
1743 $noslash = substr( $target, 1 );
1746 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1747 if( '' === $text ) {
1749 } # this might be changed for ugliness reasons
1751 # check for .. subpage backlinks
1753 $nodotdot = $target;
1754 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1756 $nodotdot = substr( $nodotdot, 3 );
1758 if($dotdotcount > 0) {
1759 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1760 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1761 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1762 # / at the end means don't show full path
1763 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1764 $nodotdot = substr( $nodotdot, 0, -1 );
1765 if( '' === $text ) {
1769 $nodotdot = trim( $nodotdot );
1770 if( $nodotdot != '' ) {
1771 $ret .= '/' . $nodotdot;
1778 wfProfileOut( $fname );
1783 * Used by doBlockLevels()
1786 /* private */ function closeParagraph() {
1788 if ( '' != $this->mLastSection
) {
1789 $result = '</' . $this->mLastSection
. ">\n";
1791 $this->mInPre
= false;
1792 $this->mLastSection
= '';
1795 # getCommon() returns the length of the longest common substring
1796 # of both arguments, starting at the beginning of both.
1798 /* private */ function getCommon( $st1, $st2 ) {
1799 $fl = strlen( $st1 );
1800 $shorter = strlen( $st2 );
1801 if ( $fl < $shorter ) { $shorter = $fl; }
1803 for ( $i = 0; $i < $shorter; ++
$i ) {
1804 if ( $st1{$i} != $st2{$i} ) { break; }
1808 # These next three functions open, continue, and close the list
1809 # element appropriate to the prefix character passed into them.
1811 /* private */ function openList( $char ) {
1812 $result = $this->closeParagraph();
1814 if ( '*' == $char ) { $result .= '<ul><li>'; }
1815 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1816 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1817 else if ( ';' == $char ) {
1818 $result .= '<dl><dt>';
1819 $this->mDTopen
= true;
1821 else { $result = '<!-- ERR 1 -->'; }
1826 /* private */ function nextItem( $char ) {
1827 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1828 else if ( ':' == $char ||
';' == $char ) {
1830 if ( $this->mDTopen
) { $close = '</dt>'; }
1831 if ( ';' == $char ) {
1832 $this->mDTopen
= true;
1833 return $close . '<dt>';
1835 $this->mDTopen
= false;
1836 return $close . '<dd>';
1839 return '<!-- ERR 2 -->';
1842 /* private */ function closeList( $char ) {
1843 if ( '*' == $char ) { $text = '</li></ul>'; }
1844 else if ( '#' == $char ) { $text = '</li></ol>'; }
1845 else if ( ':' == $char ) {
1846 if ( $this->mDTopen
) {
1847 $this->mDTopen
= false;
1848 $text = '</dt></dl>';
1850 $text = '</dd></dl>';
1853 else { return '<!-- ERR 3 -->'; }
1859 * Make lists from lines starting with ':', '*', '#', etc.
1862 * @return string the lists rendered as HTML
1864 function doBlockLevels( $text, $linestart ) {
1865 $fname = 'Parser::doBlockLevels';
1866 wfProfileIn( $fname );
1868 # Parsing through the text line by line. The main thing
1869 # happening here is handling of block-level elements p, pre,
1870 # and making lists from lines starting with * # : etc.
1872 $textLines = explode( "\n", $text );
1874 $lastPrefix = $output = '';
1875 $this->mDTopen
= $inBlockElem = false;
1877 $paragraphStack = false;
1879 if ( !$linestart ) {
1880 $output .= array_shift( $textLines );
1882 foreach ( $textLines as $oLine ) {
1883 $lastPrefixLength = strlen( $lastPrefix );
1884 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1885 $preOpenMatch = preg_match('/<pre/i', $oLine );
1886 if ( !$this->mInPre
) {
1887 # Multiple prefixes may abut each other for nested lists.
1888 $prefixLength = strspn( $oLine, '*#:;' );
1889 $pref = substr( $oLine, 0, $prefixLength );
1892 $pref2 = str_replace( ';', ':', $pref );
1893 $t = substr( $oLine, $prefixLength );
1894 $this->mInPre
= !empty($preOpenMatch);
1896 # Don't interpret any other prefixes in preformatted text
1898 $pref = $pref2 = '';
1903 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1904 # Same as the last item, so no need to deal with nesting or opening stuff
1905 $output .= $this->nextItem( substr( $pref, -1 ) );
1906 $paragraphStack = false;
1908 if ( substr( $pref, -1 ) == ';') {
1909 # The one nasty exception: definition lists work like this:
1910 # ; title : definition text
1911 # So we check for : in the remainder text to split up the
1912 # title and definition, without b0rking links.
1914 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1916 $output .= $term . $this->nextItem( ':' );
1919 } elseif( $prefixLength ||
$lastPrefixLength ) {
1920 # Either open or close a level...
1921 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1922 $paragraphStack = false;
1924 while( $commonPrefixLength < $lastPrefixLength ) {
1925 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1926 --$lastPrefixLength;
1928 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1929 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1931 while ( $prefixLength > $commonPrefixLength ) {
1932 $char = substr( $pref, $commonPrefixLength, 1 );
1933 $output .= $this->openList( $char );
1935 if ( ';' == $char ) {
1936 # FIXME: This is dupe of code above
1937 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1939 $output .= $term . $this->nextItem( ':' );
1942 ++
$commonPrefixLength;
1944 $lastPrefix = $pref2;
1946 if( 0 == $prefixLength ) {
1947 wfProfileIn( "$fname-paragraph" );
1948 # No prefix (not in list)--go to paragraph mode
1949 // XXX: use a stack for nestable elements like span, table and div
1950 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1951 $closematch = preg_match(
1952 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1953 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1954 if ( $openmatch or $closematch ) {
1955 $paragraphStack = false;
1956 #Â TODO bug 5718: paragraph closed
1957 $output .= $this->closeParagraph();
1958 if ( $preOpenMatch and !$preCloseMatch ) {
1959 $this->mInPre
= true;
1961 if ( $closematch ) {
1962 $inBlockElem = false;
1964 $inBlockElem = true;
1966 } else if ( !$inBlockElem && !$this->mInPre
) {
1967 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1969 if ($this->mLastSection
!= 'pre') {
1970 $paragraphStack = false;
1971 $output .= $this->closeParagraph().'<pre>';
1972 $this->mLastSection
= 'pre';
1974 $t = substr( $t, 1 );
1977 if ( '' == trim($t) ) {
1978 if ( $paragraphStack ) {
1979 $output .= $paragraphStack.'<br />';
1980 $paragraphStack = false;
1981 $this->mLastSection
= 'p';
1983 if ($this->mLastSection
!= 'p' ) {
1984 $output .= $this->closeParagraph();
1985 $this->mLastSection
= '';
1986 $paragraphStack = '<p>';
1988 $paragraphStack = '</p><p>';
1992 if ( $paragraphStack ) {
1993 $output .= $paragraphStack;
1994 $paragraphStack = false;
1995 $this->mLastSection
= 'p';
1996 } else if ($this->mLastSection
!= 'p') {
1997 $output .= $this->closeParagraph().'<p>';
1998 $this->mLastSection
= 'p';
2003 wfProfileOut( "$fname-paragraph" );
2005 // somewhere above we forget to get out of pre block (bug 785)
2006 if($preCloseMatch && $this->mInPre
) {
2007 $this->mInPre
= false;
2009 if ($paragraphStack === false) {
2013 while ( $prefixLength ) {
2014 $output .= $this->closeList( $pref2{$prefixLength-1} );
2017 if ( '' != $this->mLastSection
) {
2018 $output .= '</' . $this->mLastSection
. '>';
2019 $this->mLastSection
= '';
2022 wfProfileOut( $fname );
2027 * Split up a string on ':', ignoring any occurences inside
2028 * <a>..</a> or <span>...</span>
2029 * @param string $str the string to split
2030 * @param string &$before set to everything before the ':'
2031 * @param string &$after set to everything after the ':'
2032 * return string the position of the ':', or false if none found
2034 function findColonNoLinks($str, &$before, &$after) {
2035 # I wonder if we should make this count all tags, not just <a>
2036 # and <span>. That would prevent us from matching a ':' that
2037 # comes in the middle of italics other such formatting....
2039 $fname = 'Parser::findColonNoLinks';
2040 wfProfileIn( $fname );
2043 $colon = strpos($str, ':', $pos);
2045 if ($colon !== false) {
2046 $before = substr($str, 0, $colon);
2047 $after = substr($str, $colon +
1);
2049 # Skip any ':' within <a> or <span> pairs
2050 $a = substr_count($before, '<a');
2051 $s = substr_count($before, '<span');
2052 $ca = substr_count($before, '</a>');
2053 $cs = substr_count($before, '</span>');
2055 if ($a <= $ca and $s <= $cs) {
2056 # Tags are balanced before ':'; ok
2061 } while ($colon !== false);
2062 wfProfileOut( $fname );
2067 * Return value of a magic variable (like PAGENAME)
2071 function getVariableValue( $index ) {
2072 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2075 * Some of these require message or data lookups and can be
2076 * expensive to check many times.
2078 static $varCache = array();
2079 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2080 if ( isset( $varCache[$index] ) )
2081 return $varCache[$index];
2084 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2087 case MAG_CURRENTMONTH
:
2088 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2089 case MAG_CURRENTMONTHNAME
:
2090 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2091 case MAG_CURRENTMONTHNAMEGEN
:
2092 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2093 case MAG_CURRENTMONTHABBREV
:
2094 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2095 case MAG_CURRENTDAY
:
2096 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2097 case MAG_CURRENTDAY2
:
2098 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2100 return $this->mTitle
->getText();
2102 return $this->mTitle
->getPartialURL();
2103 case MAG_FULLPAGENAME
:
2104 return $this->mTitle
->getPrefixedText();
2105 case MAG_FULLPAGENAMEE
:
2106 return $this->mTitle
->getPrefixedURL();
2107 case MAG_SUBPAGENAME
:
2108 return $this->mTitle
->getSubpageText();
2109 case MAG_SUBPAGENAMEE
:
2110 return $this->mTitle
->getSubpageUrlForm();
2111 case MAG_BASEPAGENAME
:
2112 return $this->mTitle
->getBaseText();
2113 case MAG_BASEPAGENAMEE
:
2114 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2115 case MAG_TALKPAGENAME
:
2116 if( $this->mTitle
->canTalk() ) {
2117 $talkPage = $this->mTitle
->getTalkPage();
2118 return $talkPage->getPrefixedText();
2122 case MAG_TALKPAGENAMEE
:
2123 if( $this->mTitle
->canTalk() ) {
2124 $talkPage = $this->mTitle
->getTalkPage();
2125 return $talkPage->getPrefixedUrl();
2129 case MAG_SUBJECTPAGENAME
:
2130 $subjPage = $this->mTitle
->getSubjectPage();
2131 return $subjPage->getPrefixedText();
2132 case MAG_SUBJECTPAGENAMEE
:
2133 $subjPage = $this->mTitle
->getSubjectPage();
2134 return $subjPage->getPrefixedUrl();
2135 case MAG_REVISIONID
:
2136 return $this->mRevisionId
;
2138 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2139 case MAG_NAMESPACEE
:
2140 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2142 return $this->mTitle
->canTalk() ?
$this->mTitle
->getTalkNsText() : '';
2143 case MAG_TALKSPACEE
:
2144 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2145 case MAG_SUBJECTSPACE
:
2146 return $this->mTitle
->getSubjectNsText();
2147 case MAG_SUBJECTSPACEE
:
2148 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2149 case MAG_CURRENTDAYNAME
:
2150 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2151 case MAG_CURRENTYEAR
:
2152 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2153 case MAG_CURRENTTIME
:
2154 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2155 case MAG_CURRENTWEEK
:
2156 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2157 // int to remove the padding
2158 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2159 case MAG_CURRENTDOW
:
2160 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2161 case MAG_NUMBEROFARTICLES
:
2162 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2163 case MAG_NUMBEROFFILES
:
2164 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2165 case MAG_NUMBEROFUSERS
:
2166 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2167 case MAG_NUMBEROFPAGES
:
2168 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2169 case MAG_CURRENTTIMESTAMP
:
2170 return $varCache[$index] = wfTimestampNow();
2171 case MAG_CURRENTVERSION
:
2178 case MAG_SERVERNAME
:
2179 return $wgServerName;
2180 case MAG_SCRIPTPATH
:
2181 return $wgScriptPath;
2184 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2192 * initialise the magic variables (like CURRENTMONTHNAME)
2196 function initialiseVariables() {
2197 $fname = 'Parser::initialiseVariables';
2198 wfProfileIn( $fname );
2199 global $wgVariableIDs;
2200 $this->mVariables
= array();
2201 foreach ( $wgVariableIDs as $id ) {
2202 $mw =& MagicWord
::get( $id );
2203 $mw->addToArray( $this->mVariables
, $id );
2205 wfProfileOut( $fname );
2209 * parse any parentheses in format ((title|part|part))
2210 * and call callbacks to get a replacement text for any found piece
2212 * @param string $text The text to parse
2213 * @param array $callbacks rules in form:
2214 * '{' => array( # opening parentheses
2215 * 'end' => '}', # closing parentheses
2216 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2217 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2222 function replace_callback ($text, $callbacks) {
2223 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2224 $lastOpeningBrace = -1; # last not closed parentheses
2226 for ($i = 0; $i < strlen($text); $i++
) {
2227 # check for any opening brace
2230 foreach ($callbacks as $key => $value) {
2231 $pos = strpos ($text, $key, $i);
2232 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2238 if ($lastOpeningBrace >= 0) {
2239 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2241 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2246 $pos = strpos ($text, '|', $i);
2248 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2259 # found openning brace, lets add it to parentheses stack
2260 if (null != $rule) {
2261 $piece = array('brace' => $text[$i],
2262 'braceEnd' => $rule['end'],
2267 # count openning brace characters
2268 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2273 $piece['startAt'] = $i+
1;
2274 $piece['partStart'] = $i+
1;
2276 # we need to add to stack only if openning brace count is enough for any given rule
2277 foreach ($rule['cb'] as $cnt => $fn) {
2278 if ($piece['count'] >= $cnt) {
2279 $lastOpeningBrace ++
;
2280 $openingBraceStack[$lastOpeningBrace] = $piece;
2287 else if ($lastOpeningBrace >= 0) {
2288 # first check if it is a closing brace
2289 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2290 # lets check if it is enough characters for closing brace
2292 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2295 # if there are more closing parentheses than opening ones, we parse less
2296 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2297 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2299 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2301 $matchingCallback = null;
2302 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2303 if ($count >= $cnt && $matchingCount < $cnt) {
2304 $matchingCount = $cnt;
2305 $matchingCallback = $fn;
2309 if ($matchingCount == 0) {
2314 # lets set a title or last part (if '|' was found)
2315 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2316 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2318 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2320 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2321 $pieceEnd = $i +
$matchingCount;
2323 if( is_callable( $matchingCallback ) ) {
2325 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2326 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2327 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2328 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2330 # finally we can call a user callback and replace piece of text
2331 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2332 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2333 $i = $pieceStart +
strlen($replaceWith) - 1;
2336 # null value for callback means that parentheses should be parsed, but not replaced
2337 $i +
= $matchingCount - 1;
2340 # reset last openning parentheses, but keep it in case there are unused characters
2341 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2342 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2343 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2346 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2347 $openingBraceStack[$lastOpeningBrace--] = null;
2349 if ($matchingCount < $piece['count']) {
2350 $piece['count'] -= $matchingCount;
2351 $piece['startAt'] -= $matchingCount;
2352 $piece['partStart'] = $piece['startAt'];
2353 # do we still qualify for any callback with remaining count?
2354 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2355 if ($piece['count'] >= $cnt) {
2356 $lastOpeningBrace ++
;
2357 $openingBraceStack[$lastOpeningBrace] = $piece;
2365 # lets set a title if it is a first separator, or next part otherwise
2366 if ($text[$i] == '|') {
2367 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2368 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2369 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2372 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2374 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2383 * Replace magic variables, templates, and template arguments
2384 * with the appropriate text. Templates are substituted recursively,
2385 * taking care to avoid infinite loops.
2387 * Note that the substitution depends on value of $mOutputType:
2388 * OT_WIKI: only {{subst:}} templates
2389 * OT_MSG: only magic variables
2390 * OT_HTML: all templates and magic variables
2392 * @param string $tex The text to transform
2393 * @param array $args Key-value pairs representing template parameters to substitute
2394 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2397 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2398 # Prevent too big inclusions
2399 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2403 $fname = 'Parser::replaceVariables';
2404 wfProfileIn( $fname );
2406 # This function is called recursively. To keep track of arguments we need a stack:
2407 array_push( $this->mArgStack
, $args );
2409 $braceCallbacks = array();
2411 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2413 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2414 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2416 $callbacks = array();
2417 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2418 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2419 $text = $this->replace_callback ($text, $callbacks);
2421 array_pop( $this->mArgStack
);
2423 wfProfileOut( $fname );
2428 * Replace magic variables
2431 function variableSubstitution( $matches ) {
2432 $fname = 'Parser::variableSubstitution';
2433 $varname = $matches[1];
2434 wfProfileIn( $fname );
2435 if ( !$this->mVariables
) {
2436 $this->initialiseVariables();
2439 if ( $this->mOutputType
== OT_WIKI
) {
2440 # Do only magic variables prefixed by SUBST
2441 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2442 if (!$mwSubst->matchStartAndRemove( $varname ))
2444 # Note that if we don't substitute the variable below,
2445 # we don't remove the {{subst:}} magic word, in case
2446 # it is a template rather than a magic variable.
2448 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2449 $id = $this->mVariables
[$varname];
2450 $text = $this->getVariableValue( $id );
2451 $this->mOutput
->mContainsOldMagic
= true;
2453 $text = $matches[0];
2455 wfProfileOut( $fname );
2459 # Split template arguments
2460 function getTemplateArgs( $argsString ) {
2461 if ( $argsString === '' ) {
2465 $args = explode( '|', substr( $argsString, 1 ) );
2467 # If any of the arguments contains a '[[' but no ']]', it needs to be
2468 # merged with the next arg because the '|' character between belongs
2469 # to the link syntax and not the template parameter syntax.
2470 $argc = count($args);
2472 for ( $i = 0; $i < $argc-1; $i++
) {
2473 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2474 $args[$i] .= '|'.$args[$i+
1];
2475 array_splice($args, $i+
1, 1);
2485 * Return the text of a template, after recursively
2486 * replacing any variables or templates within the template.
2488 * @param array $piece The parts of the template
2489 * $piece['text']: matched text
2490 * $piece['title']: the title, i.e. the part before the |
2491 * $piece['parts']: the parameter array
2492 * @return string the text of the template
2495 function braceSubstitution( $piece ) {
2496 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2497 $fname = 'Parser::braceSubstitution';
2498 wfProfileIn( $fname );
2501 $found = false; # $text has been filled
2502 $nowiki = false; # wiki markup in $text should be escaped
2503 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2504 $noargs = false; # Don't replace triple-brace arguments in $text
2505 $replaceHeadings = false; # Make the edit section links go to the template not the article
2506 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2507 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2509 # Title object, where $text came from
2514 # $part1 is the bit before the first |, and must contain only title characters
2515 # $args is a list of arguments, starting from index 0, not including $part1
2517 $part1 = $piece['title'];
2518 # If the third subpattern matched anything, it will start with |
2520 if (null == $piece['parts']) {
2521 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2522 if ($replaceWith != $piece['text']) {
2523 $text = $replaceWith;
2530 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2531 $argc = count( $args );
2535 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2536 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2537 # One of two possibilities is true:
2538 # 1) Found SUBST but not in the PST phase
2539 # 2) Didn't find SUBST and in the PST phase
2540 # In either case, return without further processing
2541 $text = $piece['text'];
2548 # MSG, MSGNW, INT and RAW
2551 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2552 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2555 # Remove obsolete MSG:
2556 $mwMsg =& MagicWord
::get( MAG_MSG
);
2557 $mwMsg->matchStartAndRemove( $part1 );
2561 $mwRaw =& MagicWord
::get( MAG_RAW
);
2562 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2563 $forceRawInterwiki = true;
2566 # Check if it is an internal message
2567 $mwInt =& MagicWord
::get( MAG_INT
);
2568 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2569 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2570 $text = $linestart . wfMsgReal( $part1, $args, true );
2578 # Check for NS: (namespace expansion)
2579 $mwNs = MagicWord
::get( MAG_NS
);
2580 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2581 if ( intval( $part1 ) ||
$part1 == "0" ) {
2582 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2585 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2586 if ( !is_null( $index ) ) {
2587 $text = $linestart . $wgContLang->getNsText( $index );
2596 $urlencode =& MagicWord
::get( MAG_URLENCODE
);
2597 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2598 $text = $linestart . urlencode( $part1 );
2603 # LCFIRST, UCFIRST, LC and UC
2605 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2606 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2607 $lc =& MagicWord
::get( MAG_LC
);
2608 $uc =& MagicWord
::get( MAG_UC
);
2609 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2610 $text = $linestart . $wgContLang->lcfirst( $part1 );
2612 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2613 $text = $linestart . $wgContLang->ucfirst( $part1 );
2615 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2616 $text = $linestart . $wgContLang->lc( $part1 );
2618 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2619 $text = $linestart . $wgContLang->uc( $part1 );
2624 # LOCALURL and FULLURL
2626 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2627 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2628 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2629 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2632 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2633 $func = 'getLocalURL';
2634 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2635 $func = 'escapeLocalURL';
2636 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2637 $func = 'getFullURL';
2638 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2639 $func = 'escapeFullURL';
2644 if ( $func !== false ) {
2645 $title = Title
::newFromText( $part1 );
2646 # Due to order of execution of a lot of bits, the values might be encoded
2647 # before arriving here; if that's true, then the title can't be created
2648 # and the variable will fail. If we can't get a decent title from the first
2649 # attempt, url-decode and try for a second.
2650 if( is_null( $title ) )
2651 $title = Title
::newFromUrl( urldecode( $part1 ) );
2652 if ( !is_null( $title ) ) {
2654 $text = $linestart . $title->$func( $args[0] );
2656 $text = $linestart . $title->$func();
2663 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2665 if ( !$found && $argc == 1 ) {
2666 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2667 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2668 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2674 if ( !$found && $argc >= 2 ) {
2675 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2676 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2677 if ($argc==2) {$args[2]=$args[1];}
2678 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2684 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2685 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2686 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2688 # Set title in parser output object
2690 $parserOptions = new ParserOptions
;
2691 $local_parser = new Parser ();
2692 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2693 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2696 $t = $this->mTitle
->getPrefixedText();
2697 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2703 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2705 $mwWordsToCheck = array( MAG_NUMBEROFPAGES
=> 'wfNumberOfPages',
2706 MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers',
2707 MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles',
2708 MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2709 foreach( $mwWordsToCheck as $word => $func ) {
2710 $mwCurrentWord =& MagicWord
::get( $word );
2711 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2712 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2713 if( $mwRawSuffix->match( $args[0] ) ) {
2714 # Raw and unformatted
2715 $text = $linestart . call_user_func( $func );
2717 # Formatted according to the content default
2718 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2726 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2727 $colonPos = strpos( $part1, ':' );
2728 if ( $colonPos !== false ) {
2729 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2730 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2731 $funcArgs = array_map( 'trim', $args );
2732 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2733 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2736 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2740 if ( is_array( $result ) ) {
2741 $text = $linestart . $result[0];
2742 unset( $result[0] );
2744 // Extract flags into the local scope
2745 // This allows callers to set flags such as nowiki, noparse, found, etc.
2748 $text = $linestart . $result;
2754 # Template table test
2756 # Did we encounter this template already? If yes, it is in the cache
2757 # and we need to check for loops.
2758 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2761 # Infinite loop test
2762 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2766 $text = $linestart .
2767 '{{' . $part1 . '}}' .
2768 '<!-- WARNING: template loop detected -->';
2769 wfDebug( "$fname: template loop broken at '$part1'\n" );
2771 # set $text to cached message.
2772 $text = $linestart . $this->mTemplates
[$piece['title']];
2776 # Load from database
2777 $lastPathLevel = $this->mTemplatePath
;
2780 # declaring $subpage directly in the function call
2781 # does not work correctly with references and breaks
2782 # {{/subpage}}-style inclusions
2784 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2785 if ($subpage !== '') {
2786 $ns = $this->mTitle
->getNamespace();
2788 $title = Title
::newFromText( $part1, $ns );
2790 if ( !is_null( $title ) ) {
2791 if ( !$title->isExternal() ) {
2792 # Check for excessive inclusion
2793 $dbk = $title->getPrefixedDBkey();
2794 if ( $this->incrementIncludeCount( $dbk ) ) {
2795 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2796 $text = SpecialPage
::capturePath( $title );
2797 if ( is_string( $text ) ) {
2802 $this->disableCache();
2805 $articleContent = $this->fetchTemplate( $title );
2806 if ( $articleContent !== false ) {
2808 $text = $articleContent;
2809 $replaceHeadings = true;
2814 # If the title is valid but undisplayable, make a link to it
2815 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2816 $text = '[['.$title->getPrefixedText().']]';
2819 } elseif ( $title->isTrans() ) {
2820 // Interwiki transclusion
2821 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2822 $text = $this->interwikiTransclude( $title, 'render' );
2826 $text = $this->interwikiTransclude( $title, 'raw' );
2827 $replaceHeadings = true;
2832 # Template cache array insertion
2833 # Use the original $piece['title'] not the mangled $part1, so that
2834 # modifiers such as RAW: produce separate cache entries
2836 $this->mTemplates
[$piece['title']] = $text;
2837 $text = $linestart . $text;
2842 # Recursive parsing, escaping and link table handling
2843 # Only for HTML output
2844 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2845 $text = wfEscapeWikiText( $text );
2846 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2848 $assocArgs = array();
2850 # Clean up argument array
2851 $assocArgs = array();
2853 foreach( $args as $arg ) {
2854 $eqpos = strpos( $arg, '=' );
2855 if ( $eqpos === false ) {
2856 $assocArgs[$index++
] = $arg;
2858 $name = trim( substr( $arg, 0, $eqpos ) );
2859 $value = trim( substr( $arg, $eqpos+
1 ) );
2860 if ( $value === false ) {
2863 if ( $name !== false ) {
2864 $assocArgs[$name] = $value;
2869 # Add a new element to the templace recursion path
2870 $this->mTemplatePath
[$part1] = 1;
2874 # If there are any <onlyinclude> tags, only include them
2875 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2876 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2878 foreach ($m[1] as $piece)
2881 # Remove <noinclude> sections and <includeonly> tags
2882 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2883 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2885 if( $this->mOutputType
== OT_HTML
) {
2886 # Strip <nowiki>, <pre>, etc.
2887 $text = $this->strip( $text, $this->mStripState
);
2888 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2890 $text = $this->replaceVariables( $text, $assocArgs );
2892 # If the template begins with a table or block-level
2893 # element, it should be treated as beginning a new line.
2894 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2895 $text = "\n" . $text;
2897 } elseif ( !$noargs ) {
2898 # $noparse and !$noargs
2899 # Just replace the arguments, not any double-brace items
2900 # This is used for rendered interwiki transclusion
2901 $text = $this->replaceVariables( $text, $assocArgs, true );
2904 # Prune lower levels off the recursion check path
2905 $this->mTemplatePath
= $lastPathLevel;
2908 wfProfileOut( $fname );
2909 return $piece['text'];
2912 # Replace raw HTML by a placeholder
2913 # Add a blank line preceding, to prevent it from mucking up
2914 # immediately preceding headings
2915 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2917 # replace ==section headers==
2918 # XXX this needs to go away once we have a better parser.
2919 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2920 if( !is_null( $title ) )
2921 $encodedname = base64_encode($title->getPrefixedDBkey());
2923 $encodedname = base64_encode("");
2924 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2925 PREG_SPLIT_DELIM_CAPTURE
);
2928 for( $i = 0; $i < count($m); $i +
= 2 ) {
2930 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2932 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2936 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2937 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2938 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2946 # Prune lower levels off the recursion check path
2947 $this->mTemplatePath
= $lastPathLevel;
2950 wfProfileOut( $fname );
2951 return $piece['text'];
2953 wfProfileOut( $fname );
2959 * Fetch the unparsed text of a template and register a reference to it.
2961 function fetchTemplate( $title ) {
2963 // Loop to fetch the article, with up to 1 redirect
2964 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2965 $rev = Revision
::newFromTitle( $title );
2966 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2970 $text = $rev->getText();
2971 if ( $text === false ) {
2975 $title = Title
::newFromRedirect( $text );
2981 * Transclude an interwiki link.
2983 function interwikiTransclude( $title, $action ) {
2984 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2986 if (!$wgEnableScaryTranscluding)
2987 return wfMsg('scarytranscludedisabled');
2989 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2990 // But we'll handle it generally anyway
2991 if ( $title->getNamespace() ) {
2992 // Use the canonical namespace, which should work anywhere
2993 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2995 $articleName = $title->getDBkey();
2998 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2999 $url .= "?action=$action";
3000 if (strlen($url) > 255)
3001 return wfMsg('scarytranscludetoolong');
3002 return $this->fetchScaryTemplateMaybeFromCache($url);
3005 function fetchScaryTemplateMaybeFromCache($url) {
3006 global $wgTranscludeCacheExpiry;
3007 $dbr =& wfGetDB(DB_SLAVE
);
3008 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3009 array('tc_url' => $url));
3011 $time = $obj->tc_time
;
3012 $text = $obj->tc_contents
;
3013 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3018 $text = wfGetHTTP($url);
3020 return wfMsg('scarytranscludefailed', $url);
3022 $dbw =& wfGetDB(DB_MASTER
);
3023 $dbw->replace('transcache', array('tc_url'), array(
3025 'tc_time' => time(),
3026 'tc_contents' => $text));
3032 * Triple brace replacement -- used for template arguments
3035 function argSubstitution( $matches ) {
3036 $arg = trim( $matches['title'] );
3037 $text = $matches['text'];
3038 $inputArgs = end( $this->mArgStack
);
3040 if ( array_key_exists( $arg, $inputArgs ) ) {
3041 $text = $inputArgs[$arg];
3042 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3043 $text = $matches['parts'][0];
3050 * Returns true if the function is allowed to include this entity
3053 function incrementIncludeCount( $dbk ) {
3054 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3055 $this->mIncludeCount
[$dbk] = 0;
3057 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3065 * Detect __TOC__ magic word and set a placeholder
3067 function stripToc( $text ) {
3068 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3070 $mw = MagicWord
::get( MAG_NOTOC
);
3071 if( $mw->matchAndRemove( $text ) ) {
3072 $this->mShowToc
= false;
3075 $mw = MagicWord
::get( MAG_TOC
);
3076 if( $mw->match( $text ) ) {
3077 $this->mShowToc
= true;
3078 $this->mForceTocPosition
= true;
3080 // Set a placeholder. At the end we'll fill it in with the TOC.
3081 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3083 // Only keep the first one.
3084 $text = $mw->replace( '', $text );
3090 * This function accomplishes several tasks:
3091 * 1) Auto-number headings if that option is enabled
3092 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3093 * 3) Add a Table of contents on the top for users who have enabled the option
3094 * 4) Auto-anchor headings
3096 * It loops through all headlines, collects the necessary data, then splits up the
3097 * string and re-inserts the newly formatted headlines.
3099 * @param string $text
3100 * @param boolean $isMain
3103 function formatHeadings( $text, $isMain=true ) {
3104 global $wgMaxTocLevel, $wgContLang;
3106 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3107 if( !$this->mTitle
->userCanEdit() ) {
3110 $showEditLink = $this->mOptions
->getEditSection();
3113 # Inhibit editsection links if requested in the page
3114 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3115 if( $esw->matchAndRemove( $text ) ) {
3119 # Get all headlines for numbering them and adding funky stuff like [edit]
3120 # links - this is for later, but we need the number of headlines right now
3121 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3123 # if there are fewer than 4 headlines in the article, do not show TOC
3124 # unless it's been explicitly enabled.
3125 $enoughToc = $this->mShowToc
&&
3126 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3128 # Allow user to stipulate that a page should have a "new section"
3129 # link added via __NEWSECTIONLINK__
3130 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3131 if( $mw->matchAndRemove( $text ) )
3132 $this->mOutput
->setNewSection( true );
3134 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3135 # override above conditions and always show TOC above first header
3136 $mw =& MagicWord
::get( MAG_FORCETOC
);
3137 if ($mw->matchAndRemove( $text ) ) {
3138 $this->mShowToc
= true;
3142 # Never ever show TOC if no headers
3143 if( $numMatches < 1 ) {
3147 # We need this to perform operations on the HTML
3148 $sk =& $this->mOptions
->getSkin();
3152 $sectionCount = 0; # headlineCount excluding template sections
3154 # Ugh .. the TOC should have neat indentation levels which can be
3155 # passed to the skin functions. These are determined here
3159 $sublevelCount = array();
3160 $levelCount = array();
3167 foreach( $matches[3] as $headline ) {
3169 $templatetitle = '';
3170 $templatesection = 0;
3173 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3175 $templatetitle = base64_decode($mat[1]);
3176 $templatesection = 1 +
(int)base64_decode($mat[2]);
3177 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3181 $prevlevel = $level;
3182 $prevtoclevel = $toclevel;
3184 $level = $matches[1][$headlineCount];
3186 if( $doNumberHeadings ||
$enoughToc ) {
3188 if ( $level > $prevlevel ) {
3189 # Increase TOC level
3191 $sublevelCount[$toclevel] = 0;
3192 if( $toclevel<$wgMaxTocLevel ) {
3193 $toc .= $sk->tocIndent();
3196 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3197 # Decrease TOC level, find level to jump to
3199 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3200 # Can only go down to level 1
3203 for ($i = $toclevel; $i > 0; $i--) {
3204 if ( $levelCount[$i] == $level ) {
3205 # Found last matching level
3209 elseif ( $levelCount[$i] < $level ) {
3210 # Found first matching level below current level
3216 if( $toclevel<$wgMaxTocLevel ) {
3217 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3221 # No change in level, end TOC line
3222 if( $toclevel<$wgMaxTocLevel ) {
3223 $toc .= $sk->tocLineEnd();
3227 $levelCount[$toclevel] = $level;
3229 # count number of headlines for each level
3230 @$sublevelCount[$toclevel]++
;
3232 for( $i = 1; $i <= $toclevel; $i++
) {
3233 if( !empty( $sublevelCount[$i] ) ) {
3237 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3243 # The canonized header is a version of the header text safe to use for links
3244 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3245 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3246 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3248 # Remove link placeholders by the link text.
3249 # <!--LINK number-->
3251 # link text with suffix
3252 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3253 "\$this->mLinkHolders['texts'][\$1]",
3254 $canonized_headline );
3255 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3256 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3257 $canonized_headline );
3260 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3261 $tocline = trim( $canonized_headline );
3262 # Save headline for section edit hint before it's escaped
3263 $headline_hint = trim( $canonized_headline );
3264 $canonized_headline = Sanitizer
::escapeId( $tocline );
3265 $refers[$headlineCount] = $canonized_headline;
3267 # count how many in assoc. array so we can track dupes in anchors
3268 @$refers[$canonized_headline]++
;
3269 $refcount[$headlineCount]=$refers[$canonized_headline];
3271 # Don't number the heading if it is the only one (looks silly)
3272 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3273 # the two are different if the line contains a link
3274 $headline=$numbering . ' ' . $headline;
3277 # Create the anchor for linking from the TOC to the section
3278 $anchor = $canonized_headline;
3279 if($refcount[$headlineCount] > 1 ) {
3280 $anchor .= '_' . $refcount[$headlineCount];
3282 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3283 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3285 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3286 if ( empty( $head[$headlineCount] ) ) {
3287 $head[$headlineCount] = '';
3290 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3292 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3295 # give headline the correct <h#> tag
3296 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3304 if( $toclevel<$wgMaxTocLevel ) {
3305 $toc .= $sk->tocUnindent( $toclevel - 1 );
3307 $toc = $sk->tocList( $toc );
3310 # split up and insert constructed headlines
3312 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3315 foreach( $blocks as $block ) {
3316 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3317 # This is the [edit] link that appears for the top block of text when
3318 # section editing is enabled
3320 # Disabled because it broke block formatting
3321 # For example, a bullet point in the top line
3322 # $full .= $sk->editSectionLink(0);
3325 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3326 # Top anchor now in skin
3330 if( !empty( $head[$i] ) ) {
3335 if( $this->mForceTocPosition
) {
3336 return str_replace( '<!--MWTOC-->', $toc, $full );
3343 * Return an HTML link for the "ISBN 123456" text
3346 function magicISBN( $text ) {
3347 $fname = 'Parser::magicISBN';
3348 wfProfileIn( $fname );
3350 $a = split( 'ISBN ', ' '.$text );
3351 if ( count ( $a ) < 2 ) {
3352 wfProfileOut( $fname );
3355 $text = substr( array_shift( $a ), 1);
3356 $valid = '0123456789-Xx';
3358 foreach ( $a as $x ) {
3359 # hack: don't replace inside thumbnail title/alt
3361 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3366 $isbn = $blank = '' ;
3367 while ( ' ' == $x{0} ) {
3369 $x = substr( $x, 1 );
3371 if ( $x == '' ) { # blank isbn
3372 $text .= "ISBN $blank";
3375 while ( strstr( $valid, $x{0} ) != false ) {
3377 $x = substr( $x, 1 );
3379 $num = str_replace( '-', '', $isbn );
3380 $num = str_replace( ' ', '', $num );
3381 $num = str_replace( 'x', 'X', $num );
3384 $text .= "ISBN $blank$x";
3386 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3387 $text .= '<a href="' .
3388 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3389 "\" class=\"internal\">ISBN $isbn</a>";
3393 wfProfileOut( $fname );
3398 * Return an HTML link for the "RFC 1234" text
3401 * @param string $text Text to be processed
3402 * @param string $keyword Magic keyword to use (default RFC)
3403 * @param string $urlmsg Interface message to use (default rfcurl)
3406 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3408 $valid = '0123456789';
3411 $a = split( $keyword, ' '.$text );
3412 if ( count ( $a ) < 2 ) {
3415 $text = substr( array_shift( $a ), 1);
3417 /* Check if keyword is preceed by [[.
3418 * This test is made here cause of the array_shift above
3419 * that prevent the test to be done in the foreach.
3421 if ( substr( $text, -2 ) == '[[' ) {
3425 foreach ( $a as $x ) {
3426 /* token might be empty if we have RFC RFC 1234 */
3432 # hack: don't replace inside thumbnail title/alt
3434 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3435 $text .= $keyword . $x;
3441 /** remove and save whitespaces in $blank */
3442 while ( $x{0} == ' ' ) {
3444 $x = substr( $x, 1 );
3447 /** remove and save the rfc number in $id */
3448 while ( strstr( $valid, $x{0} ) != false ) {
3450 $x = substr( $x, 1 );
3454 /* call back stripped spaces*/
3455 $text .= $keyword.$blank.$x;
3456 } elseif( $internal ) {
3458 $text .= $keyword.$id.$x;
3460 /* build the external link*/
3461 $url = wfMsg( $urlmsg, $id);
3462 $sk =& $this->mOptions
->getSkin();
3463 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3464 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3467 /* Check if the next RFC keyword is preceed by [[ */
3468 $internal = ( substr($x,-2) == '[[' );
3474 * Transform wiki markup when saving a page by doing \r\n -> \n
3475 * conversion, substitting signatures, {{subst:}} templates, etc.
3477 * @param string $text the text to transform
3478 * @param Title &$title the Title object for the current article
3479 * @param User &$user the User object describing the current user
3480 * @param ParserOptions $options parsing options
3481 * @param bool $clearState whether to clear the parser state first
3482 * @return string the altered wiki markup
3485 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3486 $this->mOptions
= $options;
3487 $this->mTitle
=& $title;
3488 $this->mOutputType
= OT_WIKI
;
3490 if ( $clearState ) {
3491 $this->clearState();
3494 $stripState = false;
3498 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3499 $text = $this->strip( $text, $stripState, true );
3500 $text = $this->pstPass2( $text, $stripState, $user );
3501 $text = $this->unstrip( $text, $stripState );
3502 $text = $this->unstripNoWiki( $text, $stripState );
3507 * Pre-save transform helper function
3510 function pstPass2( $text, &$stripState, &$user ) {
3511 global $wgContLang, $wgLocaltimezone;
3513 /* Note: This is the timestamp saved as hardcoded wikitext to
3514 * the database, we use $wgContLang here in order to give
3515 * everyone the same signature and use the default one rather
3516 * than the one selected in each user's preferences.
3518 if ( isset( $wgLocaltimezone ) ) {
3519 $oldtz = getenv( 'TZ' );
3520 putenv( 'TZ='.$wgLocaltimezone );
3522 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3523 ' (' . date( 'T' ) . ')';
3524 if ( isset( $wgLocaltimezone ) ) {
3525 putenv( 'TZ='.$oldtz );
3528 # Variable replacement
3529 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3530 $text = $this->replaceVariables( $text );
3532 # Strip out <nowiki> etc. added via replaceVariables
3533 $text = $this->strip( $text, $stripState );
3536 $sigText = $this->getUserSig( $user );
3537 $text = strtr( $text, array(
3539 '~~~~' => "$sigText $d",
3543 # Context links: [[|name]] and [[name (context)|]]
3545 global $wgLegalTitleChars;
3546 $tc = "[$wgLegalTitleChars]";
3547 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3549 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3550 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3552 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3553 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3554 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3555 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3557 $t = $this->mTitle
->getText();
3558 if ( preg_match( $conpat, $t, $m ) ) {
3561 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3562 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3563 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3565 if ( '' == $context ) {
3566 $text = preg_replace( $p2, '[[\\1]]', $text );
3568 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3571 # Trim trailing whitespace
3572 # MAG_END (__END__) tag allows for trailing
3573 # whitespace to be deliberately included
3574 $text = rtrim( $text );
3575 $mw =& MagicWord
::get( MAG_END
);
3576 $mw->matchAndRemove( $text );
3582 * Fetch the user's signature text, if any, and normalize to
3583 * validated, ready-to-insert wikitext.
3589 function getUserSig( &$user ) {
3590 $username = $user->getName();
3591 $nickname = $user->getOption( 'nickname' );
3592 $nickname = $nickname === '' ?
$username : $nickname;
3594 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3595 # Sig. might contain markup; validate this
3596 if( $this->validateSig( $nickname ) !== false ) {
3597 # Validated; clean up (if needed) and return it
3598 return $this->cleanSig( $nickname, true );
3600 # Failed to validate; fall back to the default
3601 $nickname = $username;
3602 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3606 # If we're still here, make it a link to the user page
3607 $userpage = $user->getUserPage();
3608 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3612 * Check that the user's signature contains no bad XML
3614 * @param string $text
3615 * @return mixed An expanded string, or false if invalid.
3617 function validateSig( $text ) {
3618 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3622 * Clean up signature text
3624 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3625 * 2) Substitute all transclusions
3627 * @param string $text
3628 * @param $parsing Whether we're cleaning (preferences save) or parsing
3629 * @return string Signature text
3631 function cleanSig( $text, $parsing = false ) {
3633 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3635 $substWord = MagicWord
::get( MAG_SUBST
);
3636 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3637 $substText = '{{' . $substWord->getSynonym( 0 );
3639 $text = preg_replace( $substRegex, $substText, $text );
3640 $text = preg_replace( '/~{3,5}/', '', $text );
3641 $text = $this->replaceVariables( $text );
3643 $this->clearState();
3648 * Set up some variables which are usually set up in parse()
3649 * so that an external function can call some class members with confidence
3652 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3653 $this->mTitle
=& $title;
3654 $this->mOptions
= $options;
3655 $this->mOutputType
= $outputType;
3656 if ( $clearState ) {
3657 $this->clearState();
3662 * Transform a MediaWiki message by replacing magic variables.
3664 * @param string $text the text to transform
3665 * @param ParserOptions $options options
3666 * @return string the text with variables substituted
3669 function transformMsg( $text, $options ) {
3671 static $executing = false;
3673 $fname = "Parser::transformMsg";
3675 # Guard against infinite recursion
3681 wfProfileIn($fname);
3683 $this->mTitle
= $wgTitle;
3684 $this->mOptions
= $options;
3685 $this->mOutputType
= OT_MSG
;
3686 $this->clearState();
3687 $text = $this->replaceVariables( $text );
3690 wfProfileOut($fname);
3695 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3696 * The callback should have the following form:
3697 * function myParserHook( $text, $params, &$parser ) { ... }
3699 * Transform and return $text. Use $parser for any required context, e.g. use
3700 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3704 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3705 * @param mixed $callback The callback function (and object) to use for the tag
3707 * @return The old value of the mTagHooks array associated with the hook
3709 function setHook( $tag, $callback ) {
3710 $oldVal = @$this->mTagHooks
[$tag];
3711 $this->mTagHooks
[$tag] = $callback;
3717 * Create a function, e.g. {{sum:1|2|3}}
3718 * The callback function should have the form:
3719 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3721 * The callback may either return the text result of the function, or an array with the text
3722 * in element 0, and a number of flags in the other elements. The names of the flags are
3723 * specified in the keys. Valid flags are:
3724 * found The text returned is valid, stop processing the template. This
3726 * nowiki Wiki markup in the return value should be escaped
3727 * noparse Unsafe HTML tags should not be stripped, etc.
3728 * noargs Don't replace triple-brace arguments in the return value
3729 * isHTML The returned text is HTML, armour it against wikitext transformation
3733 * @param string $name The function name. Function names are case-insensitive.
3734 * @param mixed $callback The callback function (and object) to use
3736 * @return The old callback function for this name, if any
3738 function setFunctionHook( $name, $callback ) {
3739 $name = strtolower( $name );
3740 $oldVal = @$this->mFunctionHooks
[$name];
3741 $this->mFunctionHooks
[$name] = $callback;
3746 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3747 * Placeholders created in Skin::makeLinkObj()
3748 * Returns an array of links found, indexed by PDBK:
3752 * $options is a bit field, RLH_FOR_UPDATE to select for update
3754 function replaceLinkHolders( &$text, $options = 0 ) {
3756 global $wgOutputReplace;
3758 $fname = 'Parser::replaceLinkHolders';
3759 wfProfileIn( $fname );
3763 $sk =& $this->mOptions
->getSkin();
3764 $linkCache =& LinkCache
::singleton();
3766 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3767 wfProfileIn( $fname.'-check' );
3768 $dbr =& wfGetDB( DB_SLAVE
);
3769 $page = $dbr->tableName( 'page' );
3770 $threshold = $wgUser->getOption('stubthreshold');
3773 asort( $this->mLinkHolders
['namespaces'] );
3777 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3779 $title = $this->mLinkHolders
['titles'][$key];
3781 # Skip invalid entries.
3782 # Result will be ugly, but prevents crash.
3783 if ( is_null( $title ) ) {
3786 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3788 # Check if it's a static known link, e.g. interwiki
3789 if ( $title->isAlwaysKnown() ) {
3790 $colours[$pdbk] = 1;
3791 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3792 $colours[$pdbk] = 1;
3793 $this->mOutput
->addLink( $title, $id );
3794 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3795 $colours[$pdbk] = 0;
3797 # Not in the link cache, add it to the query
3798 if ( !isset( $current ) ) {
3800 $query = "SELECT page_id, page_namespace, page_title";
3801 if ( $threshold > 0 ) {
3802 $query .= ', page_len, page_is_redirect';
3804 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3805 } elseif ( $current != $ns ) {
3807 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3812 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3817 if ( $options & RLH_FOR_UPDATE
) {
3818 $query .= ' FOR UPDATE';
3821 $res = $dbr->query( $query, $fname );
3823 # Fetch data and form into an associative array
3824 # non-existent = broken
3827 while ( $s = $dbr->fetchObject($res) ) {
3828 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3829 $pdbk = $title->getPrefixedDBkey();
3830 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3831 $this->mOutput
->addLink( $title, $s->page_id
);
3833 if ( $threshold > 0 ) {
3834 $size = $s->page_len
;
3835 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3836 $colours[$pdbk] = 1;
3838 $colours[$pdbk] = 2;
3841 $colours[$pdbk] = 1;
3845 wfProfileOut( $fname.'-check' );
3847 # Construct search and replace arrays
3848 wfProfileIn( $fname.'-construct' );
3849 $wgOutputReplace = array();
3850 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3851 $pdbk = $pdbks[$key];
3852 $searchkey = "<!--LINK $key-->";
3853 $title = $this->mLinkHolders
['titles'][$key];
3854 if ( empty( $colours[$pdbk] ) ) {
3855 $linkCache->addBadLinkObj( $title );
3856 $colours[$pdbk] = 0;
3857 $this->mOutput
->addLink( $title, 0 );
3858 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3859 $this->mLinkHolders
['texts'][$key],
3860 $this->mLinkHolders
['queries'][$key] );
3861 } elseif ( $colours[$pdbk] == 1 ) {
3862 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3863 $this->mLinkHolders
['texts'][$key],
3864 $this->mLinkHolders
['queries'][$key] );
3865 } elseif ( $colours[$pdbk] == 2 ) {
3866 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3867 $this->mLinkHolders
['texts'][$key],
3868 $this->mLinkHolders
['queries'][$key] );
3871 wfProfileOut( $fname.'-construct' );
3874 wfProfileIn( $fname.'-replace' );
3876 $text = preg_replace_callback(
3877 '/(<!--LINK .*?-->)/',
3878 "wfOutputReplaceMatches",
3881 wfProfileOut( $fname.'-replace' );
3884 # Now process interwiki link holders
3885 # This is quite a bit simpler than internal links
3886 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3887 wfProfileIn( $fname.'-interwiki' );
3888 # Make interwiki link HTML
3889 $wgOutputReplace = array();
3890 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3891 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3892 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3895 $text = preg_replace_callback(
3896 '/<!--IWLINK (.*?)-->/',
3897 "wfOutputReplaceMatches",
3899 wfProfileOut( $fname.'-interwiki' );
3902 wfProfileOut( $fname );
3907 * Replace <!--LINK--> link placeholders with plain text of links
3908 * (not HTML-formatted).
3909 * @param string $text
3912 function replaceLinkHoldersText( $text ) {
3913 $fname = 'Parser::replaceLinkHoldersText';
3914 wfProfileIn( $fname );
3916 $text = preg_replace_callback(
3917 '/<!--(LINK|IWLINK) (.*?)-->/',
3918 array( &$this, 'replaceLinkHoldersTextCallback' ),
3921 wfProfileOut( $fname );
3926 * @param array $matches
3930 function replaceLinkHoldersTextCallback( $matches ) {
3931 $type = $matches[1];
3933 if( $type == 'LINK' ) {
3934 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3935 return $this->mLinkHolders
['texts'][$key];
3937 } elseif( $type == 'IWLINK' ) {
3938 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3939 return $this->mInterwikiLinkHolders
['texts'][$key];
3946 * Renders an image gallery from a text with one line per image.
3947 * text labels may be given by using |-style alternative text. E.g.
3948 * Image:one.jpg|The number "1"
3949 * Image:tree.jpg|A tree
3950 * given as text will return the HTML of a gallery with two images,
3951 * labeled 'The number "1"' and
3954 function renderImageGallery( $text ) {
3956 $parserOptions = new ParserOptions
;
3957 $localParser = new Parser();
3959 $ig = new ImageGallery();
3960 $ig->setShowBytes( false );
3961 $ig->setShowFilename( false );
3963 $lines = explode( "\n", $text );
3965 foreach ( $lines as $line ) {
3966 # match lines like these:
3967 # Image:someimage.jpg|This is some image
3968 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3970 if ( count( $matches ) == 0 ) {
3973 $nt =& Title
::newFromText( $matches[1] );
3974 if( is_null( $nt ) ) {
3975 # Bogus title. Ignore these so we don't bomb out later.
3978 if ( isset( $matches[3] ) ) {
3979 $label = $matches[3];
3984 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3985 $html = $pout->getText();
3987 $ig->add( new Image( $nt ), $html );
3989 # Only add real images (bug #5586)
3990 if ( $nt->getNamespace() == NS_IMAGE
) {
3991 $this->mOutput
->addImage( $nt->getDBkey() );
3994 # Register links with the parent parser
3995 foreach( $pout->getLinks() as $ns => $keys ) {
3996 foreach( $keys as $dbk => $id )
3997 $this->mOutput
->addLink( Title
::makeTitle( $ns, $dbk ), $id );
4001 return $ig->toHTML();
4005 * Parse image options text and use it to make an image
4007 function makeImage( &$nt, $options ) {
4008 global $wgUseImageResize;
4012 # Check if the options text is of the form "options|alt text"
4014 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4015 # * left no resizing, just left align. label is used for alt= only
4016 # * right same, but right aligned
4017 # * none same, but not aligned
4018 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4019 # * center center the image
4020 # * framed Keep original image size, no magnify-button.
4022 $part = explode( '|', $options);
4024 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
4025 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
4026 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
4027 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
4028 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
4029 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
4030 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
4031 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
4034 $width = $height = $framed = $thumb = false;
4035 $manual_thumb = '' ;
4037 foreach( $part as $key => $val ) {
4038 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4040 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4041 # use manually specified thumbnail
4043 $manual_thumb = $match;
4044 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4045 # remember to set an alignment, don't render immediately
4047 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4048 # remember to set an alignment, don't render immediately
4050 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4051 # remember to set an alignment, don't render immediately
4053 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4054 # remember to set an alignment, don't render immediately
4056 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4057 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4058 # $match is the image width in pixels
4059 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4060 $width = intval( $m[1] );
4061 $height = intval( $m[2] );
4063 $width = intval($match);
4065 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4071 # Strip bad stuff out of the alt text
4072 $alt = $this->replaceLinkHoldersText( $caption );
4074 # make sure there are no placeholders in thumbnail attributes
4075 # that are later expanded to html- so expand them now and
4077 $alt = $this->unstrip($alt, $this->mStripState
);
4078 $alt = Sanitizer
::stripAllTags( $alt );
4080 # Linker does the rest
4081 $sk =& $this->mOptions
->getSkin();
4082 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4086 * Set a flag in the output object indicating that the content is dynamic and
4087 * shouldn't be cached.
4089 function disableCache() {
4090 wfDebug( "Parser output marked as uncacheable.\n" );
4091 $this->mOutput
->mCacheTime
= -1;
4095 * Callback from the Sanitizer for expanding items found in HTML attribute
4096 * values, so they can be safely tested and escaped.
4097 * @param string $text
4098 * @param array $args
4102 function attributeStripCallback( &$text, $args ) {
4103 $text = $this->replaceVariables( $text, $args );
4104 $text = $this->unstripForHTML( $text );
4108 function unstripForHTML( $text ) {
4109 $text = $this->unstrip( $text, $this->mStripState
);
4110 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4118 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4119 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4120 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4126 function getTags() { return array_keys( $this->mTagHooks
); }
4132 * @package MediaWiki
4136 var $mText, # The output text
4137 $mLanguageLinks, # List of the full text of language links, in the order they appear
4138 $mCategories, # Map of category names to sort keys
4139 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4140 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4141 $mVersion, # Compatibility check
4142 $mTitleText, # title text of the chosen language variant
4143 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4144 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4145 $mImages, # DB keys of the images used, in the array key only
4146 $mExternalLinks, # External link URLs, in the key only
4147 $mHTMLtitle, # Display HTML title
4148 $mSubtitle, # Additional subtitle
4149 $mNewSection; # Show a new section link?
4151 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4152 $containsOldMagic = false, $titletext = '' )
4154 $this->mText
= $text;
4155 $this->mLanguageLinks
= $languageLinks;
4156 $this->mCategories
= $categoryLinks;
4157 $this->mContainsOldMagic
= $containsOldMagic;
4158 $this->mCacheTime
= '';
4159 $this->mVersion
= MW_PARSER_VERSION
;
4160 $this->mTitleText
= $titletext;
4161 $this->mLinks
= array();
4162 $this->mTemplates
= array();
4163 $this->mImages
= array();
4164 $this->mExternalLinks
= array();
4165 $this->mHTMLtitle
= "" ;
4166 $this->mSubtitle
= "" ;
4167 $this->mNewSection
= false;
4170 function getText() { return $this->mText
; }
4171 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4172 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4173 function &getCategories() { return $this->mCategories
; }
4174 function getCacheTime() { return $this->mCacheTime
; }
4175 function getTitleText() { return $this->mTitleText
; }
4176 function &getLinks() { return $this->mLinks
; }
4177 function &getTemplates() { return $this->mTemplates
; }
4178 function &getImages() { return $this->mImages
; }
4179 function &getExternalLinks() { return $this->mExternalLinks
; }
4181 function containsOldMagic() { return $this->mContainsOldMagic
; }
4182 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4183 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4184 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4185 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4186 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4187 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4189 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4190 function addImage( $name ) { $this->mImages
[$name] = 1; }
4191 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4192 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4194 function setNewSection( $value ) {
4195 $this->mNewSection
= (bool)$value;
4197 function getNewSection() {
4198 return (bool)$this->mNewSection
;
4201 function addLink( $title, $id ) {
4202 $ns = $title->getNamespace();
4203 $dbk = $title->getDBkey();
4204 if ( !isset( $this->mLinks
[$ns] ) ) {
4205 $this->mLinks
[$ns] = array();
4207 $this->mLinks
[$ns][$dbk] = $id;
4210 function addTemplate( $title, $id ) {
4211 $ns = $title->getNamespace();
4212 $dbk = $title->getDBkey();
4213 if ( !isset( $this->mTemplates
[$ns] ) ) {
4214 $this->mTemplates
[$ns] = array();
4216 $this->mTemplates
[$ns][$dbk] = $id;
4220 * Return true if this cached output object predates the global or
4221 * per-article cache invalidation timestamps, or if it comes from
4222 * an incompatible older version.
4224 * @param string $touched the affected article's last touched timestamp
4228 function expired( $touched ) {
4229 global $wgCacheEpoch;
4230 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4231 $this->getCacheTime() < $touched ||
4232 $this->getCacheTime() <= $wgCacheEpoch ||
4233 !isset( $this->mVersion
) ||
4234 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4239 * Set options of the Parser
4241 * @package MediaWiki
4245 # All variables are private
4246 var $mUseTeX; # Use texvc to expand <math> tags
4247 var $mUseDynamicDates; # Use DateFormatter to format dates
4248 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4249 var $mAllowExternalImages; # Allow external images inline
4250 var $mAllowExternalImagesFrom; # If not, any exception?
4251 var $mSkin; # Reference to the preferred skin
4252 var $mDateFormat; # Date format index
4253 var $mEditSection; # Create "edit section" links
4254 var $mNumberHeadings; # Automatically number headings
4255 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4256 var $mTidy; # Ask for tidy cleanup
4257 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4259 function getUseTeX() { return $this->mUseTeX
; }
4260 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4261 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4262 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4263 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4264 function &getSkin() { return $this->mSkin
; }
4265 function getDateFormat() { return $this->mDateFormat
; }
4266 function getEditSection() { return $this->mEditSection
; }
4267 function getNumberHeadings() { return $this->mNumberHeadings
; }
4268 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4269 function getTidy() { return $this->mTidy
; }
4270 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4272 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4273 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4274 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4275 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4276 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4277 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4278 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4279 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4280 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4281 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4282 function setSkin( &$x ) { $this->mSkin
=& $x; }
4283 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4285 function ParserOptions() {
4287 $this->initialiseFromUser( $wgUser );
4291 * Get parser options
4294 function newFromUser( &$user ) {
4295 $popts = new ParserOptions
;
4296 $popts->initialiseFromUser( $user );
4300 /** Get user options */
4301 function initialiseFromUser( &$userInput ) {
4302 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4303 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4304 $fname = 'ParserOptions::initialiseFromUser';
4305 wfProfileIn( $fname );
4306 if ( !$userInput ) {
4308 $user->setLoaded( true );
4310 $user =& $userInput;
4313 $this->mUseTeX
= $wgUseTeX;
4314 $this->mUseDynamicDates
= $wgUseDynamicDates;
4315 $this->mInterwikiMagic
= $wgInterwikiMagic;
4316 $this->mAllowExternalImages
= $wgAllowExternalImages;
4317 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4318 wfProfileIn( $fname.'-skin' );
4319 $this->mSkin
=& $user->getSkin();
4320 wfProfileOut( $fname.'-skin' );
4321 $this->mDateFormat
= $user->getOption( 'date' );
4322 $this->mEditSection
= true;
4323 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4324 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4325 $this->mTidy
= false;
4326 $this->mInterfaceMessage
= false;
4327 wfProfileOut( $fname );
4332 * Callback function used by Parser::replaceLinkHolders()
4333 * to substitute link placeholders.
4335 function &wfOutputReplaceMatches( $matches ) {
4336 global $wgOutputReplace;
4337 return $wgOutputReplace[$matches[1]];
4341 * Return the total number of articles
4343 function wfNumberOfArticles() {
4344 global $wgNumberOfArticles;
4347 return $wgNumberOfArticles;
4351 * Return the number of files
4353 function wfNumberOfFiles() {
4354 $fname = 'wfNumberOfFiles';
4356 wfProfileIn( $fname );
4357 $dbr =& wfGetDB( DB_SLAVE
);
4358 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4359 wfProfileOut( $fname );
4365 * Return the number of user accounts
4368 function wfNumberOfUsers() {
4369 wfProfileIn( 'wfNumberOfUsers' );
4370 $dbr =& wfGetDB( DB_SLAVE
);
4371 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4372 wfProfileOut( 'wfNumberOfUsers' );
4377 * Return the total number of pages
4380 function wfNumberOfPages() {
4381 wfProfileIn( 'wfNumberOfPages' );
4382 $dbr =& wfGetDB( DB_SLAVE
);
4383 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4384 wfProfileOut( 'wfNumberOfPages' );
4389 * Get various statistics from the database
4392 function wfLoadSiteStats() {
4393 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4394 $fname = 'wfLoadSiteStats';
4396 if ( -1 != $wgNumberOfArticles ) return;
4397 $dbr =& wfGetDB( DB_SLAVE
);
4398 $s = $dbr->selectRow( 'site_stats',
4399 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4400 array( 'ss_row_id' => 1 ), $fname
4403 if ( $s === false ) {
4406 $wgTotalViews = $s->ss_total_views
;
4407 $wgTotalEdits = $s->ss_total_edits
;
4408 $wgNumberOfArticles = $s->ss_good_articles
;
4414 * Basically replacing " > and < with HTML entities ( ", >, <)
4416 * @param $in String: text that might contain HTML tags.
4417 * @return string Escaped string
4419 function wfEscapeHTMLTagsOnly( $in ) {
4421 array( '"', '>', '<' ),
4422 array( '"', '>', '<' ),