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();
123 $this->mTemplates
= array();
124 $this->mTemplatePath
= array();
125 $this->mTagHooks
= array();
134 function clearState() {
135 $this->mOutput
= new ParserOutput
;
136 $this->mAutonumber
= 0;
137 $this->mLastSection
= '';
138 $this->mDTopen
= false;
139 $this->mVariables
= false;
140 $this->mIncludeCount
= array();
141 $this->mStripState
= array();
142 $this->mArgStack
= array();
143 $this->mInPre
= false;
144 $this->mInterwikiLinkHolders
= array(
148 $this->mLinkHolders
= array(
149 'namespaces' => array(),
151 'queries' => array(),
158 * First pass--just handle <nowiki> sections, pass the rest off
159 * to internalParse() which does all the real work.
162 * @param string $text Text we want to parse
163 * @param Title &$title A title object
164 * @param array $options
165 * @param boolean $linestart
166 * @param boolean $clearState
167 * @return ParserOutput a ParserOutput
169 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
170 global $wgUseTidy, $wgContLang;
171 $fname = 'Parser::parse';
172 wfProfileIn( $fname );
178 $this->mOptions
= $options;
179 $this->mTitle
=& $title;
180 $this->mOutputType
= OT_HTML
;
182 $this->mStripState
= NULL;
184 //$text = $this->strip( $text, $this->mStripState );
185 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
186 $x =& $this->mStripState
;
188 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
189 $text = $this->strip( $text, $x );
190 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
192 $text = $this->internalParse( $text );
194 $text = $this->unstrip( $text, $this->mStripState
);
196 # Clean up special characters, only run once, next-to-last before doBlockLevels
198 # french spaces, last one Guillemet-left
199 # only if there is something before the space
200 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
201 # french spaces, Guillemet-right
202 '/(\\302\\253) /' => '\\1 ',
203 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
205 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
208 $text = $this->doBlockLevels( $text, $linestart );
210 $this->replaceLinkHolders( $text );
212 # the position of the convert() call should not be changed. it
213 # assumes that the links are all replaces and the only thing left
214 # is the <nowiki> mark.
215 $text = $wgContLang->convert($text);
216 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
218 $text = $this->unstripNoWiki( $text, $this->mStripState
);
220 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
222 $text = Sanitizer
::normalizeCharReferences( $text );
225 $text = Parser
::tidy($text);
228 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
230 $this->mOutput
->setText( $text );
231 wfProfileOut( $fname );
232 return $this->mOutput
;
236 * Get a random string
241 function getRandomString() {
242 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
246 * Replaces all occurrences of <$tag>content</$tag> in the text
247 * with a random marker and returns the new text. the output parameter
248 * $content will be an associative array filled with data on the form
249 * $unique_marker => content.
251 * If $content is already set, the additional entries will be appended
252 * If $tag is set to STRIP_COMMENTS, the function will extract
253 * <!-- HTML comments -->
258 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
259 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
274 if( $tag == STRIP_COMMENTS
) {
278 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
279 $end = "/<\\/$tag\\s*>/i";
282 while ( '' != $text ) {
283 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
285 if( count( $p ) < 3 ) {
291 $marker = $rnd . sprintf('%08X', $n++
);
292 $stripped .= $marker;
294 $tags[$marker] = "<$tag$attributes>";
295 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
297 $q = preg_split( $end, $inside, 2 );
298 $content[$marker] = $q[0];
299 if( count( $q ) < 2 ) {
300 # No end tag -- let it run out to the end of the text.
310 * Wrapper function for extractTagsAndParams
311 * for cases where $tags and $params isn't needed
312 * i.e. where tags will never have params, like <nowiki>
317 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
318 $dummy_tags = array();
319 $dummy_params = array();
321 return Parser
::extractTagsAndParams( $tag, $text, $content,
322 $dummy_tags, $dummy_params, $uniq_prefix );
326 * Strips and renders nowiki, pre, math, hiero
327 * If $render is set, performs necessary rendering operations on plugins
328 * Returns the text, and fills an array with data needed in unstrip()
329 * If the $state is already a valid strip state, it adds to the state
331 * @param bool $stripcomments when set, HTML comments <!-- like this -->
332 * will be stripped in addition to other tags. This is important
333 * for section editing, where these comments cause confusion when
334 * counting the sections in the wikisource
338 function strip( $text, &$state, $stripcomments = false ) {
339 $render = ($this->mOutputType
== OT_HTML
);
340 $html_content = array();
341 $nowiki_content = array();
342 $math_content = array();
343 $pre_content = array();
344 $comment_content = array();
345 $ext_content = array();
347 $ext_params = array();
348 $gallery_content = array();
350 # Replace any instances of the placeholders
351 $uniq_prefix = UNIQ_PREFIX
;
352 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
357 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
358 foreach( $html_content as $marker => $content ) {
360 # Raw and unchecked for validity.
361 $html_content[$marker] = $content;
363 $html_content[$marker] = '<html>'.$content.'</html>';
369 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
370 foreach( $nowiki_content as $marker => $content ) {
372 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
374 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
379 if( $this->mOptions
->getUseTeX() ) {
380 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
381 foreach( $math_content as $marker => $content ){
383 $math_content[$marker] = renderMath( $content );
385 $math_content[$marker] = '<math>'.$content.'</math>';
391 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
392 foreach( $pre_content as $marker => $content ){
394 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
396 $pre_content[$marker] = '<pre>'.$content.'</pre>';
401 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
402 foreach( $gallery_content as $marker => $content ) {
403 require_once( 'ImageGallery.php' );
405 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
407 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
413 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
414 foreach( $comment_content as $marker => $content ){
415 $comment_content[$marker] = '<!--'.$content.'-->';
420 foreach ( $this->mTagHooks
as $tag => $callback ) {
421 $ext_content[$tag] = array();
422 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
423 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
424 foreach( $ext_content[$tag] as $marker => $content ) {
425 $full_tag = $ext_tags[$tag][$marker];
426 $params = $ext_params[$tag][$marker];
428 $ext_content[$tag][$marker] = $callback( $content, $params, $this );
430 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
435 # Merge state with the pre-existing state, if there is one
437 $state['html'] = $state['html'] +
$html_content;
438 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
439 $state['math'] = $state['math'] +
$math_content;
440 $state['pre'] = $state['pre'] +
$pre_content;
441 $state['comment'] = $state['comment'] +
$comment_content;
442 $state['gallery'] = $state['gallery'] +
$gallery_content;
444 foreach( $ext_content as $tag => $array ) {
445 if ( array_key_exists( $tag, $state ) ) {
446 $state[$tag] = $state[$tag] +
$array;
451 'html' => $html_content,
452 'nowiki' => $nowiki_content,
453 'math' => $math_content,
454 'pre' => $pre_content,
455 'comment' => $comment_content,
456 'gallery' => $gallery_content,
463 * restores pre, math, and hiero removed by strip()
465 * always call unstripNoWiki() after this one
468 function unstrip( $text, &$state ) {
469 if ( !is_array( $state ) ) {
473 # Must expand in reverse order, otherwise nested tags will be corrupted
474 $contentDict = end( $state );
475 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
476 if( key($state) != 'nowiki' && key($state) != 'html') {
477 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
478 $text = str_replace( key( $contentDict ), $content, $text );
487 * always call this after unstrip() to preserve the order
491 function unstripNoWiki( $text, &$state ) {
492 if ( !is_array( $state ) ) {
496 # Must expand in reverse order, otherwise nested tags will be corrupted
497 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
498 $text = str_replace( key( $state['nowiki'] ), $content, $text );
503 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
504 $text = str_replace( key( $state['html'] ), $content, $text );
512 * Add an item to the strip state
513 * Returns the unique tag which must be inserted into the stripped text
514 * The tag will be replaced with the original text in unstrip()
518 function insertStripItem( $text, &$state ) {
519 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
526 'comment' => array(),
527 'gallery' => array(),
530 $state['item'][$rnd] = $text;
535 * Interface with html tidy, used if $wgUseTidy = true.
536 * If tidy isn't able to correct the markup, the original will be
537 * returned in all its glory with a warning comment appended.
539 * Either the external tidy program or the in-process tidy extension
540 * will be used depending on availability. Override the default
541 * $wgTidyInternal setting to disable the internal if it's not working.
543 * @param string $text Hideous HTML input
544 * @return string Corrected HTML output
548 function tidy( $text ) {
549 global $wgTidyInternal;
550 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
551 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
552 '<head><title>test</title></head><body>'.$text.'</body></html>';
553 if( $wgTidyInternal ) {
554 $correctedtext = Parser
::internalTidy( $wrappedtext );
556 $correctedtext = Parser
::externalTidy( $wrappedtext );
558 if( is_null( $correctedtext ) ) {
559 wfDebug( "Tidy error detected!\n" );
560 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
562 return $correctedtext;
566 * Spawn an external HTML tidy process and get corrected markup back from it.
571 function externalTidy( $text ) {
572 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
573 $fname = 'Parser::externalTidy';
574 wfProfileIn( $fname );
579 $descriptorspec = array(
580 0 => array('pipe', 'r'),
581 1 => array('pipe', 'w'),
582 2 => array('file', '/dev/null', 'a')
585 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
586 if (is_resource($process)) {
587 fwrite($pipes[0], $text);
589 while (!feof($pipes[1])) {
590 $cleansource .= fgets($pipes[1], 1024);
593 proc_close($process);
596 wfProfileOut( $fname );
598 if( $cleansource == '' && $text != '') {
599 // Some kind of error happened, so we couldn't get the corrected text.
600 // Just give up; we'll use the source text and append a warning.
608 * Use the HTML tidy PECL extension to use the tidy library in-process,
609 * saving the overhead of spawning a new process. Currently written to
610 * the PHP 4.3.x version of the extension, may not work on PHP 5.
612 * 'pear install tidy' should be able to compile the extension module.
617 function internalTidy( $text ) {
619 $fname = 'Parser::internalTidy';
620 wfProfileIn( $fname );
622 tidy_load_config( $wgTidyConf );
623 tidy_set_encoding( 'utf8' );
624 tidy_parse_string( $text );
626 if( tidy_get_status() == 2 ) {
627 // 2 is magic number for fatal error
628 // http://www.php.net/manual/en/function.tidy-get-status.php
631 $cleansource = tidy_get_output();
633 wfProfileOut( $fname );
638 * parse the wiki syntax used to render tables
642 function doTableStuff ( $t ) {
643 $fname = 'Parser::doTableStuff';
644 wfProfileIn( $fname );
646 $t = explode ( "\n" , $t ) ;
647 $td = array () ; # Is currently a td tag open?
648 $ltd = array () ; # Was it TD or TH?
649 $tr = array () ; # Is currently a tr tag open?
650 $ltr = array () ; # tr attributes
651 $indent_level = 0; # indent level of the table
652 foreach ( $t AS $k => $x )
655 $fc = substr ( $x , 0 , 1 ) ;
656 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
657 $indent_level = strlen( $matches[1] );
659 $attributes = $this->unstripForHTML( $matches[2] );
661 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
662 '<table' . Sanitizer
::fixTagAttributes ( $attributes, '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 $attributes = $this->unstripForHTML( $x );
690 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
692 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
694 if ( '|+' == substr ( $x , 0 , 2 ) ) {
696 $x = substr ( $x , 1 ) ;
698 $after = substr ( $x , 1 ) ;
699 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
700 $after = explode ( '||' , $after ) ;
703 # Loop through each table cell
704 foreach ( $after AS $theline )
709 $tra = array_pop ( $ltr ) ;
710 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
711 array_push ( $tr , true ) ;
712 array_push ( $ltr , '' ) ;
715 $l = array_pop ( $ltd ) ;
716 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
717 if ( $fc == '|' ) $l = 'td' ;
718 else if ( $fc == '!' ) $l = 'th' ;
719 else if ( $fc == '+' ) $l = 'caption' ;
721 array_push ( $ltd , $l ) ;
724 $y = explode ( '|' , $theline , 2 ) ;
725 # Note that a '|' inside an invalid link should not
726 # be mistaken as delimiting cell parameters
727 if ( strpos( $y[0], '[[' ) !== false ) {
728 $y = array ($theline);
730 if ( count ( $y ) == 1 )
731 $y = "{$z}<{$l}>{$y[0]}" ;
733 $attributes = $this->unstripForHTML( $y[0] );
734 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
737 array_push ( $td , true ) ;
742 # Closing open td, tr && table
743 while ( count ( $td ) > 0 )
745 if ( array_pop ( $td ) ) $t[] = '</td>' ;
746 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
750 $t = implode ( "\n" , $t ) ;
751 wfProfileOut( $fname );
756 * Helper function for parse() that transforms wiki markup into
757 * HTML. Only called for $mOutputType == OT_HTML.
761 function internalParse( $text ) {
765 $fname = 'Parser::internalParse';
766 wfProfileIn( $fname );
768 # Remove <noinclude> tags and <includeonly> sections
769 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
770 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
772 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
773 $text = $this->replaceVariables( $text, $args );
775 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
777 $text = $this->doHeadings( $text );
778 if($this->mOptions
->getUseDynamicDates()) {
779 $df =& DateFormatter
::getInstance();
780 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
782 $text = $this->doAllQuotes( $text );
783 $text = $this->replaceInternalLinks( $text );
784 $text = $this->replaceExternalLinks( $text );
786 # replaceInternalLinks may sometimes leave behind
787 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
788 $text = str_replace(UNIQ_PREFIX
."NOPARSE", "", $text);
790 $text = $this->doMagicLinks( $text );
791 $text = $this->doTableStuff( $text );
792 $text = $this->formatHeadings( $text, $isMain );
794 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
795 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
797 wfProfileOut( $fname );
801 function scarySubstitution($matches) {
802 # return "[[".$matches[0]."]]";
803 return $this->mIWTransData
[(int)$matches[0]];
807 * Replace special strings like "ISBN xxx" and "RFC xxx" with
808 * magic external links.
812 function &doMagicLinks( &$text ) {
813 $text = $this->magicISBN( $text );
814 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
815 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
820 * Parse ^^ tokens and return html
824 function doExponent( $text ) {
825 $fname = 'Parser::doExponent';
826 wfProfileIn( $fname );
827 $text = preg_replace('/\^\^(.*?)\^\^/','<small><sup>\\1</sup></small>', $text);
828 wfProfileOut( $fname );
833 * Parse headers and return html
837 function doHeadings( $text ) {
838 $fname = 'Parser::doHeadings';
839 wfProfileIn( $fname );
840 for ( $i = 6; $i >= 1; --$i ) {
841 $h = substr( '======', 0, $i );
842 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
843 "<h{$i}>\\1</h{$i}>\\2", $text );
845 wfProfileOut( $fname );
850 * Replace single quotes with HTML markup
852 * @return string the altered text
854 function doAllQuotes( $text ) {
855 $fname = 'Parser::doAllQuotes';
856 wfProfileIn( $fname );
858 $lines = explode( "\n", $text );
859 foreach ( $lines as $line ) {
860 $outtext .= $this->doQuotes ( $line ) . "\n";
862 $outtext = substr($outtext, 0,-1);
863 wfProfileOut( $fname );
868 * Helper function for doAllQuotes()
871 function doQuotes( $text ) {
872 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
873 if ( count( $arr ) == 1 )
877 # First, do some preliminary work. This may shift some apostrophes from
878 # being mark-up to being text. It also counts the number of occurrences
879 # of bold and italics mark-ups.
883 foreach ( $arr as $r )
885 if ( ( $i %
2 ) == 1 )
887 # If there are ever four apostrophes, assume the first is supposed to
888 # be text, and the remaining three constitute mark-up for bold text.
889 if ( strlen( $arr[$i] ) == 4 )
894 # If there are more than 5 apostrophes in a row, assume they're all
895 # text except for the last 5.
896 else if ( strlen( $arr[$i] ) > 5 )
898 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
901 # Count the number of occurrences of bold and italics mark-ups.
902 # We are not counting sequences of five apostrophes.
903 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
904 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
905 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
910 # If there is an odd number of both bold and italics, it is likely
911 # that one of the bold ones was meant to be an apostrophe followed
912 # by italics. Which one we cannot know for certain, but it is more
913 # likely to be one that has a single-letter word before it.
914 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
917 $firstsingleletterword = -1;
918 $firstmultiletterword = -1;
920 foreach ( $arr as $r )
922 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
924 $x1 = substr ($arr[$i-1], -1);
925 $x2 = substr ($arr[$i-1], -2, 1);
927 if ($firstspace == -1) $firstspace = $i;
928 } else if ($x2 == ' ') {
929 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
931 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
937 # If there is a single-letter word, use it!
938 if ($firstsingleletterword > -1)
940 $arr [ $firstsingleletterword ] = "''";
941 $arr [ $firstsingleletterword-1 ] .= "'";
943 # If not, but there's a multi-letter word, use that one.
944 else if ($firstmultiletterword > -1)
946 $arr [ $firstmultiletterword ] = "''";
947 $arr [ $firstmultiletterword-1 ] .= "'";
949 # ... otherwise use the first one that has neither.
950 # (notice that it is possible for all three to be -1 if, for example,
951 # there is only one pentuple-apostrophe in the line)
952 else if ($firstspace > -1)
954 $arr [ $firstspace ] = "''";
955 $arr [ $firstspace-1 ] .= "'";
959 # Now let's actually convert our apostrophic mush to HTML!
968 if ($state == 'both')
975 if (strlen ($r) == 2)
978 { $output .= '</i>'; $state = ''; }
979 else if ($state == 'bi')
980 { $output .= '</i>'; $state = 'b'; }
981 else if ($state == 'ib')
982 { $output .= '</b></i><b>'; $state = 'b'; }
983 else if ($state == 'both')
984 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
985 else # $state can be 'b' or ''
986 { $output .= '<i>'; $state .= 'i'; }
988 else if (strlen ($r) == 3)
991 { $output .= '</b>'; $state = ''; }
992 else if ($state == 'bi')
993 { $output .= '</i></b><i>'; $state = 'i'; }
994 else if ($state == 'ib')
995 { $output .= '</b>'; $state = 'i'; }
996 else if ($state == 'both')
997 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
998 else # $state can be 'i' or ''
999 { $output .= '<b>'; $state .= 'b'; }
1001 else if (strlen ($r) == 5)
1004 { $output .= '</b><i>'; $state = 'i'; }
1005 else if ($state == 'i')
1006 { $output .= '</i><b>'; $state = 'b'; }
1007 else if ($state == 'bi')
1008 { $output .= '</i></b>'; $state = ''; }
1009 else if ($state == 'ib')
1010 { $output .= '</b></i>'; $state = ''; }
1011 else if ($state == 'both')
1012 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1013 else # ($state == '')
1014 { $buffer = ''; $state = 'both'; }
1019 # Now close all remaining tags. Notice that the order is important.
1020 if ($state == 'b' ||
$state == 'ib')
1022 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1026 if ($state == 'both')
1027 $output .= '<b><i>'.$buffer.'</i></b>';
1033 * Replace external links
1035 * Note: this is all very hackish and the order of execution matters a lot.
1036 * Make sure to run maintenance/parserTests.php if you change this code.
1040 function replaceExternalLinks( $text ) {
1042 $fname = 'Parser::replaceExternalLinks';
1043 wfProfileIn( $fname );
1045 $sk =& $this->mOptions
->getSkin();
1047 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1049 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1052 while ( $i<count( $bits ) ) {
1054 $protocol = $bits[$i++
];
1055 $text = $bits[$i++
];
1056 $trail = $bits[$i++
];
1058 # The characters '<' and '>' (which were escaped by
1059 # removeHTMLtags()) should not be included in
1060 # URLs, per RFC 2396.
1061 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1062 $text = substr($url, $m2[0][1]) . ' ' . $text;
1063 $url = substr($url, 0, $m2[0][1]);
1066 # If the link text is an image URL, replace it with an <img> tag
1067 # This happened by accident in the original parser, but some people used it extensively
1068 $img = $this->maybeMakeExternalImage( $text );
1069 if ( $img !== false ) {
1075 # Set linktype for CSS - if URL==text, link is essentially free
1076 $linktype = ($text == $url) ?
'free' : 'text';
1078 # No link text, e.g. [http://domain.tld/some.link]
1079 if ( $text == '' ) {
1080 # Autonumber if allowed
1081 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1082 $text = '[' . ++
$this->mAutonumber
. ']';
1083 $linktype = 'autonumber';
1085 # Otherwise just use the URL
1086 $text = htmlspecialchars( $url );
1090 # Have link text, e.g. [http://domain.tld/some.link text]s
1092 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1095 $text = $wgContLang->markNoConversion($text);
1097 # Replace & from obsolete syntax with &.
1098 # All HTML entities will be escaped by makeExternalLink()
1099 # or maybeMakeExternalImage()
1100 $url = str_replace( '&', '&', $url );
1102 # Process the trail (i.e. everything after this link up until start of the next link),
1103 # replacing any non-bracketed links
1104 $trail = $this->replaceFreeExternalLinks( $trail );
1107 # Use the encoded URL
1108 # This means that users can paste URLs directly into the text
1109 # Funny characters like ö aren't valid in URLs anyway
1110 # This was changed in August 2004
1111 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1114 wfProfileOut( $fname );
1119 * Replace anything that looks like a URL with a link
1122 function replaceFreeExternalLinks( $text ) {
1123 global $wgUrlProtocols;
1125 $fname = 'Parser::replaceFreeExternalLinks';
1126 wfProfileIn( $fname );
1128 $bits = preg_split( '/(\b(?:'.$wgUrlProtocols.'))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1129 $s = array_shift( $bits );
1132 $sk =& $this->mOptions
->getSkin();
1134 while ( $i < count( $bits ) ){
1135 $protocol = $bits[$i++
];
1136 $remainder = $bits[$i++
];
1138 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1139 # Found some characters after the protocol that look promising
1140 $url = $protocol . $m[1];
1143 # The characters '<' and '>' (which were escaped by
1144 # removeHTMLtags()) should not be included in
1145 # URLs, per RFC 2396.
1146 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1147 $trail = substr($url, $m2[0][1]) . $trail;
1148 $url = substr($url, 0, $m2[0][1]);
1151 # Move trailing punctuation to $trail
1153 # If there is no left bracket, then consider right brackets fair game too
1154 if ( strpos( $url, '(' ) === false ) {
1158 $numSepChars = strspn( strrev( $url ), $sep );
1159 if ( $numSepChars ) {
1160 $trail = substr( $url, -$numSepChars ) . $trail;
1161 $url = substr( $url, 0, -$numSepChars );
1164 # Replace & from obsolete syntax with &.
1165 # All HTML entities will be escaped by makeExternalLink()
1166 # or maybeMakeExternalImage()
1167 $url = str_replace( '&', '&', $url );
1169 # Is this an external image?
1170 $text = $this->maybeMakeExternalImage( $url );
1171 if ( $text === false ) {
1172 # Not an image, make a link
1173 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1175 $s .= $text . $trail;
1177 $s .= $protocol . $remainder;
1180 wfProfileOut( $fname );
1185 * make an image if it's allowed
1188 function maybeMakeExternalImage( $url ) {
1189 $sk =& $this->mOptions
->getSkin();
1191 if ( $this->mOptions
->getAllowExternalImages() ) {
1192 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1194 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1201 * Process [[ ]] wikilinks
1205 function replaceInternalLinks( $s ) {
1206 global $wgContLang, $wgLinkCache, $wgUrlProtocols;
1207 static $fname = 'Parser::replaceInternalLinks' ;
1209 wfProfileIn( $fname );
1211 wfProfileIn( $fname.'-setup' );
1213 # the % is needed to support urlencoded titles as well
1214 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1216 $sk =& $this->mOptions
->getSkin();
1218 #split the entire text string on occurences of [[
1219 $a = explode( '[[', ' ' . $s );
1220 #get the first element (all text up to first [[), and remove the space we added
1221 $s = array_shift( $a );
1222 $s = substr( $s, 1 );
1224 # Match a link having the form [[namespace:link|alternate]]trail
1226 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1227 # Match cases where there is no "]]", which might still be images
1228 static $e1_img = FALSE;
1229 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1230 # Match the end of a line for a word that's not followed by whitespace,
1231 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1232 $e2 = wfMsgForContent( 'linkprefix' );
1234 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1236 if( is_null( $this->mTitle
) ) {
1237 wfDebugDieBacktrace( 'nooo' );
1239 $nottalk = !$this->mTitle
->isTalkPage();
1241 if ( $useLinkPrefixExtension ) {
1242 if ( preg_match( $e2, $s, $m ) ) {
1243 $first_prefix = $m[2];
1245 $first_prefix = false;
1251 $selflink = $this->mTitle
->getPrefixedText();
1252 wfProfileOut( $fname.'-setup' );
1254 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1255 $useSubpages = $this->areSubpagesAllowed();
1257 # Loop for each link
1258 for ($k = 0; isset( $a[$k] ); $k++
) {
1260 if ( $useLinkPrefixExtension ) {
1261 wfProfileIn( $fname.'-prefixhandling' );
1262 if ( preg_match( $e2, $s, $m ) ) {
1270 $prefix = $first_prefix;
1271 $first_prefix = false;
1273 wfProfileOut( $fname.'-prefixhandling' );
1276 $might_be_img = false;
1278 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1280 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1281 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1282 # the real problem is with the $e1 regex
1285 # Still some problems for cases where the ] is meant to be outside punctuation,
1286 # and no image is in sight. See bug 2095.
1288 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1289 $text .= ']'; # so that replaceExternalLinks($text) works later
1292 # fix up urlencoded title texts
1293 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1295 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1296 $might_be_img = true;
1298 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1300 } else { # Invalid form; output directly
1301 $s .= $prefix . '[[' . $line ;
1305 # Don't allow internal links to pages containing
1306 # PROTO: where PROTO is a valid URL protocol; these
1307 # should be external links.
1308 if (preg_match('/^(\b(?:'.$wgUrlProtocols.'))/', $m[1])) {
1309 $s .= $prefix . '[[' . $line ;
1313 # Make subpage if necessary
1314 if( $useSubpages ) {
1315 $link = $this->maybeDoSubpageLink( $m[1], $text );
1320 $noforce = (substr($m[1], 0, 1) != ':');
1322 # Strip off leading ':'
1323 $link = substr($link, 1);
1326 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1328 $s .= $prefix . '[[' . $line;
1332 #check other language variants of the link
1333 #if the article does not exist
1334 if( $checkVariantLink
1335 && $nt->getArticleID() == 0 ) {
1336 $wgContLang->findVariantLink($link, $nt);
1339 $ns = $nt->getNamespace();
1340 $iw = $nt->getInterWiki();
1342 if ($might_be_img) { # if this is actually an invalid link
1343 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1345 while (isset ($a[$k+
1]) ) {
1346 #look at the next 'line' to see if we can close it there
1347 $spliced = array_splice( $a, $k +
1, 1 );
1348 $next_line = array_shift( $spliced );
1349 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1350 # the first ]] closes the inner link, the second the image
1352 $text .= '[[' . $m[1];
1355 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1356 #if there's exactly one ]] that's fine, we'll keep looking
1357 $text .= '[[' . $m[0];
1359 #if $next_line is invalid too, we need look no further
1360 $text .= '[[' . $next_line;
1365 # we couldn't find the end of this imageLink, so output it raw
1366 #but don't ignore what might be perfectly normal links in the text we've examined
1367 $text = $this->replaceInternalLinks($text);
1368 $s .= $prefix . '[[' . $link . '|' . $text;
1369 # note: no $trail, because without an end, there *is* no trail
1372 } else { #it's not an image, so output it raw
1373 $s .= $prefix . '[[' . $link . '|' . $text;
1374 # note: no $trail, because without an end, there *is* no trail
1379 $wasblank = ( '' == $text );
1380 if( $wasblank ) $text = $link;
1383 # Link not escaped by : , create the various objects
1387 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1388 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1389 $s = rtrim($s . "\n");
1390 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1394 if ( $ns == NS_IMAGE
) {
1395 wfProfileIn( "$fname-image" );
1396 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1397 # recursively parse links inside the image caption
1398 # actually, this will parse them in any other parameters, too,
1399 # but it might be hard to fix that, and it doesn't matter ATM
1400 $text = $this->replaceExternalLinks($text);
1401 $text = $this->replaceInternalLinks($text);
1403 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1404 $s .= $prefix . preg_replace("/\b($wgUrlProtocols)/", UNIQ_PREFIX
."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1405 $wgLinkCache->addImageLinkObj( $nt );
1407 wfProfileOut( "$fname-image" );
1410 wfProfileOut( "$fname-image" );
1414 if ( $ns == NS_CATEGORY
) {
1415 wfProfileIn( "$fname-category" );
1416 $t = $wgContLang->convertHtml( $nt->getText() );
1417 $s = rtrim($s . "\n"); # bug 87
1419 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1420 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1421 $wgLinkCache->resume();
1424 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1425 $sortkey = $this->mTitle
->getText();
1427 $sortkey = $this->mTitle
->getPrefixedText();
1432 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1433 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1434 $this->mOutput
->addCategoryLink( $t );
1437 * Strip the whitespace Category links produce, see bug 87
1438 * @todo We might want to use trim($tmp, "\n") here.
1440 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1442 wfProfileOut( "$fname-category" );
1447 if( ( $nt->getPrefixedText() === $selflink ) &&
1448 ( $nt->getFragment() === '' ) ) {
1449 # Self-links are handled specially; generally de-link and change to bold.
1450 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1454 # Special and Media are pseudo-namespaces; no pages actually exist in them
1455 if( $ns == NS_MEDIA
) {
1456 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1457 $wgLinkCache->addImageLinkObj( $nt );
1459 } elseif( $ns == NS_SPECIAL
) {
1460 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1463 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1465 wfProfileOut( $fname );
1470 * Make a link placeholder. The text returned can be later resolved to a real link with
1471 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1472 * parsing of interwiki links, and secondly to allow all extistence checks and
1473 * article length checks (for stub links) to be bundled into a single query.
1476 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1477 if ( ! is_object($nt) ) {
1479 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1481 # Separate the link trail from the rest of the link
1482 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1484 if ( $nt->isExternal() ) {
1485 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1486 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1487 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1489 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1490 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1491 $this->mLinkHolders
['queries'][] = $query;
1492 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1493 $this->mLinkHolders
['titles'][] = $nt;
1495 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1502 * Return true if subpage links should be expanded on this page.
1505 function areSubpagesAllowed() {
1506 # Some namespaces don't allow subpages
1507 global $wgNamespacesWithSubpages;
1508 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1512 * Handle link to subpage if necessary
1513 * @param string $target the source of the link
1514 * @param string &$text the link text, modified as necessary
1515 * @return string the full name of the link
1518 function maybeDoSubpageLink($target, &$text) {
1521 # :Foobar -- override special treatment of prefix (images, language links)
1522 # /Foobar -- convert to CurrentPage/Foobar
1523 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1524 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1525 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1527 $fname = 'Parser::maybeDoSubpageLink';
1528 wfProfileIn( $fname );
1529 $ret = $target; # default return value is no change
1531 # Some namespaces don't allow subpages,
1532 # so only perform processing if subpages are allowed
1533 if( $this->areSubpagesAllowed() ) {
1534 # Look at the first character
1535 if( $target != '' && $target{0} == '/' ) {
1536 # / at end means we don't want the slash to be shown
1537 if( substr( $target, -1, 1 ) == '/' ) {
1538 $target = substr( $target, 1, -1 );
1541 $noslash = substr( $target, 1 );
1544 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1545 if( '' === $text ) {
1547 } # this might be changed for ugliness reasons
1549 # check for .. subpage backlinks
1551 $nodotdot = $target;
1552 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1554 $nodotdot = substr( $nodotdot, 3 );
1556 if($dotdotcount > 0) {
1557 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1558 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1559 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1560 # / at the end means don't show full path
1561 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1562 $nodotdot = substr( $nodotdot, 0, -1 );
1563 if( '' === $text ) {
1567 $nodotdot = trim( $nodotdot );
1568 if( $nodotdot != '' ) {
1569 $ret .= '/' . $nodotdot;
1576 wfProfileOut( $fname );
1581 * Used by doBlockLevels()
1584 /* private */ function closeParagraph() {
1586 if ( '' != $this->mLastSection
) {
1587 $result = '</' . $this->mLastSection
. ">\n";
1589 $this->mInPre
= false;
1590 $this->mLastSection
= '';
1593 # getCommon() returns the length of the longest common substring
1594 # of both arguments, starting at the beginning of both.
1596 /* private */ function getCommon( $st1, $st2 ) {
1597 $fl = strlen( $st1 );
1598 $shorter = strlen( $st2 );
1599 if ( $fl < $shorter ) { $shorter = $fl; }
1601 for ( $i = 0; $i < $shorter; ++
$i ) {
1602 if ( $st1{$i} != $st2{$i} ) { break; }
1606 # These next three functions open, continue, and close the list
1607 # element appropriate to the prefix character passed into them.
1609 /* private */ function openList( $char ) {
1610 $result = $this->closeParagraph();
1612 if ( '*' == $char ) { $result .= '<ul><li>'; }
1613 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1614 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1615 else if ( ';' == $char ) {
1616 $result .= '<dl><dt>';
1617 $this->mDTopen
= true;
1619 else { $result = '<!-- ERR 1 -->'; }
1624 /* private */ function nextItem( $char ) {
1625 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1626 else if ( ':' == $char ||
';' == $char ) {
1628 if ( $this->mDTopen
) { $close = '</dt>'; }
1629 if ( ';' == $char ) {
1630 $this->mDTopen
= true;
1631 return $close . '<dt>';
1633 $this->mDTopen
= false;
1634 return $close . '<dd>';
1637 return '<!-- ERR 2 -->';
1640 /* private */ function closeList( $char ) {
1641 if ( '*' == $char ) { $text = '</li></ul>'; }
1642 else if ( '#' == $char ) { $text = '</li></ol>'; }
1643 else if ( ':' == $char ) {
1644 if ( $this->mDTopen
) {
1645 $this->mDTopen
= false;
1646 $text = '</dt></dl>';
1648 $text = '</dd></dl>';
1651 else { return '<!-- ERR 3 -->'; }
1657 * Make lists from lines starting with ':', '*', '#', etc.
1660 * @return string the lists rendered as HTML
1662 function doBlockLevels( $text, $linestart ) {
1663 $fname = 'Parser::doBlockLevels';
1664 wfProfileIn( $fname );
1666 # Parsing through the text line by line. The main thing
1667 # happening here is handling of block-level elements p, pre,
1668 # and making lists from lines starting with * # : etc.
1670 $textLines = explode( "\n", $text );
1672 $lastPrefix = $output = '';
1673 $this->mDTopen
= $inBlockElem = false;
1675 $paragraphStack = false;
1677 if ( !$linestart ) {
1678 $output .= array_shift( $textLines );
1680 foreach ( $textLines as $oLine ) {
1681 $lastPrefixLength = strlen( $lastPrefix );
1682 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1683 $preOpenMatch = preg_match('/<pre/i', $oLine );
1684 if ( !$this->mInPre
) {
1685 # Multiple prefixes may abut each other for nested lists.
1686 $prefixLength = strspn( $oLine, '*#:;' );
1687 $pref = substr( $oLine, 0, $prefixLength );
1690 $pref2 = str_replace( ';', ':', $pref );
1691 $t = substr( $oLine, $prefixLength );
1692 $this->mInPre
= !empty($preOpenMatch);
1694 # Don't interpret any other prefixes in preformatted text
1696 $pref = $pref2 = '';
1701 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1702 # Same as the last item, so no need to deal with nesting or opening stuff
1703 $output .= $this->nextItem( substr( $pref, -1 ) );
1704 $paragraphStack = false;
1706 if ( substr( $pref, -1 ) == ';') {
1707 # The one nasty exception: definition lists work like this:
1708 # ; title : definition text
1709 # So we check for : in the remainder text to split up the
1710 # title and definition, without b0rking links.
1712 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1714 $output .= $term . $this->nextItem( ':' );
1717 } elseif( $prefixLength ||
$lastPrefixLength ) {
1718 # Either open or close a level...
1719 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1720 $paragraphStack = false;
1722 while( $commonPrefixLength < $lastPrefixLength ) {
1723 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1724 --$lastPrefixLength;
1726 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1727 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1729 while ( $prefixLength > $commonPrefixLength ) {
1730 $char = substr( $pref, $commonPrefixLength, 1 );
1731 $output .= $this->openList( $char );
1733 if ( ';' == $char ) {
1734 # FIXME: This is dupe of code above
1735 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1737 $output .= $term . $this->nextItem( ':' );
1740 ++
$commonPrefixLength;
1742 $lastPrefix = $pref2;
1744 if( 0 == $prefixLength ) {
1745 wfProfileIn( "$fname-paragraph" );
1746 # No prefix (not in list)--go to paragraph mode
1747 $uniq_prefix = UNIQ_PREFIX
;
1748 // XXX: use a stack for nestable elements like span, table and div
1749 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1750 $closematch = preg_match(
1751 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1752 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1753 if ( $openmatch or $closematch ) {
1754 $paragraphStack = false;
1755 $output .= $this->closeParagraph();
1756 if ( $preOpenMatch and !$preCloseMatch ) {
1757 $this->mInPre
= true;
1759 if ( $closematch ) {
1760 $inBlockElem = false;
1762 $inBlockElem = true;
1764 } else if ( !$inBlockElem && !$this->mInPre
) {
1765 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1767 if ($this->mLastSection
!= 'pre') {
1768 $paragraphStack = false;
1769 $output .= $this->closeParagraph().'<pre>';
1770 $this->mLastSection
= 'pre';
1772 $t = substr( $t, 1 );
1775 if ( '' == trim($t) ) {
1776 if ( $paragraphStack ) {
1777 $output .= $paragraphStack.'<br />';
1778 $paragraphStack = false;
1779 $this->mLastSection
= 'p';
1781 if ($this->mLastSection
!= 'p' ) {
1782 $output .= $this->closeParagraph();
1783 $this->mLastSection
= '';
1784 $paragraphStack = '<p>';
1786 $paragraphStack = '</p><p>';
1790 if ( $paragraphStack ) {
1791 $output .= $paragraphStack;
1792 $paragraphStack = false;
1793 $this->mLastSection
= 'p';
1794 } else if ($this->mLastSection
!= 'p') {
1795 $output .= $this->closeParagraph().'<p>';
1796 $this->mLastSection
= 'p';
1801 wfProfileOut( "$fname-paragraph" );
1803 // somewhere above we forget to get out of pre block (bug 785)
1804 if($preCloseMatch && $this->mInPre
) {
1805 $this->mInPre
= false;
1807 if ($paragraphStack === false) {
1811 while ( $prefixLength ) {
1812 $output .= $this->closeList( $pref2{$prefixLength-1} );
1815 if ( '' != $this->mLastSection
) {
1816 $output .= '</' . $this->mLastSection
. '>';
1817 $this->mLastSection
= '';
1820 wfProfileOut( $fname );
1825 * Split up a string on ':', ignoring any occurences inside
1826 * <a>..</a> or <span>...</span>
1827 * @param string $str the string to split
1828 * @param string &$before set to everything before the ':'
1829 * @param string &$after set to everything after the ':'
1830 * return string the position of the ':', or false if none found
1832 function findColonNoLinks($str, &$before, &$after) {
1833 # I wonder if we should make this count all tags, not just <a>
1834 # and <span>. That would prevent us from matching a ':' that
1835 # comes in the middle of italics other such formatting....
1837 $fname = 'Parser::findColonNoLinks';
1838 wfProfileIn( $fname );
1841 $colon = strpos($str, ':', $pos);
1843 if ($colon !== false) {
1844 $before = substr($str, 0, $colon);
1845 $after = substr($str, $colon +
1);
1847 # Skip any ':' within <a> or <span> pairs
1848 $a = substr_count($before, '<a');
1849 $s = substr_count($before, '<span');
1850 $ca = substr_count($before, '</a>');
1851 $cs = substr_count($before, '</span>');
1853 if ($a <= $ca and $s <= $cs) {
1854 # Tags are balanced before ':'; ok
1859 } while ($colon !== false);
1860 wfProfileOut( $fname );
1865 * Return value of a magic variable (like PAGENAME)
1869 function getVariableValue( $index ) {
1870 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1873 * Some of these require message or data lookups and can be
1874 * expensive to check many times.
1876 static $varCache = array();
1877 if( isset( $varCache[$index] ) ) return $varCache[$index];
1880 case MAG_CURRENTMONTH
:
1881 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1882 case MAG_CURRENTMONTHNAME
:
1883 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1884 case MAG_CURRENTMONTHNAMEGEN
:
1885 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1886 case MAG_CURRENTMONTHABBREV
:
1887 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1888 case MAG_CURRENTDAY
:
1889 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1891 return $this->mTitle
->getText();
1893 return $this->mTitle
->getPartialURL();
1894 case MAG_REVISIONID
:
1895 return $wgArticle->getRevIdFetched();
1897 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1898 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1899 case MAG_CURRENTDAYNAME
:
1900 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1901 case MAG_CURRENTYEAR
:
1902 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1903 case MAG_CURRENTTIME
:
1904 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1905 case MAG_CURRENTWEEK
:
1906 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1907 case MAG_CURRENTDOW
:
1908 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1909 case MAG_NUMBEROFARTICLES
:
1910 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1911 case MAG_NUMBEROFFILES
:
1912 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1917 case MAG_SERVERNAME
:
1918 return $wgServerName;
1919 case MAG_SCRIPTPATH
:
1920 return $wgScriptPath;
1927 * initialise the magic variables (like CURRENTMONTHNAME)
1931 function initialiseVariables() {
1932 $fname = 'Parser::initialiseVariables';
1933 wfProfileIn( $fname );
1934 global $wgVariableIDs;
1935 $this->mVariables
= array();
1936 foreach ( $wgVariableIDs as $id ) {
1937 $mw =& MagicWord
::get( $id );
1938 $mw->addToArray( $this->mVariables
, $id );
1940 wfProfileOut( $fname );
1944 * Replace magic variables, templates, and template arguments
1945 * with the appropriate text. Templates are substituted recursively,
1946 * taking care to avoid infinite loops.
1948 * Note that the substitution depends on value of $mOutputType:
1949 * OT_WIKI: only {{subst:}} templates
1950 * OT_MSG: only magic variables
1951 * OT_HTML: all templates and magic variables
1953 * @param string $tex The text to transform
1954 * @param array $args Key-value pairs representing template parameters to substitute
1957 function replaceVariables( $text, $args = array() ) {
1959 # Prevent too big inclusions
1960 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1964 $fname = 'Parser::replaceVariables';
1965 wfProfileIn( $fname );
1967 $titleChars = Title
::legalChars();
1968 $dtitleChars = "$titleChars|{}\[\]"; // [] so that {{{arg|[[foo|bar]]}} will work
1970 # This function is called recursively. To keep track of arguments we need a stack:
1971 array_push( $this->mArgStack
, $args );
1973 # Variable substitution
1974 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1976 if ( $this->mOutputType
== OT_WIKI
) {
1977 # Argument substitution
1978 $text = preg_replace_callback( "/{{{([$dtitleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1979 } elseif ( $this->mOutputType
== OT_HTML
) {
1980 # Argument substitution + default argument substitution
1981 $text = preg_replace_callback( "/{{{([$dtitleChars]*?)}}}/", array( &$this, 'argSubstitutionWDefaults' ), $text );
1983 # Template substitution
1984 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1985 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1987 array_pop( $this->mArgStack
);
1989 wfProfileOut( $fname );
1994 * Replace magic variables
1997 function variableSubstitution( $matches ) {
1998 $fname = 'parser::variableSubstitution';
1999 $varname = $matches[1];
2000 wfProfileIn( $fname );
2001 if ( !$this->mVariables
) {
2002 $this->initialiseVariables();
2005 if ( $this->mOutputType
== OT_WIKI
) {
2006 # Do only magic variables prefixed by SUBST
2007 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2008 if (!$mwSubst->matchStartAndRemove( $varname ))
2010 # Note that if we don't substitute the variable below,
2011 # we don't remove the {{subst:}} magic word, in case
2012 # it is a template rather than a magic variable.
2014 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2015 $id = $this->mVariables
[$varname];
2016 $text = $this->getVariableValue( $id );
2017 $this->mOutput
->mContainsOldMagic
= true;
2019 $text = $matches[0];
2021 wfProfileOut( $fname );
2025 # Split template arguments
2026 function getTemplateArgs( $argsString ) {
2027 if ( $argsString === '' ) {
2031 $args = explode( '|', substr( $argsString, 1 ) );
2033 # If any of the arguments contains a '[[' but no ']]', it needs to be
2034 # merged with the next arg because the '|' character between belongs
2035 # to the link syntax and not the template parameter syntax.
2036 $argc = count($args);
2038 for ( $i = 0; $i < $argc-1; $i++
) {
2039 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2040 $args[$i] .= '|'.$args[$i+
1];
2041 array_splice($args, $i+
1, 1);
2051 * Return the text of a template, after recursively
2052 * replacing any variables or templates within the template.
2054 * @param array $matches The parts of the template
2055 * $matches[1]: the title, i.e. the part before the |
2056 * $matches[2]: the parameters (including a leading |), if any
2057 * @return string the text of the template
2060 function braceSubstitution( $matches ) {
2061 global $wgLinkCache, $wgContLang;
2062 $fname = 'Parser::braceSubstitution';
2063 wfProfileIn( $fname );
2071 # Need to know if the template comes at the start of a line,
2072 # to treat the beginning of the template like the beginning
2073 # of a line for tables and block-level elements.
2074 $linestart = $matches[1];
2076 # $part1 is the bit before the first |, and must contain only title characters
2077 # $args is a list of arguments, starting from index 0, not including $part1
2079 $part1 = $matches[2];
2080 # If the third subpattern matched anything, it will start with |
2082 $args = $this->getTemplateArgs($matches[3]);
2083 $argc = count( $args );
2085 # Don't parse {{{}}} because that's only for template arguments
2086 if ( $linestart === '{' ) {
2087 $text = $matches[0];
2094 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2095 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2096 # One of two possibilities is true:
2097 # 1) Found SUBST but not in the PST phase
2098 # 2) Didn't find SUBST and in the PST phase
2099 # In either case, return without further processing
2100 $text = $matches[0];
2106 # MSG, MSGNW and INT
2109 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2110 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2113 # Remove obsolete MSG:
2114 $mwMsg =& MagicWord
::get( MAG_MSG
);
2115 $mwMsg->matchStartAndRemove( $part1 );
2118 # Check if it is an internal message
2119 $mwInt =& MagicWord
::get( MAG_INT
);
2120 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2121 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2122 $text = $linestart . wfMsgReal( $part1, $args, true );
2130 # Check for NS: (namespace expansion)
2131 $mwNs = MagicWord
::get( MAG_NS
);
2132 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2133 if ( intval( $part1 ) ) {
2134 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2137 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2138 if ( !is_null( $index ) ) {
2139 $text = $linestart . $wgContLang->getNsText( $index );
2146 # LOCALURL and LOCALURLE
2148 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2149 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2151 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2152 $func = 'getLocalURL';
2153 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2154 $func = 'escapeLocalURL';
2159 if ( $func !== '' ) {
2160 $title = Title
::newFromText( $part1 );
2161 if ( !is_null( $title ) ) {
2163 $text = $linestart . $title->$func( $args[0] );
2165 $text = $linestart . $title->$func();
2173 if ( !$found && $argc == 1 ) {
2174 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2175 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2176 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2182 if ( !$found && $argc >= 2 ) {
2183 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2184 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2185 if ($argc==2) {$args[2]=$args[1];}
2186 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2191 # Template table test
2193 # Did we encounter this template already? If yes, it is in the cache
2194 # and we need to check for loops.
2195 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2198 # Infinite loop test
2199 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2202 $text = $linestart .
2204 '<!-- WARNING: template loop detected -->';
2205 wfDebug( "$fname: template loop broken at '$part1'\n" );
2207 # set $text to cached message.
2208 $text = $linestart . $this->mTemplates
[$part1];
2212 # Load from database
2213 $replaceHeadings = false;
2215 $lastPathLevel = $this->mTemplatePath
;
2218 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2219 if ($subpage !== '') {
2220 $ns = $this->mTitle
->getNamespace();
2222 $title = Title
::newFromText( $part1, $ns );
2225 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2226 if ($interwiki != '' && $title->isTrans()) {
2227 return $this->scarytransclude($title, $interwiki);
2231 if ( !is_null( $title ) && !$title->isExternal() ) {
2232 # Check for excessive inclusion
2233 $dbk = $title->getPrefixedDBkey();
2234 if ( $this->incrementIncludeCount( $dbk ) ) {
2235 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2236 # Capture special page output
2237 $text = SpecialPage
::capturePath( $title );
2238 if ( is_string( $text ) ) {
2242 $this->disableCache();
2245 $article = new Article( $title );
2246 $articleContent = $article->fetchContent(0, false);
2247 if ( $articleContent !== false ) {
2249 $text = $articleContent;
2250 $replaceHeadings = true;
2255 # If the title is valid but undisplayable, make a link to it
2256 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2257 $text = '[['.$title->getPrefixedText().']]';
2261 # Template cache array insertion
2263 $this->mTemplates
[$part1] = $text;
2264 $text = $linestart . $text;
2269 # Recursive parsing, escaping and link table handling
2270 # Only for HTML output
2271 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2272 $text = wfEscapeWikiText( $text );
2273 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2274 # Clean up argument array
2275 $assocArgs = array();
2277 foreach( $args as $arg ) {
2278 $eqpos = strpos( $arg, '=' );
2279 if ( $eqpos === false ) {
2280 $assocArgs[$index++
] = $arg;
2282 $name = trim( substr( $arg, 0, $eqpos ) );
2283 $value = trim( substr( $arg, $eqpos+
1 ) );
2284 if ( $value === false ) {
2287 if ( $name !== false ) {
2288 $assocArgs[$name] = $value;
2293 # Add a new element to the templace recursion path
2294 $this->mTemplatePath
[$part1] = 1;
2296 if( $this->mOutputType
== OT_HTML
) {
2297 # Remove <noinclude> sections and <includeonly> tags
2298 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2299 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2300 # Strip <nowiki>, <pre>, etc.
2301 $text = $this->strip( $text, $this->mStripState
);
2302 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2304 $text = $this->replaceVariables( $text, $assocArgs );
2306 # Resume the link cache and register the inclusion as a link
2307 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2308 $wgLinkCache->addLinkObj( $title );
2311 # If the template begins with a table or block-level
2312 # element, it should be treated as beginning a new line.
2313 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2314 $text = "\n" . $text;
2317 # Prune lower levels off the recursion check path
2318 $this->mTemplatePath
= $lastPathLevel;
2321 wfProfileOut( $fname );
2325 # Replace raw HTML by a placeholder
2326 # Add a blank line preceding, to prevent it from mucking up
2327 # immediately preceding headings
2328 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2330 # replace ==section headers==
2331 # XXX this needs to go away once we have a better parser.
2332 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2333 if( !is_null( $title ) )
2334 $encodedname = base64_encode($title->getPrefixedDBkey());
2336 $encodedname = base64_encode("");
2337 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2338 PREG_SPLIT_DELIM_CAPTURE
);
2341 for( $i = 0; $i < count($m); $i +
= 2 ) {
2343 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2345 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2349 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2350 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2351 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2359 # Prune lower levels off the recursion check path
2360 $this->mTemplatePath
= $lastPathLevel;
2363 wfProfileOut( $fname );
2366 wfProfileOut( $fname );
2372 * Translude an interwiki link.
2374 function scarytransclude($title, $interwiki) {
2375 global $wgEnableScaryTranscluding;
2377 if (!$wgEnableScaryTranscluding)
2378 return wfMsg('scarytranscludedisabled');
2380 $articlename = "Template:" . $title->getDBkey();
2381 $url = str_replace('$1', urlencode($articlename), $interwiki);
2382 if (strlen($url) > 255)
2383 return wfMsg('scarytranscludetoolong');
2384 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2385 $this->mIWTransData
[] = $text;
2386 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2389 function fetchScaryTemplateMaybeFromCache($url) {
2390 $dbr =& wfGetDB(DB_SLAVE
);
2391 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2392 array('tc_url' => $url));
2394 $time = $obj->tc_time
;
2395 $text = $obj->tc_contents
;
2396 if ($time && $time < (time() +
(60*60))) {
2401 $text = wfGetHTTP($url . '?action=render');
2403 return wfMsg('scarytranscludefailed', $url);
2405 $dbw =& wfGetDB(DB_MASTER
);
2406 $dbw->replace('transcache', array(), array(
2408 'tc_time' => time(),
2409 'tc_contents' => $text));
2415 * Triple brace replacement -- used for template arguments
2418 function argSubstitution( $matches ) {
2419 $arg = trim( $matches[1] );
2420 $text = $matches[0];
2421 $inputArgs = end( $this->mArgStack
);
2423 if ( array_key_exists( $arg, $inputArgs ) ) {
2424 $text = $inputArgs[$arg];
2431 * Triple brace replacement with default arguments-- used for template arguments
2434 function argSubstitutionWDefaults( $matches ) {
2435 $arg = trim( $matches[1] );
2437 if ( strpos( $arg, '|' ) !== false ) {
2438 list( $arg, $default ) = explode( '|', $arg, 2 );
2439 $arg = rtrim( $arg );
2440 $default = ltrim( $default );
2444 $text = $matches[0];
2445 $inputArgs = end( $this->mArgStack
);
2447 if ( array_key_exists( $arg, $inputArgs ) ) {
2448 $text = $inputArgs[$arg];
2449 } else if ( $default !== null )
2456 * Returns true if the function is allowed to include this entity
2459 function incrementIncludeCount( $dbk ) {
2460 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2461 $this->mIncludeCount
[$dbk] = 0;
2463 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2471 * This function accomplishes several tasks:
2472 * 1) Auto-number headings if that option is enabled
2473 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2474 * 3) Add a Table of contents on the top for users who have enabled the option
2475 * 4) Auto-anchor headings
2477 * It loops through all headlines, collects the necessary data, then splits up the
2478 * string and re-inserts the newly formatted headlines.
2480 * @param string $text
2481 * @param boolean $isMain
2484 function formatHeadings( $text, $isMain=true ) {
2485 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2487 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2489 $forceTocHere = false;
2490 if( !$this->mTitle
->userCanEdit() ) {
2493 $showEditLink = $this->mOptions
->getEditSection();
2496 # Inhibit editsection links if requested in the page
2497 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2498 if( $esw->matchAndRemove( $text ) ) {
2501 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2503 $mw =& MagicWord
::get( MAG_NOTOC
);
2504 if( $mw->matchAndRemove( $text ) ) {
2508 # Get all headlines for numbering them and adding funky stuff like [edit]
2509 # links - this is for later, but we need the number of headlines right now
2510 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2512 # if there are fewer than 4 headlines in the article, do not show TOC
2513 if( $numMatches < 4 ) {
2517 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2518 # override above conditions and always show TOC at that place
2520 $mw =& MagicWord
::get( MAG_TOC
);
2521 if($mw->match( $text ) ) {
2523 $forceTocHere = true;
2525 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2526 # override above conditions and always show TOC above first header
2527 $mw =& MagicWord
::get( MAG_FORCETOC
);
2528 if ($mw->matchAndRemove( $text ) ) {
2533 # Never ever show TOC if no headers
2534 if( $numMatches < 1 ) {
2538 # We need this to perform operations on the HTML
2539 $sk =& $this->mOptions
->getSkin();
2543 $sectionCount = 0; # headlineCount excluding template sections
2545 # Ugh .. the TOC should have neat indentation levels which can be
2546 # passed to the skin functions. These are determined here
2550 $sublevelCount = array();
2551 $levelCount = array();
2558 foreach( $matches[3] as $headline ) {
2560 $templatetitle = '';
2561 $templatesection = 0;
2564 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2566 $templatetitle = base64_decode($mat[1]);
2567 $templatesection = 1 +
(int)base64_decode($mat[2]);
2568 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2572 $prevlevel = $level;
2573 $prevtoclevel = $toclevel;
2575 $level = $matches[1][$headlineCount];
2577 if( $doNumberHeadings ||
$doShowToc ) {
2579 if ( $level > $prevlevel ) {
2580 # Increase TOC level
2582 $sublevelCount[$toclevel] = 0;
2583 $toc .= $sk->tocIndent();
2585 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2586 # Decrease TOC level, find level to jump to
2588 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2589 # Can only go down to level 1
2592 for ($i = $toclevel; $i > 0; $i--) {
2593 if ( $levelCount[$i] == $level ) {
2594 # Found last matching level
2598 elseif ( $levelCount[$i] < $level ) {
2599 # Found first matching level below current level
2606 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2609 # No change in level, end TOC line
2610 $toc .= $sk->tocLineEnd();
2613 $levelCount[$toclevel] = $level;
2615 # count number of headlines for each level
2616 @$sublevelCount[$toclevel]++
;
2618 for( $i = 1; $i <= $toclevel; $i++
) {
2619 if( !empty( $sublevelCount[$i] ) ) {
2623 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2629 # The canonized header is a version of the header text safe to use for links
2630 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2631 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2632 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2634 # Remove link placeholders by the link text.
2635 # <!--LINK number-->
2637 # link text with suffix
2638 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2639 "\$this->mLinkHolders['texts'][\$1]",
2640 $canonized_headline );
2641 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2642 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2643 $canonized_headline );
2646 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2647 $tocline = trim( $canonized_headline );
2648 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2649 $replacearray = array(
2653 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2654 $refers[$headlineCount] = $canonized_headline;
2656 # count how many in assoc. array so we can track dupes in anchors
2657 @$refers[$canonized_headline]++
;
2658 $refcount[$headlineCount]=$refers[$canonized_headline];
2660 # Don't number the heading if it is the only one (looks silly)
2661 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2662 # the two are different if the line contains a link
2663 $headline=$numbering . ' ' . $headline;
2666 # Create the anchor for linking from the TOC to the section
2667 $anchor = $canonized_headline;
2668 if($refcount[$headlineCount] > 1 ) {
2669 $anchor .= '_' . $refcount[$headlineCount];
2671 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2672 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2674 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2675 if ( empty( $head[$headlineCount] ) ) {
2676 $head[$headlineCount] = '';
2679 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2681 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2684 # give headline the correct <h#> tag
2685 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2693 $toc .= $sk->tocUnindent( $toclevel - 1 );
2694 $toc = $sk->tocList( $toc );
2697 # split up and insert constructed headlines
2699 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2702 foreach( $blocks as $block ) {
2703 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2704 # This is the [edit] link that appears for the top block of text when
2705 # section editing is enabled
2707 # Disabled because it broke block formatting
2708 # For example, a bullet point in the top line
2709 # $full .= $sk->editSectionLink(0);
2712 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2713 # Top anchor now in skin
2717 if( !empty( $head[$i] ) ) {
2723 $mw =& MagicWord
::get( MAG_TOC
);
2724 return $mw->replace( $toc, $full );
2731 * Return an HTML link for the "ISBN 123456" text
2734 function magicISBN( $text ) {
2735 $fname = 'Parser::magicISBN';
2736 wfProfileIn( $fname );
2738 $a = split( 'ISBN ', ' '.$text );
2739 if ( count ( $a ) < 2 ) {
2740 wfProfileOut( $fname );
2743 $text = substr( array_shift( $a ), 1);
2744 $valid = '0123456789-Xx';
2746 foreach ( $a as $x ) {
2747 $isbn = $blank = '' ;
2748 while ( ' ' == $x{0} ) {
2750 $x = substr( $x, 1 );
2752 if ( $x == '' ) { # blank isbn
2753 $text .= "ISBN $blank";
2756 while ( strstr( $valid, $x{0} ) != false ) {
2758 $x = substr( $x, 1 );
2760 $num = str_replace( '-', '', $isbn );
2761 $num = str_replace( ' ', '', $num );
2762 $num = str_replace( 'x', 'X', $num );
2765 $text .= "ISBN $blank$x";
2767 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2768 $text .= '<a href="' .
2769 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2770 "\" class=\"internal\">ISBN $isbn</a>";
2774 wfProfileOut( $fname );
2779 * Return an HTML link for the "RFC 1234" text
2782 * @param string $text Text to be processed
2783 * @param string $keyword Magic keyword to use (default RFC)
2784 * @param string $urlmsg Interface message to use (default rfcurl)
2787 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2789 $valid = '0123456789';
2792 $a = split( $keyword, ' '.$text );
2793 if ( count ( $a ) < 2 ) {
2796 $text = substr( array_shift( $a ), 1);
2798 /* Check if keyword is preceed by [[.
2799 * This test is made here cause of the array_shift above
2800 * that prevent the test to be done in the foreach.
2802 if ( substr( $text, -2 ) == '[[' ) {
2806 foreach ( $a as $x ) {
2807 /* token might be empty if we have RFC RFC 1234 */
2815 /** remove and save whitespaces in $blank */
2816 while ( $x{0} == ' ' ) {
2818 $x = substr( $x, 1 );
2821 /** remove and save the rfc number in $id */
2822 while ( strstr( $valid, $x{0} ) != false ) {
2824 $x = substr( $x, 1 );
2828 /* call back stripped spaces*/
2829 $text .= $keyword.$blank.$x;
2830 } elseif( $internal ) {
2832 $text .= $keyword.$id.$x;
2834 /* build the external link*/
2835 $url = wfMsg( $urlmsg, $id);
2836 $sk =& $this->mOptions
->getSkin();
2837 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2838 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2841 /* Check if the next RFC keyword is preceed by [[ */
2842 $internal = ( substr($x,-2) == '[[' );
2848 * Transform wiki markup when saving a page by doing \r\n -> \n
2849 * conversion, substitting signatures, {{subst:}} templates, etc.
2851 * @param string $text the text to transform
2852 * @param Title &$title the Title object for the current article
2853 * @param User &$user the User object describing the current user
2854 * @param ParserOptions $options parsing options
2855 * @param bool $clearState whether to clear the parser state first
2856 * @return string the altered wiki markup
2859 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2860 $this->mOptions
= $options;
2861 $this->mTitle
=& $title;
2862 $this->mOutputType
= OT_WIKI
;
2864 if ( $clearState ) {
2865 $this->clearState();
2868 $stripState = false;
2872 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2873 $text = $this->strip( $text, $stripState, false );
2874 $text = $this->pstPass2( $text, $user );
2875 $text = $this->unstrip( $text, $stripState );
2876 $text = $this->unstripNoWiki( $text, $stripState );
2881 * Pre-save transform helper function
2884 function pstPass2( $text, &$user ) {
2885 global $wgContLang, $wgLocaltimezone;
2887 # Variable replacement
2888 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2889 $text = $this->replaceVariables( $text );
2893 $n = $user->getName();
2894 $k = $user->getOption( 'nickname' );
2895 if ( '' == $k ) { $k = $n; }
2896 if ( isset( $wgLocaltimezone ) ) {
2897 $oldtz = getenv( 'TZ' );
2898 putenv( 'TZ='.$wgLocaltimezone );
2901 /* Note: This is the timestamp saved as hardcoded wikitext to
2902 * the database, we use $wgContLang here in order to give
2903 * everyone the same signiture and use the default one rather
2904 * than the one selected in each users preferences.
2906 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
2907 ' (' . date( 'T' ) . ')';
2908 if ( isset( $wgLocaltimezone ) ) {
2909 putenv( 'TZ='.$oldtz );
2912 if( $user->getOption( 'fancysig' ) ) {
2915 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2917 $text = preg_replace( '/~~~~~/', $d, $text );
2918 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2919 $text = preg_replace( '/~~~/', $sigText, $text );
2921 # Context links: [[|name]] and [[name (context)|]]
2923 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2924 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2925 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2926 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2928 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2929 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2930 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2931 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2933 $t = $this->mTitle
->getText();
2934 if ( preg_match( $conpat, $t, $m ) ) {
2937 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2938 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2939 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2941 if ( '' == $context ) {
2942 $text = preg_replace( $p2, '[[\\1]]', $text );
2944 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2947 # Trim trailing whitespace
2948 # MAG_END (__END__) tag allows for trailing
2949 # whitespace to be deliberately included
2950 $text = rtrim( $text );
2951 $mw =& MagicWord
::get( MAG_END
);
2952 $mw->matchAndRemove( $text );
2958 * Set up some variables which are usually set up in parse()
2959 * so that an external function can call some class members with confidence
2962 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2963 $this->mTitle
=& $title;
2964 $this->mOptions
= $options;
2965 $this->mOutputType
= $outputType;
2966 if ( $clearState ) {
2967 $this->clearState();
2972 * Transform a MediaWiki message by replacing magic variables.
2974 * @param string $text the text to transform
2975 * @param ParserOptions $options options
2976 * @return string the text with variables substituted
2979 function transformMsg( $text, $options ) {
2981 static $executing = false;
2983 # Guard against infinite recursion
2989 $this->mTitle
= $wgTitle;
2990 $this->mOptions
= $options;
2991 $this->mOutputType
= OT_MSG
;
2992 $this->clearState();
2993 $text = $this->replaceVariables( $text );
3000 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3001 * Callback will be called with the text within
3002 * Transform and return the text within
3005 function setHook( $tag, $callback ) {
3006 $oldVal = @$this->mTagHooks
[$tag];
3007 $this->mTagHooks
[$tag] = $callback;
3012 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3013 * Placeholders created in Skin::makeLinkObj()
3014 * Returns an array of links found, indexed by PDBK:
3018 * $options is a bit field, RLH_FOR_UPDATE to select for update
3020 function replaceLinkHolders( &$text, $options = 0 ) {
3021 global $wgUser, $wgLinkCache;
3022 global $wgOutputReplace;
3024 $fname = 'Parser::replaceLinkHolders';
3025 wfProfileIn( $fname );
3029 $sk = $this->mOptions
->getSkin();
3031 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3032 wfProfileIn( $fname.'-check' );
3033 $dbr =& wfGetDB( DB_SLAVE
);
3034 $page = $dbr->tableName( 'page' );
3035 $threshold = $wgUser->getOption('stubthreshold');
3038 asort( $this->mLinkHolders
['namespaces'] );
3042 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
3044 $title = $this->mLinkHolders
['titles'][$key];
3046 # Skip invalid entries.
3047 # Result will be ugly, but prevents crash.
3048 if ( is_null( $title ) ) {
3051 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3053 # Check if it's in the link cache already
3054 if ( $title->isAlwaysKnown() ||
$wgLinkCache->getGoodLinkID( $pdbk ) ) {
3055 $colours[$pdbk] = 1;
3056 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3057 $colours[$pdbk] = 0;
3059 # Not in the link cache, add it to the query
3060 if ( !isset( $current ) ) {
3062 $query = "SELECT page_id, page_namespace, page_title";
3063 if ( $threshold > 0 ) {
3064 $query .= ', page_len, page_is_redirect';
3066 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3067 } elseif ( $current != $val ) {
3069 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3074 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3079 if ( $options & RLH_FOR_UPDATE
) {
3080 $query .= ' FOR UPDATE';
3083 $res = $dbr->query( $query, $fname );
3085 # Fetch data and form into an associative array
3086 # non-existent = broken
3089 while ( $s = $dbr->fetchObject($res) ) {
3090 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3091 $pdbk = $title->getPrefixedDBkey();
3092 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
3094 if ( $threshold > 0 ) {
3095 $size = $s->page_len
;
3096 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3097 $colours[$pdbk] = 1;
3099 $colours[$pdbk] = 2;
3102 $colours[$pdbk] = 1;
3106 wfProfileOut( $fname.'-check' );
3108 # Construct search and replace arrays
3109 wfProfileIn( $fname.'-construct' );
3110 $wgOutputReplace = array();
3111 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3112 $pdbk = $pdbks[$key];
3113 $searchkey = "<!--LINK $key-->";
3114 $title = $this->mLinkHolders
['titles'][$key];
3115 if ( empty( $colours[$pdbk] ) ) {
3116 $wgLinkCache->addBadLinkObj( $title );
3117 $colours[$pdbk] = 0;
3118 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3119 $this->mLinkHolders
['texts'][$key],
3120 $this->mLinkHolders
['queries'][$key] );
3121 } elseif ( $colours[$pdbk] == 1 ) {
3122 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3123 $this->mLinkHolders
['texts'][$key],
3124 $this->mLinkHolders
['queries'][$key] );
3125 } elseif ( $colours[$pdbk] == 2 ) {
3126 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3127 $this->mLinkHolders
['texts'][$key],
3128 $this->mLinkHolders
['queries'][$key] );
3131 wfProfileOut( $fname.'-construct' );
3134 wfProfileIn( $fname.'-replace' );
3136 $text = preg_replace_callback(
3137 '/(<!--LINK .*?-->)/',
3138 "wfOutputReplaceMatches",
3141 wfProfileOut( $fname.'-replace' );
3144 # Now process interwiki link holders
3145 # This is quite a bit simpler than internal links
3146 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3147 wfProfileIn( $fname.'-interwiki' );
3148 # Make interwiki link HTML
3149 $wgOutputReplace = array();
3150 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3151 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3152 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3155 $text = preg_replace_callback(
3156 '/<!--IWLINK (.*?)-->/',
3157 "wfOutputReplaceMatches",
3159 wfProfileOut( $fname.'-interwiki' );
3162 wfProfileOut( $fname );
3167 * Replace <!--LINK--> link placeholders with plain text of links
3168 * (not HTML-formatted).
3169 * @param string $text
3172 function replaceLinkHoldersText( $text ) {
3173 global $wgUser, $wgLinkCache;
3174 global $wgOutputReplace;
3176 $fname = 'Parser::replaceLinkHoldersText';
3177 wfProfileIn( $fname );
3179 $text = preg_replace_callback(
3180 '/<!--(LINK|IWLINK) (.*?)-->/',
3181 array( &$this, 'replaceLinkHoldersTextCallback' ),
3184 wfProfileOut( $fname );
3189 * @param array $matches
3193 function replaceLinkHoldersTextCallback( $matches ) {
3194 $type = $matches[1];
3196 if( $type == 'LINK' ) {
3197 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3198 return $this->mLinkHolders
['texts'][$key];
3200 } elseif( $type == 'IWLINK' ) {
3201 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3202 return $this->mInterwikiLinkHolders
['texts'][$key];
3209 * Renders an image gallery from a text with one line per image.
3210 * text labels may be given by using |-style alternative text. E.g.
3211 * Image:one.jpg|The number "1"
3212 * Image:tree.jpg|A tree
3213 * given as text will return the HTML of a gallery with two images,
3214 * labeled 'The number "1"' and
3219 function renderImageGallery( $text ) {
3221 global $wgUser, $wgTitle;
3222 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3223 $localParser = new Parser();
3225 global $wgLinkCache;
3226 $ig = new ImageGallery();
3227 $ig->setShowBytes( false );
3228 $ig->setShowFilename( false );
3229 $lines = explode( "\n", $text );
3231 foreach ( $lines as $line ) {
3232 # match lines like these:
3233 # Image:someimage.jpg|This is some image
3234 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3236 if ( count( $matches ) == 0 ) {
3239 $nt = Title
::newFromURL( $matches[1] );
3240 if( is_null( $nt ) ) {
3241 # Bogus title. Ignore these so we don't bomb out later.
3244 if ( isset( $matches[3] ) ) {
3245 $label = $matches[3];
3250 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3251 $html = $html->mText
;
3253 $ig->add( new Image( $nt ), $html );
3254 $wgLinkCache->addImageLinkObj( $nt );
3256 return $ig->toHTML();
3260 * Parse image options text and use it to make an image
3262 function makeImage( &$nt, $options ) {
3263 global $wgContLang, $wgUseImageResize;
3264 global $wgUser, $wgThumbLimits;
3268 # Check if the options text is of the form "options|alt text"
3270 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3271 # * left no resizing, just left align. label is used for alt= only
3272 # * right same, but right aligned
3273 # * none same, but not aligned
3274 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3275 # * center center the image
3276 # * framed Keep original image size, no magnify-button.
3278 $part = explode( '|', $options);
3280 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3281 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3282 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3283 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3284 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3285 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3286 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3287 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3290 $width = $height = $framed = $thumb = false;
3291 $manual_thumb = '' ;
3293 foreach( $part as $key => $val ) {
3294 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3296 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3297 # use manually specified thumbnail
3299 $manual_thumb = $match;
3300 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3301 # remember to set an alignment, don't render immediately
3303 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3304 # remember to set an alignment, don't render immediately
3306 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3307 # remember to set an alignment, don't render immediately
3309 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3310 # remember to set an alignment, don't render immediately
3312 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3313 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3314 # $match is the image width in pixels
3315 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3316 $width = intval( $m[1] );
3317 $height = intval( $m[2] );
3319 $width = intval($match);
3321 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3327 # Strip bad stuff out of the alt text
3328 $alt = $this->replaceLinkHoldersText( $caption );
3329 $alt = Sanitizer
::stripAllTags( $alt );
3331 # Linker does the rest
3332 $sk =& $this->mOptions
->getSkin();
3333 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3337 * Set a flag in the output object indicating that the content is dynamic and
3338 * shouldn't be cached.
3340 function disableCache() {
3341 $this->mOutput
->mCacheTime
= -1;
3345 * Callback from the Sanitizer for expanding items found in HTML attribute
3346 * values, so they can be safely tested and escaped.
3347 * @param string $text
3348 * @param array $args
3352 function attributeStripCallback( &$text, $args ) {
3353 $text = $this->replaceVariables( $text, $args );
3354 $text = $this->unstripForHTML( $text );
3358 function unstripForHTML( $text ) {
3359 $text = $this->unstrip( $text, $this->mStripState
);
3360 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3367 * @package MediaWiki
3371 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3372 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3373 var $mVersion; # Compatibility check
3374 var $mTitleText; # title text of the chosen language variant
3376 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3377 $containsOldMagic = false, $titletext = '' )
3379 $this->mText
= $text;
3380 $this->mLanguageLinks
= $languageLinks;
3381 $this->mCategoryLinks
= $categoryLinks;
3382 $this->mContainsOldMagic
= $containsOldMagic;
3383 $this->mCacheTime
= '';
3384 $this->mVersion
= MW_PARSER_VERSION
;
3385 $this->mTitleText
= $titletext;
3388 function getText() { return $this->mText
; }
3389 function getLanguageLinks() { return $this->mLanguageLinks
; }
3390 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3391 function getCacheTime() { return $this->mCacheTime
; }
3392 function getTitleText() { return $this->mTitleText
; }
3393 function containsOldMagic() { return $this->mContainsOldMagic
; }
3394 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3395 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3396 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3397 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3398 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3399 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3401 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3403 function merge( $other ) {
3404 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3405 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3406 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3410 * Return true if this cached output object predates the global or
3411 * per-article cache invalidation timestamps, or if it comes from
3412 * an incompatible older version.
3414 * @param string $touched the affected article's last touched timestamp
3418 function expired( $touched ) {
3419 global $wgCacheEpoch;
3420 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3421 $this->getCacheTime() <= $touched ||
3422 $this->getCacheTime() <= $wgCacheEpoch ||
3423 !isset( $this->mVersion
) ||
3424 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3429 * Set options of the Parser
3431 * @package MediaWiki
3435 # All variables are private
3436 var $mUseTeX; # Use texvc to expand <math> tags
3437 var $mUseDynamicDates; # Use DateFormatter to format dates
3438 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3439 var $mAllowExternalImages; # Allow external images inline
3440 var $mSkin; # Reference to the preferred skin
3441 var $mDateFormat; # Date format index
3442 var $mEditSection; # Create "edit section" links
3443 var $mNumberHeadings; # Automatically number headings
3444 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3446 function getUseTeX() { return $this->mUseTeX
; }
3447 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3448 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3449 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3450 function &getSkin() { return $this->mSkin
; }
3451 function getDateFormat() { return $this->mDateFormat
; }
3452 function getEditSection() { return $this->mEditSection
; }
3453 function getNumberHeadings() { return $this->mNumberHeadings
; }
3454 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3457 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3458 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3459 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3460 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3461 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3462 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3463 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3464 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3466 function setSkin( &$x ) { $this->mSkin
=& $x; }
3468 function ParserOptions() {
3470 $this->initialiseFromUser( $wgUser );
3474 * Get parser options
3477 function newFromUser( &$user ) {
3478 $popts = new ParserOptions
;
3479 $popts->initialiseFromUser( $user );
3483 /** Get user options */
3484 function initialiseFromUser( &$userInput ) {
3485 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3486 $wgAllowSpecialInclusion;
3487 $fname = 'ParserOptions::initialiseFromUser';
3488 wfProfileIn( $fname );
3489 if ( !$userInput ) {
3491 $user->setLoaded( true );
3493 $user =& $userInput;
3496 $this->mUseTeX
= $wgUseTeX;
3497 $this->mUseDynamicDates
= $wgUseDynamicDates;
3498 $this->mInterwikiMagic
= $wgInterwikiMagic;
3499 $this->mAllowExternalImages
= $wgAllowExternalImages;
3500 wfProfileIn( $fname.'-skin' );
3501 $this->mSkin
=& $user->getSkin();
3502 wfProfileOut( $fname.'-skin' );
3503 $this->mDateFormat
= $user->getOption( 'date' );
3504 $this->mEditSection
= true;
3505 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3506 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3507 wfProfileOut( $fname );
3512 * Callback function used by Parser::replaceLinkHolders()
3513 * to substitute link placeholders.
3515 function &wfOutputReplaceMatches( $matches ) {
3516 global $wgOutputReplace;
3517 return $wgOutputReplace[$matches[1]];
3521 * Return the total number of articles
3523 function wfNumberOfArticles() {
3524 global $wgNumberOfArticles;
3527 return $wgNumberOfArticles;
3531 * Return the number of files
3533 function wfNumberOfFiles() {
3534 $fname = 'Parser::wfNumberOfFiles';
3536 wfProfileIn( $fname );
3537 $dbr =& wfGetDB( DB_SLAVE
);
3538 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3539 wfProfileOut( $fname );
3545 * Get various statistics from the database
3548 function wfLoadSiteStats() {
3549 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3550 $fname = 'wfLoadSiteStats';
3552 if ( -1 != $wgNumberOfArticles ) return;
3553 $dbr =& wfGetDB( DB_SLAVE
);
3554 $s = $dbr->selectRow( 'site_stats',
3555 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3556 array( 'ss_row_id' => 1 ), $fname
3559 if ( $s === false ) {
3562 $wgTotalViews = $s->ss_total_views
;
3563 $wgTotalEdits = $s->ss_total_edits
;
3564 $wgNumberOfArticles = $s->ss_good_articles
;
3570 * Basicly replacing " > and < with HTML entities ( ", >, <)
3572 * @param string $in Text that might contain HTML tags
3573 * @return string Escaped string
3575 function wfEscapeHTMLTagsOnly( $in ) {
3577 array( '"', '>', '<' ),
3578 array( '"', '>', '<' ),