3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
13 * Update this version number when the ParserOutput format
14 * changes in an incompatible way, so the parser cache
15 * can automatically discard old data.
17 define( 'MW_PARSER_VERSION', '1.5.0' );
20 * Variable substitution O(N^2) attack
22 * Without countermeasures, it would be possible to attack the parser by saving
23 * a page filled with a large number of inclusions of large pages. The size of
24 * the generated page would be proportional to the square of the input size.
25 * Hence, we limit the number of inclusions of any given page, thus bringing any
26 * attack back to O(N).
29 define( 'MAX_INCLUDE_REPEAT', 100 );
30 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32 define( 'RLH_FOR_UPDATE', 1 );
34 # Allowed values for $mOutputType
35 define( 'OT_HTML', 1 );
36 define( 'OT_WIKI', 2 );
37 define( 'OT_MSG' , 3 );
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45 # prefix for escaping, used in two functions at least
46 define( 'UNIQ_PREFIX', 'NaodW29');
48 # Constants needed for external link processing
49 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
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('.URL_PROTOCOLS
.'):'.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.
122 $this->mTemplates
= array();
123 $this->mTemplatePath
= array();
124 $this->mTagHooks
= array();
133 function clearState() {
134 $this->mOutput
= new ParserOutput
;
135 $this->mAutonumber
= 0;
136 $this->mLastSection
= '';
137 $this->mDTopen
= false;
138 $this->mVariables
= false;
139 $this->mIncludeCount
= array();
140 $this->mStripState
= array();
141 $this->mArgStack
= array();
142 $this->mInPre
= false;
143 $this->mInterwikiLinkHolders
= array(
147 $this->mLinkHolders
= array(
148 'namespaces' => array(),
150 'queries' => array(),
157 * First pass--just handle <nowiki> sections, pass the rest off
158 * to internalParse() which does all the real work.
161 * @param string $text Text we want to parse
162 * @param Title &$title A title object
163 * @param array $options
164 * @param boolean $linestart
165 * @param boolean $clearState
166 * @return ParserOutput a ParserOutput
168 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
169 global $wgUseTidy, $wgContLang;
170 $fname = 'Parser::parse';
171 wfProfileIn( $fname );
177 $this->mOptions
= $options;
178 $this->mTitle
=& $title;
179 $this->mOutputType
= OT_HTML
;
181 $this->mStripState
= NULL;
183 //$text = $this->strip( $text, $this->mStripState );
184 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
185 $x =& $this->mStripState
;
186 $text = $this->strip( $text, $x );
188 $text = $this->internalParse( $text );
191 $text = $this->unstrip( $text, $this->mStripState
);
193 # Clean up special characters, only run once, next-to-last before doBlockLevels
195 # french spaces, last one Guillemet-left
196 # only if there is something before the space
197 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
198 # french spaces, Guillemet-right
199 '/(\\302\\253) /' => '\\1 ',
200 '/<center *>/i' => '<div class="center">',
201 '/<\\/center *>/i' => '</div>',
203 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
206 $text = $this->doBlockLevels( $text, $linestart );
208 $this->replaceLinkHolders( $text );
210 $dashReplace = array(
211 '/ - /' => " – ", # N dash
212 '/(?<=[\d])-(?=[\d])/' => "–", # N dash between numbers
213 '/ -- /' => " — " # M dash
215 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
217 # the position of the convert() call should not be changed. it
218 # assumes that the links are all replaces and the only thing left
219 # is the <nowiki> mark.
220 $text = $wgContLang->convert($text);
221 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
223 $text = $this->unstripNoWiki( $text, $this->mStripState
);
225 $text = Sanitizer
::normalizeCharReferences( $text );
228 $text = Parser
::tidy($text);
231 $this->mOutput
->setText( $text );
232 wfProfileOut( $fname );
233 return $this->mOutput
;
237 * Get a random string
242 function getRandomString() {
243 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
247 * Replaces all occurrences of <$tag>content</$tag> in the text
248 * with a random marker and returns the new text. the output parameter
249 * $content will be an associative array filled with data on the form
250 * $unique_marker => content.
252 * If $content is already set, the additional entries will be appended
253 * If $tag is set to STRIP_COMMENTS, the function will extract
254 * <!-- HTML comments -->
259 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
260 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
275 // Hack to support short XML style tags
276 $text = preg_replace( "/<$tag(\\s+[^>]*|\\s*)\\/>/i", "<$tag\\1></$tag>", $text );
278 if( $tag == STRIP_COMMENTS
) {
282 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
283 $end = "/<\\/$tag\\s*>/i";
286 while ( '' != $text ) {
287 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
289 if( count( $p ) < 3 ) {
295 $marker = $rnd . sprintf('%08X', $n++
);
296 $stripped .= $marker;
298 $tags[$marker] = "<$tag$attributes>";
299 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
301 $q = preg_split( $end, $inside, 2 );
302 $content[$marker] = $q[0];
303 if( count( $q ) < 1 ) {
304 # No end tag -- let it run out to the end of the text.
314 * Wrapper function for extractTagsAndParams
315 * for cases where $tags and $params isn't needed
316 * i.e. where tags will never have params, like <nowiki>
321 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
322 $dummy_tags = array();
323 $dummy_params = array();
325 return Parser
::extractTagsAndParams( $tag, $text, $content,
326 $dummy_tags, $dummy_params, $uniq_prefix );
330 * Strips and renders nowiki, pre, math, hiero
331 * If $render is set, performs necessary rendering operations on plugins
332 * Returns the text, and fills an array with data needed in unstrip()
333 * If the $state is already a valid strip state, it adds to the state
335 * @param bool $stripcomments when set, HTML comments <!-- like this -->
336 * will be stripped in addition to other tags. This is important
337 * for section editing, where these comments cause confusion when
338 * counting the sections in the wikisource
342 function strip( $text, &$state, $stripcomments = false ) {
343 $render = ($this->mOutputType
== OT_HTML
);
344 $html_content = array();
345 $nowiki_content = array();
346 $math_content = array();
347 $pre_content = array();
348 $comment_content = array();
349 $ext_content = array();
351 $ext_params = array();
352 $gallery_content = array();
354 # Replace any instances of the placeholders
355 $uniq_prefix = UNIQ_PREFIX
;
356 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
359 global $wgRawHtml, $wgWhitelistEdit;
360 if( $wgRawHtml && $wgWhitelistEdit ) {
361 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
362 foreach( $html_content as $marker => $content ) {
364 # Raw and unchecked for validity.
365 $html_content[$marker] = $content;
367 $html_content[$marker] = '<html>'.$content.'</html>';
373 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
374 foreach( $nowiki_content as $marker => $content ) {
376 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
378 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
383 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
384 foreach( $math_content as $marker => $content ){
386 if( $this->mOptions
->getUseTeX() ) {
387 $math_content[$marker] = renderMath( $content );
389 $math_content[$marker] = '<math>'.$content.'<math>';
392 $math_content[$marker] = '<math>'.$content.'</math>';
397 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
398 foreach( $pre_content as $marker => $content ){
400 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
402 $pre_content[$marker] = '<pre>'.$content.'</pre>';
407 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
408 foreach( $gallery_content as $marker => $content ) {
409 require_once( 'ImageGallery.php' );
411 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
413 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
419 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
420 foreach( $comment_content as $marker => $content ){
421 $comment_content[$marker] = '<!--'.$content.'-->';
426 foreach ( $this->mTagHooks
as $tag => $callback ) {
427 $ext_content[$tag] = array();
428 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
429 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
430 foreach( $ext_content[$tag] as $marker => $content ) {
431 $full_tag = $ext_tags[$tag][$marker];
432 $params = $ext_params[$tag][$marker];
434 $ext_content[$tag][$marker] = $callback( $content, $params );
436 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
441 # Merge state with the pre-existing state, if there is one
443 $state['html'] = $state['html'] +
$html_content;
444 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
445 $state['math'] = $state['math'] +
$math_content;
446 $state['pre'] = $state['pre'] +
$pre_content;
447 $state['comment'] = $state['comment'] +
$comment_content;
448 $state['gallery'] = $state['gallery'] +
$gallery_content;
450 foreach( $ext_content as $tag => $array ) {
451 if ( array_key_exists( $tag, $state ) ) {
452 $state[$tag] = $state[$tag] +
$array;
457 'html' => $html_content,
458 'nowiki' => $nowiki_content,
459 'math' => $math_content,
460 'pre' => $pre_content,
461 'comment' => $comment_content,
462 'gallery' => $gallery_content,
469 * restores pre, math, and hiero removed by strip()
471 * always call unstripNoWiki() after this one
474 function unstrip( $text, &$state ) {
475 # Must expand in reverse order, otherwise nested tags will be corrupted
476 $contentDict = end( $state );
477 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
478 if( key($state) != 'nowiki' && key($state) != 'html') {
479 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
480 $text = str_replace( key( $contentDict ), $content, $text );
489 * always call this after unstrip() to preserve the order
493 function unstripNoWiki( $text, &$state ) {
494 # Must expand in reverse order, otherwise nested tags will be corrupted
495 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
496 $text = str_replace( key( $state['nowiki'] ), $content, $text );
501 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
502 $text = str_replace( key( $state['html'] ), $content, $text );
510 * Add an item to the strip state
511 * Returns the unique tag which must be inserted into the stripped text
512 * The tag will be replaced with the original text in unstrip()
516 function insertStripItem( $text, &$state ) {
517 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
526 $state['item'][$rnd] = $text;
531 * Interface with html tidy, used if $wgUseTidy = true.
532 * If tidy isn't able to correct the markup, the original will be
533 * returned in all its glory with a warning comment appended.
535 * Either the external tidy program or the in-process tidy extension
536 * will be used depending on availability. Override the default
537 * $wgTidyInternal setting to disable the internal if it's not working.
539 * @param string $text Hideous HTML input
540 * @return string Corrected HTML output
544 function tidy( $text ) {
545 global $wgTidyInternal;
546 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
547 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
548 '<head><title>test</title></head><body>'.$text.'</body></html>';
549 if( $wgTidyInternal ) {
550 $correctedtext = Parser
::internalTidy( $wrappedtext );
552 $correctedtext = Parser
::externalTidy( $wrappedtext );
554 if( is_null( $correctedtext ) ) {
555 wfDebug( "Tidy error detected!\n" );
556 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
558 return $correctedtext;
562 * Spawn an external HTML tidy process and get corrected markup back from it.
567 function externalTidy( $text ) {
568 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
569 $fname = 'Parser::externalTidy';
570 wfProfileIn( $fname );
575 $descriptorspec = array(
576 0 => array('pipe', 'r'),
577 1 => array('pipe', 'w'),
578 2 => array('file', '/dev/null', 'a')
581 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
582 if (is_resource($process)) {
583 fwrite($pipes[0], $text);
585 while (!feof($pipes[1])) {
586 $cleansource .= fgets($pipes[1], 1024);
589 proc_close($process);
592 wfProfileOut( $fname );
594 if( $cleansource == '' && $text != '') {
595 // Some kind of error happened, so we couldn't get the corrected text.
596 // Just give up; we'll use the source text and append a warning.
604 * Use the HTML tidy PECL extension to use the tidy library in-process,
605 * saving the overhead of spawning a new process. Currently written to
606 * the PHP 4.3.x version of the extension, may not work on PHP 5.
608 * 'pear install tidy' should be able to compile the extension module.
613 function internalTidy( $text ) {
615 $fname = 'Parser::internalTidy';
616 wfProfileIn( $fname );
618 tidy_load_config( $wgTidyConf );
619 tidy_set_encoding( 'utf8' );
620 tidy_parse_string( $text );
622 if( tidy_get_status() == 2 ) {
623 // 2 is magic number for fatal error
624 // http://www.php.net/manual/en/function.tidy-get-status.php
627 $cleansource = tidy_get_output();
629 wfProfileOut( $fname );
634 * parse the wiki syntax used to render tables
638 function doTableStuff ( $t ) {
639 $fname = 'Parser::doTableStuff';
640 wfProfileIn( $fname );
642 $t = explode ( "\n" , $t ) ;
643 $td = array () ; # Is currently a td tag open?
644 $ltd = array () ; # Was it TD or TH?
645 $tr = array () ; # Is currently a tr tag open?
646 $ltr = array () ; # tr attributes
647 $indent_level = 0; # indent level of the table
648 foreach ( $t AS $k => $x )
651 $fc = substr ( $x , 0 , 1 ) ;
652 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
653 $indent_level = strlen( $matches[1] );
654 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
655 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
656 array_push ( $td , false ) ;
657 array_push ( $ltd , '' ) ;
658 array_push ( $tr , false ) ;
659 array_push ( $ltr , '' ) ;
661 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
662 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
663 $z = "</table>" . substr ( $x , 2);
664 $l = array_pop ( $ltd ) ;
665 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
666 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
668 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
670 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
671 $x = substr ( $x , 1 ) ;
672 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
674 $l = array_pop ( $ltd ) ;
675 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
676 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
679 array_push ( $tr , false ) ;
680 array_push ( $td , false ) ;
681 array_push ( $ltd , '' ) ;
682 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
684 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
686 if ( '|+' == substr ( $x , 0 , 2 ) ) {
688 $x = substr ( $x , 1 ) ;
690 $after = substr ( $x , 1 ) ;
691 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
692 $after = explode ( '||' , $after ) ;
695 # Loop through each table cell
696 foreach ( $after AS $theline )
701 $tra = array_pop ( $ltr ) ;
702 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
703 array_push ( $tr , true ) ;
704 array_push ( $ltr , '' ) ;
707 $l = array_pop ( $ltd ) ;
708 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
709 if ( $fc == '|' ) $l = 'td' ;
710 else if ( $fc == '!' ) $l = 'th' ;
711 else if ( $fc == '+' ) $l = 'caption' ;
713 array_push ( $ltd , $l ) ;
716 $y = explode ( '|' , $theline , 2 ) ;
717 # Note that a '|' inside an invalid link should not
718 # be mistaken as delimiting cell parameters
719 if ( strpos( $y[0], '[[' ) !== false ) {
720 $y = array ($theline);
722 if ( count ( $y ) == 1 )
723 $y = "{$z}<{$l}>{$y[0]}" ;
724 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
726 array_push ( $td , true ) ;
731 # Closing open td, tr && table
732 while ( count ( $td ) > 0 )
734 if ( array_pop ( $td ) ) $t[] = '</td>' ;
735 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
739 $t = implode ( "\n" , $t ) ;
740 wfProfileOut( $fname );
745 * Helper function for parse() that transforms wiki markup into
746 * HTML. Only called for $mOutputType == OT_HTML.
750 function internalParse( $text ) {
754 $fname = 'Parser::internalParse';
755 wfProfileIn( $fname );
757 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ) );
758 $text = $this->replaceVariables( $text, $args );
760 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
762 $text = $this->doHeadings( $text );
763 if($this->mOptions
->getUseDynamicDates()) {
764 $df =& DateFormatter
::getInstance();
765 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
767 $text = $this->doAllQuotes( $text );
768 $text = $this->replaceInternalLinks( $text );
769 $text = $this->replaceExternalLinks( $text );
771 # replaceInternalLinks may sometimes leave behind
772 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
773 $text = str_replace("http-noparse://","http://",$text);
775 $text = $this->doMagicLinks( $text );
776 $text = $this->doTableStuff( $text );
777 $text = $this->formatHeadings( $text, $isMain );
779 wfProfileOut( $fname );
784 * Replace special strings like "ISBN xxx" and "RFC xxx" with
785 * magic external links.
789 function &doMagicLinks( &$text ) {
790 $text = $this->magicISBN( $text );
791 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
792 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
797 * Parse ^^ tokens and return html
801 function doExponent( $text ) {
802 $fname = 'Parser::doExponent';
803 wfProfileIn( $fname );
804 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
805 wfProfileOut( $fname );
810 * Parse headers and return html
814 function doHeadings( $text ) {
815 $fname = 'Parser::doHeadings';
816 wfProfileIn( $fname );
817 for ( $i = 6; $i >= 1; --$i ) {
818 $h = substr( '======', 0, $i );
819 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
820 "<h{$i}>\\1</h{$i}>\\2", $text );
822 wfProfileOut( $fname );
827 * Replace single quotes with HTML markup
829 * @return string the altered text
831 function doAllQuotes( $text ) {
832 $fname = 'Parser::doAllQuotes';
833 wfProfileIn( $fname );
835 $lines = explode( "\n", $text );
836 foreach ( $lines as $line ) {
837 $outtext .= $this->doQuotes ( $line ) . "\n";
839 $outtext = substr($outtext, 0,-1);
840 wfProfileOut( $fname );
845 * Helper function for doAllQuotes()
848 function doQuotes( $text ) {
849 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
850 if ( count( $arr ) == 1 )
854 # First, do some preliminary work. This may shift some apostrophes from
855 # being mark-up to being text. It also counts the number of occurrences
856 # of bold and italics mark-ups.
860 foreach ( $arr as $r )
862 if ( ( $i %
2 ) == 1 )
864 # If there are ever four apostrophes, assume the first is supposed to
865 # be text, and the remaining three constitute mark-up for bold text.
866 if ( strlen( $arr[$i] ) == 4 )
871 # If there are more than 5 apostrophes in a row, assume they're all
872 # text except for the last 5.
873 else if ( strlen( $arr[$i] ) > 5 )
875 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
878 # Count the number of occurrences of bold and italics mark-ups.
879 # We are not counting sequences of five apostrophes.
880 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
881 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
882 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
887 # If there is an odd number of both bold and italics, it is likely
888 # that one of the bold ones was meant to be an apostrophe followed
889 # by italics. Which one we cannot know for certain, but it is more
890 # likely to be one that has a single-letter word before it.
891 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
894 $firstsingleletterword = -1;
895 $firstmultiletterword = -1;
897 foreach ( $arr as $r )
899 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
901 $x1 = substr ($arr[$i-1], -1);
902 $x2 = substr ($arr[$i-1], -2, 1);
904 if ($firstspace == -1) $firstspace = $i;
905 } else if ($x2 == ' ') {
906 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
908 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
914 # If there is a single-letter word, use it!
915 if ($firstsingleletterword > -1)
917 $arr [ $firstsingleletterword ] = "''";
918 $arr [ $firstsingleletterword-1 ] .= "'";
920 # If not, but there's a multi-letter word, use that one.
921 else if ($firstmultiletterword > -1)
923 $arr [ $firstmultiletterword ] = "''";
924 $arr [ $firstmultiletterword-1 ] .= "'";
926 # ... otherwise use the first one that has neither.
927 # (notice that it is possible for all three to be -1 if, for example,
928 # there is only one pentuple-apostrophe in the line)
929 else if ($firstspace > -1)
931 $arr [ $firstspace ] = "''";
932 $arr [ $firstspace-1 ] .= "'";
936 # Now let's actually convert our apostrophic mush to HTML!
945 if ($state == 'both')
952 if (strlen ($r) == 2)
955 { $output .= '</i>'; $state = ''; }
956 else if ($state == 'bi')
957 { $output .= '</i>'; $state = 'b'; }
958 else if ($state == 'ib')
959 { $output .= '</b></i><b>'; $state = 'b'; }
960 else if ($state == 'both')
961 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
962 else # $state can be 'b' or ''
963 { $output .= '<i>'; $state .= 'i'; }
965 else if (strlen ($r) == 3)
968 { $output .= '</b>'; $state = ''; }
969 else if ($state == 'bi')
970 { $output .= '</i></b><i>'; $state = 'i'; }
971 else if ($state == 'ib')
972 { $output .= '</b>'; $state = 'i'; }
973 else if ($state == 'both')
974 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
975 else # $state can be 'i' or ''
976 { $output .= '<b>'; $state .= 'b'; }
978 else if (strlen ($r) == 5)
981 { $output .= '</b><i>'; $state = 'i'; }
982 else if ($state == 'i')
983 { $output .= '</i><b>'; $state = 'b'; }
984 else if ($state == 'bi')
985 { $output .= '</i></b>'; $state = ''; }
986 else if ($state == 'ib')
987 { $output .= '</b></i>'; $state = ''; }
988 else if ($state == 'both')
989 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
990 else # ($state == '')
991 { $buffer = ''; $state = 'both'; }
996 # Now close all remaining tags. Notice that the order is important.
997 if ($state == 'b' ||
$state == 'ib')
999 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1003 if ($state == 'both')
1004 $output .= '<b><i>'.$buffer.'</i></b>';
1010 * Replace external links
1012 * Note: this is all very hackish and the order of execution matters a lot.
1013 * Make sure to run maintenance/parserTests.php if you change this code.
1017 function replaceExternalLinks( $text ) {
1019 $fname = 'Parser::replaceExternalLinks';
1020 wfProfileIn( $fname );
1022 $sk =& $this->mOptions
->getSkin();
1024 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1026 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1029 while ( $i<count( $bits ) ) {
1031 $protocol = $bits[$i++
];
1032 $text = $bits[$i++
];
1033 $trail = $bits[$i++
];
1035 # The characters '<' and '>' (which were escaped by
1036 # removeHTMLtags()) should not be included in
1037 # URLs, per RFC 2396.
1038 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1039 $text = substr($url, $m2[0][1]) . ' ' . $text;
1040 $url = substr($url, 0, $m2[0][1]);
1043 # If the link text is an image URL, replace it with an <img> tag
1044 # This happened by accident in the original parser, but some people used it extensively
1045 $img = $this->maybeMakeExternalImage( $text );
1046 if ( $img !== false ) {
1052 # Set linktype for CSS - if URL==text, link is essentially free
1053 $linktype = ($text == $url) ?
'free' : 'text';
1055 # No link text, e.g. [http://domain.tld/some.link]
1056 if ( $text == '' ) {
1057 # Autonumber if allowed
1058 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1059 $text = '[' . ++
$this->mAutonumber
. ']';
1060 $linktype = 'autonumber';
1062 # Otherwise just use the URL
1063 $text = htmlspecialchars( $url );
1067 # Have link text, e.g. [http://domain.tld/some.link text]s
1069 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1072 $text = $wgContLang->markNoConversion($text);
1074 # Replace & from obsolete syntax with &.
1075 # All HTML entities will be escaped by makeExternalLink()
1076 # or maybeMakeExternalImage()
1077 $url = str_replace( '&', '&', $url );
1079 # Process the trail (i.e. everything after this link up until start of the next link),
1080 # replacing any non-bracketed links
1081 $trail = $this->replaceFreeExternalLinks( $trail );
1084 # Use the encoded URL
1085 # This means that users can paste URLs directly into the text
1086 # Funny characters like ö aren't valid in URLs anyway
1087 # This was changed in August 2004
1088 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1091 wfProfileOut( $fname );
1096 * Replace anything that looks like a URL with a link
1099 function replaceFreeExternalLinks( $text ) {
1101 $fname = 'Parser::replaceFreeExternalLinks';
1102 wfProfileIn( $fname );
1104 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1105 $s = array_shift( $bits );
1108 $sk =& $this->mOptions
->getSkin();
1110 while ( $i < count( $bits ) ){
1111 $protocol = $bits[$i++
];
1112 $remainder = $bits[$i++
];
1114 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1115 # Found some characters after the protocol that look promising
1116 $url = $protocol . $m[1];
1119 # The characters '<' and '>' (which were escaped by
1120 # removeHTMLtags()) should not be included in
1121 # URLs, per RFC 2396.
1122 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1123 $trail = substr($url, $m2[0][1]) . $trail;
1124 $url = substr($url, 0, $m2[0][1]);
1127 # Move trailing punctuation to $trail
1129 # If there is no left bracket, then consider right brackets fair game too
1130 if ( strpos( $url, '(' ) === false ) {
1134 $numSepChars = strspn( strrev( $url ), $sep );
1135 if ( $numSepChars ) {
1136 $trail = substr( $url, -$numSepChars ) . $trail;
1137 $url = substr( $url, 0, -$numSepChars );
1140 # Replace & from obsolete syntax with &.
1141 # All HTML entities will be escaped by makeExternalLink()
1142 # or maybeMakeExternalImage()
1143 $url = str_replace( '&', '&', $url );
1145 # Is this an external image?
1146 $text = $this->maybeMakeExternalImage( $url );
1147 if ( $text === false ) {
1148 # Not an image, make a link
1149 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1151 $s .= $text . $trail;
1153 $s .= $protocol . $remainder;
1161 * make an image if it's allowed
1164 function maybeMakeExternalImage( $url ) {
1165 $sk =& $this->mOptions
->getSkin();
1167 if ( $this->mOptions
->getAllowExternalImages() ) {
1168 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1170 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1177 * Process [[ ]] wikilinks
1181 function replaceInternalLinks( $s ) {
1182 global $wgContLang, $wgLinkCache;
1183 static $fname = 'Parser::replaceInternalLinks' ;
1185 wfProfileIn( $fname );
1187 wfProfileIn( $fname.'-setup' );
1189 # the % is needed to support urlencoded titles as well
1190 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1192 $sk =& $this->mOptions
->getSkin();
1194 #split the entire text string on occurences of [[
1195 $a = explode( '[[', ' ' . $s );
1196 #get the first element (all text up to first [[), and remove the space we added
1197 $s = array_shift( $a );
1198 $s = substr( $s, 1 );
1200 # Match a link having the form [[namespace:link|alternate]]trail
1202 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1203 # Match cases where there is no "]]", which might still be images
1204 static $e1_img = FALSE;
1205 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1206 # Match the end of a line for a word that's not followed by whitespace,
1207 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1208 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1210 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1212 if( is_null( $this->mTitle
) ) {
1213 wfDebugDieBacktrace( 'nooo' );
1215 $nottalk = !$this->mTitle
->isTalkPage();
1217 if ( $useLinkPrefixExtension ) {
1218 if ( preg_match( $e2, $s, $m ) ) {
1219 $first_prefix = $m[2];
1222 $first_prefix = false;
1228 $selflink = $this->mTitle
->getPrefixedText();
1229 wfProfileOut( $fname.'-setup' );
1231 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1232 $useSubpages = $this->areSubpagesAllowed();
1234 # Loop for each link
1235 for ($k = 0; isset( $a[$k] ); $k++
) {
1237 if ( $useLinkPrefixExtension ) {
1238 wfProfileIn( $fname.'-prefixhandling' );
1239 if ( preg_match( $e2, $s, $m ) ) {
1247 $prefix = $first_prefix;
1248 $first_prefix = false;
1250 wfProfileOut( $fname.'-prefixhandling' );
1253 $might_be_img = false;
1255 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1257 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1258 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1259 # the real problem is with the $e1 regex
1262 # Still some problems for cases where the ] is meant to be outside punctuation,
1263 # and no image is in sight. See bug 2095.
1265 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1266 $text .= ']'; # so that replaceExternalLinks($text) works later
1269 # fix up urlencoded title texts
1270 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1272 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1273 $might_be_img = true;
1275 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1277 } else { # Invalid form; output directly
1278 $s .= $prefix . '[[' . $line ;
1282 # Don't allow internal links to pages containing
1283 # PROTO: where PROTO is a valid URL protocol; these
1284 # should be external links.
1285 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1286 $s .= $prefix . '[[' . $line ;
1290 # Make subpage if necessary
1291 if( $useSubpages ) {
1292 $link = $this->maybeDoSubpageLink( $m[1], $text );
1297 $noforce = (substr($m[1], 0, 1) != ':');
1299 # Strip off leading ':'
1300 $link = substr($link, 1);
1303 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1305 $s .= $prefix . '[[' . $line;
1309 #check other language variants of the link
1310 #if the article does not exist
1311 if( $checkVariantLink
1312 && $nt->getArticleID() == 0 ) {
1313 $wgContLang->findVariantLink($link, $nt);
1316 $ns = $nt->getNamespace();
1317 $iw = $nt->getInterWiki();
1319 if ($might_be_img) { # if this is actually an invalid link
1320 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1322 while (isset ($a[$k+
1]) ) {
1323 #look at the next 'line' to see if we can close it there
1324 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1325 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1326 # the first ]] closes the inner link, the second the image
1328 $text .= '[[' . $m[1];
1331 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1332 #if there's exactly one ]] that's fine, we'll keep looking
1333 $text .= '[[' . $m[0];
1335 #if $next_line is invalid too, we need look no further
1336 $text .= '[[' . $next_line;
1341 # we couldn't find the end of this imageLink, so output it raw
1342 #but don't ignore what might be perfectly normal links in the text we've examined
1343 $text = $this->replaceInternalLinks($text);
1344 $s .= $prefix . '[[' . $link . '|' . $text;
1345 # note: no $trail, because without an end, there *is* no trail
1348 } else { #it's not an image, so output it raw
1349 $s .= $prefix . '[[' . $link . '|' . $text;
1350 # note: no $trail, because without an end, there *is* no trail
1355 $wasblank = ( '' == $text );
1356 if( $wasblank ) $text = $link;
1359 # Link not escaped by : , create the various objects
1363 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1364 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1365 $s = rtrim($s . "\n");
1366 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1370 if ( $ns == NS_IMAGE
) {
1371 wfProfileIn( "$fname-image" );
1372 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1373 # recursively parse links inside the image caption
1374 # actually, this will parse them in any other parameters, too,
1375 # but it might be hard to fix that, and it doesn't matter ATM
1376 $text = $this->replaceExternalLinks($text);
1377 $text = $this->replaceInternalLinks($text);
1379 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1380 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1381 $wgLinkCache->addImageLinkObj( $nt );
1383 wfProfileOut( "$fname-image" );
1386 wfProfileOut( "$fname-image" );
1390 if ( $ns == NS_CATEGORY
) {
1391 wfProfileIn( "$fname-category" );
1392 $t = $wgContLang->convert($nt->getText());
1393 $s = rtrim($s . "\n"); # bug 87
1395 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1396 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1397 $wgLinkCache->resume();
1400 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1401 $sortkey = $this->mTitle
->getText();
1403 $sortkey = $this->mTitle
->getPrefixedText();
1408 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1409 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1410 $this->mOutput
->addCategoryLink( $t );
1413 * Strip the whitespace Category links produce, see bug 87
1414 * @todo We might want to use trim($tmp, "\n") here.
1416 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1418 wfProfileOut( "$fname-category" );
1423 if( ( $nt->getPrefixedText() === $selflink ) &&
1424 ( $nt->getFragment() === '' ) ) {
1425 # Self-links are handled specially; generally de-link and change to bold.
1426 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1430 # Special and Media are pseudo-namespaces; no pages actually exist in them
1431 if( $ns == NS_MEDIA
) {
1432 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1433 $wgLinkCache->addImageLinkObj( $nt );
1435 } elseif( $ns == NS_SPECIAL
) {
1436 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1439 if( $nt->isLocal() && $nt->isAlwaysKnown() ) {
1441 * Skip lookups for special pages and self-links.
1442 * External interwiki links are not included here because
1443 * the HTTP urls would break output in the next parse step;
1444 * they will have placeholders kept.
1446 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1449 * Add a link placeholder
1450 * Later, this will be replaced by a real link, after the existence or
1451 * non-existence of all the links is known
1453 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1456 wfProfileOut( $fname );
1461 * Make a link placeholder. The text returned can be later resolved to a real link with
1462 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1463 * parsing of interwiki links, and secondly to allow all extistence checks and
1464 * article length checks (for stub links) to be bundled into a single query.
1467 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1468 if ( ! is_object($nt) ) {
1470 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1472 # Separate the link trail from the rest of the link
1473 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1475 if ( $nt->isExternal() ) {
1476 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1477 $this->mInterwikiLinkHolders
['titles'][] =& $nt;
1478 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1480 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1481 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1482 $this->mLinkHolders
['queries'][] = $query;
1483 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1484 $this->mLinkHolders
['titles'][] =& $nt;
1486 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1493 * Return true if subpage links should be expanded on this page.
1496 function areSubpagesAllowed() {
1497 # Some namespaces don't allow subpages
1498 global $wgNamespacesWithSubpages;
1499 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1503 * Handle link to subpage if necessary
1504 * @param string $target the source of the link
1505 * @param string &$text the link text, modified as necessary
1506 * @return string the full name of the link
1509 function maybeDoSubpageLink($target, &$text) {
1512 # :Foobar -- override special treatment of prefix (images, language links)
1513 # /Foobar -- convert to CurrentPage/Foobar
1514 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1515 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1516 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1518 $fname = 'Parser::maybeDoSubpageLink';
1519 wfProfileIn( $fname );
1520 $ret = $target; # default return value is no change
1522 # Some namespaces don't allow subpages,
1523 # so only perform processing if subpages are allowed
1524 if( $this->areSubpagesAllowed() ) {
1525 # Look at the first character
1526 if( $target != '' && $target{0} == '/' ) {
1527 # / at end means we don't want the slash to be shown
1528 if( substr( $target, -1, 1 ) == '/' ) {
1529 $target = substr( $target, 1, -1 );
1532 $noslash = substr( $target, 1 );
1535 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1536 if( '' === $text ) {
1538 } # this might be changed for ugliness reasons
1540 # check for .. subpage backlinks
1542 $nodotdot = $target;
1543 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1545 $nodotdot = substr( $nodotdot, 3 );
1547 if($dotdotcount > 0) {
1548 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1549 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1550 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1551 # / at the end means don't show full path
1552 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1553 $nodotdot = substr( $nodotdot, 0, -1 );
1554 if( '' === $text ) {
1558 $nodotdot = trim( $nodotdot );
1559 if( $nodotdot != '' ) {
1560 $ret .= '/' . $nodotdot;
1567 wfProfileOut( $fname );
1572 * Used by doBlockLevels()
1575 /* private */ function closeParagraph() {
1577 if ( '' != $this->mLastSection
) {
1578 $result = '</' . $this->mLastSection
. ">\n";
1580 $this->mInPre
= false;
1581 $this->mLastSection
= '';
1584 # getCommon() returns the length of the longest common substring
1585 # of both arguments, starting at the beginning of both.
1587 /* private */ function getCommon( $st1, $st2 ) {
1588 $fl = strlen( $st1 );
1589 $shorter = strlen( $st2 );
1590 if ( $fl < $shorter ) { $shorter = $fl; }
1592 for ( $i = 0; $i < $shorter; ++
$i ) {
1593 if ( $st1{$i} != $st2{$i} ) { break; }
1597 # These next three functions open, continue, and close the list
1598 # element appropriate to the prefix character passed into them.
1600 /* private */ function openList( $char ) {
1601 $result = $this->closeParagraph();
1603 if ( '*' == $char ) { $result .= '<ul><li>'; }
1604 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1605 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1606 else if ( ';' == $char ) {
1607 $result .= '<dl><dt>';
1608 $this->mDTopen
= true;
1610 else { $result = '<!-- ERR 1 -->'; }
1615 /* private */ function nextItem( $char ) {
1616 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1617 else if ( ':' == $char ||
';' == $char ) {
1619 if ( $this->mDTopen
) { $close = '</dt>'; }
1620 if ( ';' == $char ) {
1621 $this->mDTopen
= true;
1622 return $close . '<dt>';
1624 $this->mDTopen
= false;
1625 return $close . '<dd>';
1628 return '<!-- ERR 2 -->';
1631 /* private */ function closeList( $char ) {
1632 if ( '*' == $char ) { $text = '</li></ul>'; }
1633 else if ( '#' == $char ) { $text = '</li></ol>'; }
1634 else if ( ':' == $char ) {
1635 if ( $this->mDTopen
) {
1636 $this->mDTopen
= false;
1637 $text = '</dt></dl>';
1639 $text = '</dd></dl>';
1642 else { return '<!-- ERR 3 -->'; }
1648 * Make lists from lines starting with ':', '*', '#', etc.
1651 * @return string the lists rendered as HTML
1653 function doBlockLevels( $text, $linestart ) {
1654 $fname = 'Parser::doBlockLevels';
1655 wfProfileIn( $fname );
1657 # Parsing through the text line by line. The main thing
1658 # happening here is handling of block-level elements p, pre,
1659 # and making lists from lines starting with * # : etc.
1661 $textLines = explode( "\n", $text );
1663 $lastPrefix = $output = '';
1664 $this->mDTopen
= $inBlockElem = false;
1666 $paragraphStack = false;
1668 if ( !$linestart ) {
1669 $output .= array_shift( $textLines );
1671 foreach ( $textLines as $oLine ) {
1672 $lastPrefixLength = strlen( $lastPrefix );
1673 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1674 $preOpenMatch = preg_match('/<pre/i', $oLine );
1675 if ( !$this->mInPre
) {
1676 # Multiple prefixes may abut each other for nested lists.
1677 $prefixLength = strspn( $oLine, '*#:;' );
1678 $pref = substr( $oLine, 0, $prefixLength );
1681 $pref2 = str_replace( ';', ':', $pref );
1682 $t = substr( $oLine, $prefixLength );
1683 $this->mInPre
= !empty($preOpenMatch);
1685 # Don't interpret any other prefixes in preformatted text
1687 $pref = $pref2 = '';
1692 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1693 # Same as the last item, so no need to deal with nesting or opening stuff
1694 $output .= $this->nextItem( substr( $pref, -1 ) );
1695 $paragraphStack = false;
1697 if ( substr( $pref, -1 ) == ';') {
1698 # The one nasty exception: definition lists work like this:
1699 # ; title : definition text
1700 # So we check for : in the remainder text to split up the
1701 # title and definition, without b0rking links.
1703 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1705 $output .= $term . $this->nextItem( ':' );
1708 } elseif( $prefixLength ||
$lastPrefixLength ) {
1709 # Either open or close a level...
1710 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1711 $paragraphStack = false;
1713 while( $commonPrefixLength < $lastPrefixLength ) {
1714 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1715 --$lastPrefixLength;
1717 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1718 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1720 while ( $prefixLength > $commonPrefixLength ) {
1721 $char = substr( $pref, $commonPrefixLength, 1 );
1722 $output .= $this->openList( $char );
1724 if ( ';' == $char ) {
1725 # FIXME: This is dupe of code above
1726 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1728 $output .= $term . $this->nextItem( ':' );
1731 ++
$commonPrefixLength;
1733 $lastPrefix = $pref2;
1735 if( 0 == $prefixLength ) {
1736 wfProfileIn( "$fname-paragraph" );
1737 # No prefix (not in list)--go to paragraph mode
1738 $uniq_prefix = UNIQ_PREFIX
;
1739 // XXX: use a stack for nestable elements like span, table and div
1740 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1741 $closematch = preg_match(
1742 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1743 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1744 if ( $openmatch or $closematch ) {
1745 $paragraphStack = false;
1746 $output .= $this->closeParagraph();
1747 if($preOpenMatch and !$preCloseMatch) {
1748 $this->mInPre
= true;
1750 if ( $closematch ) {
1751 $inBlockElem = false;
1753 $inBlockElem = true;
1755 } else if ( !$inBlockElem && !$this->mInPre
) {
1756 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1758 if ($this->mLastSection
!= 'pre') {
1759 $paragraphStack = false;
1760 $output .= $this->closeParagraph().'<pre>';
1761 $this->mLastSection
= 'pre';
1763 $t = substr( $t, 1 );
1766 if ( '' == trim($t) ) {
1767 if ( $paragraphStack ) {
1768 $output .= $paragraphStack.'<br />';
1769 $paragraphStack = false;
1770 $this->mLastSection
= 'p';
1772 if ($this->mLastSection
!= 'p' ) {
1773 $output .= $this->closeParagraph();
1774 $this->mLastSection
= '';
1775 $paragraphStack = '<p>';
1777 $paragraphStack = '</p><p>';
1781 if ( $paragraphStack ) {
1782 $output .= $paragraphStack;
1783 $paragraphStack = false;
1784 $this->mLastSection
= 'p';
1785 } else if ($this->mLastSection
!= 'p') {
1786 $output .= $this->closeParagraph().'<p>';
1787 $this->mLastSection
= 'p';
1792 wfProfileOut( "$fname-paragraph" );
1794 if ($paragraphStack === false) {
1798 while ( $prefixLength ) {
1799 $output .= $this->closeList( $pref2{$prefixLength-1} );
1802 if ( '' != $this->mLastSection
) {
1803 $output .= '</' . $this->mLastSection
. '>';
1804 $this->mLastSection
= '';
1807 wfProfileOut( $fname );
1812 * Split up a string on ':', ignoring any occurences inside
1813 * <a>..</a> or <span>...</span>
1814 * @param string $str the string to split
1815 * @param string &$before set to everything before the ':'
1816 * @param string &$after set to everything after the ':'
1817 * return string the position of the ':', or false if none found
1819 function findColonNoLinks($str, &$before, &$after) {
1820 # I wonder if we should make this count all tags, not just <a>
1821 # and <span>. That would prevent us from matching a ':' that
1822 # comes in the middle of italics other such formatting....
1824 $fname = 'Parser::findColonNoLinks';
1825 wfProfileIn( $fname );
1828 $colon = strpos($str, ':', $pos);
1830 if ($colon !== false) {
1831 $before = substr($str, 0, $colon);
1832 $after = substr($str, $colon +
1);
1834 # Skip any ':' within <a> or <span> pairs
1835 $a = substr_count($before, '<a');
1836 $s = substr_count($before, '<span');
1837 $ca = substr_count($before, '</a>');
1838 $cs = substr_count($before, '</span>');
1840 if ($a <= $ca and $s <= $cs) {
1841 # Tags are balanced before ':'; ok
1846 } while ($colon !== false);
1847 wfProfileOut( $fname );
1852 * Return value of a magic variable (like PAGENAME)
1856 function getVariableValue( $index ) {
1857 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1860 * Some of these require message or data lookups and can be
1861 * expensive to check many times.
1863 static $varCache = array();
1864 if( isset( $varCache[$index] ) ) return $varCache[$index];
1867 case MAG_CURRENTMONTH
:
1868 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1869 case MAG_CURRENTMONTHNAME
:
1870 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1871 case MAG_CURRENTMONTHNAMEGEN
:
1872 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1873 case MAG_CURRENTMONTHABBREV
:
1874 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1875 case MAG_CURRENTDAY
:
1876 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1878 return $this->mTitle
->getText();
1880 return $this->mTitle
->getPartialURL();
1881 case MAG_REVISIONID
:
1882 return $wgArticle->getRevIdFetched();
1884 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1885 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1886 case MAG_CURRENTDAYNAME
:
1887 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1888 case MAG_CURRENTYEAR
:
1889 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1890 case MAG_CURRENTTIME
:
1891 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1892 case MAG_CURRENTWEEK
:
1893 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1894 case MAG_CURRENTDOW
:
1895 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1896 case MAG_NUMBEROFARTICLES
:
1897 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1908 * initialise the magic variables (like CURRENTMONTHNAME)
1912 function initialiseVariables() {
1913 $fname = 'Parser::initialiseVariables';
1914 wfProfileIn( $fname );
1915 global $wgVariableIDs;
1916 $this->mVariables
= array();
1917 foreach ( $wgVariableIDs as $id ) {
1918 $mw =& MagicWord
::get( $id );
1919 $mw->addToArray( $this->mVariables
, $id );
1921 wfProfileOut( $fname );
1925 * Replace magic variables, templates, and template arguments
1926 * with the appropriate text. Templates are substituted recursively,
1927 * taking care to avoid infinite loops.
1929 * Note that the substitution depends on value of $mOutputType:
1930 * OT_WIKI: only {{subst:}} templates
1931 * OT_MSG: only magic variables
1932 * OT_HTML: all templates and magic variables
1934 * @param string $tex The text to transform
1935 * @param array $args Key-value pairs representing template parameters to substitute
1938 function replaceVariables( $text, $args = array() ) {
1940 # Prevent too big inclusions
1941 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1945 $fname = 'Parser::replaceVariables';
1946 wfProfileIn( $fname );
1948 $titleChars = Title
::legalChars();
1950 # This function is called recursively. To keep track of arguments we need a stack:
1951 array_push( $this->mArgStack
, $args );
1953 # Variable substitution
1954 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1956 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1957 # Argument substitution
1958 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1960 # Template substitution
1961 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1962 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1964 array_pop( $this->mArgStack
);
1966 wfProfileOut( $fname );
1971 * Replace magic variables
1974 function variableSubstitution( $matches ) {
1975 $fname = 'parser::variableSubstitution';
1976 $varname = $matches[1];
1977 wfProfileIn( $fname );
1978 if ( !$this->mVariables
) {
1979 $this->initialiseVariables();
1982 if ( $this->mOutputType
== OT_WIKI
) {
1983 # Do only magic variables prefixed by SUBST
1984 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1985 if (!$mwSubst->matchStartAndRemove( $varname ))
1987 # Note that if we don't substitute the variable below,
1988 # we don't remove the {{subst:}} magic word, in case
1989 # it is a template rather than a magic variable.
1991 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1992 $id = $this->mVariables
[$varname];
1993 $text = $this->getVariableValue( $id );
1994 $this->mOutput
->mContainsOldMagic
= true;
1996 $text = $matches[0];
1998 wfProfileOut( $fname );
2002 # Split template arguments
2003 function getTemplateArgs( $argsString ) {
2004 if ( $argsString === '' ) {
2008 $args = explode( '|', substr( $argsString, 1 ) );
2010 # If any of the arguments contains a '[[' but no ']]', it needs to be
2011 # merged with the next arg because the '|' character between belongs
2012 # to the link syntax and not the template parameter syntax.
2013 $argc = count($args);
2015 for ( $i = 0; $i < $argc-1; $i++
) {
2016 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2017 $args[$i] .= '|'.$args[$i+
1];
2018 array_splice($args, $i+
1, 1);
2028 * Return the text of a template, after recursively
2029 * replacing any variables or templates within the template.
2031 * @param array $matches The parts of the template
2032 * $matches[1]: the title, i.e. the part before the |
2033 * $matches[2]: the parameters (including a leading |), if any
2034 * @return string the text of the template
2037 function braceSubstitution( $matches ) {
2038 global $wgLinkCache, $wgContLang;
2039 $fname = 'Parser::braceSubstitution';
2040 wfProfileIn( $fname );
2048 # Need to know if the template comes at the start of a line,
2049 # to treat the beginning of the template like the beginning
2050 # of a line for tables and block-level elements.
2051 $linestart = $matches[1];
2053 # $part1 is the bit before the first |, and must contain only title characters
2054 # $args is a list of arguments, starting from index 0, not including $part1
2056 $part1 = $matches[2];
2057 # If the third subpattern matched anything, it will start with |
2059 $args = $this->getTemplateArgs($matches[3]);
2060 $argc = count( $args );
2062 # Don't parse {{{}}} because that's only for template arguments
2063 if ( $linestart === '{' ) {
2064 $text = $matches[0];
2071 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2072 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2073 # One of two possibilities is true:
2074 # 1) Found SUBST but not in the PST phase
2075 # 2) Didn't find SUBST and in the PST phase
2076 # In either case, return without further processing
2077 $text = $matches[0];
2083 # MSG, MSGNW and INT
2086 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2087 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2090 # Remove obsolete MSG:
2091 $mwMsg =& MagicWord
::get( MAG_MSG
);
2092 $mwMsg->matchStartAndRemove( $part1 );
2095 # Check if it is an internal message
2096 $mwInt =& MagicWord
::get( MAG_INT
);
2097 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2098 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2099 $text = $linestart . wfMsgReal( $part1, $args, true );
2107 # Check for NS: (namespace expansion)
2108 $mwNs = MagicWord
::get( MAG_NS
);
2109 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2110 if ( intval( $part1 ) ) {
2111 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2114 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2115 if ( !is_null( $index ) ) {
2116 $text = $linestart . $wgContLang->getNsText( $index );
2123 # LOCALURL and LOCALURLE
2125 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2126 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2128 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2129 $func = 'getLocalURL';
2130 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2131 $func = 'escapeLocalURL';
2136 if ( $func !== '' ) {
2137 $title = Title
::newFromText( $part1 );
2138 if ( !is_null( $title ) ) {
2140 $text = $linestart . $title->$func( $args[0] );
2142 $text = $linestart . $title->$func();
2150 if ( !$found && $argc == 1 ) {
2151 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2152 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2153 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2158 # Template table test
2160 # Did we encounter this template already? If yes, it is in the cache
2161 # and we need to check for loops.
2162 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2165 # Infinite loop test
2166 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2169 $text = $linestart .
2171 '<!-- WARNING: template loop detected -->';
2172 wfDebug( "$fname: template loop broken at '$part1'\n" );
2174 # set $text to cached message.
2175 $text = $linestart . $this->mTemplates
[$part1];
2179 # Load from database
2180 $replaceHeadings = false;
2182 $lastPathLevel = $this->mTemplatePath
;
2185 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2186 if ($subpage !== '') {
2187 $ns = $this->mTitle
->getNamespace();
2189 $title = Title
::newFromText( $part1, $ns );
2190 if ( !is_null( $title ) && !$title->isExternal() ) {
2191 # Check for excessive inclusion
2192 $dbk = $title->getPrefixedDBkey();
2193 if ( $this->incrementIncludeCount( $dbk ) ) {
2194 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2195 # Capture special page output
2196 $text = SpecialPage
::capturePath( $title );
2197 if ( $text && !is_object( $text ) ) {
2201 $this->mOutput
->setCacheTime( -1 );
2204 $article = new Article( $title );
2205 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2206 if ( $articleContent !== false ) {
2208 $text = $articleContent;
2209 $replaceHeadings = true;
2214 # If the title is valid but undisplayable, make a link to it
2215 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2216 $text = '[['.$title->getPrefixedText().']]';
2220 # Template cache array insertion
2222 $this->mTemplates
[$part1] = $text;
2223 $text = $linestart . $text;
2228 # Recursive parsing, escaping and link table handling
2229 # Only for HTML output
2230 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2231 $text = wfEscapeWikiText( $text );
2232 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2233 # Clean up argument array
2234 $assocArgs = array();
2236 foreach( $args as $arg ) {
2237 $eqpos = strpos( $arg, '=' );
2238 if ( $eqpos === false ) {
2239 $assocArgs[$index++
] = $arg;
2241 $name = trim( substr( $arg, 0, $eqpos ) );
2242 $value = trim( substr( $arg, $eqpos+
1 ) );
2243 if ( $value === false ) {
2246 if ( $name !== false ) {
2247 $assocArgs[$name] = $value;
2252 # Add a new element to the templace recursion path
2253 $this->mTemplatePath
[$part1] = 1;
2255 if( $this->mOutputType
== OT_HTML
) {
2256 $text = $this->strip( $text, $this->mStripState
);
2257 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2259 $text = $this->replaceVariables( $text, $assocArgs );
2261 # Resume the link cache and register the inclusion as a link
2262 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2263 $wgLinkCache->addLinkObj( $title );
2266 # If the template begins with a table or block-level
2267 # element, it should be treated as beginning a new line.
2268 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2269 $text = "\n" . $text;
2272 # Prune lower levels off the recursion check path
2273 $this->mTemplatePath
= $lastPathLevel;
2276 wfProfileOut( $fname );
2280 # Replace raw HTML by a placeholder
2281 # Add a blank line preceding, to prevent it from mucking up
2282 # immediately preceding headings
2283 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2285 # replace ==section headers==
2286 # XXX this needs to go away once we have a better parser.
2287 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2288 if( !is_null( $title ) )
2289 $encodedname = base64_encode($title->getPrefixedDBkey());
2291 $encodedname = base64_encode("");
2292 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2293 PREG_SPLIT_DELIM_CAPTURE
);
2296 for( $i = 0; $i < count($m); $i +
= 2 ) {
2298 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2300 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2304 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2305 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2306 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2314 # Prune lower levels off the recursion check path
2315 $this->mTemplatePath
= $lastPathLevel;
2318 wfProfileOut( $fname );
2321 wfProfileOut( $fname );
2327 * Triple brace replacement -- used for template arguments
2330 function argSubstitution( $matches ) {
2331 $arg = trim( $matches[1] );
2332 $text = $matches[0];
2333 $inputArgs = end( $this->mArgStack
);
2335 if ( array_key_exists( $arg, $inputArgs ) ) {
2336 $text = $inputArgs[$arg];
2343 * Returns true if the function is allowed to include this entity
2346 function incrementIncludeCount( $dbk ) {
2347 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2348 $this->mIncludeCount
[$dbk] = 0;
2350 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2358 * This function accomplishes several tasks:
2359 * 1) Auto-number headings if that option is enabled
2360 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2361 * 3) Add a Table of contents on the top for users who have enabled the option
2362 * 4) Auto-anchor headings
2364 * It loops through all headlines, collects the necessary data, then splits up the
2365 * string and re-inserts the newly formatted headlines.
2367 * @param string $text
2368 * @param boolean $isMain
2371 function formatHeadings( $text, $isMain=true ) {
2372 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2374 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2376 $forceTocHere = false;
2377 if( !$this->mTitle
->userCanEdit() ) {
2380 $showEditLink = $this->mOptions
->getEditSection();
2383 # Inhibit editsection links if requested in the page
2384 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2385 if( $esw->matchAndRemove( $text ) ) {
2388 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2390 $mw =& MagicWord
::get( MAG_NOTOC
);
2391 if( $mw->matchAndRemove( $text ) ) {
2395 # Get all headlines for numbering them and adding funky stuff like [edit]
2396 # links - this is for later, but we need the number of headlines right now
2397 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2399 # if there are fewer than 4 headlines in the article, do not show TOC
2400 if( $numMatches < 4 ) {
2404 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2405 # override above conditions and always show TOC at that place
2407 $mw =& MagicWord
::get( MAG_TOC
);
2408 if($mw->match( $text ) ) {
2410 $forceTocHere = true;
2412 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2413 # override above conditions and always show TOC above first header
2414 $mw =& MagicWord
::get( MAG_FORCETOC
);
2415 if ($mw->matchAndRemove( $text ) ) {
2420 # Never ever show TOC if no headers
2421 if( $numMatches < 1 ) {
2425 # We need this to perform operations on the HTML
2426 $sk =& $this->mOptions
->getSkin();
2430 $sectionCount = 0; # headlineCount excluding template sections
2432 # Ugh .. the TOC should have neat indentation levels which can be
2433 # passed to the skin functions. These are determined here
2437 $sublevelCount = array();
2438 $levelCount = array();
2445 foreach( $matches[3] as $headline ) {
2447 $templatetitle = '';
2448 $templatesection = 0;
2451 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2453 $templatetitle = base64_decode($mat[1]);
2454 $templatesection = 1 +
(int)base64_decode($mat[2]);
2455 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2459 $prevlevel = $level;
2460 $prevtoclevel = $toclevel;
2462 $level = $matches[1][$headlineCount];
2464 if( $doNumberHeadings ||
$doShowToc ) {
2466 if ( $level > $prevlevel ) {
2467 # Increase TOC level
2469 $sublevelCount[$toclevel] = 0;
2470 $toc .= $sk->tocIndent();
2472 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2473 # Decrease TOC level, find level to jump to
2475 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2476 # Can only go down to level 1
2479 for ($i = $toclevel; $i > 0; $i--) {
2480 if ( $levelCount[$i] == $level ) {
2481 # Found last matching level
2485 elseif ( $levelCount[$i] < $level ) {
2486 # Found first matching level below current level
2493 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2496 # No change in level, end TOC line
2497 $toc .= $sk->tocLineEnd();
2500 $levelCount[$toclevel] = $level;
2502 # count number of headlines for each level
2503 @$sublevelCount[$toclevel]++
;
2505 for( $i = 1; $i <= $toclevel; $i++
) {
2506 if( !empty( $sublevelCount[$i] ) ) {
2510 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2516 # The canonized header is a version of the header text safe to use for links
2517 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2518 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2519 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2521 # Remove link placeholders by the link text.
2522 # <!--LINK number-->
2524 # link text with suffix
2525 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2526 "\$this->mLinkHolders['texts'][\$1]",
2527 $canonized_headline );
2528 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2529 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2530 $canonized_headline );
2533 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2534 $tocline = trim( $canonized_headline );
2535 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2536 $replacearray = array(
2540 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2541 $refers[$headlineCount] = $canonized_headline;
2543 # count how many in assoc. array so we can track dupes in anchors
2544 @$refers[$canonized_headline]++
;
2545 $refcount[$headlineCount]=$refers[$canonized_headline];
2547 # Don't number the heading if it is the only one (looks silly)
2548 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2549 # the two are different if the line contains a link
2550 $headline=$numbering . ' ' . $headline;
2553 # Create the anchor for linking from the TOC to the section
2554 $anchor = $canonized_headline;
2555 if($refcount[$headlineCount] > 1 ) {
2556 $anchor .= '_' . $refcount[$headlineCount];
2558 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2559 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2561 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2562 if ( empty( $head[$headlineCount] ) ) {
2563 $head[$headlineCount] = '';
2566 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2568 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2571 # give headline the correct <h#> tag
2572 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2580 $toc .= $sk->tocUnindent( $toclevel - 1 );
2581 $toc = $sk->tocList( $toc );
2584 # split up and insert constructed headlines
2586 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2589 foreach( $blocks as $block ) {
2590 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2591 # This is the [edit] link that appears for the top block of text when
2592 # section editing is enabled
2594 # Disabled because it broke block formatting
2595 # For example, a bullet point in the top line
2596 # $full .= $sk->editSectionLink(0);
2599 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2600 # Top anchor now in skin
2604 if( !empty( $head[$i] ) ) {
2610 $mw =& MagicWord
::get( MAG_TOC
);
2611 return $mw->replace( $toc, $full );
2618 * Return an HTML link for the "ISBN 123456" text
2621 function magicISBN( $text ) {
2622 $fname = 'Parser::magicISBN';
2623 wfProfileIn( $fname );
2625 $a = split( 'ISBN ', ' '.$text );
2626 if ( count ( $a ) < 2 ) {
2627 wfProfileOut( $fname );
2630 $text = substr( array_shift( $a ), 1);
2631 $valid = '0123456789-Xx';
2633 foreach ( $a as $x ) {
2634 $isbn = $blank = '' ;
2635 while ( ' ' == $x{0} ) {
2637 $x = substr( $x, 1 );
2639 if ( $x == '' ) { # blank isbn
2640 $text .= "ISBN $blank";
2643 while ( strstr( $valid, $x{0} ) != false ) {
2645 $x = substr( $x, 1 );
2647 $num = str_replace( '-', '', $isbn );
2648 $num = str_replace( ' ', '', $num );
2649 $num = str_replace( 'x', 'X', $num );
2652 $text .= "ISBN $blank$x";
2654 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2655 $text .= '<a href="' .
2656 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2657 "\" class=\"internal\">ISBN $isbn</a>";
2661 wfProfileOut( $fname );
2666 * Return an HTML link for the "RFC 1234" text
2669 * @param string $text Text to be processed
2670 * @param string $keyword Magic keyword to use (default RFC)
2671 * @param string $urlmsg Interface message to use (default rfcurl)
2674 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2676 $valid = '0123456789';
2679 $a = split( $keyword, ' '.$text );
2680 if ( count ( $a ) < 2 ) {
2683 $text = substr( array_shift( $a ), 1);
2685 /* Check if keyword is preceed by [[.
2686 * This test is made here cause of the array_shift above
2687 * that prevent the test to be done in the foreach.
2689 if ( substr( $text, -2 ) == '[[' ) {
2693 foreach ( $a as $x ) {
2694 /* token might be empty if we have RFC RFC 1234 */
2702 /** remove and save whitespaces in $blank */
2703 while ( $x{0} == ' ' ) {
2705 $x = substr( $x, 1 );
2708 /** remove and save the rfc number in $id */
2709 while ( strstr( $valid, $x{0} ) != false ) {
2711 $x = substr( $x, 1 );
2715 /* call back stripped spaces*/
2716 $text .= $keyword.$blank.$x;
2717 } elseif( $internal ) {
2719 $text .= $keyword.$id.$x;
2721 /* build the external link*/
2722 $url = wfMsg( $urlmsg, $id);
2723 $sk =& $this->mOptions
->getSkin();
2724 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2725 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2728 /* Check if the next RFC keyword is preceed by [[ */
2729 $internal = ( substr($x,-2) == '[[' );
2735 * Transform wiki markup when saving a page by doing \r\n -> \n
2736 * conversion, substitting signatures, {{subst:}} templates, etc.
2738 * @param string $text the text to transform
2739 * @param Title &$title the Title object for the current article
2740 * @param User &$user the User object describing the current user
2741 * @param ParserOptions $options parsing options
2742 * @param bool $clearState whether to clear the parser state first
2743 * @return string the altered wiki markup
2746 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2747 $this->mOptions
= $options;
2748 $this->mTitle
=& $title;
2749 $this->mOutputType
= OT_WIKI
;
2751 if ( $clearState ) {
2752 $this->clearState();
2755 $stripState = false;
2759 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2760 $text = $this->strip( $text, $stripState, false );
2761 $text = $this->pstPass2( $text, $user );
2762 $text = $this->unstrip( $text, $stripState );
2763 $text = $this->unstripNoWiki( $text, $stripState );
2768 * Pre-save transform helper function
2771 function pstPass2( $text, &$user ) {
2772 global $wgContLang, $wgLocaltimezone;
2774 # Variable replacement
2775 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2776 $text = $this->replaceVariables( $text );
2780 $n = $user->getName();
2781 $k = $user->getOption( 'nickname' );
2782 if ( '' == $k ) { $k = $n; }
2783 if ( isset( $wgLocaltimezone ) ) {
2784 $oldtz = getenv( 'TZ' );
2785 putenv( 'TZ='.$wgLocaltimezone );
2788 /* Note: This is the timestamp saved as hardcoded wikitext to
2789 * the database, we use $wgContLang here in order to give
2790 * everyone the same signiture and use the default one rather
2791 * than the one selected in each users preferences.
2793 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2794 ' (' . date( 'T' ) . ')';
2795 if ( isset( $wgLocaltimezone ) ) {
2796 putenv( 'TZ='.$oldtz );
2799 if( $user->getOption( 'fancysig' ) ) {
2802 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2804 $text = preg_replace( '/~~~~~/', $d, $text );
2805 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2806 $text = preg_replace( '/~~~/', $sigText, $text );
2808 # Context links: [[|name]] and [[name (context)|]]
2810 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2811 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2812 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2813 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2815 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2816 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2817 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2818 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2820 $t = $this->mTitle
->getText();
2821 if ( preg_match( $conpat, $t, $m ) ) {
2824 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2825 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2826 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2828 if ( '' == $context ) {
2829 $text = preg_replace( $p2, '[[\\1]]', $text );
2831 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2834 # Trim trailing whitespace
2835 # MAG_END (__END__) tag allows for trailing
2836 # whitespace to be deliberately included
2837 $text = rtrim( $text );
2838 $mw =& MagicWord
::get( MAG_END
);
2839 $mw->matchAndRemove( $text );
2845 * Set up some variables which are usually set up in parse()
2846 * so that an external function can call some class members with confidence
2849 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2850 $this->mTitle
=& $title;
2851 $this->mOptions
= $options;
2852 $this->mOutputType
= $outputType;
2853 if ( $clearState ) {
2854 $this->clearState();
2859 * Transform a MediaWiki message by replacing magic variables.
2861 * @param string $text the text to transform
2862 * @param ParserOptions $options options
2863 * @return string the text with variables substituted
2866 function transformMsg( $text, $options ) {
2868 static $executing = false;
2870 # Guard against infinite recursion
2876 $this->mTitle
= $wgTitle;
2877 $this->mOptions
= $options;
2878 $this->mOutputType
= OT_MSG
;
2879 $this->clearState();
2880 $text = $this->replaceVariables( $text );
2887 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2888 * Callback will be called with the text within
2889 * Transform and return the text within
2892 function setHook( $tag, $callback ) {
2893 $oldVal = @$this->mTagHooks
[$tag];
2894 $this->mTagHooks
[$tag] = $callback;
2899 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2900 * Placeholders created in Skin::makeLinkObj()
2901 * Returns an array of links found, indexed by PDBK:
2905 * $options is a bit field, RLH_FOR_UPDATE to select for update
2907 function replaceLinkHolders( &$text, $options = 0 ) {
2908 global $wgUser, $wgLinkCache;
2909 global $wgOutputReplace;
2911 $fname = 'Parser::replaceLinkHolders';
2912 wfProfileIn( $fname );
2916 $sk = $this->mOptions
->getSkin();
2918 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
2919 wfProfileIn( $fname.'-check' );
2920 $dbr =& wfGetDB( DB_SLAVE
);
2921 $page = $dbr->tableName( 'page' );
2922 $threshold = $wgUser->getOption('stubthreshold');
2925 asort( $this->mLinkHolders
['namespaces'] );
2929 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
2931 $title = $this->mLinkHolders
['titles'][$key];
2933 # Skip invalid entries.
2934 # Result will be ugly, but prevents crash.
2935 if ( is_null( $title ) ) {
2938 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2940 # Check if it's in the link cache already
2941 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2942 $colours[$pdbk] = 1;
2943 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2944 $colours[$pdbk] = 0;
2946 # Not in the link cache, add it to the query
2947 if ( !isset( $current ) ) {
2949 $query = "SELECT page_id, page_namespace, page_title";
2950 if ( $threshold > 0 ) {
2951 $query .= ', page_len, page_is_redirect';
2953 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2954 } elseif ( $current != $val ) {
2956 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2961 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
2966 if ( $options & RLH_FOR_UPDATE
) {
2967 $query .= ' FOR UPDATE';
2970 $res = $dbr->query( $query, $fname );
2972 # Fetch data and form into an associative array
2973 # non-existent = broken
2976 while ( $s = $dbr->fetchObject($res) ) {
2977 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2978 $pdbk = $title->getPrefixedDBkey();
2979 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
2981 if ( $threshold > 0 ) {
2982 $size = $s->page_len
;
2983 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2984 $colours[$pdbk] = 1;
2986 $colours[$pdbk] = 2;
2989 $colours[$pdbk] = 1;
2993 wfProfileOut( $fname.'-check' );
2995 # Construct search and replace arrays
2996 wfProfileIn( $fname.'-construct' );
2997 $wgOutputReplace = array();
2998 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
2999 $pdbk = $pdbks[$key];
3000 $searchkey = "<!--LINK $key-->";
3001 $title = $this->mLinkHolders
['titles'][$key];
3002 if ( empty( $colours[$pdbk] ) ) {
3003 $wgLinkCache->addBadLinkObj( $title );
3004 $colours[$pdbk] = 0;
3005 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3006 $this->mLinkHolders
['texts'][$key],
3007 $this->mLinkHolders
['queries'][$key] );
3008 } elseif ( $colours[$pdbk] == 1 ) {
3009 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3010 $this->mLinkHolders
['texts'][$key],
3011 $this->mLinkHolders
['queries'][$key] );
3012 } elseif ( $colours[$pdbk] == 2 ) {
3013 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3014 $this->mLinkHolders
['texts'][$key],
3015 $this->mLinkHolders
['queries'][$key] );
3018 wfProfileOut( $fname.'-construct' );
3021 wfProfileIn( $fname.'-replace' );
3023 $text = preg_replace_callback(
3024 '/(<!--LINK .*?-->)/',
3025 "wfOutputReplaceMatches",
3028 wfProfileOut( $fname.'-replace' );
3031 # Now process interwiki link holders
3032 # This is quite a bit simpler than internal links
3033 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3034 wfProfileIn( $fname.'-interwiki' );
3035 # Make interwiki link HTML
3036 $wgOutputReplace = array();
3037 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3038 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3039 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3042 $text = preg_replace_callback(
3043 '/<!--IWLINK (.*?)-->/',
3044 "wfOutputReplaceMatches",
3046 wfProfileOut( $fname.'-interwiki' );
3049 wfProfileOut( $fname );
3054 * Replace <!--LINK--> link placeholders with plain text of links
3055 * (not HTML-formatted).
3056 * @param string $text
3059 function replaceLinkHoldersText( $text ) {
3060 global $wgUser, $wgLinkCache;
3061 global $wgOutputReplace;
3063 $fname = 'Parser::replaceLinkHoldersText';
3064 wfProfileIn( $fname );
3066 $text = preg_replace_callback(
3067 '/<!--(LINK|IWLINK) (.*?)-->/',
3068 array( &$this, 'replaceLinkHoldersTextCallback' ),
3071 wfProfileOut( $fname );
3076 * @param array $matches
3080 function replaceLinkHoldersTextCallback( $matches ) {
3081 $type = $matches[1];
3083 if( $type == 'LINK' ) {
3084 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3085 return $this->mLinkHolders
['texts'][$key];
3087 } elseif( $type == 'IWLINK' ) {
3088 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3089 return $this->mInterwikiLinkHolders
['texts'][$key];
3096 * Renders an image gallery from a text with one line per image.
3097 * text labels may be given by using |-style alternative text. E.g.
3098 * Image:one.jpg|The number "1"
3099 * Image:tree.jpg|A tree
3100 * given as text will return the HTML of a gallery with two images,
3101 * labeled 'The number "1"' and
3106 function renderImageGallery( $text ) {
3108 global $wgUser, $wgTitle;
3109 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3110 $localParser = new Parser();
3112 global $wgLinkCache;
3113 $ig = new ImageGallery();
3114 $ig->setShowBytes( false );
3115 $ig->setShowFilename( false );
3116 $lines = explode( "\n", $text );
3118 foreach ( $lines as $line ) {
3119 # match lines like these:
3120 # Image:someimage.jpg|This is some image
3121 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3123 if ( count( $matches ) == 0 ) {
3126 $nt = Title
::newFromURL( $matches[1] );
3127 if( is_null( $nt ) ) {
3128 # Bogus title. Ignore these so we don't bomb out later.
3131 if ( isset( $matches[3] ) ) {
3132 $label = $matches[3];
3137 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3138 $html = $html->mText
;
3140 $ig->add( new Image( $nt ), $html );
3141 $wgLinkCache->addImageLinkObj( $nt );
3143 return $ig->toHTML();
3147 * Parse image options text and use it to make an image
3149 function makeImage( &$nt, $options ) {
3150 global $wgContLang, $wgUseImageResize;
3151 global $wgUser, $wgThumbLimits;
3155 # Check if the options text is of the form "options|alt text"
3157 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3158 # * left no resizing, just left align. label is used for alt= only
3159 # * right same, but right aligned
3160 # * none same, but not aligned
3161 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3162 # * center center the image
3163 # * framed Keep original image size, no magnify-button.
3165 $part = explode( '|', $options);
3167 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3168 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3169 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3170 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3171 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3172 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3173 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3176 $width = $height = $framed = $thumb = false;
3177 $manual_thumb = "" ;
3179 foreach( $part as $key => $val ) {
3180 $val_parts = explode ( "=" , $val , 2 ) ;
3181 $left_part = array_shift ( $val_parts ) ;
3182 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3184 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3185 # use manually specified thumbnail
3187 $manual_thumb = array_shift ( $val_parts ) ;
3188 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3189 # remember to set an alignment, don't render immediately
3191 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3192 # remember to set an alignment, don't render immediately
3194 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3195 # remember to set an alignment, don't render immediately
3197 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3198 # remember to set an alignment, don't render immediately
3200 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3201 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3202 # $match is the image width in pixels
3203 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3204 $width = intval( $m[1] );
3205 $height = intval( $m[2] );
3207 $width = intval($match);
3209 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3215 # Strip bad stuff out of the alt text
3216 $alt = $this->replaceLinkHoldersText( $caption );
3217 $alt = Sanitizer
::stripAllTags( $alt );
3219 # Linker does the rest
3220 $sk =& $this->mOptions
->getSkin();
3221 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3227 * @package MediaWiki
3231 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3232 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3233 var $mVersion; # Compatibility check
3234 var $mTitleText; # title text of the chosen language variant
3236 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3237 $containsOldMagic = false, $titletext = '' )
3239 $this->mText
= $text;
3240 $this->mLanguageLinks
= $languageLinks;
3241 $this->mCategoryLinks
= $categoryLinks;
3242 $this->mContainsOldMagic
= $containsOldMagic;
3243 $this->mCacheTime
= '';
3244 $this->mVersion
= MW_PARSER_VERSION
;
3245 $this->mTitleText
= $titletext;
3248 function getText() { return $this->mText
; }
3249 function getLanguageLinks() { return $this->mLanguageLinks
; }
3250 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3251 function getCacheTime() { return $this->mCacheTime
; }
3252 function getTitleText() { return $this->mTitleText
; }
3253 function containsOldMagic() { return $this->mContainsOldMagic
; }
3254 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3255 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3256 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3257 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3258 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3259 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3261 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3263 function merge( $other ) {
3264 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3265 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3266 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3270 * Return true if this cached output object predates the global or
3271 * per-article cache invalidation timestamps, or if it comes from
3272 * an incompatible older version.
3274 * @param string $touched the affected article's last touched timestamp
3278 function expired( $touched ) {
3279 global $wgCacheEpoch;
3280 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3281 $this->getCacheTime() <= $touched ||
3282 $this->getCacheTime() <= $wgCacheEpoch ||
3283 !isset( $this->mVersion
) ||
3284 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3289 * Set options of the Parser
3291 * @package MediaWiki
3295 # All variables are private
3296 var $mUseTeX; # Use texvc to expand <math> tags
3297 var $mUseDynamicDates; # Use DateFormatter to format dates
3298 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3299 var $mAllowExternalImages; # Allow external images inline
3300 var $mSkin; # Reference to the preferred skin
3301 var $mDateFormat; # Date format index
3302 var $mEditSection; # Create "edit section" links
3303 var $mNumberHeadings; # Automatically number headings
3304 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3306 function getUseTeX() { return $this->mUseTeX
; }
3307 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3308 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3309 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3310 function getSkin() { return $this->mSkin
; }
3311 function getDateFormat() { return $this->mDateFormat
; }
3312 function getEditSection() { return $this->mEditSection
; }
3313 function getNumberHeadings() { return $this->mNumberHeadings
; }
3314 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3317 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3318 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3319 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3320 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3321 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3322 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3323 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3324 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3326 function setSkin( &$x ) { $this->mSkin
=& $x; }
3328 function ParserOptions() {
3330 $this->initialiseFromUser( $wgUser );
3334 * Get parser options
3337 function newFromUser( &$user ) {
3338 $popts = new ParserOptions
;
3339 $popts->initialiseFromUser( $user );
3343 /** Get user options */
3344 function initialiseFromUser( &$userInput ) {
3345 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3346 $wgAllowSpecialInclusion;
3347 $fname = 'ParserOptions::initialiseFromUser';
3348 wfProfileIn( $fname );
3349 if ( !$userInput ) {
3351 $user->setLoaded( true );
3353 $user =& $userInput;
3356 $this->mUseTeX
= $wgUseTeX;
3357 $this->mUseDynamicDates
= $wgUseDynamicDates;
3358 $this->mInterwikiMagic
= $wgInterwikiMagic;
3359 $this->mAllowExternalImages
= $wgAllowExternalImages;
3360 wfProfileIn( $fname.'-skin' );
3361 $this->mSkin
=& $user->getSkin();
3362 wfProfileOut( $fname.'-skin' );
3363 $this->mDateFormat
= $user->getOption( 'date' );
3364 $this->mEditSection
= $user->getOption( 'editsection' );
3365 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3366 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3367 wfProfileOut( $fname );
3372 * Callback function used by Parser::replaceLinkHolders()
3373 * to substitute link placeholders.
3375 function &wfOutputReplaceMatches( $matches ) {
3376 global $wgOutputReplace;
3377 return $wgOutputReplace[$matches[1]];
3381 * Return the total number of articles
3383 function wfNumberOfArticles() {
3384 global $wgNumberOfArticles;
3387 return $wgNumberOfArticles;
3391 * Get various statistics from the database
3394 function wfLoadSiteStats() {
3395 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3396 $fname = 'wfLoadSiteStats';
3398 if ( -1 != $wgNumberOfArticles ) return;
3399 $dbr =& wfGetDB( DB_SLAVE
);
3400 $s = $dbr->selectRow( 'site_stats',
3401 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3402 array( 'ss_row_id' => 1 ), $fname
3405 if ( $s === false ) {
3408 $wgTotalViews = $s->ss_total_views
;
3409 $wgTotalEdits = $s->ss_total_edits
;
3410 $wgNumberOfArticles = $s->ss_good_articles
;
3416 * Basicly replacing " > and < with HTML entities ( ", >, <)
3418 * @param string $in Text that might contain HTML tags
3419 * @return string Escaped string
3421 function wfEscapeHTMLTagsOnly( $in ) {
3423 array( '"', '>', '<' ),
3424 array( '"', '>', '<' ),