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.0' );
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
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
104 var $mOptions, // ParserOptions object
105 $mTitle, // Title context, used for self-link rendering and similar things
106 $mOutputType, // Output type, one of the OT_xxx constants
107 $mTemplates, // cache of already loaded templates, avoids
108 // multiple SQL queries for the same string
109 $mTemplatePath, // stores an unsorted hash of all the templates already loaded
110 // in this path. Used for loop detection.
111 $mIWTransData = array(),
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTemplates
= array();
123 $this->mTemplatePath
= array();
124 $this->mTagHooks
= array();
133 function clearState() {
134 $this->mOutput
= new ParserOutput
;
135 $this->mAutonumber
= 0;
136 $this->mLastSection
= '';
137 $this->mDTopen
= false;
138 $this->mVariables
= false;
139 $this->mIncludeCount
= array();
140 $this->mStripState
= array();
141 $this->mArgStack
= array();
142 $this->mInPre
= false;
143 $this->mInterwikiLinkHolders
= array(
147 $this->mLinkHolders
= array(
148 'namespaces' => array(),
150 'queries' => array(),
154 $this->mRevisionId
= null;
155 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
157 wfRunHooks( 'ParserClearState', array( &$this ) );
161 * Accessor for mUniqPrefix.
165 function UniqPrefix() {
166 return $this->mUniqPrefix
;
170 * Convert wikitext to HTML
171 * Do not call this function recursively.
174 * @param string $text Text we want to parse
175 * @param Title &$title A title object
176 * @param array $options
177 * @param boolean $linestart
178 * @param boolean $clearState
179 * @param int $revid number to pass in {{REVISIONID}}
180 * @return ParserOutput a ParserOutput
182 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
184 * First pass--just handle <nowiki> sections, pass the rest off
185 * to internalParse() which does all the real work.
188 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
189 $fname = 'Parser::parse';
190 wfProfileIn( $fname );
196 $this->mOptions
= $options;
197 $this->mTitle
=& $title;
198 $this->mRevisionId
= $revid;
199 $this->mOutputType
= OT_HTML
;
201 $this->mStripState
= NULL;
203 //$text = $this->strip( $text, $this->mStripState );
204 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
205 $x =& $this->mStripState
;
207 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
208 $text = $this->strip( $text, $x );
209 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
211 # Hook to suspend the parser in this state
212 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
213 wfProfileOut( $fname );
217 $text = $this->internalParse( $text );
219 $text = $this->unstrip( $text, $this->mStripState
);
221 # Clean up special characters, only run once, next-to-last before doBlockLevels
223 # french spaces, last one Guillemet-left
224 # only if there is something before the space
225 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
226 # french spaces, Guillemet-right
227 '/(\\302\\253) /' => '\\1 ',
228 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
230 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
233 $text = $this->doBlockLevels( $text, $linestart );
235 $this->replaceLinkHolders( $text );
237 # the position of the convert() call should not be changed. it
238 # assumes that the links are all replaces and the only thing left
239 # is the <nowiki> mark.
240 $text = $wgContLang->convert($text);
241 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
243 $text = $this->unstripNoWiki( $text, $this->mStripState
);
245 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
247 $text = Sanitizer
::normalizeCharReferences( $text );
249 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
250 $text = Parser
::tidy($text);
253 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
255 $this->mOutput
->setText( $text );
256 wfProfileOut( $fname );
258 return $this->mOutput
;
262 * Get a random string
267 function getRandomString() {
268 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
272 * Replaces all occurrences of <$tag>content</$tag> in the text
273 * with a random marker and returns the new text. the output parameter
274 * $content will be an associative array filled with data on the form
275 * $unique_marker => content.
277 * If $content is already set, the additional entries will be appended
278 * If $tag is set to STRIP_COMMENTS, the function will extract
279 * <!-- HTML comments -->
284 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
285 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
300 if( $tag == STRIP_COMMENTS
) {
301 $start = '/<!--()()/';
304 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
305 $end = "/<\\/$tag\\s*>/i";
308 while ( '' != $text ) {
309 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
311 if( count( $p ) < 4 ) {
318 $marker = $rnd . sprintf('%08X', $n++
);
319 $stripped .= $marker;
321 $tags[$marker] = "<$tag$attributes$empty>";
322 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
324 if ( $empty === '/' ) {
325 // Empty element tag, <tag />
326 $content[$marker] = null;
329 $q = preg_split( $end, $inside, 2 );
330 $content[$marker] = $q[0];
331 if( count( $q ) < 2 ) {
332 # No end tag -- let it run out to the end of the text.
343 * Wrapper function for extractTagsAndParams
344 * for cases where $tags and $params isn't needed
345 * i.e. where tags will never have params, like <nowiki>
350 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
351 $dummy_tags = array();
352 $dummy_params = array();
354 return Parser
::extractTagsAndParams( $tag, $text, $content,
355 $dummy_tags, $dummy_params, $uniq_prefix );
359 * Strips and renders nowiki, pre, math, hiero
360 * If $render is set, performs necessary rendering operations on plugins
361 * Returns the text, and fills an array with data needed in unstrip()
362 * If the $state is already a valid strip state, it adds to the state
364 * @param bool $stripcomments when set, HTML comments <!-- like this -->
365 * will be stripped in addition to other tags. This is important
366 * for section editing, where these comments cause confusion when
367 * counting the sections in the wikisource
371 function strip( $text, &$state, $stripcomments = false ) {
372 $render = ($this->mOutputType
== OT_HTML
);
373 $html_content = array();
374 $nowiki_content = array();
375 $math_content = array();
376 $pre_content = array();
377 $comment_content = array();
378 $ext_content = array();
380 $ext_params = array();
381 $gallery_content = array();
383 # Replace any instances of the placeholders
384 $uniq_prefix = $this->mUniqPrefix
;
385 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
390 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
391 foreach( $html_content as $marker => $content ) {
393 # Raw and unchecked for validity.
394 $html_content[$marker] = $content;
396 $html_content[$marker] = '<html>'.$content.'</html>';
402 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
403 foreach( $nowiki_content as $marker => $content ) {
405 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
407 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
412 if( $this->mOptions
->getUseTeX() ) {
413 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
414 foreach( $math_content as $marker => $content ){
416 $math_content[$marker] = renderMath( $content );
418 $math_content[$marker] = '<math>'.$content.'</math>';
424 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
425 foreach( $pre_content as $marker => $content ){
427 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
429 $pre_content[$marker] = '<pre>'.$content.'</pre>';
434 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
435 foreach( $gallery_content as $marker => $content ) {
436 require_once( 'ImageGallery.php' );
438 $gallery_content[$marker] = $this->renderImageGallery( $content );
440 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
446 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
447 foreach( $comment_content as $marker => $content ){
448 $comment_content[$marker] = '<!--'.$content.'-->';
453 foreach ( $this->mTagHooks
as $tag => $callback ) {
454 $ext_content[$tag] = array();
455 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
456 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
457 foreach( $ext_content[$tag] as $marker => $content ) {
458 $full_tag = $ext_tags[$tag][$marker];
459 $params = $ext_params[$tag][$marker];
461 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
463 if ( is_null( $content ) ) {
465 $ext_content[$tag][$marker] = $full_tag;
467 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
473 # Merge state with the pre-existing state, if there is one
475 $state['html'] = $state['html'] +
$html_content;
476 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
477 $state['math'] = $state['math'] +
$math_content;
478 $state['pre'] = $state['pre'] +
$pre_content;
479 $state['comment'] = $state['comment'] +
$comment_content;
480 $state['gallery'] = $state['gallery'] +
$gallery_content;
482 foreach( $ext_content as $tag => $array ) {
483 if ( array_key_exists( $tag, $state ) ) {
484 $state[$tag] = $state[$tag] +
$array;
489 'html' => $html_content,
490 'nowiki' => $nowiki_content,
491 'math' => $math_content,
492 'pre' => $pre_content,
493 'comment' => $comment_content,
494 'gallery' => $gallery_content,
501 * restores pre, math, and hiero removed by strip()
503 * always call unstripNoWiki() after this one
506 function unstrip( $text, &$state ) {
507 if ( !is_array( $state ) ) {
511 # Must expand in reverse order, otherwise nested tags will be corrupted
512 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
513 if( $tag != 'nowiki' && $tag != 'html' ) {
514 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
515 $text = str_replace( $uniq, $content, $text );
524 * always call this after unstrip() to preserve the order
528 function unstripNoWiki( $text, &$state ) {
529 if ( !is_array( $state ) ) {
533 # Must expand in reverse order, otherwise nested tags will be corrupted
534 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
535 $text = str_replace( key( $state['nowiki'] ), $content, $text );
540 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
541 $text = str_replace( key( $state['html'] ), $content, $text );
549 * Add an item to the strip state
550 * Returns the unique tag which must be inserted into the stripped text
551 * The tag will be replaced with the original text in unstrip()
555 function insertStripItem( $text, &$state ) {
556 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
563 'comment' => array(),
564 'gallery' => array(),
567 $state['item'][$rnd] = $text;
572 * Interface with html tidy, used if $wgUseTidy = true.
573 * If tidy isn't able to correct the markup, the original will be
574 * returned in all its glory with a warning comment appended.
576 * Either the external tidy program or the in-process tidy extension
577 * will be used depending on availability. Override the default
578 * $wgTidyInternal setting to disable the internal if it's not working.
580 * @param string $text Hideous HTML input
581 * @return string Corrected HTML output
585 function tidy( $text ) {
586 global $wgTidyInternal;
587 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
588 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
589 '<head><title>test</title></head><body>'.$text.'</body></html>';
590 if( $wgTidyInternal ) {
591 $correctedtext = Parser
::internalTidy( $wrappedtext );
593 $correctedtext = Parser
::externalTidy( $wrappedtext );
595 if( is_null( $correctedtext ) ) {
596 wfDebug( "Tidy error detected!\n" );
597 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
599 return $correctedtext;
603 * Spawn an external HTML tidy process and get corrected markup back from it.
608 function externalTidy( $text ) {
609 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
610 $fname = 'Parser::externalTidy';
611 wfProfileIn( $fname );
616 $descriptorspec = array(
617 0 => array('pipe', 'r'),
618 1 => array('pipe', 'w'),
619 2 => array('file', '/dev/null', 'a')
622 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
623 if (is_resource($process)) {
624 fwrite($pipes[0], $text);
626 while (!feof($pipes[1])) {
627 $cleansource .= fgets($pipes[1], 1024);
630 proc_close($process);
633 wfProfileOut( $fname );
635 if( $cleansource == '' && $text != '') {
636 // Some kind of error happened, so we couldn't get the corrected text.
637 // Just give up; we'll use the source text and append a warning.
645 * Use the HTML tidy PECL extension to use the tidy library in-process,
646 * saving the overhead of spawning a new process. Currently written to
647 * the PHP 4.3.x version of the extension, may not work on PHP 5.
649 * 'pear install tidy' should be able to compile the extension module.
654 function internalTidy( $text ) {
656 $fname = 'Parser::internalTidy';
657 wfProfileIn( $fname );
659 tidy_load_config( $wgTidyConf );
660 tidy_set_encoding( 'utf8' );
661 tidy_parse_string( $text );
663 if( tidy_get_status() == 2 ) {
664 // 2 is magic number for fatal error
665 // http://www.php.net/manual/en/function.tidy-get-status.php
668 $cleansource = tidy_get_output();
670 wfProfileOut( $fname );
675 * parse the wiki syntax used to render tables
679 function doTableStuff ( $t ) {
680 $fname = 'Parser::doTableStuff';
681 wfProfileIn( $fname );
683 $t = explode ( "\n" , $t ) ;
684 $td = array () ; # Is currently a td tag open?
685 $ltd = array () ; # Was it TD or TH?
686 $tr = array () ; # Is currently a tr tag open?
687 $ltr = array () ; # tr attributes
688 $indent_level = 0; # indent level of the table
689 foreach ( $t AS $k => $x )
692 $fc = substr ( $x , 0 , 1 ) ;
693 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
694 $indent_level = strlen( $matches[1] );
696 $attributes = $this->unstripForHTML( $matches[2] );
698 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
699 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
700 array_push ( $td , false ) ;
701 array_push ( $ltd , '' ) ;
702 array_push ( $tr , false ) ;
703 array_push ( $ltr , '' ) ;
705 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
706 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
707 $z = "</table>" . substr ( $x , 2);
708 $l = array_pop ( $ltd ) ;
709 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
710 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
712 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
714 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
715 $x = substr ( $x , 1 ) ;
716 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
718 $l = array_pop ( $ltd ) ;
719 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
720 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
723 array_push ( $tr , false ) ;
724 array_push ( $td , false ) ;
725 array_push ( $ltd , '' ) ;
726 $attributes = $this->unstripForHTML( $x );
727 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
729 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
731 if ( '|+' == substr ( $x , 0 , 2 ) ) {
733 $x = substr ( $x , 1 ) ;
735 $after = substr ( $x , 1 ) ;
736 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
737 $after = explode ( '||' , $after ) ;
740 # Loop through each table cell
741 foreach ( $after AS $theline )
746 $tra = array_pop ( $ltr ) ;
747 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
748 array_push ( $tr , true ) ;
749 array_push ( $ltr , '' ) ;
752 $l = array_pop ( $ltd ) ;
753 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
754 if ( $fc == '|' ) $l = 'td' ;
755 else if ( $fc == '!' ) $l = 'th' ;
756 else if ( $fc == '+' ) $l = 'caption' ;
758 array_push ( $ltd , $l ) ;
761 $y = explode ( '|' , $theline , 2 ) ;
762 # Note that a '|' inside an invalid link should not
763 # be mistaken as delimiting cell parameters
764 if ( strpos( $y[0], '[[' ) !== false ) {
765 $y = array ($theline);
767 if ( count ( $y ) == 1 )
768 $y = "{$z}<{$l}>{$y[0]}" ;
770 $attributes = $this->unstripForHTML( $y[0] );
771 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
774 array_push ( $td , true ) ;
779 # Closing open td, tr && table
780 while ( count ( $td ) > 0 )
782 if ( array_pop ( $td ) ) $t[] = '</td>' ;
783 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
787 $t = implode ( "\n" , $t ) ;
788 wfProfileOut( $fname );
793 * Helper function for parse() that transforms wiki markup into
794 * HTML. Only called for $mOutputType == OT_HTML.
798 function internalParse( $text ) {
802 $fname = 'Parser::internalParse';
803 wfProfileIn( $fname );
805 # Remove <noinclude> tags and <includeonly> sections
806 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
807 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
808 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
810 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
811 $text = $this->replaceVariables( $text, $args );
813 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
815 $text = $this->doHeadings( $text );
816 if($this->mOptions
->getUseDynamicDates()) {
817 $df =& DateFormatter
::getInstance();
818 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
820 $text = $this->doAllQuotes( $text );
821 $text = $this->replaceInternalLinks( $text );
822 $text = $this->replaceExternalLinks( $text );
824 # replaceInternalLinks may sometimes leave behind
825 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
826 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
828 $text = $this->doMagicLinks( $text );
829 $text = $this->doTableStuff( $text );
830 $text = $this->formatHeadings( $text, $isMain );
832 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
833 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
835 wfProfileOut( $fname );
839 function scarySubstitution($matches) {
840 # return "[[".$matches[0]."]]";
841 return $this->mIWTransData
[(int)$matches[0]];
845 * Replace special strings like "ISBN xxx" and "RFC xxx" with
846 * magic external links.
850 function &doMagicLinks( &$text ) {
851 $text = $this->magicISBN( $text );
852 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
853 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
858 * Parse headers and return html
862 function doHeadings( $text ) {
863 $fname = 'Parser::doHeadings';
864 wfProfileIn( $fname );
865 for ( $i = 6; $i >= 1; --$i ) {
866 $h = str_repeat( '=', $i );
867 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
868 "<h{$i}>\\1</h{$i}>\\2", $text );
870 wfProfileOut( $fname );
875 * Replace single quotes with HTML markup
877 * @return string the altered text
879 function doAllQuotes( $text ) {
880 $fname = 'Parser::doAllQuotes';
881 wfProfileIn( $fname );
883 $lines = explode( "\n", $text );
884 foreach ( $lines as $line ) {
885 $outtext .= $this->doQuotes ( $line ) . "\n";
887 $outtext = substr($outtext, 0,-1);
888 wfProfileOut( $fname );
893 * Helper function for doAllQuotes()
896 function doQuotes( $text ) {
897 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
898 if ( count( $arr ) == 1 )
902 # First, do some preliminary work. This may shift some apostrophes from
903 # being mark-up to being text. It also counts the number of occurrences
904 # of bold and italics mark-ups.
908 foreach ( $arr as $r )
910 if ( ( $i %
2 ) == 1 )
912 # If there are ever four apostrophes, assume the first is supposed to
913 # be text, and the remaining three constitute mark-up for bold text.
914 if ( strlen( $arr[$i] ) == 4 )
919 # If there are more than 5 apostrophes in a row, assume they're all
920 # text except for the last 5.
921 else if ( strlen( $arr[$i] ) > 5 )
923 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
926 # Count the number of occurrences of bold and italics mark-ups.
927 # We are not counting sequences of five apostrophes.
928 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
929 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
930 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
935 # If there is an odd number of both bold and italics, it is likely
936 # that one of the bold ones was meant to be an apostrophe followed
937 # by italics. Which one we cannot know for certain, but it is more
938 # likely to be one that has a single-letter word before it.
939 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
942 $firstsingleletterword = -1;
943 $firstmultiletterword = -1;
945 foreach ( $arr as $r )
947 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
949 $x1 = substr ($arr[$i-1], -1);
950 $x2 = substr ($arr[$i-1], -2, 1);
952 if ($firstspace == -1) $firstspace = $i;
953 } else if ($x2 == ' ') {
954 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
956 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
962 # If there is a single-letter word, use it!
963 if ($firstsingleletterword > -1)
965 $arr [ $firstsingleletterword ] = "''";
966 $arr [ $firstsingleletterword-1 ] .= "'";
968 # If not, but there's a multi-letter word, use that one.
969 else if ($firstmultiletterword > -1)
971 $arr [ $firstmultiletterword ] = "''";
972 $arr [ $firstmultiletterword-1 ] .= "'";
974 # ... otherwise use the first one that has neither.
975 # (notice that it is possible for all three to be -1 if, for example,
976 # there is only one pentuple-apostrophe in the line)
977 else if ($firstspace > -1)
979 $arr [ $firstspace ] = "''";
980 $arr [ $firstspace-1 ] .= "'";
984 # Now let's actually convert our apostrophic mush to HTML!
993 if ($state == 'both')
1000 if (strlen ($r) == 2)
1003 { $output .= '</i>'; $state = ''; }
1004 else if ($state == 'bi')
1005 { $output .= '</i>'; $state = 'b'; }
1006 else if ($state == 'ib')
1007 { $output .= '</b></i><b>'; $state = 'b'; }
1008 else if ($state == 'both')
1009 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1010 else # $state can be 'b' or ''
1011 { $output .= '<i>'; $state .= 'i'; }
1013 else if (strlen ($r) == 3)
1016 { $output .= '</b>'; $state = ''; }
1017 else if ($state == 'bi')
1018 { $output .= '</i></b><i>'; $state = 'i'; }
1019 else if ($state == 'ib')
1020 { $output .= '</b>'; $state = 'i'; }
1021 else if ($state == 'both')
1022 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1023 else # $state can be 'i' or ''
1024 { $output .= '<b>'; $state .= 'b'; }
1026 else if (strlen ($r) == 5)
1029 { $output .= '</b><i>'; $state = 'i'; }
1030 else if ($state == 'i')
1031 { $output .= '</i><b>'; $state = 'b'; }
1032 else if ($state == 'bi')
1033 { $output .= '</i></b>'; $state = ''; }
1034 else if ($state == 'ib')
1035 { $output .= '</b></i>'; $state = ''; }
1036 else if ($state == 'both')
1037 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1038 else # ($state == '')
1039 { $buffer = ''; $state = 'both'; }
1044 # Now close all remaining tags. Notice that the order is important.
1045 if ($state == 'b' ||
$state == 'ib')
1047 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1051 if ($state == 'both')
1052 $output .= '<b><i>'.$buffer.'</i></b>';
1058 * Replace external links
1060 * Note: this is all very hackish and the order of execution matters a lot.
1061 * Make sure to run maintenance/parserTests.php if you change this code.
1065 function replaceExternalLinks( $text ) {
1067 $fname = 'Parser::replaceExternalLinks';
1068 wfProfileIn( $fname );
1070 $sk =& $this->mOptions
->getSkin();
1072 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1074 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1077 while ( $i<count( $bits ) ) {
1079 $protocol = $bits[$i++
];
1080 $text = $bits[$i++
];
1081 $trail = $bits[$i++
];
1083 # The characters '<' and '>' (which were escaped by
1084 # removeHTMLtags()) should not be included in
1085 # URLs, per RFC 2396.
1086 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1087 $text = substr($url, $m2[0][1]) . ' ' . $text;
1088 $url = substr($url, 0, $m2[0][1]);
1091 # If the link text is an image URL, replace it with an <img> tag
1092 # This happened by accident in the original parser, but some people used it extensively
1093 $img = $this->maybeMakeExternalImage( $text );
1094 if ( $img !== false ) {
1100 # Set linktype for CSS - if URL==text, link is essentially free
1101 $linktype = ($text == $url) ?
'free' : 'text';
1103 # No link text, e.g. [http://domain.tld/some.link]
1104 if ( $text == '' ) {
1105 # Autonumber if allowed
1106 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1107 $text = '[' . ++
$this->mAutonumber
. ']';
1108 $linktype = 'autonumber';
1110 # Otherwise just use the URL
1111 $text = htmlspecialchars( $url );
1115 # Have link text, e.g. [http://domain.tld/some.link text]s
1117 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1120 $text = $wgContLang->markNoConversion($text);
1122 # Replace & from obsolete syntax with &.
1123 # All HTML entities will be escaped by makeExternalLink()
1124 # or maybeMakeExternalImage()
1125 $url = str_replace( '&', '&', $url );
1127 # Process the trail (i.e. everything after this link up until start of the next link),
1128 # replacing any non-bracketed links
1129 $trail = $this->replaceFreeExternalLinks( $trail );
1132 # Use the encoded URL
1133 # This means that users can paste URLs directly into the text
1134 # Funny characters like ö aren't valid in URLs anyway
1135 # This was changed in August 2004
1136 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1139 wfProfileOut( $fname );
1144 * Replace anything that looks like a URL with a link
1147 function replaceFreeExternalLinks( $text ) {
1149 $fname = 'Parser::replaceFreeExternalLinks';
1150 wfProfileIn( $fname );
1152 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1153 $s = array_shift( $bits );
1156 $sk =& $this->mOptions
->getSkin();
1158 while ( $i < count( $bits ) ){
1159 $protocol = $bits[$i++
];
1160 $remainder = $bits[$i++
];
1162 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1163 # Found some characters after the protocol that look promising
1164 $url = $protocol . $m[1];
1167 # The characters '<' and '>' (which were escaped by
1168 # removeHTMLtags()) should not be included in
1169 # URLs, per RFC 2396.
1170 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1171 $trail = substr($url, $m2[0][1]) . $trail;
1172 $url = substr($url, 0, $m2[0][1]);
1175 # Move trailing punctuation to $trail
1177 # If there is no left bracket, then consider right brackets fair game too
1178 if ( strpos( $url, '(' ) === false ) {
1182 $numSepChars = strspn( strrev( $url ), $sep );
1183 if ( $numSepChars ) {
1184 $trail = substr( $url, -$numSepChars ) . $trail;
1185 $url = substr( $url, 0, -$numSepChars );
1188 # Replace & from obsolete syntax with &.
1189 # All HTML entities will be escaped by makeExternalLink()
1190 # or maybeMakeExternalImage()
1191 $url = str_replace( '&', '&', $url );
1193 # Is this an external image?
1194 $text = $this->maybeMakeExternalImage( $url );
1195 if ( $text === false ) {
1196 # Not an image, make a link
1197 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1199 $s .= $text . $trail;
1201 $s .= $protocol . $remainder;
1204 wfProfileOut( $fname );
1209 * make an image if it's allowed, either through the global
1210 * option or through the exception
1213 function maybeMakeExternalImage( $url ) {
1214 $sk =& $this->mOptions
->getSkin();
1215 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1216 $imagesexception = !empty($imagesfrom);
1218 if ( $this->mOptions
->getAllowExternalImages()
1219 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1220 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1222 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1229 * Process [[ ]] wikilinks
1233 function replaceInternalLinks( $s ) {
1235 static $fname = 'Parser::replaceInternalLinks' ;
1237 wfProfileIn( $fname );
1239 wfProfileIn( $fname.'-setup' );
1241 # the % is needed to support urlencoded titles as well
1242 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1244 $sk =& $this->mOptions
->getSkin();
1246 #split the entire text string on occurences of [[
1247 $a = explode( '[[', ' ' . $s );
1248 #get the first element (all text up to first [[), and remove the space we added
1249 $s = array_shift( $a );
1250 $s = substr( $s, 1 );
1252 # Match a link having the form [[namespace:link|alternate]]trail
1254 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1255 # Match cases where there is no "]]", which might still be images
1256 static $e1_img = FALSE;
1257 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1258 # Match the end of a line for a word that's not followed by whitespace,
1259 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1260 $e2 = wfMsgForContent( 'linkprefix' );
1262 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1264 if( is_null( $this->mTitle
) ) {
1265 wfDebugDieBacktrace( 'nooo' );
1267 $nottalk = !$this->mTitle
->isTalkPage();
1269 if ( $useLinkPrefixExtension ) {
1270 if ( preg_match( $e2, $s, $m ) ) {
1271 $first_prefix = $m[2];
1273 $first_prefix = false;
1279 $selflink = $this->mTitle
->getPrefixedText();
1280 wfProfileOut( $fname.'-setup' );
1282 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1283 $useSubpages = $this->areSubpagesAllowed();
1285 # Loop for each link
1286 for ($k = 0; isset( $a[$k] ); $k++
) {
1288 if ( $useLinkPrefixExtension ) {
1289 wfProfileIn( $fname.'-prefixhandling' );
1290 if ( preg_match( $e2, $s, $m ) ) {
1298 $prefix = $first_prefix;
1299 $first_prefix = false;
1301 wfProfileOut( $fname.'-prefixhandling' );
1304 $might_be_img = false;
1306 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1308 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1309 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1310 # the real problem is with the $e1 regex
1313 # Still some problems for cases where the ] is meant to be outside punctuation,
1314 # and no image is in sight. See bug 2095.
1316 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1317 $text .= ']'; # so that replaceExternalLinks($text) works later
1320 # fix up urlencoded title texts
1321 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1323 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1324 $might_be_img = true;
1326 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1328 } else { # Invalid form; output directly
1329 $s .= $prefix . '[[' . $line ;
1333 # Don't allow internal links to pages containing
1334 # PROTO: where PROTO is a valid URL protocol; these
1335 # should be external links.
1336 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1337 $s .= $prefix . '[[' . $line ;
1341 # Make subpage if necessary
1342 if( $useSubpages ) {
1343 $link = $this->maybeDoSubpageLink( $m[1], $text );
1348 $noforce = (substr($m[1], 0, 1) != ':');
1350 # Strip off leading ':'
1351 $link = substr($link, 1);
1354 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1356 $s .= $prefix . '[[' . $line;
1360 #check other language variants of the link
1361 #if the article does not exist
1362 if( $checkVariantLink
1363 && $nt->getArticleID() == 0 ) {
1364 $wgContLang->findVariantLink($link, $nt);
1367 $ns = $nt->getNamespace();
1368 $iw = $nt->getInterWiki();
1370 if ($might_be_img) { # if this is actually an invalid link
1371 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1373 while (isset ($a[$k+
1]) ) {
1374 #look at the next 'line' to see if we can close it there
1375 $spliced = array_splice( $a, $k +
1, 1 );
1376 $next_line = array_shift( $spliced );
1377 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1378 # the first ]] closes the inner link, the second the image
1380 $text .= '[[' . $m[1];
1383 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1384 #if there's exactly one ]] that's fine, we'll keep looking
1385 $text .= '[[' . $m[0];
1387 #if $next_line is invalid too, we need look no further
1388 $text .= '[[' . $next_line;
1393 # we couldn't find the end of this imageLink, so output it raw
1394 #but don't ignore what might be perfectly normal links in the text we've examined
1395 $text = $this->replaceInternalLinks($text);
1396 $s .= $prefix . '[[' . $link . '|' . $text;
1397 # note: no $trail, because without an end, there *is* no trail
1400 } else { #it's not an image, so output it raw
1401 $s .= $prefix . '[[' . $link . '|' . $text;
1402 # note: no $trail, because without an end, there *is* no trail
1407 $wasblank = ( '' == $text );
1408 if( $wasblank ) $text = $link;
1411 # Link not escaped by : , create the various objects
1415 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1416 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1417 $s = rtrim($s . "\n");
1418 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1422 if ( $ns == NS_IMAGE
) {
1423 wfProfileIn( "$fname-image" );
1424 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1425 # recursively parse links inside the image caption
1426 # actually, this will parse them in any other parameters, too,
1427 # but it might be hard to fix that, and it doesn't matter ATM
1428 $text = $this->replaceExternalLinks($text);
1429 $text = $this->replaceInternalLinks($text);
1431 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1432 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1433 $this->mOutput
->addImage( $nt->getDBkey() );
1435 wfProfileOut( "$fname-image" );
1438 wfProfileOut( "$fname-image" );
1442 if ( $ns == NS_CATEGORY
) {
1443 wfProfileIn( "$fname-category" );
1444 $s = rtrim($s . "\n"); # bug 87
1447 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1448 $sortkey = $this->mTitle
->getText();
1450 $sortkey = $this->mTitle
->getPrefixedText();
1455 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1456 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1457 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1460 * Strip the whitespace Category links produce, see bug 87
1461 * @todo We might want to use trim($tmp, "\n") here.
1463 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1465 wfProfileOut( "$fname-category" );
1470 if( ( $nt->getPrefixedText() === $selflink ) &&
1471 ( $nt->getFragment() === '' ) ) {
1472 # Self-links are handled specially; generally de-link and change to bold.
1473 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1477 # Special and Media are pseudo-namespaces; no pages actually exist in them
1478 if( $ns == NS_MEDIA
) {
1479 $link = $sk->makeMediaLinkObj( $nt, $text );
1480 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1481 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1482 $this->mOutput
->addImage( $nt->getDBkey() );
1484 } elseif( $ns == NS_SPECIAL
) {
1485 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1487 } elseif( $ns == NS_IMAGE
) {
1488 $img = Image
::newFromTitle( $nt );
1489 if( $img->exists() ) {
1490 // Force a blue link if the file exists; may be a remote
1491 // upload on the shared repository, and we want to see its
1492 // auto-generated page.
1493 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1497 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1499 wfProfileOut( $fname );
1504 * Make a link placeholder. The text returned can be later resolved to a real link with
1505 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1506 * parsing of interwiki links, and secondly to allow all extistence checks and
1507 * article length checks (for stub links) to be bundled into a single query.
1510 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1511 if ( ! is_object($nt) ) {
1513 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1515 # Separate the link trail from the rest of the link
1516 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1518 if ( $nt->isExternal() ) {
1519 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1520 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1521 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1523 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1524 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1525 $this->mLinkHolders
['queries'][] = $query;
1526 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1527 $this->mLinkHolders
['titles'][] = $nt;
1529 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1536 * Render a forced-blue link inline; protect against double expansion of
1537 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1538 * Since this little disaster has to split off the trail text to avoid
1539 * breaking URLs in the following text without breaking trails on the
1540 * wiki links, it's been made into a horrible function.
1543 * @param string $text
1544 * @param string $query
1545 * @param string $trail
1546 * @param string $prefix
1547 * @return string HTML-wikitext mix oh yuck
1549 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1550 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1551 $sk =& $this->mOptions
->getSkin();
1552 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1553 return $this->armorLinks( $link ) . $trail;
1557 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1558 * going to go through further parsing steps before inline URL expansion.
1560 * In particular this is important when using action=render, which causes
1561 * full URLs to be included.
1563 * Oh man I hate our multi-layer parser!
1565 * @param string more-or-less HTML
1566 * @return string less-or-more HTML with NOPARSE bits
1568 function armorLinks( $text ) {
1569 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1570 "{$this->mUniqPrefix}NOPARSE$1", $text );
1574 * Return true if subpage links should be expanded on this page.
1577 function areSubpagesAllowed() {
1578 # Some namespaces don't allow subpages
1579 global $wgNamespacesWithSubpages;
1580 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1584 * Handle link to subpage if necessary
1585 * @param string $target the source of the link
1586 * @param string &$text the link text, modified as necessary
1587 * @return string the full name of the link
1590 function maybeDoSubpageLink($target, &$text) {
1593 # :Foobar -- override special treatment of prefix (images, language links)
1594 # /Foobar -- convert to CurrentPage/Foobar
1595 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1596 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1597 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1599 $fname = 'Parser::maybeDoSubpageLink';
1600 wfProfileIn( $fname );
1601 $ret = $target; # default return value is no change
1603 # Some namespaces don't allow subpages,
1604 # so only perform processing if subpages are allowed
1605 if( $this->areSubpagesAllowed() ) {
1606 # Look at the first character
1607 if( $target != '' && $target{0} == '/' ) {
1608 # / at end means we don't want the slash to be shown
1609 if( substr( $target, -1, 1 ) == '/' ) {
1610 $target = substr( $target, 1, -1 );
1613 $noslash = substr( $target, 1 );
1616 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1617 if( '' === $text ) {
1619 } # this might be changed for ugliness reasons
1621 # check for .. subpage backlinks
1623 $nodotdot = $target;
1624 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1626 $nodotdot = substr( $nodotdot, 3 );
1628 if($dotdotcount > 0) {
1629 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1630 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1631 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1632 # / at the end means don't show full path
1633 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1634 $nodotdot = substr( $nodotdot, 0, -1 );
1635 if( '' === $text ) {
1639 $nodotdot = trim( $nodotdot );
1640 if( $nodotdot != '' ) {
1641 $ret .= '/' . $nodotdot;
1648 wfProfileOut( $fname );
1653 * Used by doBlockLevels()
1656 /* private */ function closeParagraph() {
1658 if ( '' != $this->mLastSection
) {
1659 $result = '</' . $this->mLastSection
. ">\n";
1661 $this->mInPre
= false;
1662 $this->mLastSection
= '';
1665 # getCommon() returns the length of the longest common substring
1666 # of both arguments, starting at the beginning of both.
1668 /* private */ function getCommon( $st1, $st2 ) {
1669 $fl = strlen( $st1 );
1670 $shorter = strlen( $st2 );
1671 if ( $fl < $shorter ) { $shorter = $fl; }
1673 for ( $i = 0; $i < $shorter; ++
$i ) {
1674 if ( $st1{$i} != $st2{$i} ) { break; }
1678 # These next three functions open, continue, and close the list
1679 # element appropriate to the prefix character passed into them.
1681 /* private */ function openList( $char ) {
1682 $result = $this->closeParagraph();
1684 if ( '*' == $char ) { $result .= '<ul><li>'; }
1685 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1686 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1687 else if ( ';' == $char ) {
1688 $result .= '<dl><dt>';
1689 $this->mDTopen
= true;
1691 else { $result = '<!-- ERR 1 -->'; }
1696 /* private */ function nextItem( $char ) {
1697 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1698 else if ( ':' == $char ||
';' == $char ) {
1700 if ( $this->mDTopen
) { $close = '</dt>'; }
1701 if ( ';' == $char ) {
1702 $this->mDTopen
= true;
1703 return $close . '<dt>';
1705 $this->mDTopen
= false;
1706 return $close . '<dd>';
1709 return '<!-- ERR 2 -->';
1712 /* private */ function closeList( $char ) {
1713 if ( '*' == $char ) { $text = '</li></ul>'; }
1714 else if ( '#' == $char ) { $text = '</li></ol>'; }
1715 else if ( ':' == $char ) {
1716 if ( $this->mDTopen
) {
1717 $this->mDTopen
= false;
1718 $text = '</dt></dl>';
1720 $text = '</dd></dl>';
1723 else { return '<!-- ERR 3 -->'; }
1729 * Make lists from lines starting with ':', '*', '#', etc.
1732 * @return string the lists rendered as HTML
1734 function doBlockLevels( $text, $linestart ) {
1735 $fname = 'Parser::doBlockLevels';
1736 wfProfileIn( $fname );
1738 # Parsing through the text line by line. The main thing
1739 # happening here is handling of block-level elements p, pre,
1740 # and making lists from lines starting with * # : etc.
1742 $textLines = explode( "\n", $text );
1744 $lastPrefix = $output = '';
1745 $this->mDTopen
= $inBlockElem = false;
1747 $paragraphStack = false;
1749 if ( !$linestart ) {
1750 $output .= array_shift( $textLines );
1752 foreach ( $textLines as $oLine ) {
1753 $lastPrefixLength = strlen( $lastPrefix );
1754 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1755 $preOpenMatch = preg_match('/<pre/i', $oLine );
1756 if ( !$this->mInPre
) {
1757 # Multiple prefixes may abut each other for nested lists.
1758 $prefixLength = strspn( $oLine, '*#:;' );
1759 $pref = substr( $oLine, 0, $prefixLength );
1762 $pref2 = str_replace( ';', ':', $pref );
1763 $t = substr( $oLine, $prefixLength );
1764 $this->mInPre
= !empty($preOpenMatch);
1766 # Don't interpret any other prefixes in preformatted text
1768 $pref = $pref2 = '';
1773 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1774 # Same as the last item, so no need to deal with nesting or opening stuff
1775 $output .= $this->nextItem( substr( $pref, -1 ) );
1776 $paragraphStack = false;
1778 if ( substr( $pref, -1 ) == ';') {
1779 # The one nasty exception: definition lists work like this:
1780 # ; title : definition text
1781 # So we check for : in the remainder text to split up the
1782 # title and definition, without b0rking links.
1784 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1786 $output .= $term . $this->nextItem( ':' );
1789 } elseif( $prefixLength ||
$lastPrefixLength ) {
1790 # Either open or close a level...
1791 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1792 $paragraphStack = false;
1794 while( $commonPrefixLength < $lastPrefixLength ) {
1795 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1796 --$lastPrefixLength;
1798 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1799 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1801 while ( $prefixLength > $commonPrefixLength ) {
1802 $char = substr( $pref, $commonPrefixLength, 1 );
1803 $output .= $this->openList( $char );
1805 if ( ';' == $char ) {
1806 # FIXME: This is dupe of code above
1807 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1809 $output .= $term . $this->nextItem( ':' );
1812 ++
$commonPrefixLength;
1814 $lastPrefix = $pref2;
1816 if( 0 == $prefixLength ) {
1817 wfProfileIn( "$fname-paragraph" );
1818 # No prefix (not in list)--go to paragraph mode
1819 // XXX: use a stack for nestable elements like span, table and div
1820 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1821 $closematch = preg_match(
1822 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1823 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1824 if ( $openmatch or $closematch ) {
1825 $paragraphStack = false;
1826 $output .= $this->closeParagraph();
1827 if ( $preOpenMatch and !$preCloseMatch ) {
1828 $this->mInPre
= true;
1830 if ( $closematch ) {
1831 $inBlockElem = false;
1833 $inBlockElem = true;
1835 } else if ( !$inBlockElem && !$this->mInPre
) {
1836 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1838 if ($this->mLastSection
!= 'pre') {
1839 $paragraphStack = false;
1840 $output .= $this->closeParagraph().'<pre>';
1841 $this->mLastSection
= 'pre';
1843 $t = substr( $t, 1 );
1846 if ( '' == trim($t) ) {
1847 if ( $paragraphStack ) {
1848 $output .= $paragraphStack.'<br />';
1849 $paragraphStack = false;
1850 $this->mLastSection
= 'p';
1852 if ($this->mLastSection
!= 'p' ) {
1853 $output .= $this->closeParagraph();
1854 $this->mLastSection
= '';
1855 $paragraphStack = '<p>';
1857 $paragraphStack = '</p><p>';
1861 if ( $paragraphStack ) {
1862 $output .= $paragraphStack;
1863 $paragraphStack = false;
1864 $this->mLastSection
= 'p';
1865 } else if ($this->mLastSection
!= 'p') {
1866 $output .= $this->closeParagraph().'<p>';
1867 $this->mLastSection
= 'p';
1872 wfProfileOut( "$fname-paragraph" );
1874 // somewhere above we forget to get out of pre block (bug 785)
1875 if($preCloseMatch && $this->mInPre
) {
1876 $this->mInPre
= false;
1878 if ($paragraphStack === false) {
1882 while ( $prefixLength ) {
1883 $output .= $this->closeList( $pref2{$prefixLength-1} );
1886 if ( '' != $this->mLastSection
) {
1887 $output .= '</' . $this->mLastSection
. '>';
1888 $this->mLastSection
= '';
1891 wfProfileOut( $fname );
1896 * Split up a string on ':', ignoring any occurences inside
1897 * <a>..</a> or <span>...</span>
1898 * @param string $str the string to split
1899 * @param string &$before set to everything before the ':'
1900 * @param string &$after set to everything after the ':'
1901 * return string the position of the ':', or false if none found
1903 function findColonNoLinks($str, &$before, &$after) {
1904 # I wonder if we should make this count all tags, not just <a>
1905 # and <span>. That would prevent us from matching a ':' that
1906 # comes in the middle of italics other such formatting....
1908 $fname = 'Parser::findColonNoLinks';
1909 wfProfileIn( $fname );
1912 $colon = strpos($str, ':', $pos);
1914 if ($colon !== false) {
1915 $before = substr($str, 0, $colon);
1916 $after = substr($str, $colon +
1);
1918 # Skip any ':' within <a> or <span> pairs
1919 $a = substr_count($before, '<a');
1920 $s = substr_count($before, '<span');
1921 $ca = substr_count($before, '</a>');
1922 $cs = substr_count($before, '</span>');
1924 if ($a <= $ca and $s <= $cs) {
1925 # Tags are balanced before ':'; ok
1930 } while ($colon !== false);
1931 wfProfileOut( $fname );
1936 * Return value of a magic variable (like PAGENAME)
1940 function getVariableValue( $index ) {
1941 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1944 * Some of these require message or data lookups and can be
1945 * expensive to check many times.
1947 static $varCache = array();
1948 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1949 if ( isset( $varCache[$index] ) )
1950 return $varCache[$index];
1953 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1956 case MAG_CURRENTMONTH
:
1957 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1958 case MAG_CURRENTMONTHNAME
:
1959 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1960 case MAG_CURRENTMONTHNAMEGEN
:
1961 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1962 case MAG_CURRENTMONTHABBREV
:
1963 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1964 case MAG_CURRENTDAY
:
1965 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1966 case MAG_CURRENTDAY2
:
1967 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
1969 return $this->mTitle
->getText();
1971 return $this->mTitle
->getPartialURL();
1972 case MAG_FULLPAGENAME
:
1973 return $this->mTitle
->getPrefixedText();
1974 case MAG_FULLPAGENAMEE
:
1975 return $this->mTitle
->getPrefixedURL();
1976 case MAG_REVISIONID
:
1977 return $this->mRevisionId
;
1979 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
1980 case MAG_NAMESPACEE
:
1981 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
1982 case MAG_CURRENTDAYNAME
:
1983 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
1984 case MAG_CURRENTYEAR
:
1985 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
1986 case MAG_CURRENTTIME
:
1987 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
1988 case MAG_CURRENTWEEK
:
1989 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
1990 // int to remove the padding
1991 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
1992 case MAG_CURRENTDOW
:
1993 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
1994 case MAG_NUMBEROFARTICLES
:
1995 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1996 case MAG_NUMBEROFFILES
:
1997 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2002 case MAG_SERVERNAME
:
2003 return $wgServerName;
2004 case MAG_SCRIPTPATH
:
2005 return $wgScriptPath;
2008 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2016 * initialise the magic variables (like CURRENTMONTHNAME)
2020 function initialiseVariables() {
2021 $fname = 'Parser::initialiseVariables';
2022 wfProfileIn( $fname );
2023 global $wgVariableIDs;
2024 $this->mVariables
= array();
2025 foreach ( $wgVariableIDs as $id ) {
2026 $mw =& MagicWord
::get( $id );
2027 $mw->addToArray( $this->mVariables
, $id );
2029 wfProfileOut( $fname );
2033 * parse any parentheses in format ((title|part|part))
2034 * and call callbacks to get a replacement text for any found piece
2036 * @param string $text The text to parse
2037 * @param array $callbacks rules in form:
2038 * '{' => array( # opening parentheses
2039 * 'end' => '}', # closing parentheses
2040 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2041 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2046 function replace_callback ($text, $callbacks) {
2047 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2048 $lastOpeningBrace = -1; # last not closed parentheses
2050 for ($i = 0; $i < strlen($text); $i++
) {
2051 # check for any opening brace
2054 foreach ($callbacks as $key => $value) {
2055 $pos = strpos ($text, $key, $i);
2056 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2062 if ($lastOpeningBrace >= 0) {
2063 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2065 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2070 $pos = strpos ($text, '|', $i);
2072 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2083 # found openning brace, lets add it to parentheses stack
2084 if (null != $rule) {
2085 $piece = array('brace' => $text[$i],
2086 'braceEnd' => $rule['end'],
2091 # count openning brace characters
2092 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2097 $piece['startAt'] = $i+
1;
2098 $piece['partStart'] = $i+
1;
2100 # we need to add to stack only if openning brace count is enough for any given rule
2101 foreach ($rule['cb'] as $cnt => $fn) {
2102 if ($piece['count'] >= $cnt) {
2103 $lastOpeningBrace ++
;
2104 $openingBraceStack[$lastOpeningBrace] = $piece;
2111 else if ($lastOpeningBrace >= 0) {
2112 # first check if it is a closing brace
2113 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2114 # lets check if it is enough characters for closing brace
2116 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2119 # if there are more closing parentheses than opening ones, we parse less
2120 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2121 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2123 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2125 $matchingCallback = null;
2126 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2127 if ($count >= $cnt && $matchingCount < $cnt) {
2128 $matchingCount = $cnt;
2129 $matchingCallback = $fn;
2133 if ($matchingCount == 0) {
2138 # lets set a title or last part (if '|' was found)
2139 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2140 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2142 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2144 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2145 $pieceEnd = $i +
$matchingCount;
2147 if( is_callable( $matchingCallback ) ) {
2149 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2150 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2151 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2152 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2154 # finally we can call a user callback and replace piece of text
2155 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2156 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2157 $i = $pieceStart +
strlen($replaceWith) - 1;
2160 # null value for callback means that parentheses should be parsed, but not replaced
2161 $i +
= $matchingCount - 1;
2164 # reset last openning parentheses, but keep it in case there are unused characters
2165 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2166 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2167 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2170 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2171 $openingBraceStack[$lastOpeningBrace--] = null;
2173 if ($matchingCount < $piece['count']) {
2174 $piece['count'] -= $matchingCount;
2175 $piece['startAt'] -= $matchingCount;
2176 $piece['partStart'] = $piece['startAt'];
2177 # do we still qualify for any callback with remaining count?
2178 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2179 if ($piece['count'] >= $cnt) {
2180 $lastOpeningBrace ++
;
2181 $openingBraceStack[$lastOpeningBrace] = $piece;
2189 # lets set a title if it is a first separator, or next part otherwise
2190 if ($text[$i] == '|') {
2191 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2192 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2193 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2196 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2198 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2207 * Replace magic variables, templates, and template arguments
2208 * with the appropriate text. Templates are substituted recursively,
2209 * taking care to avoid infinite loops.
2211 * Note that the substitution depends on value of $mOutputType:
2212 * OT_WIKI: only {{subst:}} templates
2213 * OT_MSG: only magic variables
2214 * OT_HTML: all templates and magic variables
2216 * @param string $tex The text to transform
2217 * @param array $args Key-value pairs representing template parameters to substitute
2220 function replaceVariables( $text, $args = array() ) {
2221 # Prevent too big inclusions
2222 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2226 $fname = 'Parser::replaceVariables';
2227 wfProfileIn( $fname );
2229 # This function is called recursively. To keep track of arguments we need a stack:
2230 array_push( $this->mArgStack
, $args );
2232 $braceCallbacks = array();
2233 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2234 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2235 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2237 $callbacks = array();
2238 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2239 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2240 $text = $this->replace_callback ($text, $callbacks);
2242 array_pop( $this->mArgStack
);
2244 wfProfileOut( $fname );
2249 * Replace magic variables
2252 function variableSubstitution( $matches ) {
2253 $fname = 'Parser::variableSubstitution';
2254 $varname = $matches[1];
2255 wfProfileIn( $fname );
2256 if ( !$this->mVariables
) {
2257 $this->initialiseVariables();
2260 if ( $this->mOutputType
== OT_WIKI
) {
2261 # Do only magic variables prefixed by SUBST
2262 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2263 if (!$mwSubst->matchStartAndRemove( $varname ))
2265 # Note that if we don't substitute the variable below,
2266 # we don't remove the {{subst:}} magic word, in case
2267 # it is a template rather than a magic variable.
2269 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2270 $id = $this->mVariables
[$varname];
2271 $text = $this->getVariableValue( $id );
2272 $this->mOutput
->mContainsOldMagic
= true;
2274 $text = $matches[0];
2276 wfProfileOut( $fname );
2280 # Split template arguments
2281 function getTemplateArgs( $argsString ) {
2282 if ( $argsString === '' ) {
2286 $args = explode( '|', substr( $argsString, 1 ) );
2288 # If any of the arguments contains a '[[' but no ']]', it needs to be
2289 # merged with the next arg because the '|' character between belongs
2290 # to the link syntax and not the template parameter syntax.
2291 $argc = count($args);
2293 for ( $i = 0; $i < $argc-1; $i++
) {
2294 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2295 $args[$i] .= '|'.$args[$i+
1];
2296 array_splice($args, $i+
1, 1);
2306 * Return the text of a template, after recursively
2307 * replacing any variables or templates within the template.
2309 * @param array $piece The parts of the template
2310 * $piece['text']: matched text
2311 * $piece['title']: the title, i.e. the part before the |
2312 * $piece['parts']: the parameter array
2313 * @return string the text of the template
2316 function braceSubstitution( $piece ) {
2318 $fname = 'Parser::braceSubstitution';
2319 wfProfileIn( $fname );
2329 # $part1 is the bit before the first |, and must contain only title characters
2330 # $args is a list of arguments, starting from index 0, not including $part1
2332 $part1 = $piece['title'];
2333 # If the third subpattern matched anything, it will start with |
2335 if (null == $piece['parts']) {
2336 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2337 if ($replaceWith != $piece['text']) {
2338 $text = $replaceWith;
2344 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2345 $argc = count( $args );
2349 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2350 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2351 # One of two possibilities is true:
2352 # 1) Found SUBST but not in the PST phase
2353 # 2) Didn't find SUBST and in the PST phase
2354 # In either case, return without further processing
2355 $text = $piece['text'];
2361 # MSG, MSGNW and INT
2364 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2365 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2368 # Remove obsolete MSG:
2369 $mwMsg =& MagicWord
::get( MAG_MSG
);
2370 $mwMsg->matchStartAndRemove( $part1 );
2373 # Check if it is an internal message
2374 $mwInt =& MagicWord
::get( MAG_INT
);
2375 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2376 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2377 $text = $linestart . wfMsgReal( $part1, $args, true );
2385 # Check for NS: (namespace expansion)
2386 $mwNs = MagicWord
::get( MAG_NS
);
2387 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2388 if ( intval( $part1 ) ) {
2389 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2392 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2393 if ( !is_null( $index ) ) {
2394 $text = $linestart . $wgContLang->getNsText( $index );
2401 # LCFIRST, UCFIRST, LC and UC
2403 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2404 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2405 $lc =& MagicWord
::get( MAG_LC
);
2406 $uc =& MagicWord
::get( MAG_UC
);
2407 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2408 $text = $linestart . $wgContLang->lcfirst( $part1 );
2410 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2411 $text = $linestart . $wgContLang->ucfirst( $part1 );
2413 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2414 $text = $linestart . $wgContLang->lc( $part1 );
2416 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2417 $text = $linestart . $wgContLang->uc( $part1 );
2422 # LOCALURL and FULLURL
2424 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2425 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2426 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2427 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2430 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2431 $func = 'getLocalURL';
2432 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2433 $func = 'escapeLocalURL';
2434 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2435 $func = 'getFullURL';
2436 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2437 $func = 'escapeFullURL';
2442 if ( $func !== false ) {
2443 $title = Title
::newFromText( $part1 );
2444 if ( !is_null( $title ) ) {
2446 $text = $linestart . $title->$func( $args[0] );
2448 $text = $linestart . $title->$func();
2456 if ( !$found && $argc == 1 ) {
2457 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2458 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2459 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2465 if ( !$found && $argc >= 2 ) {
2466 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2467 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2468 if ($argc==2) {$args[2]=$args[1];}
2469 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2474 # Template table test
2476 # Did we encounter this template already? If yes, it is in the cache
2477 # and we need to check for loops.
2478 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2481 # Infinite loop test
2482 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2485 $text = $linestart .
2486 '{{' . $part1 . '}}' .
2487 '<!-- WARNING: template loop detected -->';
2488 wfDebug( "$fname: template loop broken at '$part1'\n" );
2490 # set $text to cached message.
2491 $text = $linestart . $this->mTemplates
[$part1];
2495 # Load from database
2496 $replaceHeadings = false;
2498 $lastPathLevel = $this->mTemplatePath
;
2501 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2502 if ($subpage !== '') {
2503 $ns = $this->mTitle
->getNamespace();
2505 $title = Title
::newFromText( $part1, $ns );
2508 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2509 if ($interwiki != '' && $title->isTrans()) {
2510 return $this->scarytransclude($title, $interwiki);
2514 if ( !is_null( $title ) && !$title->isExternal() ) {
2515 # Check for excessive inclusion
2516 $dbk = $title->getPrefixedDBkey();
2517 if ( $this->incrementIncludeCount( $dbk ) ) {
2518 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2519 # Capture special page output
2520 $text = SpecialPage
::capturePath( $title );
2521 if ( is_string( $text ) ) {
2525 $this->disableCache();
2528 $articleContent = $this->fetchTemplate( $title );
2529 if ( $articleContent !== false ) {
2531 $text = $articleContent;
2532 $replaceHeadings = true;
2537 # If the title is valid but undisplayable, make a link to it
2538 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2539 $text = '[['.$title->getPrefixedText().']]';
2543 # Template cache array insertion
2545 $this->mTemplates
[$part1] = $text;
2546 $text = $linestart . $text;
2551 # Recursive parsing, escaping and link table handling
2552 # Only for HTML output
2553 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2554 $text = wfEscapeWikiText( $text );
2555 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2556 # Clean up argument array
2557 $assocArgs = array();
2559 foreach( $args as $arg ) {
2560 $eqpos = strpos( $arg, '=' );
2561 if ( $eqpos === false ) {
2562 $assocArgs[$index++
] = $arg;
2564 $name = trim( substr( $arg, 0, $eqpos ) );
2565 $value = trim( substr( $arg, $eqpos+
1 ) );
2566 if ( $value === false ) {
2569 if ( $name !== false ) {
2570 $assocArgs[$name] = $value;
2575 # Add a new element to the templace recursion path
2576 $this->mTemplatePath
[$part1] = 1;
2578 # If there are any <onlyinclude> tags, only include them
2579 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2580 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2582 foreach ($m[1] as $piece)
2585 # Remove <noinclude> sections and <includeonly> tags
2586 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2587 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2589 if( $this->mOutputType
== OT_HTML
) {
2590 # Strip <nowiki>, <pre>, etc.
2591 $text = $this->strip( $text, $this->mStripState
);
2592 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2594 $text = $this->replaceVariables( $text, $assocArgs );
2596 # If the template begins with a table or block-level
2597 # element, it should be treated as beginning a new line.
2598 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2599 $text = "\n" . $text;
2602 # Prune lower levels off the recursion check path
2603 $this->mTemplatePath
= $lastPathLevel;
2606 wfProfileOut( $fname );
2607 return $piece['text'];
2610 # Replace raw HTML by a placeholder
2611 # Add a blank line preceding, to prevent it from mucking up
2612 # immediately preceding headings
2613 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2615 # replace ==section headers==
2616 # XXX this needs to go away once we have a better parser.
2617 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2618 if( !is_null( $title ) )
2619 $encodedname = base64_encode($title->getPrefixedDBkey());
2621 $encodedname = base64_encode("");
2622 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2623 PREG_SPLIT_DELIM_CAPTURE
);
2626 for( $i = 0; $i < count($m); $i +
= 2 ) {
2628 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2630 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2634 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2635 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2636 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2644 # Prune lower levels off the recursion check path
2645 $this->mTemplatePath
= $lastPathLevel;
2648 wfProfileOut( $fname );
2649 return $piece['text'];
2651 wfProfileOut( $fname );
2657 * Fetch the unparsed text of a template and register a reference to it.
2659 function fetchTemplate( $title ) {
2661 // Loop to fetch the article, with up to 1 redirect
2662 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2663 $rev = Revision
::newFromTitle( $title );
2664 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2668 $text = $rev->getText();
2669 if ( $text === false ) {
2673 $title = Title
::newFromRedirect( $text );
2679 * Translude an interwiki link.
2681 function scarytransclude($title, $interwiki) {
2682 global $wgEnableScaryTranscluding;
2684 if (!$wgEnableScaryTranscluding)
2685 return wfMsg('scarytranscludedisabled');
2687 $articlename = "Template:" . $title->getDBkey();
2688 $url = str_replace('$1', urlencode($articlename), $interwiki);
2689 if (strlen($url) > 255)
2690 return wfMsg('scarytranscludetoolong');
2691 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2692 $this->mIWTransData
[] = $text;
2693 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2696 function fetchScaryTemplateMaybeFromCache($url) {
2697 $dbr =& wfGetDB(DB_SLAVE
);
2698 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2699 array('tc_url' => $url));
2701 $time = $obj->tc_time
;
2702 $text = $obj->tc_contents
;
2703 if ($time && $time < (time() +
(60*60))) {
2708 $text = wfGetHTTP($url . '?action=render');
2710 return wfMsg('scarytranscludefailed', $url);
2712 $dbw =& wfGetDB(DB_MASTER
);
2713 $dbw->replace('transcache', array(), array(
2715 'tc_time' => time(),
2716 'tc_contents' => $text));
2722 * Triple brace replacement -- used for template arguments
2725 function argSubstitution( $matches ) {
2726 $arg = trim( $matches['title'] );
2727 $text = $matches['text'];
2728 $inputArgs = end( $this->mArgStack
);
2730 if ( array_key_exists( $arg, $inputArgs ) ) {
2731 $text = $inputArgs[$arg];
2732 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2733 $text = $matches['parts'][0];
2740 * Returns true if the function is allowed to include this entity
2743 function incrementIncludeCount( $dbk ) {
2744 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2745 $this->mIncludeCount
[$dbk] = 0;
2747 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2755 * This function accomplishes several tasks:
2756 * 1) Auto-number headings if that option is enabled
2757 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2758 * 3) Add a Table of contents on the top for users who have enabled the option
2759 * 4) Auto-anchor headings
2761 * It loops through all headlines, collects the necessary data, then splits up the
2762 * string and re-inserts the newly formatted headlines.
2764 * @param string $text
2765 * @param boolean $isMain
2768 function formatHeadings( $text, $isMain=true ) {
2769 global $wgMaxTocLevel, $wgContLang;
2771 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2773 $forceTocHere = false;
2774 if( !$this->mTitle
->userCanEdit() ) {
2777 $showEditLink = $this->mOptions
->getEditSection();
2780 # Inhibit editsection links if requested in the page
2781 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2782 if( $esw->matchAndRemove( $text ) ) {
2785 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2787 $mw =& MagicWord
::get( MAG_NOTOC
);
2788 if( $mw->matchAndRemove( $text ) ) {
2792 # Get all headlines for numbering them and adding funky stuff like [edit]
2793 # links - this is for later, but we need the number of headlines right now
2794 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2796 # if there are fewer than 4 headlines in the article, do not show TOC
2797 if( $numMatches < 4 ) {
2801 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2802 # override above conditions and always show TOC at that place
2804 $mw =& MagicWord
::get( MAG_TOC
);
2805 if($mw->match( $text ) ) {
2807 $forceTocHere = true;
2809 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2810 # override above conditions and always show TOC above first header
2811 $mw =& MagicWord
::get( MAG_FORCETOC
);
2812 if ($mw->matchAndRemove( $text ) ) {
2817 # Never ever show TOC if no headers
2818 if( $numMatches < 1 ) {
2822 # We need this to perform operations on the HTML
2823 $sk =& $this->mOptions
->getSkin();
2827 $sectionCount = 0; # headlineCount excluding template sections
2829 # Ugh .. the TOC should have neat indentation levels which can be
2830 # passed to the skin functions. These are determined here
2834 $sublevelCount = array();
2835 $levelCount = array();
2842 foreach( $matches[3] as $headline ) {
2844 $templatetitle = '';
2845 $templatesection = 0;
2848 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2850 $templatetitle = base64_decode($mat[1]);
2851 $templatesection = 1 +
(int)base64_decode($mat[2]);
2852 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2856 $prevlevel = $level;
2857 $prevtoclevel = $toclevel;
2859 $level = $matches[1][$headlineCount];
2861 if( $doNumberHeadings ||
$doShowToc ) {
2863 if ( $level > $prevlevel ) {
2864 # Increase TOC level
2866 $sublevelCount[$toclevel] = 0;
2867 $toc .= $sk->tocIndent();
2869 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2870 # Decrease TOC level, find level to jump to
2872 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2873 # Can only go down to level 1
2876 for ($i = $toclevel; $i > 0; $i--) {
2877 if ( $levelCount[$i] == $level ) {
2878 # Found last matching level
2882 elseif ( $levelCount[$i] < $level ) {
2883 # Found first matching level below current level
2890 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2893 # No change in level, end TOC line
2894 $toc .= $sk->tocLineEnd();
2897 $levelCount[$toclevel] = $level;
2899 # count number of headlines for each level
2900 @$sublevelCount[$toclevel]++
;
2902 for( $i = 1; $i <= $toclevel; $i++
) {
2903 if( !empty( $sublevelCount[$i] ) ) {
2907 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2913 # The canonized header is a version of the header text safe to use for links
2914 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2915 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2916 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2918 # Remove link placeholders by the link text.
2919 # <!--LINK number-->
2921 # link text with suffix
2922 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2923 "\$this->mLinkHolders['texts'][\$1]",
2924 $canonized_headline );
2925 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2926 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2927 $canonized_headline );
2930 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2931 $tocline = trim( $canonized_headline );
2932 $canonized_headline = Sanitizer
::escapeId( $tocline );
2933 $refers[$headlineCount] = $canonized_headline;
2935 # count how many in assoc. array so we can track dupes in anchors
2936 @$refers[$canonized_headline]++
;
2937 $refcount[$headlineCount]=$refers[$canonized_headline];
2939 # Don't number the heading if it is the only one (looks silly)
2940 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2941 # the two are different if the line contains a link
2942 $headline=$numbering . ' ' . $headline;
2945 # Create the anchor for linking from the TOC to the section
2946 $anchor = $canonized_headline;
2947 if($refcount[$headlineCount] > 1 ) {
2948 $anchor .= '_' . $refcount[$headlineCount];
2950 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2951 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2953 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2954 if ( empty( $head[$headlineCount] ) ) {
2955 $head[$headlineCount] = '';
2958 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2960 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2963 # give headline the correct <h#> tag
2964 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2972 $toc .= $sk->tocUnindent( $toclevel - 1 );
2973 $toc = $sk->tocList( $toc );
2976 # split up and insert constructed headlines
2978 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2981 foreach( $blocks as $block ) {
2982 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2983 # This is the [edit] link that appears for the top block of text when
2984 # section editing is enabled
2986 # Disabled because it broke block formatting
2987 # For example, a bullet point in the top line
2988 # $full .= $sk->editSectionLink(0);
2991 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2992 # Top anchor now in skin
2996 if( !empty( $head[$i] ) ) {
3002 $mw =& MagicWord
::get( MAG_TOC
);
3003 return $mw->replace( $toc, $full );
3010 * Return an HTML link for the "ISBN 123456" text
3013 function magicISBN( $text ) {
3014 $fname = 'Parser::magicISBN';
3015 wfProfileIn( $fname );
3017 $a = split( 'ISBN ', ' '.$text );
3018 if ( count ( $a ) < 2 ) {
3019 wfProfileOut( $fname );
3022 $text = substr( array_shift( $a ), 1);
3023 $valid = '0123456789-Xx';
3025 foreach ( $a as $x ) {
3026 $isbn = $blank = '' ;
3027 while ( ' ' == $x{0} ) {
3029 $x = substr( $x, 1 );
3031 if ( $x == '' ) { # blank isbn
3032 $text .= "ISBN $blank";
3035 while ( strstr( $valid, $x{0} ) != false ) {
3037 $x = substr( $x, 1 );
3039 $num = str_replace( '-', '', $isbn );
3040 $num = str_replace( ' ', '', $num );
3041 $num = str_replace( 'x', 'X', $num );
3044 $text .= "ISBN $blank$x";
3046 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3047 $text .= '<a href="' .
3048 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3049 "\" class=\"internal\">ISBN $isbn</a>";
3053 wfProfileOut( $fname );
3058 * Return an HTML link for the "RFC 1234" text
3061 * @param string $text Text to be processed
3062 * @param string $keyword Magic keyword to use (default RFC)
3063 * @param string $urlmsg Interface message to use (default rfcurl)
3066 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3068 $valid = '0123456789';
3071 $a = split( $keyword, ' '.$text );
3072 if ( count ( $a ) < 2 ) {
3075 $text = substr( array_shift( $a ), 1);
3077 /* Check if keyword is preceed by [[.
3078 * This test is made here cause of the array_shift above
3079 * that prevent the test to be done in the foreach.
3081 if ( substr( $text, -2 ) == '[[' ) {
3085 foreach ( $a as $x ) {
3086 /* token might be empty if we have RFC RFC 1234 */
3094 /** remove and save whitespaces in $blank */
3095 while ( $x{0} == ' ' ) {
3097 $x = substr( $x, 1 );
3100 /** remove and save the rfc number in $id */
3101 while ( strstr( $valid, $x{0} ) != false ) {
3103 $x = substr( $x, 1 );
3107 /* call back stripped spaces*/
3108 $text .= $keyword.$blank.$x;
3109 } elseif( $internal ) {
3111 $text .= $keyword.$id.$x;
3113 /* build the external link*/
3114 $url = wfMsg( $urlmsg, $id);
3115 $sk =& $this->mOptions
->getSkin();
3116 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3117 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3120 /* Check if the next RFC keyword is preceed by [[ */
3121 $internal = ( substr($x,-2) == '[[' );
3127 * Transform wiki markup when saving a page by doing \r\n -> \n
3128 * conversion, substitting signatures, {{subst:}} templates, etc.
3130 * @param string $text the text to transform
3131 * @param Title &$title the Title object for the current article
3132 * @param User &$user the User object describing the current user
3133 * @param ParserOptions $options parsing options
3134 * @param bool $clearState whether to clear the parser state first
3135 * @return string the altered wiki markup
3138 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3139 $this->mOptions
= $options;
3140 $this->mTitle
=& $title;
3141 $this->mOutputType
= OT_WIKI
;
3143 if ( $clearState ) {
3144 $this->clearState();
3147 $stripState = false;
3151 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3152 $text = $this->strip( $text, $stripState, true );
3153 $text = $this->pstPass2( $text, $user );
3154 $text = $this->unstrip( $text, $stripState );
3155 $text = $this->unstripNoWiki( $text, $stripState );
3160 * Pre-save transform helper function
3163 function pstPass2( $text, &$user ) {
3164 global $wgContLang, $wgLocaltimezone;
3166 /* Note: This is the timestamp saved as hardcoded wikitext to
3167 * the database, we use $wgContLang here in order to give
3168 * everyone the same signiture and use the default one rather
3169 * than the one selected in each users preferences.
3171 if ( isset( $wgLocaltimezone ) ) {
3172 $oldtz = getenv( 'TZ' );
3173 putenv( 'TZ='.$wgLocaltimezone );
3175 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3176 ' (' . date( 'T' ) . ')';
3177 if ( isset( $wgLocaltimezone ) ) {
3178 putenv( 'TZ='.$oldtz );
3181 # Variable replacement
3182 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3183 $text = $this->replaceVariables( $text );
3186 $sigText = $this->getUserSig( $user );
3187 $text = strtr( $text, array(
3189 '~~~~' => "$sigText $d",
3193 # Context links: [[|name]] and [[name (context)|]]
3195 global $wgLegalTitleChars;
3196 $tc = "[$wgLegalTitleChars]";
3197 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3199 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3200 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3202 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3203 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3204 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3205 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3207 $t = $this->mTitle
->getText();
3208 if ( preg_match( $conpat, $t, $m ) ) {
3211 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3212 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3213 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3215 if ( '' == $context ) {
3216 $text = preg_replace( $p2, '[[\\1]]', $text );
3218 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3221 # Trim trailing whitespace
3222 # MAG_END (__END__) tag allows for trailing
3223 # whitespace to be deliberately included
3224 $text = rtrim( $text );
3225 $mw =& MagicWord
::get( MAG_END
);
3226 $mw->matchAndRemove( $text );
3232 * Fetch the user's signature text, if any, and normalize to
3233 * validated, ready-to-insert wikitext.
3239 function getUserSig( &$user ) {
3242 $username = $user->getName();
3243 $nickname = $user->getOption( 'nickname' );
3244 $nickname = $nickname === '' ?
$username : $nickname;
3246 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3247 # Sig. might contain markup; validate this
3248 if( $this->validateSig( $nickname ) !== false ) {
3249 # Validated; clean up (if needed) and return it
3250 return( $this->cleanSig( $nickname ) );
3252 # Failed to validate; fall back to the default
3253 $nickname = $username;
3254 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3258 # If we're still here, make it a link to the user page
3259 $userpage = $user->getUserPage();
3260 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3264 * Check that the user's signature contains no bad XML
3266 * @param string $text
3267 * @return mixed An expanded string, or false if invalid.
3269 function validateSig( $text ) {
3270 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3274 * Clean up signature text
3276 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3277 * 2) Substitute all transclusions
3279 * @param string $text
3280 * @return string Signature text
3282 function cleanSig( $text ) {
3283 $substWord = MagicWord
::get( MAG_SUBST
);
3284 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3285 $substText = '{{' . $substWord->getSynonym( 0 );
3287 $text = preg_replace( $substRegex, $substText, $text );
3288 $text = preg_replace( '/~{3,5}/', '', $text );
3289 $text = $this->replaceVariables( $text );
3295 * Set up some variables which are usually set up in parse()
3296 * so that an external function can call some class members with confidence
3299 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3300 $this->mTitle
=& $title;
3301 $this->mOptions
= $options;
3302 $this->mOutputType
= $outputType;
3303 if ( $clearState ) {
3304 $this->clearState();
3309 * Transform a MediaWiki message by replacing magic variables.
3311 * @param string $text the text to transform
3312 * @param ParserOptions $options options
3313 * @return string the text with variables substituted
3316 function transformMsg( $text, $options ) {
3318 static $executing = false;
3320 $fname = "Parser::transformMsg";
3322 # Guard against infinite recursion
3328 wfProfileIn($fname);
3330 $this->mTitle
= $wgTitle;
3331 $this->mOptions
= $options;
3332 $this->mOutputType
= OT_MSG
;
3333 $this->clearState();
3334 $text = $this->replaceVariables( $text );
3337 wfProfileOut($fname);
3342 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3343 * Callback will be called with the text within
3344 * Transform and return the text within
3348 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3349 * @param mixed $callback The callback function (and object) to use for the tag
3351 * @return The old value of the mTagHooks array associated with the hook
3353 function setHook( $tag, $callback ) {
3354 $oldVal = @$this->mTagHooks
[$tag];
3355 $this->mTagHooks
[$tag] = $callback;
3361 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3362 * Placeholders created in Skin::makeLinkObj()
3363 * Returns an array of links found, indexed by PDBK:
3367 * $options is a bit field, RLH_FOR_UPDATE to select for update
3369 function replaceLinkHolders( &$text, $options = 0 ) {
3371 global $wgOutputReplace;
3373 $fname = 'Parser::replaceLinkHolders';
3374 wfProfileIn( $fname );
3378 $sk =& $this->mOptions
->getSkin();
3379 $linkCache =& LinkCache
::singleton();
3381 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3382 wfProfileIn( $fname.'-check' );
3383 $dbr =& wfGetDB( DB_SLAVE
);
3384 $page = $dbr->tableName( 'page' );
3385 $threshold = $wgUser->getOption('stubthreshold');
3388 asort( $this->mLinkHolders
['namespaces'] );
3392 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3394 $title = $this->mLinkHolders
['titles'][$key];
3396 # Skip invalid entries.
3397 # Result will be ugly, but prevents crash.
3398 if ( is_null( $title ) ) {
3401 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3403 # Check if it's a static known link, e.g. interwiki
3404 if ( $title->isAlwaysKnown() ) {
3405 $colours[$pdbk] = 1;
3406 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3407 $colours[$pdbk] = 1;
3408 $this->mOutput
->addLink( $title, $id );
3409 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3410 $colours[$pdbk] = 0;
3412 # Not in the link cache, add it to the query
3413 if ( !isset( $current ) ) {
3415 $query = "SELECT page_id, page_namespace, page_title";
3416 if ( $threshold > 0 ) {
3417 $query .= ', page_len, page_is_redirect';
3419 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3420 } elseif ( $current != $ns ) {
3422 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3427 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3432 if ( $options & RLH_FOR_UPDATE
) {
3433 $query .= ' FOR UPDATE';
3436 $res = $dbr->query( $query, $fname );
3438 # Fetch data and form into an associative array
3439 # non-existent = broken
3442 while ( $s = $dbr->fetchObject($res) ) {
3443 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3444 $pdbk = $title->getPrefixedDBkey();
3445 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3446 $this->mOutput
->addLink( $title, $s->page_id
);
3448 if ( $threshold > 0 ) {
3449 $size = $s->page_len
;
3450 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3451 $colours[$pdbk] = 1;
3453 $colours[$pdbk] = 2;
3456 $colours[$pdbk] = 1;
3460 wfProfileOut( $fname.'-check' );
3462 # Construct search and replace arrays
3463 wfProfileIn( $fname.'-construct' );
3464 $wgOutputReplace = array();
3465 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3466 $pdbk = $pdbks[$key];
3467 $searchkey = "<!--LINK $key-->";
3468 $title = $this->mLinkHolders
['titles'][$key];
3469 if ( empty( $colours[$pdbk] ) ) {
3470 $linkCache->addBadLinkObj( $title );
3471 $colours[$pdbk] = 0;
3472 $this->mOutput
->addLink( $title, 0 );
3473 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3474 $this->mLinkHolders
['texts'][$key],
3475 $this->mLinkHolders
['queries'][$key] );
3476 } elseif ( $colours[$pdbk] == 1 ) {
3477 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3478 $this->mLinkHolders
['texts'][$key],
3479 $this->mLinkHolders
['queries'][$key] );
3480 } elseif ( $colours[$pdbk] == 2 ) {
3481 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3482 $this->mLinkHolders
['texts'][$key],
3483 $this->mLinkHolders
['queries'][$key] );
3486 wfProfileOut( $fname.'-construct' );
3489 wfProfileIn( $fname.'-replace' );
3491 $text = preg_replace_callback(
3492 '/(<!--LINK .*?-->)/',
3493 "wfOutputReplaceMatches",
3496 wfProfileOut( $fname.'-replace' );
3499 # Now process interwiki link holders
3500 # This is quite a bit simpler than internal links
3501 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3502 wfProfileIn( $fname.'-interwiki' );
3503 # Make interwiki link HTML
3504 $wgOutputReplace = array();
3505 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3506 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3507 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3510 $text = preg_replace_callback(
3511 '/<!--IWLINK (.*?)-->/',
3512 "wfOutputReplaceMatches",
3514 wfProfileOut( $fname.'-interwiki' );
3517 wfProfileOut( $fname );
3522 * Replace <!--LINK--> link placeholders with plain text of links
3523 * (not HTML-formatted).
3524 * @param string $text
3527 function replaceLinkHoldersText( $text ) {
3529 global $wgOutputReplace;
3531 $fname = 'Parser::replaceLinkHoldersText';
3532 wfProfileIn( $fname );
3534 $text = preg_replace_callback(
3535 '/<!--(LINK|IWLINK) (.*?)-->/',
3536 array( &$this, 'replaceLinkHoldersTextCallback' ),
3539 wfProfileOut( $fname );
3544 * @param array $matches
3548 function replaceLinkHoldersTextCallback( $matches ) {
3549 $type = $matches[1];
3551 if( $type == 'LINK' ) {
3552 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3553 return $this->mLinkHolders
['texts'][$key];
3555 } elseif( $type == 'IWLINK' ) {
3556 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3557 return $this->mInterwikiLinkHolders
['texts'][$key];
3564 * Renders an image gallery from a text with one line per image.
3565 * text labels may be given by using |-style alternative text. E.g.
3566 * Image:one.jpg|The number "1"
3567 * Image:tree.jpg|A tree
3568 * given as text will return the HTML of a gallery with two images,
3569 * labeled 'The number "1"' and
3572 function renderImageGallery( $text ) {
3574 $parserOptions = new ParserOptions
;
3575 $localParser = new Parser();
3577 $ig = new ImageGallery();
3578 $ig->setShowBytes( false );
3579 $ig->setShowFilename( false );
3580 $lines = explode( "\n", $text );
3582 foreach ( $lines as $line ) {
3583 # match lines like these:
3584 # Image:someimage.jpg|This is some image
3585 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3587 if ( count( $matches ) == 0 ) {
3590 $nt =& Title
::newFromText( $matches[1] );
3591 if( is_null( $nt ) ) {
3592 # Bogus title. Ignore these so we don't bomb out later.
3595 if ( isset( $matches[3] ) ) {
3596 $label = $matches[3];
3601 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3602 $html = $pout->getText();
3604 $ig->add( new Image( $nt ), $html );
3605 $this->mOutput
->addImage( $nt->getDBkey() );
3607 return $ig->toHTML();
3611 * Parse image options text and use it to make an image
3613 function makeImage( &$nt, $options ) {
3614 global $wgContLang, $wgUseImageResize, $wgUser;
3618 # Check if the options text is of the form "options|alt text"
3620 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3621 # * left no resizing, just left align. label is used for alt= only
3622 # * right same, but right aligned
3623 # * none same, but not aligned
3624 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3625 # * center center the image
3626 # * framed Keep original image size, no magnify-button.
3628 $part = explode( '|', $options);
3630 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3631 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3632 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3633 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3634 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3635 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3636 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3637 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3640 $width = $height = $framed = $thumb = false;
3641 $manual_thumb = '' ;
3643 foreach( $part as $key => $val ) {
3644 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3646 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3647 # use manually specified thumbnail
3649 $manual_thumb = $match;
3650 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3651 # remember to set an alignment, don't render immediately
3653 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3654 # remember to set an alignment, don't render immediately
3656 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3657 # remember to set an alignment, don't render immediately
3659 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3660 # remember to set an alignment, don't render immediately
3662 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3663 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3664 # $match is the image width in pixels
3665 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3666 $width = intval( $m[1] );
3667 $height = intval( $m[2] );
3669 $width = intval($match);
3671 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3677 # Strip bad stuff out of the alt text
3678 $alt = $this->replaceLinkHoldersText( $caption );
3679 $alt = Sanitizer
::stripAllTags( $alt );
3681 # Linker does the rest
3682 $sk =& $this->mOptions
->getSkin();
3683 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3687 * Set a flag in the output object indicating that the content is dynamic and
3688 * shouldn't be cached.
3690 function disableCache() {
3691 $this->mOutput
->mCacheTime
= -1;
3695 * Callback from the Sanitizer for expanding items found in HTML attribute
3696 * values, so they can be safely tested and escaped.
3697 * @param string $text
3698 * @param array $args
3702 function attributeStripCallback( &$text, $args ) {
3703 $text = $this->replaceVariables( $text, $args );
3704 $text = $this->unstripForHTML( $text );
3708 function unstripForHTML( $text ) {
3709 $text = $this->unstrip( $text, $this->mStripState
);
3710 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3718 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3719 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3720 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3726 function getTags() { return array_keys( $this->mTagHooks
); }
3732 * @package MediaWiki
3736 var $mText, # The output text
3737 $mLanguageLinks, # List of the full text of language links, in the order they appear
3738 $mCategories, # Map of category names to sort keys
3739 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3740 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3741 $mVersion, # Compatibility check
3742 $mTitleText, # title text of the chosen language variant
3743 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3744 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3745 $mImages; # DB keys of the images used, in the array key only
3747 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3748 $containsOldMagic = false, $titletext = '' )
3750 $this->mText
= $text;
3751 $this->mLanguageLinks
= $languageLinks;
3752 $this->mCategories
= $categoryLinks;
3753 $this->mContainsOldMagic
= $containsOldMagic;
3754 $this->mCacheTime
= '';
3755 $this->mVersion
= MW_PARSER_VERSION
;
3756 $this->mTitleText
= $titletext;
3757 $this->mLinks
= array();
3758 $this->mTemplates
= array();
3759 $this->mImages
= array();
3762 function getText() { return $this->mText
; }
3763 function getLanguageLinks() { return $this->mLanguageLinks
; }
3764 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3765 function &getCategories() { return $this->mCategories
; }
3766 function getCacheTime() { return $this->mCacheTime
; }
3767 function getTitleText() { return $this->mTitleText
; }
3768 function &getLinks() { return $this->mLinks
; }
3769 function &getTemplates() { return $this->mTemplates
; }
3770 function &getImages() { return $this->mImages
; }
3772 function containsOldMagic() { return $this->mContainsOldMagic
; }
3773 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3774 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3775 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3776 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3777 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3778 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3780 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3781 function addImage( $name ) { $this->mImages
[$name] = 1; }
3782 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3784 function addLink( $title, $id ) {
3785 $ns = $title->getNamespace();
3786 $dbk = $title->getDBkey();
3787 if ( !isset( $this->mLinks
[$ns] ) ) {
3788 $this->mLinks
[$ns] = array();
3790 $this->mLinks
[$ns][$dbk] = $id;
3793 function addTemplate( $title, $id ) {
3794 $ns = $title->getNamespace();
3795 $dbk = $title->getDBkey();
3796 if ( !isset( $this->mTemplates
[$ns] ) ) {
3797 $this->mTemplates
[$ns] = array();
3799 $this->mTemplates
[$ns][$dbk] = $id;
3806 function merge( $other ) {
3807 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3808 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3809 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3813 * Return true if this cached output object predates the global or
3814 * per-article cache invalidation timestamps, or if it comes from
3815 * an incompatible older version.
3817 * @param string $touched the affected article's last touched timestamp
3821 function expired( $touched ) {
3822 global $wgCacheEpoch;
3823 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3824 $this->getCacheTime() < $touched ||
3825 $this->getCacheTime() <= $wgCacheEpoch ||
3826 !isset( $this->mVersion
) ||
3827 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3832 * Set options of the Parser
3834 * @package MediaWiki
3838 # All variables are private
3839 var $mUseTeX; # Use texvc to expand <math> tags
3840 var $mUseDynamicDates; # Use DateFormatter to format dates
3841 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3842 var $mAllowExternalImages; # Allow external images inline
3843 var $mAllowExternalImagesFrom; # If not, any exception?
3844 var $mSkin; # Reference to the preferred skin
3845 var $mDateFormat; # Date format index
3846 var $mEditSection; # Create "edit section" links
3847 var $mNumberHeadings; # Automatically number headings
3848 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3849 var $mTidy; # Ask for tidy cleanup
3851 function getUseTeX() { return $this->mUseTeX
; }
3852 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3853 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3854 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3855 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3856 function &getSkin() { return $this->mSkin
; }
3857 function getDateFormat() { return $this->mDateFormat
; }
3858 function getEditSection() { return $this->mEditSection
; }
3859 function getNumberHeadings() { return $this->mNumberHeadings
; }
3860 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3861 function getTidy() { return $this->mTidy
; }
3863 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3864 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3865 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3866 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3867 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3868 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3869 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3870 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3871 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3872 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3873 function setSkin( &$x ) { $this->mSkin
=& $x; }
3875 function ParserOptions() {
3877 $this->initialiseFromUser( $wgUser );
3881 * Get parser options
3884 function newFromUser( &$user ) {
3885 $popts = new ParserOptions
;
3886 $popts->initialiseFromUser( $user );
3890 /** Get user options */
3891 function initialiseFromUser( &$userInput ) {
3892 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3893 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3894 $fname = 'ParserOptions::initialiseFromUser';
3895 wfProfileIn( $fname );
3896 if ( !$userInput ) {
3898 $user->setLoaded( true );
3900 $user =& $userInput;
3903 $this->mUseTeX
= $wgUseTeX;
3904 $this->mUseDynamicDates
= $wgUseDynamicDates;
3905 $this->mInterwikiMagic
= $wgInterwikiMagic;
3906 $this->mAllowExternalImages
= $wgAllowExternalImages;
3907 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3908 wfProfileIn( $fname.'-skin' );
3909 $this->mSkin
=& $user->getSkin();
3910 wfProfileOut( $fname.'-skin' );
3911 $this->mDateFormat
= $user->getOption( 'date' );
3912 $this->mEditSection
= true;
3913 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3914 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3915 $this->mTidy
= false;
3916 wfProfileOut( $fname );
3921 * Callback function used by Parser::replaceLinkHolders()
3922 * to substitute link placeholders.
3924 function &wfOutputReplaceMatches( $matches ) {
3925 global $wgOutputReplace;
3926 return $wgOutputReplace[$matches[1]];
3930 * Return the total number of articles
3932 function wfNumberOfArticles() {
3933 global $wgNumberOfArticles;
3936 return $wgNumberOfArticles;
3940 * Return the number of files
3942 function wfNumberOfFiles() {
3943 $fname = 'Parser::wfNumberOfFiles';
3945 wfProfileIn( $fname );
3946 $dbr =& wfGetDB( DB_SLAVE
);
3947 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3948 wfProfileOut( $fname );
3954 * Get various statistics from the database
3957 function wfLoadSiteStats() {
3958 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3959 $fname = 'wfLoadSiteStats';
3961 if ( -1 != $wgNumberOfArticles ) return;
3962 $dbr =& wfGetDB( DB_SLAVE
);
3963 $s = $dbr->selectRow( 'site_stats',
3964 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3965 array( 'ss_row_id' => 1 ), $fname
3968 if ( $s === false ) {
3971 $wgTotalViews = $s->ss_total_views
;
3972 $wgTotalEdits = $s->ss_total_edits
;
3973 $wgNumberOfArticles = $s->ss_good_articles
;
3979 * Basically replacing " > and < with HTML entities ( ", >, <)
3981 * @param string $in Text that might contain HTML tags
3982 * @return string Escaped string
3984 function wfEscapeHTMLTagsOnly( $in ) {
3986 array( '"', '>', '<' ),
3987 array( '"', '>', '<' ),