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.5.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 # prefix for escaping, used in two functions at least
47 define( 'UNIQ_PREFIX', 'NaodW29');
49 # Constants needed for external link processing
50 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.$wgUrlProtocols.')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone, $wgAllowSpecialInclusion*
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
113 var $mIWTransData = array();
124 $this->mTemplates
= array();
125 $this->mTemplatePath
= array();
126 $this->mTagHooks
= array();
135 function clearState() {
136 $this->mOutput
= new ParserOutput
;
137 $this->mAutonumber
= 0;
138 $this->mLastSection
= '';
139 $this->mDTopen
= false;
140 $this->mVariables
= false;
141 $this->mIncludeCount
= array();
142 $this->mStripState
= array();
143 $this->mArgStack
= array();
144 $this->mInPre
= false;
145 $this->mInterwikiLinkHolders
= array(
149 $this->mLinkHolders
= array(
150 'namespaces' => array(),
152 'queries' => array(),
159 * First pass--just handle <nowiki> sections, pass the rest off
160 * to internalParse() which does all the real work.
163 * @param string $text Text we want to parse
164 * @param Title &$title A title object
165 * @param array $options
166 * @param boolean $linestart
167 * @param boolean $clearState
168 * @return ParserOutput a ParserOutput
170 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
171 global $wgUseTidy, $wgContLang;
172 $fname = 'Parser::parse';
173 wfProfileIn( $fname );
179 $this->mOptions
= $options;
180 $this->mTitle
=& $title;
181 $this->mOutputType
= OT_HTML
;
183 $this->mStripState
= NULL;
185 //$text = $this->strip( $text, $this->mStripState );
186 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
187 $x =& $this->mStripState
;
189 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
190 $text = $this->strip( $text, $x );
191 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
193 $text = $this->internalParse( $text );
195 $text = $this->unstrip( $text, $this->mStripState
);
197 # Clean up special characters, only run once, next-to-last before doBlockLevels
199 # french spaces, last one Guillemet-left
200 # only if there is something before the space
201 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
202 # french spaces, Guillemet-right
203 '/(\\302\\253) /' => '\\1 ',
204 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
206 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
209 $text = $this->doBlockLevels( $text, $linestart );
211 $this->replaceLinkHolders( $text );
213 # the position of the convert() call should not be changed. it
214 # assumes that the links are all replaces and the only thing left
215 # is the <nowiki> mark.
216 $text = $wgContLang->convert($text);
217 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
219 $text = $this->unstripNoWiki( $text, $this->mStripState
);
221 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
223 $text = Sanitizer
::normalizeCharReferences( $text );
226 $text = Parser
::tidy($text);
229 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
231 $this->mOutput
->setText( $text );
232 wfProfileOut( $fname );
233 return $this->mOutput
;
237 * Get a random string
242 function getRandomString() {
243 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
247 * Replaces all occurrences of <$tag>content</$tag> in the text
248 * with a random marker and returns the new text. the output parameter
249 * $content will be an associative array filled with data on the form
250 * $unique_marker => content.
252 * If $content is already set, the additional entries will be appended
253 * If $tag is set to STRIP_COMMENTS, the function will extract
254 * <!-- HTML comments -->
259 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
260 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
275 if( $tag == STRIP_COMMENTS
) {
279 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
280 $end = "/<\\/$tag\\s*>/i";
283 while ( '' != $text ) {
284 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
286 if( count( $p ) < 3 ) {
292 $marker = $rnd . sprintf('%08X', $n++
);
293 $stripped .= $marker;
295 $tags[$marker] = "<$tag$attributes>";
296 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
298 $q = preg_split( $end, $inside, 2 );
299 $content[$marker] = $q[0];
300 if( count( $q ) < 2 ) {
301 # No end tag -- let it run out to the end of the text.
311 * Wrapper function for extractTagsAndParams
312 * for cases where $tags and $params isn't needed
313 * i.e. where tags will never have params, like <nowiki>
318 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
319 $dummy_tags = array();
320 $dummy_params = array();
322 return Parser
::extractTagsAndParams( $tag, $text, $content,
323 $dummy_tags, $dummy_params, $uniq_prefix );
327 * Strips and renders nowiki, pre, math, hiero
328 * If $render is set, performs necessary rendering operations on plugins
329 * Returns the text, and fills an array with data needed in unstrip()
330 * If the $state is already a valid strip state, it adds to the state
332 * @param bool $stripcomments when set, HTML comments <!-- like this -->
333 * will be stripped in addition to other tags. This is important
334 * for section editing, where these comments cause confusion when
335 * counting the sections in the wikisource
339 function strip( $text, &$state, $stripcomments = false ) {
340 $render = ($this->mOutputType
== OT_HTML
);
341 $html_content = array();
342 $nowiki_content = array();
343 $math_content = array();
344 $pre_content = array();
345 $comment_content = array();
346 $ext_content = array();
348 $ext_params = array();
349 $gallery_content = array();
351 # Replace any instances of the placeholders
352 $uniq_prefix = UNIQ_PREFIX
;
353 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
358 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
359 foreach( $html_content as $marker => $content ) {
361 # Raw and unchecked for validity.
362 $html_content[$marker] = $content;
364 $html_content[$marker] = '<html>'.$content.'</html>';
370 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
371 foreach( $nowiki_content as $marker => $content ) {
373 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
375 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
380 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
381 foreach( $math_content as $marker => $content ){
383 if( $this->mOptions
->getUseTeX() ) {
384 $math_content[$marker] = renderMath( $content );
386 $math_content[$marker] = '<math>'.$content.'<math>';
389 $math_content[$marker] = '<math>'.$content.'</math>';
394 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
395 foreach( $pre_content as $marker => $content ){
397 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
399 $pre_content[$marker] = '<pre>'.$content.'</pre>';
404 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
405 foreach( $gallery_content as $marker => $content ) {
406 require_once( 'ImageGallery.php' );
408 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
410 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
416 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
417 foreach( $comment_content as $marker => $content ){
418 $comment_content[$marker] = '<!--'.$content.'-->';
423 foreach ( $this->mTagHooks
as $tag => $callback ) {
424 $ext_content[$tag] = array();
425 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
426 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
427 foreach( $ext_content[$tag] as $marker => $content ) {
428 $full_tag = $ext_tags[$tag][$marker];
429 $params = $ext_params[$tag][$marker];
431 $ext_content[$tag][$marker] = $callback( $content, $params, $this );
433 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
438 # Merge state with the pre-existing state, if there is one
440 $state['html'] = $state['html'] +
$html_content;
441 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
442 $state['math'] = $state['math'] +
$math_content;
443 $state['pre'] = $state['pre'] +
$pre_content;
444 $state['comment'] = $state['comment'] +
$comment_content;
445 $state['gallery'] = $state['gallery'] +
$gallery_content;
447 foreach( $ext_content as $tag => $array ) {
448 if ( array_key_exists( $tag, $state ) ) {
449 $state[$tag] = $state[$tag] +
$array;
454 'html' => $html_content,
455 'nowiki' => $nowiki_content,
456 'math' => $math_content,
457 'pre' => $pre_content,
458 'comment' => $comment_content,
459 'gallery' => $gallery_content,
466 * restores pre, math, and hiero removed by strip()
468 * always call unstripNoWiki() after this one
471 function unstrip( $text, &$state ) {
472 if ( !is_array( $state ) ) {
476 # Must expand in reverse order, otherwise nested tags will be corrupted
477 $contentDict = end( $state );
478 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
479 if( key($state) != 'nowiki' && key($state) != 'html') {
480 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
481 $text = str_replace( key( $contentDict ), $content, $text );
490 * always call this after unstrip() to preserve the order
494 function unstripNoWiki( $text, &$state ) {
495 if ( !is_array( $state ) ) {
499 # Must expand in reverse order, otherwise nested tags will be corrupted
500 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
501 $text = str_replace( key( $state['nowiki'] ), $content, $text );
506 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
507 $text = str_replace( key( $state['html'] ), $content, $text );
515 * Add an item to the strip state
516 * Returns the unique tag which must be inserted into the stripped text
517 * The tag will be replaced with the original text in unstrip()
521 function insertStripItem( $text, &$state ) {
522 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
529 'comment' => array(),
530 'gallery' => array(),
533 $state['item'][$rnd] = $text;
538 * Interface with html tidy, used if $wgUseTidy = true.
539 * If tidy isn't able to correct the markup, the original will be
540 * returned in all its glory with a warning comment appended.
542 * Either the external tidy program or the in-process tidy extension
543 * will be used depending on availability. Override the default
544 * $wgTidyInternal setting to disable the internal if it's not working.
546 * @param string $text Hideous HTML input
547 * @return string Corrected HTML output
551 function tidy( $text ) {
552 global $wgTidyInternal;
553 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
554 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
555 '<head><title>test</title></head><body>'.$text.'</body></html>';
556 if( $wgTidyInternal ) {
557 $correctedtext = Parser
::internalTidy( $wrappedtext );
559 $correctedtext = Parser
::externalTidy( $wrappedtext );
561 if( is_null( $correctedtext ) ) {
562 wfDebug( "Tidy error detected!\n" );
563 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
565 return $correctedtext;
569 * Spawn an external HTML tidy process and get corrected markup back from it.
574 function externalTidy( $text ) {
575 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
576 $fname = 'Parser::externalTidy';
577 wfProfileIn( $fname );
582 $descriptorspec = array(
583 0 => array('pipe', 'r'),
584 1 => array('pipe', 'w'),
585 2 => array('file', '/dev/null', 'a')
588 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
589 if (is_resource($process)) {
590 fwrite($pipes[0], $text);
592 while (!feof($pipes[1])) {
593 $cleansource .= fgets($pipes[1], 1024);
596 proc_close($process);
599 wfProfileOut( $fname );
601 if( $cleansource == '' && $text != '') {
602 // Some kind of error happened, so we couldn't get the corrected text.
603 // Just give up; we'll use the source text and append a warning.
611 * Use the HTML tidy PECL extension to use the tidy library in-process,
612 * saving the overhead of spawning a new process. Currently written to
613 * the PHP 4.3.x version of the extension, may not work on PHP 5.
615 * 'pear install tidy' should be able to compile the extension module.
620 function internalTidy( $text ) {
622 $fname = 'Parser::internalTidy';
623 wfProfileIn( $fname );
625 tidy_load_config( $wgTidyConf );
626 tidy_set_encoding( 'utf8' );
627 tidy_parse_string( $text );
629 if( tidy_get_status() == 2 ) {
630 // 2 is magic number for fatal error
631 // http://www.php.net/manual/en/function.tidy-get-status.php
634 $cleansource = tidy_get_output();
636 wfProfileOut( $fname );
641 * parse the wiki syntax used to render tables
645 function doTableStuff ( $t ) {
646 $fname = 'Parser::doTableStuff';
647 wfProfileIn( $fname );
649 $t = explode ( "\n" , $t ) ;
650 $td = array () ; # Is currently a td tag open?
651 $ltd = array () ; # Was it TD or TH?
652 $tr = array () ; # Is currently a tr tag open?
653 $ltr = array () ; # tr attributes
654 $indent_level = 0; # indent level of the table
655 foreach ( $t AS $k => $x )
658 $fc = substr ( $x , 0 , 1 ) ;
659 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
660 $indent_level = strlen( $matches[1] );
661 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
662 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
663 array_push ( $td , false ) ;
664 array_push ( $ltd , '' ) ;
665 array_push ( $tr , false ) ;
666 array_push ( $ltr , '' ) ;
668 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
669 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
670 $z = "</table>" . substr ( $x , 2);
671 $l = array_pop ( $ltd ) ;
672 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
673 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
675 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
677 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
678 $x = substr ( $x , 1 ) ;
679 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
681 $l = array_pop ( $ltd ) ;
682 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
683 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
686 array_push ( $tr , false ) ;
687 array_push ( $td , false ) ;
688 array_push ( $ltd , '' ) ;
689 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
691 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
693 if ( '|+' == substr ( $x , 0 , 2 ) ) {
695 $x = substr ( $x , 1 ) ;
697 $after = substr ( $x , 1 ) ;
698 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
699 $after = explode ( '||' , $after ) ;
702 # Loop through each table cell
703 foreach ( $after AS $theline )
708 $tra = array_pop ( $ltr ) ;
709 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
710 array_push ( $tr , true ) ;
711 array_push ( $ltr , '' ) ;
714 $l = array_pop ( $ltd ) ;
715 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
716 if ( $fc == '|' ) $l = 'td' ;
717 else if ( $fc == '!' ) $l = 'th' ;
718 else if ( $fc == '+' ) $l = 'caption' ;
720 array_push ( $ltd , $l ) ;
723 $y = explode ( '|' , $theline , 2 ) ;
724 # Note that a '|' inside an invalid link should not
725 # be mistaken as delimiting cell parameters
726 if ( strpos( $y[0], '[[' ) !== false ) {
727 $y = array ($theline);
729 if ( count ( $y ) == 1 )
730 $y = "{$z}<{$l}>{$y[0]}" ;
731 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
733 array_push ( $td , true ) ;
738 # Closing open td, tr && table
739 while ( count ( $td ) > 0 )
741 if ( array_pop ( $td ) ) $t[] = '</td>' ;
742 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
746 $t = implode ( "\n" , $t ) ;
747 wfProfileOut( $fname );
752 * Helper function for parse() that transforms wiki markup into
753 * HTML. Only called for $mOutputType == OT_HTML.
757 function internalParse( $text ) {
761 $fname = 'Parser::internalParse';
762 wfProfileIn( $fname );
764 # Remove <noinclude> tags and <includeonly> sections
765 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
766 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
768 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ) );
769 $text = $this->replaceVariables( $text, $args );
771 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
773 $text = $this->doHeadings( $text );
774 if($this->mOptions
->getUseDynamicDates()) {
775 $df =& DateFormatter
::getInstance();
776 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
778 $text = $this->doAllQuotes( $text );
779 $text = $this->replaceInternalLinks( $text );
780 $text = $this->replaceExternalLinks( $text );
782 # replaceInternalLinks may sometimes leave behind
783 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
784 $text = str_replace(UNIQ_PREFIX
."NOPARSE", "", $text);
786 $text = $this->doMagicLinks( $text );
787 $text = $this->doTableStuff( $text );
788 $text = $this->formatHeadings( $text, $isMain );
790 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
791 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
793 wfProfileOut( $fname );
797 function scarySubstitution($matches) {
798 # return "[[".$matches[0]."]]";
799 return $this->mIWTransData
[(int)$matches[0]];
803 * Replace special strings like "ISBN xxx" and "RFC xxx" with
804 * magic external links.
808 function &doMagicLinks( &$text ) {
809 $text = $this->magicISBN( $text );
810 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
811 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
816 * Parse ^^ tokens and return html
820 function doExponent( $text ) {
821 $fname = 'Parser::doExponent';
822 wfProfileIn( $fname );
823 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
824 wfProfileOut( $fname );
829 * Parse headers and return html
833 function doHeadings( $text ) {
834 $fname = 'Parser::doHeadings';
835 wfProfileIn( $fname );
836 for ( $i = 6; $i >= 1; --$i ) {
837 $h = substr( '======', 0, $i );
838 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
839 "<h{$i}>\\1</h{$i}>\\2", $text );
841 wfProfileOut( $fname );
846 * Replace single quotes with HTML markup
848 * @return string the altered text
850 function doAllQuotes( $text ) {
851 $fname = 'Parser::doAllQuotes';
852 wfProfileIn( $fname );
854 $lines = explode( "\n", $text );
855 foreach ( $lines as $line ) {
856 $outtext .= $this->doQuotes ( $line ) . "\n";
858 $outtext = substr($outtext, 0,-1);
859 wfProfileOut( $fname );
864 * Helper function for doAllQuotes()
867 function doQuotes( $text ) {
868 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
869 if ( count( $arr ) == 1 )
873 # First, do some preliminary work. This may shift some apostrophes from
874 # being mark-up to being text. It also counts the number of occurrences
875 # of bold and italics mark-ups.
879 foreach ( $arr as $r )
881 if ( ( $i %
2 ) == 1 )
883 # If there are ever four apostrophes, assume the first is supposed to
884 # be text, and the remaining three constitute mark-up for bold text.
885 if ( strlen( $arr[$i] ) == 4 )
890 # If there are more than 5 apostrophes in a row, assume they're all
891 # text except for the last 5.
892 else if ( strlen( $arr[$i] ) > 5 )
894 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
897 # Count the number of occurrences of bold and italics mark-ups.
898 # We are not counting sequences of five apostrophes.
899 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
900 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
901 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
906 # If there is an odd number of both bold and italics, it is likely
907 # that one of the bold ones was meant to be an apostrophe followed
908 # by italics. Which one we cannot know for certain, but it is more
909 # likely to be one that has a single-letter word before it.
910 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
913 $firstsingleletterword = -1;
914 $firstmultiletterword = -1;
916 foreach ( $arr as $r )
918 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
920 $x1 = substr ($arr[$i-1], -1);
921 $x2 = substr ($arr[$i-1], -2, 1);
923 if ($firstspace == -1) $firstspace = $i;
924 } else if ($x2 == ' ') {
925 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
927 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
933 # If there is a single-letter word, use it!
934 if ($firstsingleletterword > -1)
936 $arr [ $firstsingleletterword ] = "''";
937 $arr [ $firstsingleletterword-1 ] .= "'";
939 # If not, but there's a multi-letter word, use that one.
940 else if ($firstmultiletterword > -1)
942 $arr [ $firstmultiletterword ] = "''";
943 $arr [ $firstmultiletterword-1 ] .= "'";
945 # ... otherwise use the first one that has neither.
946 # (notice that it is possible for all three to be -1 if, for example,
947 # there is only one pentuple-apostrophe in the line)
948 else if ($firstspace > -1)
950 $arr [ $firstspace ] = "''";
951 $arr [ $firstspace-1 ] .= "'";
955 # Now let's actually convert our apostrophic mush to HTML!
964 if ($state == 'both')
971 if (strlen ($r) == 2)
974 { $output .= '</i>'; $state = ''; }
975 else if ($state == 'bi')
976 { $output .= '</i>'; $state = 'b'; }
977 else if ($state == 'ib')
978 { $output .= '</b></i><b>'; $state = 'b'; }
979 else if ($state == 'both')
980 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
981 else # $state can be 'b' or ''
982 { $output .= '<i>'; $state .= 'i'; }
984 else if (strlen ($r) == 3)
987 { $output .= '</b>'; $state = ''; }
988 else if ($state == 'bi')
989 { $output .= '</i></b><i>'; $state = 'i'; }
990 else if ($state == 'ib')
991 { $output .= '</b>'; $state = 'i'; }
992 else if ($state == 'both')
993 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
994 else # $state can be 'i' or ''
995 { $output .= '<b>'; $state .= 'b'; }
997 else if (strlen ($r) == 5)
1000 { $output .= '</b><i>'; $state = 'i'; }
1001 else if ($state == 'i')
1002 { $output .= '</i><b>'; $state = 'b'; }
1003 else if ($state == 'bi')
1004 { $output .= '</i></b>'; $state = ''; }
1005 else if ($state == 'ib')
1006 { $output .= '</b></i>'; $state = ''; }
1007 else if ($state == 'both')
1008 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1009 else # ($state == '')
1010 { $buffer = ''; $state = 'both'; }
1015 # Now close all remaining tags. Notice that the order is important.
1016 if ($state == 'b' ||
$state == 'ib')
1018 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1022 if ($state == 'both')
1023 $output .= '<b><i>'.$buffer.'</i></b>';
1029 * Replace external links
1031 * Note: this is all very hackish and the order of execution matters a lot.
1032 * Make sure to run maintenance/parserTests.php if you change this code.
1036 function replaceExternalLinks( $text ) {
1038 $fname = 'Parser::replaceExternalLinks';
1039 wfProfileIn( $fname );
1041 $sk =& $this->mOptions
->getSkin();
1043 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1045 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1048 while ( $i<count( $bits ) ) {
1050 $protocol = $bits[$i++
];
1051 $text = $bits[$i++
];
1052 $trail = $bits[$i++
];
1054 # The characters '<' and '>' (which were escaped by
1055 # removeHTMLtags()) should not be included in
1056 # URLs, per RFC 2396.
1057 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1058 $text = substr($url, $m2[0][1]) . ' ' . $text;
1059 $url = substr($url, 0, $m2[0][1]);
1062 # If the link text is an image URL, replace it with an <img> tag
1063 # This happened by accident in the original parser, but some people used it extensively
1064 $img = $this->maybeMakeExternalImage( $text );
1065 if ( $img !== false ) {
1071 # Set linktype for CSS - if URL==text, link is essentially free
1072 $linktype = ($text == $url) ?
'free' : 'text';
1074 # No link text, e.g. [http://domain.tld/some.link]
1075 if ( $text == '' ) {
1076 # Autonumber if allowed
1077 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1078 $text = '[' . ++
$this->mAutonumber
. ']';
1079 $linktype = 'autonumber';
1081 # Otherwise just use the URL
1082 $text = htmlspecialchars( $url );
1086 # Have link text, e.g. [http://domain.tld/some.link text]s
1088 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1091 $text = $wgContLang->markNoConversion($text);
1093 # Replace & from obsolete syntax with &.
1094 # All HTML entities will be escaped by makeExternalLink()
1095 # or maybeMakeExternalImage()
1096 $url = str_replace( '&', '&', $url );
1098 # Process the trail (i.e. everything after this link up until start of the next link),
1099 # replacing any non-bracketed links
1100 $trail = $this->replaceFreeExternalLinks( $trail );
1103 # Use the encoded URL
1104 # This means that users can paste URLs directly into the text
1105 # Funny characters like ö aren't valid in URLs anyway
1106 # This was changed in August 2004
1107 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1110 wfProfileOut( $fname );
1115 * Replace anything that looks like a URL with a link
1118 function replaceFreeExternalLinks( $text ) {
1119 global $wgUrlProtocols;
1121 $fname = 'Parser::replaceFreeExternalLinks';
1122 wfProfileIn( $fname );
1124 $bits = preg_split( '/(\b(?:'.$wgUrlProtocols.'))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1125 $s = array_shift( $bits );
1128 $sk =& $this->mOptions
->getSkin();
1130 while ( $i < count( $bits ) ){
1131 $protocol = $bits[$i++
];
1132 $remainder = $bits[$i++
];
1134 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1135 # Found some characters after the protocol that look promising
1136 $url = $protocol . $m[1];
1139 # The characters '<' and '>' (which were escaped by
1140 # removeHTMLtags()) should not be included in
1141 # URLs, per RFC 2396.
1142 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1143 $trail = substr($url, $m2[0][1]) . $trail;
1144 $url = substr($url, 0, $m2[0][1]);
1147 # Move trailing punctuation to $trail
1149 # If there is no left bracket, then consider right brackets fair game too
1150 if ( strpos( $url, '(' ) === false ) {
1154 $numSepChars = strspn( strrev( $url ), $sep );
1155 if ( $numSepChars ) {
1156 $trail = substr( $url, -$numSepChars ) . $trail;
1157 $url = substr( $url, 0, -$numSepChars );
1160 # Replace & from obsolete syntax with &.
1161 # All HTML entities will be escaped by makeExternalLink()
1162 # or maybeMakeExternalImage()
1163 $url = str_replace( '&', '&', $url );
1165 # Is this an external image?
1166 $text = $this->maybeMakeExternalImage( $url );
1167 if ( $text === false ) {
1168 # Not an image, make a link
1169 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1171 $s .= $text . $trail;
1173 $s .= $protocol . $remainder;
1176 wfProfileOut( $fname );
1181 * make an image if it's allowed
1184 function maybeMakeExternalImage( $url ) {
1185 $sk =& $this->mOptions
->getSkin();
1187 if ( $this->mOptions
->getAllowExternalImages() ) {
1188 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1190 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1197 * Process [[ ]] wikilinks
1201 function replaceInternalLinks( $s ) {
1202 global $wgContLang, $wgLinkCache, $wgUrlProtocols;
1203 static $fname = 'Parser::replaceInternalLinks' ;
1205 wfProfileIn( $fname );
1207 wfProfileIn( $fname.'-setup' );
1209 # the % is needed to support urlencoded titles as well
1210 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1212 $sk =& $this->mOptions
->getSkin();
1214 #split the entire text string on occurences of [[
1215 $a = explode( '[[', ' ' . $s );
1216 #get the first element (all text up to first [[), and remove the space we added
1217 $s = array_shift( $a );
1218 $s = substr( $s, 1 );
1220 # Match a link having the form [[namespace:link|alternate]]trail
1222 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1223 # Match cases where there is no "]]", which might still be images
1224 static $e1_img = FALSE;
1225 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1226 # Match the end of a line for a word that's not followed by whitespace,
1227 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1228 $e2 = wfMsgForContent( 'linkprefix' );
1230 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1232 if( is_null( $this->mTitle
) ) {
1233 wfDebugDieBacktrace( 'nooo' );
1235 $nottalk = !$this->mTitle
->isTalkPage();
1237 if ( $useLinkPrefixExtension ) {
1238 if ( preg_match( $e2, $s, $m ) ) {
1239 $first_prefix = $m[2];
1241 $first_prefix = false;
1247 $selflink = $this->mTitle
->getPrefixedText();
1248 wfProfileOut( $fname.'-setup' );
1250 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1251 $useSubpages = $this->areSubpagesAllowed();
1253 # Loop for each link
1254 for ($k = 0; isset( $a[$k] ); $k++
) {
1256 if ( $useLinkPrefixExtension ) {
1257 wfProfileIn( $fname.'-prefixhandling' );
1258 if ( preg_match( $e2, $s, $m ) ) {
1266 $prefix = $first_prefix;
1267 $first_prefix = false;
1269 wfProfileOut( $fname.'-prefixhandling' );
1272 $might_be_img = false;
1274 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1276 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1277 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1278 # the real problem is with the $e1 regex
1281 # Still some problems for cases where the ] is meant to be outside punctuation,
1282 # and no image is in sight. See bug 2095.
1284 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1285 $text .= ']'; # so that replaceExternalLinks($text) works later
1288 # fix up urlencoded title texts
1289 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1291 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1292 $might_be_img = true;
1294 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1296 } else { # Invalid form; output directly
1297 $s .= $prefix . '[[' . $line ;
1301 # Don't allow internal links to pages containing
1302 # PROTO: where PROTO is a valid URL protocol; these
1303 # should be external links.
1304 if (preg_match('/^(\b(?:'.$wgUrlProtocols.'))/', $m[1])) {
1305 $s .= $prefix . '[[' . $line ;
1309 # Make subpage if necessary
1310 if( $useSubpages ) {
1311 $link = $this->maybeDoSubpageLink( $m[1], $text );
1316 $noforce = (substr($m[1], 0, 1) != ':');
1318 # Strip off leading ':'
1319 $link = substr($link, 1);
1322 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1324 $s .= $prefix . '[[' . $line;
1328 #check other language variants of the link
1329 #if the article does not exist
1330 if( $checkVariantLink
1331 && $nt->getArticleID() == 0 ) {
1332 $wgContLang->findVariantLink($link, $nt);
1335 $ns = $nt->getNamespace();
1336 $iw = $nt->getInterWiki();
1338 if ($might_be_img) { # if this is actually an invalid link
1339 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1341 while (isset ($a[$k+
1]) ) {
1342 #look at the next 'line' to see if we can close it there
1343 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1344 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1345 # the first ]] closes the inner link, the second the image
1347 $text .= '[[' . $m[1];
1350 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1351 #if there's exactly one ]] that's fine, we'll keep looking
1352 $text .= '[[' . $m[0];
1354 #if $next_line is invalid too, we need look no further
1355 $text .= '[[' . $next_line;
1360 # we couldn't find the end of this imageLink, so output it raw
1361 #but don't ignore what might be perfectly normal links in the text we've examined
1362 $text = $this->replaceInternalLinks($text);
1363 $s .= $prefix . '[[' . $link . '|' . $text;
1364 # note: no $trail, because without an end, there *is* no trail
1367 } else { #it's not an image, so output it raw
1368 $s .= $prefix . '[[' . $link . '|' . $text;
1369 # note: no $trail, because without an end, there *is* no trail
1374 $wasblank = ( '' == $text );
1375 if( $wasblank ) $text = $link;
1378 # Link not escaped by : , create the various objects
1382 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1383 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1384 $s = rtrim($s . "\n");
1385 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1389 if ( $ns == NS_IMAGE
) {
1390 wfProfileIn( "$fname-image" );
1391 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1392 # recursively parse links inside the image caption
1393 # actually, this will parse them in any other parameters, too,
1394 # but it might be hard to fix that, and it doesn't matter ATM
1395 $text = $this->replaceExternalLinks($text);
1396 $text = $this->replaceInternalLinks($text);
1398 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1399 $s .= $prefix . preg_replace("/\b($wgUrlProtocols)/", UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1400 $wgLinkCache->addImageLinkObj( $nt );
1402 wfProfileOut( "$fname-image" );
1405 wfProfileOut( "$fname-image" );
1409 if ( $ns == NS_CATEGORY
) {
1410 wfProfileIn( "$fname-category" );
1411 $t = $wgContLang->convertHtml( $nt->getText() );
1412 $s = rtrim($s . "\n"); # bug 87
1414 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1415 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1416 $wgLinkCache->resume();
1419 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1420 $sortkey = $this->mTitle
->getText();
1422 $sortkey = $this->mTitle
->getPrefixedText();
1427 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1428 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1429 $this->mOutput
->addCategoryLink( $t );
1432 * Strip the whitespace Category links produce, see bug 87
1433 * @todo We might want to use trim($tmp, "\n") here.
1435 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1437 wfProfileOut( "$fname-category" );
1442 if( ( $nt->getPrefixedText() === $selflink ) &&
1443 ( $nt->getFragment() === '' ) ) {
1444 # Self-links are handled specially; generally de-link and change to bold.
1445 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1449 # Special and Media are pseudo-namespaces; no pages actually exist in them
1450 if( $ns == NS_MEDIA
) {
1451 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1452 $wgLinkCache->addImageLinkObj( $nt );
1454 } elseif( $ns == NS_SPECIAL
) {
1455 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1458 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1460 wfProfileOut( $fname );
1465 * Hardens some text possibly containing URLs against mangling by
1466 * replaceExternalLinks()
1468 function hardenURLs( $text ) {
1469 return str_replace( 'http://', 'http-noparse://', $text );
1473 * Make a link placeholder. The text returned can be later resolved to a real link with
1474 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1475 * parsing of interwiki links, and secondly to allow all extistence checks and
1476 * article length checks (for stub links) to be bundled into a single query.
1479 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1480 if ( ! is_object($nt) ) {
1482 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1484 # Separate the link trail from the rest of the link
1485 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1487 if ( $nt->isExternal() ) {
1488 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1489 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1490 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1492 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1493 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1494 $this->mLinkHolders
['queries'][] = $query;
1495 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1496 $this->mLinkHolders
['titles'][] = $nt;
1498 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1505 * Return true if subpage links should be expanded on this page.
1508 function areSubpagesAllowed() {
1509 # Some namespaces don't allow subpages
1510 global $wgNamespacesWithSubpages;
1511 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1515 * Handle link to subpage if necessary
1516 * @param string $target the source of the link
1517 * @param string &$text the link text, modified as necessary
1518 * @return string the full name of the link
1521 function maybeDoSubpageLink($target, &$text) {
1524 # :Foobar -- override special treatment of prefix (images, language links)
1525 # /Foobar -- convert to CurrentPage/Foobar
1526 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1527 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1528 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1530 $fname = 'Parser::maybeDoSubpageLink';
1531 wfProfileIn( $fname );
1532 $ret = $target; # default return value is no change
1534 # Some namespaces don't allow subpages,
1535 # so only perform processing if subpages are allowed
1536 if( $this->areSubpagesAllowed() ) {
1537 # Look at the first character
1538 if( $target != '' && $target{0} == '/' ) {
1539 # / at end means we don't want the slash to be shown
1540 if( substr( $target, -1, 1 ) == '/' ) {
1541 $target = substr( $target, 1, -1 );
1544 $noslash = substr( $target, 1 );
1547 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1548 if( '' === $text ) {
1550 } # this might be changed for ugliness reasons
1552 # check for .. subpage backlinks
1554 $nodotdot = $target;
1555 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1557 $nodotdot = substr( $nodotdot, 3 );
1559 if($dotdotcount > 0) {
1560 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1561 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1562 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1563 # / at the end means don't show full path
1564 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1565 $nodotdot = substr( $nodotdot, 0, -1 );
1566 if( '' === $text ) {
1570 $nodotdot = trim( $nodotdot );
1571 if( $nodotdot != '' ) {
1572 $ret .= '/' . $nodotdot;
1579 wfProfileOut( $fname );
1584 * Used by doBlockLevels()
1587 /* private */ function closeParagraph() {
1589 if ( '' != $this->mLastSection
) {
1590 $result = '</' . $this->mLastSection
. ">\n";
1592 $this->mInPre
= false;
1593 $this->mLastSection
= '';
1596 # getCommon() returns the length of the longest common substring
1597 # of both arguments, starting at the beginning of both.
1599 /* private */ function getCommon( $st1, $st2 ) {
1600 $fl = strlen( $st1 );
1601 $shorter = strlen( $st2 );
1602 if ( $fl < $shorter ) { $shorter = $fl; }
1604 for ( $i = 0; $i < $shorter; ++
$i ) {
1605 if ( $st1{$i} != $st2{$i} ) { break; }
1609 # These next three functions open, continue, and close the list
1610 # element appropriate to the prefix character passed into them.
1612 /* private */ function openList( $char ) {
1613 $result = $this->closeParagraph();
1615 if ( '*' == $char ) { $result .= '<ul><li>'; }
1616 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1617 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1618 else if ( ';' == $char ) {
1619 $result .= '<dl><dt>';
1620 $this->mDTopen
= true;
1622 else { $result = '<!-- ERR 1 -->'; }
1627 /* private */ function nextItem( $char ) {
1628 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1629 else if ( ':' == $char ||
';' == $char ) {
1631 if ( $this->mDTopen
) { $close = '</dt>'; }
1632 if ( ';' == $char ) {
1633 $this->mDTopen
= true;
1634 return $close . '<dt>';
1636 $this->mDTopen
= false;
1637 return $close . '<dd>';
1640 return '<!-- ERR 2 -->';
1643 /* private */ function closeList( $char ) {
1644 if ( '*' == $char ) { $text = '</li></ul>'; }
1645 else if ( '#' == $char ) { $text = '</li></ol>'; }
1646 else if ( ':' == $char ) {
1647 if ( $this->mDTopen
) {
1648 $this->mDTopen
= false;
1649 $text = '</dt></dl>';
1651 $text = '</dd></dl>';
1654 else { return '<!-- ERR 3 -->'; }
1660 * Make lists from lines starting with ':', '*', '#', etc.
1663 * @return string the lists rendered as HTML
1665 function doBlockLevels( $text, $linestart ) {
1666 $fname = 'Parser::doBlockLevels';
1667 wfProfileIn( $fname );
1669 # Parsing through the text line by line. The main thing
1670 # happening here is handling of block-level elements p, pre,
1671 # and making lists from lines starting with * # : etc.
1673 $textLines = explode( "\n", $text );
1675 $lastPrefix = $output = '';
1676 $this->mDTopen
= $inBlockElem = false;
1678 $paragraphStack = false;
1680 if ( !$linestart ) {
1681 $output .= array_shift( $textLines );
1683 foreach ( $textLines as $oLine ) {
1684 $lastPrefixLength = strlen( $lastPrefix );
1685 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1686 $preOpenMatch = preg_match('/<pre/i', $oLine );
1687 if ( !$this->mInPre
) {
1688 # Multiple prefixes may abut each other for nested lists.
1689 $prefixLength = strspn( $oLine, '*#:;' );
1690 $pref = substr( $oLine, 0, $prefixLength );
1693 $pref2 = str_replace( ';', ':', $pref );
1694 $t = substr( $oLine, $prefixLength );
1695 $this->mInPre
= !empty($preOpenMatch);
1697 # Don't interpret any other prefixes in preformatted text
1699 $pref = $pref2 = '';
1704 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1705 # Same as the last item, so no need to deal with nesting or opening stuff
1706 $output .= $this->nextItem( substr( $pref, -1 ) );
1707 $paragraphStack = false;
1709 if ( substr( $pref, -1 ) == ';') {
1710 # The one nasty exception: definition lists work like this:
1711 # ; title : definition text
1712 # So we check for : in the remainder text to split up the
1713 # title and definition, without b0rking links.
1715 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1717 $output .= $term . $this->nextItem( ':' );
1720 } elseif( $prefixLength ||
$lastPrefixLength ) {
1721 # Either open or close a level...
1722 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1723 $paragraphStack = false;
1725 while( $commonPrefixLength < $lastPrefixLength ) {
1726 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1727 --$lastPrefixLength;
1729 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1730 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1732 while ( $prefixLength > $commonPrefixLength ) {
1733 $char = substr( $pref, $commonPrefixLength, 1 );
1734 $output .= $this->openList( $char );
1736 if ( ';' == $char ) {
1737 # FIXME: This is dupe of code above
1738 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1740 $output .= $term . $this->nextItem( ':' );
1743 ++
$commonPrefixLength;
1745 $lastPrefix = $pref2;
1747 if( 0 == $prefixLength ) {
1748 wfProfileIn( "$fname-paragraph" );
1749 # No prefix (not in list)--go to paragraph mode
1750 $uniq_prefix = UNIQ_PREFIX
;
1751 // XXX: use a stack for nestable elements like span, table and div
1752 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1753 $closematch = preg_match(
1754 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1755 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1756 if ( $openmatch or $closematch ) {
1757 $paragraphStack = false;
1758 $output .= $this->closeParagraph();
1759 if ( $preOpenMatch and !$preCloseMatch ) {
1760 $this->mInPre
= true;
1762 if ( $closematch ) {
1763 $inBlockElem = false;
1765 $inBlockElem = true;
1767 } else if ( !$inBlockElem && !$this->mInPre
) {
1768 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1770 if ($this->mLastSection
!= 'pre') {
1771 $paragraphStack = false;
1772 $output .= $this->closeParagraph().'<pre>';
1773 $this->mLastSection
= 'pre';
1775 $t = substr( $t, 1 );
1778 if ( '' == trim($t) ) {
1779 if ( $paragraphStack ) {
1780 $output .= $paragraphStack.'<br />';
1781 $paragraphStack = false;
1782 $this->mLastSection
= 'p';
1784 if ($this->mLastSection
!= 'p' ) {
1785 $output .= $this->closeParagraph();
1786 $this->mLastSection
= '';
1787 $paragraphStack = '<p>';
1789 $paragraphStack = '</p><p>';
1793 if ( $paragraphStack ) {
1794 $output .= $paragraphStack;
1795 $paragraphStack = false;
1796 $this->mLastSection
= 'p';
1797 } else if ($this->mLastSection
!= 'p') {
1798 $output .= $this->closeParagraph().'<p>';
1799 $this->mLastSection
= 'p';
1804 wfProfileOut( "$fname-paragraph" );
1806 // somewhere above we forget to get out of pre block (bug 785)
1807 if($preCloseMatch && $this->mInPre
) {
1808 $this->mInPre
= false;
1810 if ($paragraphStack === false) {
1814 while ( $prefixLength ) {
1815 $output .= $this->closeList( $pref2{$prefixLength-1} );
1818 if ( '' != $this->mLastSection
) {
1819 $output .= '</' . $this->mLastSection
. '>';
1820 $this->mLastSection
= '';
1823 wfProfileOut( $fname );
1828 * Split up a string on ':', ignoring any occurences inside
1829 * <a>..</a> or <span>...</span>
1830 * @param string $str the string to split
1831 * @param string &$before set to everything before the ':'
1832 * @param string &$after set to everything after the ':'
1833 * return string the position of the ':', or false if none found
1835 function findColonNoLinks($str, &$before, &$after) {
1836 # I wonder if we should make this count all tags, not just <a>
1837 # and <span>. That would prevent us from matching a ':' that
1838 # comes in the middle of italics other such formatting....
1840 $fname = 'Parser::findColonNoLinks';
1841 wfProfileIn( $fname );
1844 $colon = strpos($str, ':', $pos);
1846 if ($colon !== false) {
1847 $before = substr($str, 0, $colon);
1848 $after = substr($str, $colon +
1);
1850 # Skip any ':' within <a> or <span> pairs
1851 $a = substr_count($before, '<a');
1852 $s = substr_count($before, '<span');
1853 $ca = substr_count($before, '</a>');
1854 $cs = substr_count($before, '</span>');
1856 if ($a <= $ca and $s <= $cs) {
1857 # Tags are balanced before ':'; ok
1862 } while ($colon !== false);
1863 wfProfileOut( $fname );
1868 * Return value of a magic variable (like PAGENAME)
1872 function getVariableValue( $index ) {
1873 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1876 * Some of these require message or data lookups and can be
1877 * expensive to check many times.
1879 static $varCache = array();
1880 if( isset( $varCache[$index] ) ) return $varCache[$index];
1883 case MAG_CURRENTMONTH
:
1884 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1885 case MAG_CURRENTMONTHNAME
:
1886 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1887 case MAG_CURRENTMONTHNAMEGEN
:
1888 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1889 case MAG_CURRENTMONTHABBREV
:
1890 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1891 case MAG_CURRENTDAY
:
1892 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1894 return $this->mTitle
->getText();
1896 return $this->mTitle
->getPartialURL();
1897 case MAG_REVISIONID
:
1898 return $wgArticle->getRevIdFetched();
1900 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1901 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1902 case MAG_CURRENTDAYNAME
:
1903 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1904 case MAG_CURRENTYEAR
:
1905 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1906 case MAG_CURRENTTIME
:
1907 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1908 case MAG_CURRENTWEEK
:
1909 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1910 case MAG_CURRENTDOW
:
1911 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1912 case MAG_NUMBEROFARTICLES
:
1913 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1914 case MAG_NUMBEROFFILES
:
1915 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1920 case MAG_SERVERNAME
:
1921 return $wgServerName;
1922 case MAG_SCRIPTPATH
:
1923 return $wgScriptPath;
1930 * initialise the magic variables (like CURRENTMONTHNAME)
1934 function initialiseVariables() {
1935 $fname = 'Parser::initialiseVariables';
1936 wfProfileIn( $fname );
1937 global $wgVariableIDs;
1938 $this->mVariables
= array();
1939 foreach ( $wgVariableIDs as $id ) {
1940 $mw =& MagicWord
::get( $id );
1941 $mw->addToArray( $this->mVariables
, $id );
1943 wfProfileOut( $fname );
1947 * Replace magic variables, templates, and template arguments
1948 * with the appropriate text. Templates are substituted recursively,
1949 * taking care to avoid infinite loops.
1951 * Note that the substitution depends on value of $mOutputType:
1952 * OT_WIKI: only {{subst:}} templates
1953 * OT_MSG: only magic variables
1954 * OT_HTML: all templates and magic variables
1956 * @param string $tex The text to transform
1957 * @param array $args Key-value pairs representing template parameters to substitute
1960 function replaceVariables( $text, $args = array() ) {
1962 # Prevent too big inclusions
1963 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1967 $fname = 'Parser::replaceVariables';
1968 wfProfileIn( $fname );
1970 $titleChars = Title
::legalChars();
1972 # This function is called recursively. To keep track of arguments we need a stack:
1973 array_push( $this->mArgStack
, $args );
1975 # Variable substitution
1976 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1978 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1979 # Argument substitution
1980 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1982 # Template substitution
1983 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1984 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1986 array_pop( $this->mArgStack
);
1988 wfProfileOut( $fname );
1993 * Replace magic variables
1996 function variableSubstitution( $matches ) {
1997 $fname = 'parser::variableSubstitution';
1998 $varname = $matches[1];
1999 wfProfileIn( $fname );
2000 if ( !$this->mVariables
) {
2001 $this->initialiseVariables();
2004 if ( $this->mOutputType
== OT_WIKI
) {
2005 # Do only magic variables prefixed by SUBST
2006 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2007 if (!$mwSubst->matchStartAndRemove( $varname ))
2009 # Note that if we don't substitute the variable below,
2010 # we don't remove the {{subst:}} magic word, in case
2011 # it is a template rather than a magic variable.
2013 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2014 $id = $this->mVariables
[$varname];
2015 $text = $this->getVariableValue( $id );
2016 $this->mOutput
->mContainsOldMagic
= true;
2018 $text = $matches[0];
2020 wfProfileOut( $fname );
2024 # Split template arguments
2025 function getTemplateArgs( $argsString ) {
2026 if ( $argsString === '' ) {
2030 $args = explode( '|', substr( $argsString, 1 ) );
2032 # If any of the arguments contains a '[[' but no ']]', it needs to be
2033 # merged with the next arg because the '|' character between belongs
2034 # to the link syntax and not the template parameter syntax.
2035 $argc = count($args);
2037 for ( $i = 0; $i < $argc-1; $i++
) {
2038 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2039 $args[$i] .= '|'.$args[$i+
1];
2040 array_splice($args, $i+
1, 1);
2050 * Return the text of a template, after recursively
2051 * replacing any variables or templates within the template.
2053 * @param array $matches The parts of the template
2054 * $matches[1]: the title, i.e. the part before the |
2055 * $matches[2]: the parameters (including a leading |), if any
2056 * @return string the text of the template
2059 function braceSubstitution( $matches ) {
2060 global $wgLinkCache, $wgContLang;
2061 $fname = 'Parser::braceSubstitution';
2062 wfProfileIn( $fname );
2070 # Need to know if the template comes at the start of a line,
2071 # to treat the beginning of the template like the beginning
2072 # of a line for tables and block-level elements.
2073 $linestart = $matches[1];
2075 # $part1 is the bit before the first |, and must contain only title characters
2076 # $args is a list of arguments, starting from index 0, not including $part1
2078 $part1 = $matches[2];
2079 # If the third subpattern matched anything, it will start with |
2081 $args = $this->getTemplateArgs($matches[3]);
2082 $argc = count( $args );
2084 # Don't parse {{{}}} because that's only for template arguments
2085 if ( $linestart === '{' ) {
2086 $text = $matches[0];
2093 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2094 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2095 # One of two possibilities is true:
2096 # 1) Found SUBST but not in the PST phase
2097 # 2) Didn't find SUBST and in the PST phase
2098 # In either case, return without further processing
2099 $text = $matches[0];
2105 # MSG, MSGNW and INT
2108 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2109 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2112 # Remove obsolete MSG:
2113 $mwMsg =& MagicWord
::get( MAG_MSG
);
2114 $mwMsg->matchStartAndRemove( $part1 );
2117 # Check if it is an internal message
2118 $mwInt =& MagicWord
::get( MAG_INT
);
2119 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2120 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2121 $text = $linestart . wfMsgReal( $part1, $args, true );
2129 # Check for NS: (namespace expansion)
2130 $mwNs = MagicWord
::get( MAG_NS
);
2131 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2132 if ( intval( $part1 ) ) {
2133 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2136 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2137 if ( !is_null( $index ) ) {
2138 $text = $linestart . $wgContLang->getNsText( $index );
2145 # LOCALURL and LOCALURLE
2147 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2148 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2150 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2151 $func = 'getLocalURL';
2152 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2153 $func = 'escapeLocalURL';
2158 if ( $func !== '' ) {
2159 $title = Title
::newFromText( $part1 );
2160 if ( !is_null( $title ) ) {
2162 $text = $linestart . $title->$func( $args[0] );
2164 $text = $linestart . $title->$func();
2172 if ( !$found && $argc == 1 ) {
2173 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2174 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2175 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2180 # Template table test
2182 # Did we encounter this template already? If yes, it is in the cache
2183 # and we need to check for loops.
2184 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2187 # Infinite loop test
2188 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2191 $text = $linestart .
2193 '<!-- WARNING: template loop detected -->';
2194 wfDebug( "$fname: template loop broken at '$part1'\n" );
2196 # set $text to cached message.
2197 $text = $linestart . $this->mTemplates
[$part1];
2201 # Load from database
2202 $replaceHeadings = false;
2204 $lastPathLevel = $this->mTemplatePath
;
2207 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2208 if ($subpage !== '') {
2209 $ns = $this->mTitle
->getNamespace();
2211 $title = Title
::newFromText( $part1, $ns );
2214 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2215 if ($interwiki != '' && $title->isTrans()) {
2216 return $this->scarytransclude($title, $interwiki);
2220 if ( !is_null( $title ) && !$title->isExternal() ) {
2221 # Check for excessive inclusion
2222 $dbk = $title->getPrefixedDBkey();
2223 if ( $this->incrementIncludeCount( $dbk ) ) {
2224 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2225 # Capture special page output
2226 $text = SpecialPage
::capturePath( $title );
2227 if ( is_string( $text ) ) {
2231 $this->disableCache();
2234 $article = new Article( $title );
2235 $articleContent = $article->fetchContent(0, false);
2236 if ( $articleContent !== false ) {
2238 $text = $articleContent;
2239 $replaceHeadings = true;
2244 # If the title is valid but undisplayable, make a link to it
2245 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2246 $text = '[['.$title->getPrefixedText().']]';
2250 # Template cache array insertion
2252 $this->mTemplates
[$part1] = $text;
2253 $text = $linestart . $text;
2258 # Recursive parsing, escaping and link table handling
2259 # Only for HTML output
2260 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2261 $text = wfEscapeWikiText( $text );
2262 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2263 # Clean up argument array
2264 $assocArgs = array();
2266 foreach( $args as $arg ) {
2267 $eqpos = strpos( $arg, '=' );
2268 if ( $eqpos === false ) {
2269 $assocArgs[$index++
] = $arg;
2271 $name = trim( substr( $arg, 0, $eqpos ) );
2272 $value = trim( substr( $arg, $eqpos+
1 ) );
2273 if ( $value === false ) {
2276 if ( $name !== false ) {
2277 $assocArgs[$name] = $value;
2282 # Add a new element to the templace recursion path
2283 $this->mTemplatePath
[$part1] = 1;
2285 if( $this->mOutputType
== OT_HTML
) {
2286 # Remove <noinclude> sections and <includeonly> tags
2287 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2288 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2289 # Strip <nowiki>, <pre>, etc.
2290 $text = $this->strip( $text, $this->mStripState
);
2291 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2293 $text = $this->replaceVariables( $text, $assocArgs );
2295 # Resume the link cache and register the inclusion as a link
2296 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2297 $wgLinkCache->addLinkObj( $title );
2300 # If the template begins with a table or block-level
2301 # element, it should be treated as beginning a new line.
2302 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2303 $text = "\n" . $text;
2306 # Prune lower levels off the recursion check path
2307 $this->mTemplatePath
= $lastPathLevel;
2310 wfProfileOut( $fname );
2314 # Replace raw HTML by a placeholder
2315 # Add a blank line preceding, to prevent it from mucking up
2316 # immediately preceding headings
2317 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2319 # replace ==section headers==
2320 # XXX this needs to go away once we have a better parser.
2321 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2322 if( !is_null( $title ) )
2323 $encodedname = base64_encode($title->getPrefixedDBkey());
2325 $encodedname = base64_encode("");
2326 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2327 PREG_SPLIT_DELIM_CAPTURE
);
2330 for( $i = 0; $i < count($m); $i +
= 2 ) {
2332 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2334 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2338 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2339 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2340 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2348 # Prune lower levels off the recursion check path
2349 $this->mTemplatePath
= $lastPathLevel;
2352 wfProfileOut( $fname );
2355 wfProfileOut( $fname );
2361 * Translude an interwiki link.
2363 function scarytransclude($title, $interwiki) {
2364 global $wgEnableScaryTranscluding;
2366 if (!$wgEnableScaryTranscluding)
2367 return wfMsg('scarytranscludedisabled');
2369 $articlename = "Template:" . $title->getDBkey();
2370 $url = str_replace('$1', urlencode($articlename), $interwiki);
2371 if (strlen($url) > 255)
2372 return wfMsg('scarytranscludetoolong');
2373 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2374 $this->mIWTransData
[] = $text;
2375 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2378 function fetchScaryTemplateMaybeFromCache($url) {
2379 $dbr =& wfGetDB(DB_SLAVE
);
2380 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2381 array('tc_url' => $url));
2383 $time = $obj->tc_time
;
2384 $text = $obj->tc_contents
;
2385 if ($time && $time < (time() +
(60*60))) {
2390 $text = wfGetHTTP($url . '?action=render');
2392 return wfMsg('scarytranscludefailed', $url);
2394 $dbw =& wfGetDB(DB_MASTER
);
2395 $dbw->replace('transcache', array(), array(
2397 'tc_time' => time(),
2398 'tc_contents' => $text));
2404 * Triple brace replacement -- used for template arguments
2407 function argSubstitution( $matches ) {
2408 $arg = trim( $matches[1] );
2409 $text = $matches[0];
2410 $inputArgs = end( $this->mArgStack
);
2412 if ( array_key_exists( $arg, $inputArgs ) ) {
2413 $text = $inputArgs[$arg];
2420 * Returns true if the function is allowed to include this entity
2423 function incrementIncludeCount( $dbk ) {
2424 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2425 $this->mIncludeCount
[$dbk] = 0;
2427 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2435 * This function accomplishes several tasks:
2436 * 1) Auto-number headings if that option is enabled
2437 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2438 * 3) Add a Table of contents on the top for users who have enabled the option
2439 * 4) Auto-anchor headings
2441 * It loops through all headlines, collects the necessary data, then splits up the
2442 * string and re-inserts the newly formatted headlines.
2444 * @param string $text
2445 * @param boolean $isMain
2448 function formatHeadings( $text, $isMain=true ) {
2449 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2451 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2453 $forceTocHere = false;
2454 if( !$this->mTitle
->userCanEdit() ) {
2457 $showEditLink = $this->mOptions
->getEditSection();
2460 # Inhibit editsection links if requested in the page
2461 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2462 if( $esw->matchAndRemove( $text ) ) {
2465 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2467 $mw =& MagicWord
::get( MAG_NOTOC
);
2468 if( $mw->matchAndRemove( $text ) ) {
2472 # Get all headlines for numbering them and adding funky stuff like [edit]
2473 # links - this is for later, but we need the number of headlines right now
2474 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2476 # if there are fewer than 4 headlines in the article, do not show TOC
2477 if( $numMatches < 4 ) {
2481 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2482 # override above conditions and always show TOC at that place
2484 $mw =& MagicWord
::get( MAG_TOC
);
2485 if($mw->match( $text ) ) {
2487 $forceTocHere = true;
2489 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2490 # override above conditions and always show TOC above first header
2491 $mw =& MagicWord
::get( MAG_FORCETOC
);
2492 if ($mw->matchAndRemove( $text ) ) {
2497 # Never ever show TOC if no headers
2498 if( $numMatches < 1 ) {
2502 # We need this to perform operations on the HTML
2503 $sk =& $this->mOptions
->getSkin();
2507 $sectionCount = 0; # headlineCount excluding template sections
2509 # Ugh .. the TOC should have neat indentation levels which can be
2510 # passed to the skin functions. These are determined here
2514 $sublevelCount = array();
2515 $levelCount = array();
2522 foreach( $matches[3] as $headline ) {
2524 $templatetitle = '';
2525 $templatesection = 0;
2528 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2530 $templatetitle = base64_decode($mat[1]);
2531 $templatesection = 1 +
(int)base64_decode($mat[2]);
2532 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2536 $prevlevel = $level;
2537 $prevtoclevel = $toclevel;
2539 $level = $matches[1][$headlineCount];
2541 if( $doNumberHeadings ||
$doShowToc ) {
2543 if ( $level > $prevlevel ) {
2544 # Increase TOC level
2546 $sublevelCount[$toclevel] = 0;
2547 $toc .= $sk->tocIndent();
2549 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2550 # Decrease TOC level, find level to jump to
2552 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2553 # Can only go down to level 1
2556 for ($i = $toclevel; $i > 0; $i--) {
2557 if ( $levelCount[$i] == $level ) {
2558 # Found last matching level
2562 elseif ( $levelCount[$i] < $level ) {
2563 # Found first matching level below current level
2570 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2573 # No change in level, end TOC line
2574 $toc .= $sk->tocLineEnd();
2577 $levelCount[$toclevel] = $level;
2579 # count number of headlines for each level
2580 @$sublevelCount[$toclevel]++
;
2582 for( $i = 1; $i <= $toclevel; $i++
) {
2583 if( !empty( $sublevelCount[$i] ) ) {
2587 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2593 # The canonized header is a version of the header text safe to use for links
2594 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2595 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2596 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2598 # Remove link placeholders by the link text.
2599 # <!--LINK number-->
2601 # link text with suffix
2602 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2603 "\$this->mLinkHolders['texts'][\$1]",
2604 $canonized_headline );
2605 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2606 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2607 $canonized_headline );
2610 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2611 $tocline = trim( $canonized_headline );
2612 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2613 $replacearray = array(
2617 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2618 $refers[$headlineCount] = $canonized_headline;
2620 # count how many in assoc. array so we can track dupes in anchors
2621 @$refers[$canonized_headline]++
;
2622 $refcount[$headlineCount]=$refers[$canonized_headline];
2624 # Don't number the heading if it is the only one (looks silly)
2625 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2626 # the two are different if the line contains a link
2627 $headline=$numbering . ' ' . $headline;
2630 # Create the anchor for linking from the TOC to the section
2631 $anchor = $canonized_headline;
2632 if($refcount[$headlineCount] > 1 ) {
2633 $anchor .= '_' . $refcount[$headlineCount];
2635 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2636 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2638 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2639 if ( empty( $head[$headlineCount] ) ) {
2640 $head[$headlineCount] = '';
2643 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2645 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2648 # give headline the correct <h#> tag
2649 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2657 $toc .= $sk->tocUnindent( $toclevel - 1 );
2658 $toc = $sk->tocList( $toc );
2661 # split up and insert constructed headlines
2663 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2666 foreach( $blocks as $block ) {
2667 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2668 # This is the [edit] link that appears for the top block of text when
2669 # section editing is enabled
2671 # Disabled because it broke block formatting
2672 # For example, a bullet point in the top line
2673 # $full .= $sk->editSectionLink(0);
2676 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2677 # Top anchor now in skin
2681 if( !empty( $head[$i] ) ) {
2687 $mw =& MagicWord
::get( MAG_TOC
);
2688 return $mw->replace( $toc, $full );
2695 * Return an HTML link for the "ISBN 123456" text
2698 function magicISBN( $text ) {
2699 $fname = 'Parser::magicISBN';
2700 wfProfileIn( $fname );
2702 $a = split( 'ISBN ', ' '.$text );
2703 if ( count ( $a ) < 2 ) {
2704 wfProfileOut( $fname );
2707 $text = substr( array_shift( $a ), 1);
2708 $valid = '0123456789-Xx';
2710 foreach ( $a as $x ) {
2711 $isbn = $blank = '' ;
2712 while ( ' ' == $x{0} ) {
2714 $x = substr( $x, 1 );
2716 if ( $x == '' ) { # blank isbn
2717 $text .= "ISBN $blank";
2720 while ( strstr( $valid, $x{0} ) != false ) {
2722 $x = substr( $x, 1 );
2724 $num = str_replace( '-', '', $isbn );
2725 $num = str_replace( ' ', '', $num );
2726 $num = str_replace( 'x', 'X', $num );
2729 $text .= "ISBN $blank$x";
2731 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2732 $text .= '<a href="' .
2733 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2734 "\" class=\"internal\">ISBN $isbn</a>";
2738 wfProfileOut( $fname );
2743 * Return an HTML link for the "RFC 1234" text
2746 * @param string $text Text to be processed
2747 * @param string $keyword Magic keyword to use (default RFC)
2748 * @param string $urlmsg Interface message to use (default rfcurl)
2751 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2753 $valid = '0123456789';
2756 $a = split( $keyword, ' '.$text );
2757 if ( count ( $a ) < 2 ) {
2760 $text = substr( array_shift( $a ), 1);
2762 /* Check if keyword is preceed by [[.
2763 * This test is made here cause of the array_shift above
2764 * that prevent the test to be done in the foreach.
2766 if ( substr( $text, -2 ) == '[[' ) {
2770 foreach ( $a as $x ) {
2771 /* token might be empty if we have RFC RFC 1234 */
2779 /** remove and save whitespaces in $blank */
2780 while ( $x{0} == ' ' ) {
2782 $x = substr( $x, 1 );
2785 /** remove and save the rfc number in $id */
2786 while ( strstr( $valid, $x{0} ) != false ) {
2788 $x = substr( $x, 1 );
2792 /* call back stripped spaces*/
2793 $text .= $keyword.$blank.$x;
2794 } elseif( $internal ) {
2796 $text .= $keyword.$id.$x;
2798 /* build the external link*/
2799 $url = wfMsg( $urlmsg, $id);
2800 $sk =& $this->mOptions
->getSkin();
2801 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2802 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2805 /* Check if the next RFC keyword is preceed by [[ */
2806 $internal = ( substr($x,-2) == '[[' );
2812 * Transform wiki markup when saving a page by doing \r\n -> \n
2813 * conversion, substitting signatures, {{subst:}} templates, etc.
2815 * @param string $text the text to transform
2816 * @param Title &$title the Title object for the current article
2817 * @param User &$user the User object describing the current user
2818 * @param ParserOptions $options parsing options
2819 * @param bool $clearState whether to clear the parser state first
2820 * @return string the altered wiki markup
2823 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2824 $this->mOptions
= $options;
2825 $this->mTitle
=& $title;
2826 $this->mOutputType
= OT_WIKI
;
2828 if ( $clearState ) {
2829 $this->clearState();
2832 $stripState = false;
2836 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2837 $text = $this->strip( $text, $stripState, false );
2838 $text = $this->pstPass2( $text, $user );
2839 $text = $this->unstrip( $text, $stripState );
2840 $text = $this->unstripNoWiki( $text, $stripState );
2845 * Pre-save transform helper function
2848 function pstPass2( $text, &$user ) {
2849 global $wgContLang, $wgLocaltimezone;
2851 # Variable replacement
2852 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2853 $text = $this->replaceVariables( $text );
2857 $n = $user->getName();
2858 $k = $user->getOption( 'nickname' );
2859 if ( '' == $k ) { $k = $n; }
2860 if ( isset( $wgLocaltimezone ) ) {
2861 $oldtz = getenv( 'TZ' );
2862 putenv( 'TZ='.$wgLocaltimezone );
2865 /* Note: This is the timestamp saved as hardcoded wikitext to
2866 * the database, we use $wgContLang here in order to give
2867 * everyone the same signiture and use the default one rather
2868 * than the one selected in each users preferences.
2870 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
2871 ' (' . date( 'T' ) . ')';
2872 if ( isset( $wgLocaltimezone ) ) {
2873 putenv( 'TZ='.$oldtz );
2876 if( $user->getOption( 'fancysig' ) ) {
2879 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2881 $text = preg_replace( '/~~~~~/', $d, $text );
2882 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2883 $text = preg_replace( '/~~~/', $sigText, $text );
2885 # Context links: [[|name]] and [[name (context)|]]
2887 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2888 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2889 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2890 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2892 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2893 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2894 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2895 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2897 $t = $this->mTitle
->getText();
2898 if ( preg_match( $conpat, $t, $m ) ) {
2901 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2902 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2903 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2905 if ( '' == $context ) {
2906 $text = preg_replace( $p2, '[[\\1]]', $text );
2908 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2911 # Trim trailing whitespace
2912 # MAG_END (__END__) tag allows for trailing
2913 # whitespace to be deliberately included
2914 $text = rtrim( $text );
2915 $mw =& MagicWord
::get( MAG_END
);
2916 $mw->matchAndRemove( $text );
2922 * Set up some variables which are usually set up in parse()
2923 * so that an external function can call some class members with confidence
2926 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2927 $this->mTitle
=& $title;
2928 $this->mOptions
= $options;
2929 $this->mOutputType
= $outputType;
2930 if ( $clearState ) {
2931 $this->clearState();
2936 * Transform a MediaWiki message by replacing magic variables.
2938 * @param string $text the text to transform
2939 * @param ParserOptions $options options
2940 * @return string the text with variables substituted
2943 function transformMsg( $text, $options ) {
2945 static $executing = false;
2947 # Guard against infinite recursion
2953 $this->mTitle
= $wgTitle;
2954 $this->mOptions
= $options;
2955 $this->mOutputType
= OT_MSG
;
2956 $this->clearState();
2957 $text = $this->replaceVariables( $text );
2964 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2965 * Callback will be called with the text within
2966 * Transform and return the text within
2969 function setHook( $tag, $callback ) {
2970 $oldVal = @$this->mTagHooks
[$tag];
2971 $this->mTagHooks
[$tag] = $callback;
2976 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2977 * Placeholders created in Skin::makeLinkObj()
2978 * Returns an array of links found, indexed by PDBK:
2982 * $options is a bit field, RLH_FOR_UPDATE to select for update
2984 function replaceLinkHolders( &$text, $options = 0 ) {
2985 global $wgUser, $wgLinkCache;
2986 global $wgOutputReplace;
2988 $fname = 'Parser::replaceLinkHolders';
2989 wfProfileIn( $fname );
2993 $sk = $this->mOptions
->getSkin();
2995 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
2996 wfProfileIn( $fname.'-check' );
2997 $dbr =& wfGetDB( DB_SLAVE
);
2998 $page = $dbr->tableName( 'page' );
2999 $threshold = $wgUser->getOption('stubthreshold');
3002 asort( $this->mLinkHolders
['namespaces'] );
3006 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3008 $title = $this->mLinkHolders
['titles'][$key];
3010 # Skip invalid entries.
3011 # Result will be ugly, but prevents crash.
3012 if ( is_null( $title ) ) {
3015 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3017 # Check if it's in the link cache already
3018 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3019 $colours[$pdbk] = 1;
3020 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3021 $colours[$pdbk] = 0;
3023 # Not in the link cache, add it to the query
3024 if ( !isset( $current ) ) {
3026 $query = "SELECT page_id, page_namespace, page_title";
3027 if ( $threshold > 0 ) {
3028 $query .= ', page_len, page_is_redirect';
3030 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3031 } elseif ( $current != $val ) {
3033 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3038 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3043 if ( $options & RLH_FOR_UPDATE
) {
3044 $query .= ' FOR UPDATE';
3047 $res = $dbr->query( $query, $fname );
3049 # Fetch data and form into an associative array
3050 # non-existent = broken
3053 while ( $s = $dbr->fetchObject($res) ) {
3054 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3055 $pdbk = $title->getPrefixedDBkey();
3056 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3058 if ( $threshold > 0 ) {
3059 $size = $s->page_len
;
3060 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3061 $colours[$pdbk] = 1;
3063 $colours[$pdbk] = 2;
3066 $colours[$pdbk] = 1;
3070 wfProfileOut( $fname.'-check' );
3072 # Construct search and replace arrays
3073 wfProfileIn( $fname.'-construct' );
3074 $wgOutputReplace = array();
3075 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3076 $pdbk = $pdbks[$key];
3077 $searchkey = "<!--LINK $key-->";
3078 $title = $this->mLinkHolders
['titles'][$key];
3079 if ( empty( $colours[$pdbk] ) ) {
3080 $wgLinkCache->addBadLinkObj( $title );
3081 $colours[$pdbk] = 0;
3082 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3083 $this->mLinkHolders
['texts'][$key],
3084 $this->mLinkHolders
['queries'][$key] );
3085 } elseif ( $colours[$pdbk] == 1 ) {
3086 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3087 $this->mLinkHolders
['texts'][$key],
3088 $this->mLinkHolders
['queries'][$key] );
3089 } elseif ( $colours[$pdbk] == 2 ) {
3090 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3091 $this->mLinkHolders
['texts'][$key],
3092 $this->mLinkHolders
['queries'][$key] );
3095 wfProfileOut( $fname.'-construct' );
3098 wfProfileIn( $fname.'-replace' );
3100 $text = preg_replace_callback(
3101 '/(<!--LINK .*?-->)/',
3102 "wfOutputReplaceMatches",
3105 wfProfileOut( $fname.'-replace' );
3108 # Now process interwiki link holders
3109 # This is quite a bit simpler than internal links
3110 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3111 wfProfileIn( $fname.'-interwiki' );
3112 # Make interwiki link HTML
3113 $wgOutputReplace = array();
3114 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3115 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3116 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3119 $text = preg_replace_callback(
3120 '/<!--IWLINK (.*?)-->/',
3121 "wfOutputReplaceMatches",
3123 wfProfileOut( $fname.'-interwiki' );
3126 wfProfileOut( $fname );
3131 * Replace <!--LINK--> link placeholders with plain text of links
3132 * (not HTML-formatted).
3133 * @param string $text
3136 function replaceLinkHoldersText( $text ) {
3137 global $wgUser, $wgLinkCache;
3138 global $wgOutputReplace;
3140 $fname = 'Parser::replaceLinkHoldersText';
3141 wfProfileIn( $fname );
3143 $text = preg_replace_callback(
3144 '/<!--(LINK|IWLINK) (.*?)-->/',
3145 array( &$this, 'replaceLinkHoldersTextCallback' ),
3148 wfProfileOut( $fname );
3153 * @param array $matches
3157 function replaceLinkHoldersTextCallback( $matches ) {
3158 $type = $matches[1];
3160 if( $type == 'LINK' ) {
3161 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3162 return $this->mLinkHolders
['texts'][$key];
3164 } elseif( $type == 'IWLINK' ) {
3165 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3166 return $this->mInterwikiLinkHolders
['texts'][$key];
3173 * Renders an image gallery from a text with one line per image.
3174 * text labels may be given by using |-style alternative text. E.g.
3175 * Image:one.jpg|The number "1"
3176 * Image:tree.jpg|A tree
3177 * given as text will return the HTML of a gallery with two images,
3178 * labeled 'The number "1"' and
3183 function renderImageGallery( $text ) {
3185 global $wgUser, $wgTitle;
3186 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3187 $localParser = new Parser();
3189 global $wgLinkCache;
3190 $ig = new ImageGallery();
3191 $ig->setShowBytes( false );
3192 $ig->setShowFilename( false );
3193 $lines = explode( "\n", $text );
3195 foreach ( $lines as $line ) {
3196 # match lines like these:
3197 # Image:someimage.jpg|This is some image
3198 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3200 if ( count( $matches ) == 0 ) {
3203 $nt = Title
::newFromURL( $matches[1] );
3204 if( is_null( $nt ) ) {
3205 # Bogus title. Ignore these so we don't bomb out later.
3208 if ( isset( $matches[3] ) ) {
3209 $label = $matches[3];
3214 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3215 $html = $html->mText
;
3217 $ig->add( new Image( $nt ), $html );
3218 $wgLinkCache->addImageLinkObj( $nt );
3220 return $ig->toHTML();
3224 * Parse image options text and use it to make an image
3226 function makeImage( &$nt, $options ) {
3227 global $wgContLang, $wgUseImageResize;
3228 global $wgUser, $wgThumbLimits;
3232 # Check if the options text is of the form "options|alt text"
3234 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3235 # * left no resizing, just left align. label is used for alt= only
3236 # * right same, but right aligned
3237 # * none same, but not aligned
3238 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3239 # * center center the image
3240 # * framed Keep original image size, no magnify-button.
3242 $part = explode( '|', $options);
3244 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3245 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3246 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3247 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3248 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3249 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3250 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3251 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3254 $width = $height = $framed = $thumb = false;
3255 $manual_thumb = '' ;
3257 foreach( $part as $key => $val ) {
3258 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3260 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3261 # use manually specified thumbnail
3263 $manual_thumb = $match;
3264 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3265 # remember to set an alignment, don't render immediately
3267 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3268 # remember to set an alignment, don't render immediately
3270 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3271 # remember to set an alignment, don't render immediately
3273 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3274 # remember to set an alignment, don't render immediately
3276 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3277 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3278 # $match is the image width in pixels
3279 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3280 $width = intval( $m[1] );
3281 $height = intval( $m[2] );
3283 $width = intval($match);
3285 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3291 # Strip bad stuff out of the alt text
3292 $alt = $this->replaceLinkHoldersText( $caption );
3293 $alt = Sanitizer
::stripAllTags( $alt );
3295 # Linker does the rest
3296 $sk =& $this->mOptions
->getSkin();
3297 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3301 * Set a flag in the output object indicating that the content is dynamic and
3302 * shouldn't be cached.
3304 function disableCache() {
3305 $this->mOutput
->mCacheTime
= -1;
3311 * @package MediaWiki
3315 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3316 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3317 var $mVersion; # Compatibility check
3318 var $mTitleText; # title text of the chosen language variant
3320 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3321 $containsOldMagic = false, $titletext = '' )
3323 $this->mText
= $text;
3324 $this->mLanguageLinks
= $languageLinks;
3325 $this->mCategoryLinks
= $categoryLinks;
3326 $this->mContainsOldMagic
= $containsOldMagic;
3327 $this->mCacheTime
= '';
3328 $this->mVersion
= MW_PARSER_VERSION
;
3329 $this->mTitleText
= $titletext;
3332 function getText() { return $this->mText
; }
3333 function getLanguageLinks() { return $this->mLanguageLinks
; }
3334 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3335 function getCacheTime() { return $this->mCacheTime
; }
3336 function getTitleText() { return $this->mTitleText
; }
3337 function containsOldMagic() { return $this->mContainsOldMagic
; }
3338 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3339 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3340 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3341 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3342 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3343 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3345 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3347 function merge( $other ) {
3348 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3349 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3350 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3354 * Return true if this cached output object predates the global or
3355 * per-article cache invalidation timestamps, or if it comes from
3356 * an incompatible older version.
3358 * @param string $touched the affected article's last touched timestamp
3362 function expired( $touched ) {
3363 global $wgCacheEpoch;
3364 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3365 $this->getCacheTime() <= $touched ||
3366 $this->getCacheTime() <= $wgCacheEpoch ||
3367 !isset( $this->mVersion
) ||
3368 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3373 * Set options of the Parser
3375 * @package MediaWiki
3379 # All variables are private
3380 var $mUseTeX; # Use texvc to expand <math> tags
3381 var $mUseDynamicDates; # Use DateFormatter to format dates
3382 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3383 var $mAllowExternalImages; # Allow external images inline
3384 var $mSkin; # Reference to the preferred skin
3385 var $mDateFormat; # Date format index
3386 var $mEditSection; # Create "edit section" links
3387 var $mNumberHeadings; # Automatically number headings
3388 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3390 function getUseTeX() { return $this->mUseTeX
; }
3391 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3392 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3393 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3394 function &getSkin() { return $this->mSkin
; }
3395 function getDateFormat() { return $this->mDateFormat
; }
3396 function getEditSection() { return $this->mEditSection
; }
3397 function getNumberHeadings() { return $this->mNumberHeadings
; }
3398 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3401 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3402 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3403 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3404 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3405 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3406 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3407 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3408 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3410 function setSkin( &$x ) { $this->mSkin
=& $x; }
3412 function ParserOptions() {
3414 $this->initialiseFromUser( $wgUser );
3418 * Get parser options
3421 function newFromUser( &$user ) {
3422 $popts = new ParserOptions
;
3423 $popts->initialiseFromUser( $user );
3427 /** Get user options */
3428 function initialiseFromUser( &$userInput ) {
3429 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3430 $wgAllowSpecialInclusion;
3431 $fname = 'ParserOptions::initialiseFromUser';
3432 wfProfileIn( $fname );
3433 if ( !$userInput ) {
3435 $user->setLoaded( true );
3437 $user =& $userInput;
3440 $this->mUseTeX
= $wgUseTeX;
3441 $this->mUseDynamicDates
= $wgUseDynamicDates;
3442 $this->mInterwikiMagic
= $wgInterwikiMagic;
3443 $this->mAllowExternalImages
= $wgAllowExternalImages;
3444 wfProfileIn( $fname.'-skin' );
3445 $this->mSkin
=& $user->getSkin();
3446 wfProfileOut( $fname.'-skin' );
3447 $this->mDateFormat
= $user->getOption( 'date' );
3448 $this->mEditSection
= true;
3449 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3450 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3451 wfProfileOut( $fname );
3456 * Callback function used by Parser::replaceLinkHolders()
3457 * to substitute link placeholders.
3459 function &wfOutputReplaceMatches( $matches ) {
3460 global $wgOutputReplace;
3461 return $wgOutputReplace[$matches[1]];
3465 * Return the total number of articles
3467 function wfNumberOfArticles() {
3468 global $wgNumberOfArticles;
3471 return $wgNumberOfArticles;
3475 * Return the number of files
3477 function wfNumberOfFiles() {
3478 $fname = 'Parser::wfNumberOfFiles';
3480 wfProfileIn( $fname );
3481 $dbr =& wfGetDB( DB_SLAVE
);
3482 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3483 wfProfileOut( $fname );
3489 * Get various statistics from the database
3492 function wfLoadSiteStats() {
3493 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3494 $fname = 'wfLoadSiteStats';
3496 if ( -1 != $wgNumberOfArticles ) return;
3497 $dbr =& wfGetDB( DB_SLAVE
);
3498 $s = $dbr->selectRow( 'site_stats',
3499 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3500 array( 'ss_row_id' => 1 ), $fname
3503 if ( $s === false ) {
3506 $wgTotalViews = $s->ss_total_views
;
3507 $wgTotalEdits = $s->ss_total_edits
;
3508 $wgNumberOfArticles = $s->ss_good_articles
;
3514 * Basicly replacing " > and < with HTML entities ( ", >, <)
3516 * @param string $in Text that might contain HTML tags
3517 * @return string Escaped string
3519 function wfEscapeHTMLTagsOnly( $in ) {
3521 array( '"', '>', '<' ),
3522 array( '"', '>', '<' ),